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/java/modules/core/src/main/java/org/apache/synapse/config/xml/IterateMediatorFactory.java b/java/modules/core/src/main/java/org/apache/synapse/config/xml/IterateMediatorFactory.java index 67a0ac46c..61f69c90f 100644 --- a/java/modules/core/src/main/java/org/apache/synapse/config/xml/IterateMediatorFactory.java +++ b/java/modules/core/src/main/java/org/apache/synapse/config/xml/IterateMediatorFactory.java @@ -1,151 +1,151 @@ /* * 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.synapse.config.xml; import org.apache.axiom.om.OMAttribute; import org.apache.axiom.om.OMElement; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.Mediator; import org.apache.synapse.SynapseConstants; import org.apache.synapse.mediators.eip.splitter.IterateMediator; import org.apache.synapse.mediators.eip.Target; import org.apache.synapse.util.xpath.SynapseXPath; import org.jaxen.JaxenException; import javax.xml.namespace.QName; import java.util.Properties; /** * The &lt;iterate&gt; element is used to split messages in Synapse to smaller messages with only * one part of the elements described in the XPATH expression. * <p/> * <pre> * &lt;iterate [continueParent=(true | false)] [preservePayload=(true | false)] * (attachPath="xpath")? expression="xpath"&gt; * &lt;target [to="uri"] [soapAction="qname"] [sequence="sequence_ref"] * [endpoint="endpoint_ref"]&gt; * &lt;sequence&gt; * (mediator)+ * &lt;/sequence&gt;? * &lt;endpoint&gt; * endpoint * &lt;/endpoint&gt;? * &lt;/target&gt;+ * &lt;/iterate&gt; * </pre> */ public class IterateMediatorFactory extends AbstractMediatorFactory { private static final Log log = LogFactory.getLog(IterateMediatorFactory.class); /** * Holds the QName for the IterateMediator xml configuration */ private static final QName ITERATE_Q = new QName(SynapseConstants.SYNAPSE_NAMESPACE, "iterate"); private static final QName ATT_CONTPAR = new QName("continueParent"); private static final QName ATT_PREPLD = new QName("preservePayload"); private static final QName ATT_ATTACHPATH = new QName("attachPath"); private static final QName ATT_SEQUENCIAL = new QName("sequential"); /** * This method will create the IterateMediator by parsing the given xml configuration * * @param elem OMElement describing the configuration of the IterateMediaotr * @param properties properties passed * @return IterateMediator created from the given configuration */ public Mediator createSpecificMediator(OMElement elem, Properties properties) { IterateMediator mediator = new IterateMediator(); processAuditStatus(mediator, elem); OMAttribute continueParent = elem.getAttribute(ATT_CONTPAR); if (continueParent != null) { mediator.setContinueParent( Boolean.valueOf(continueParent.getAttributeValue())); } OMAttribute preservePayload = elem.getAttribute(ATT_PREPLD); if (preservePayload != null) { mediator.setPreservePayload( Boolean.valueOf(preservePayload.getAttributeValue())); } OMAttribute expression = elem.getAttribute(ATT_EXPRN); if (expression != null) { try { mediator.setExpression(SynapseXPathFactory.getSynapseXPath(elem, ATT_EXPRN)); } catch (JaxenException e) { handleException("Unable to build the IterateMediator. " + "Invalid XPATH " + expression.getAttributeValue(), e); } } else { handleException("XPATH expression is required " + "for an IterateMediator under the \"expression\" attribute"); } OMAttribute attachPath = elem.getAttribute(ATT_ATTACHPATH); String attachPathValue = "."; if (attachPath != null && !mediator.isPreservePayload()) { handleException("Wrong configuration for the iterate mediator :: if the iterator " + "should not preserve payload, then attachPath can not be present"); } else if (attachPath != null) { attachPathValue = attachPath.getAttributeValue(); } try { SynapseXPath xp = new SynapseXPath(attachPathValue); OMElementUtils.addNameSpaces(xp, elem, log); mediator.setAttachPath(xp); } catch (JaxenException e) { handleException("Unable to build the IterateMediator. Invalid XPATH " + attachPathValue, e); } boolean asynchronous = true; OMAttribute asynchronousAttr = elem.getAttribute(ATT_SEQUENCIAL); - if (asynchronousAttr != null && asynchronousAttr.getAttributeValue().equals("false")) { + if (asynchronousAttr != null && asynchronousAttr.getAttributeValue().equals("true")) { asynchronous = false; } OMElement targetElement = elem.getFirstChildWithName(TARGET_Q); if (targetElement != null) { Target target = TargetFactory.createTarget(targetElement, properties); if (target != null) { target.setAsynchronous(asynchronous); mediator.setTarget(target); } } else { handleException("Target for an iterate mediator is required :: missing target"); } return mediator; } /** * Get the IterateMediator configuration tag name * * @return QName specifying the IterateMediator tag name of the xml configuration */ public QName getTagQName() { return ITERATE_Q; } }
true
true
public Mediator createSpecificMediator(OMElement elem, Properties properties) { IterateMediator mediator = new IterateMediator(); processAuditStatus(mediator, elem); OMAttribute continueParent = elem.getAttribute(ATT_CONTPAR); if (continueParent != null) { mediator.setContinueParent( Boolean.valueOf(continueParent.getAttributeValue())); } OMAttribute preservePayload = elem.getAttribute(ATT_PREPLD); if (preservePayload != null) { mediator.setPreservePayload( Boolean.valueOf(preservePayload.getAttributeValue())); } OMAttribute expression = elem.getAttribute(ATT_EXPRN); if (expression != null) { try { mediator.setExpression(SynapseXPathFactory.getSynapseXPath(elem, ATT_EXPRN)); } catch (JaxenException e) { handleException("Unable to build the IterateMediator. " + "Invalid XPATH " + expression.getAttributeValue(), e); } } else { handleException("XPATH expression is required " + "for an IterateMediator under the \"expression\" attribute"); } OMAttribute attachPath = elem.getAttribute(ATT_ATTACHPATH); String attachPathValue = "."; if (attachPath != null && !mediator.isPreservePayload()) { handleException("Wrong configuration for the iterate mediator :: if the iterator " + "should not preserve payload, then attachPath can not be present"); } else if (attachPath != null) { attachPathValue = attachPath.getAttributeValue(); } try { SynapseXPath xp = new SynapseXPath(attachPathValue); OMElementUtils.addNameSpaces(xp, elem, log); mediator.setAttachPath(xp); } catch (JaxenException e) { handleException("Unable to build the IterateMediator. Invalid XPATH " + attachPathValue, e); } boolean asynchronous = true; OMAttribute asynchronousAttr = elem.getAttribute(ATT_SEQUENCIAL); if (asynchronousAttr != null && asynchronousAttr.getAttributeValue().equals("false")) { asynchronous = false; } OMElement targetElement = elem.getFirstChildWithName(TARGET_Q); if (targetElement != null) { Target target = TargetFactory.createTarget(targetElement, properties); if (target != null) { target.setAsynchronous(asynchronous); mediator.setTarget(target); } } else { handleException("Target for an iterate mediator is required :: missing target"); } return mediator; }
public Mediator createSpecificMediator(OMElement elem, Properties properties) { IterateMediator mediator = new IterateMediator(); processAuditStatus(mediator, elem); OMAttribute continueParent = elem.getAttribute(ATT_CONTPAR); if (continueParent != null) { mediator.setContinueParent( Boolean.valueOf(continueParent.getAttributeValue())); } OMAttribute preservePayload = elem.getAttribute(ATT_PREPLD); if (preservePayload != null) { mediator.setPreservePayload( Boolean.valueOf(preservePayload.getAttributeValue())); } OMAttribute expression = elem.getAttribute(ATT_EXPRN); if (expression != null) { try { mediator.setExpression(SynapseXPathFactory.getSynapseXPath(elem, ATT_EXPRN)); } catch (JaxenException e) { handleException("Unable to build the IterateMediator. " + "Invalid XPATH " + expression.getAttributeValue(), e); } } else { handleException("XPATH expression is required " + "for an IterateMediator under the \"expression\" attribute"); } OMAttribute attachPath = elem.getAttribute(ATT_ATTACHPATH); String attachPathValue = "."; if (attachPath != null && !mediator.isPreservePayload()) { handleException("Wrong configuration for the iterate mediator :: if the iterator " + "should not preserve payload, then attachPath can not be present"); } else if (attachPath != null) { attachPathValue = attachPath.getAttributeValue(); } try { SynapseXPath xp = new SynapseXPath(attachPathValue); OMElementUtils.addNameSpaces(xp, elem, log); mediator.setAttachPath(xp); } catch (JaxenException e) { handleException("Unable to build the IterateMediator. Invalid XPATH " + attachPathValue, e); } boolean asynchronous = true; OMAttribute asynchronousAttr = elem.getAttribute(ATT_SEQUENCIAL); if (asynchronousAttr != null && asynchronousAttr.getAttributeValue().equals("true")) { asynchronous = false; } OMElement targetElement = elem.getFirstChildWithName(TARGET_Q); if (targetElement != null) { Target target = TargetFactory.createTarget(targetElement, properties); if (target != null) { target.setAsynchronous(asynchronous); mediator.setTarget(target); } } else { handleException("Target for an iterate mediator is required :: missing target"); } return mediator; }
diff --git a/src/org/omegat/filters3/xml/resx/ResXFilter.java b/src/org/omegat/filters3/xml/resx/ResXFilter.java index fe377adf..da4ef59b 100644 --- a/src/org/omegat/filters3/xml/resx/ResXFilter.java +++ b/src/org/omegat/filters3/xml/resx/ResXFilter.java @@ -1,127 +1,129 @@ /************************************************************************** OmegaT - Computer Assisted Translation (CAT) tool with fuzzy matching, translation memory, keyword search, glossaries, and translation leveraging into updated projects. Copyright (C) 2000-2006 Keith Godfrey and Maxym Mykhalchuk 2009 Didier Briel Home page: http://www.omegat.org/ Support center: http://groups.yahoo.com/group/OmegaT/ 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.omegat.filters3.xml.resx; import org.omegat.filters2.Instance; import org.omegat.filters3.xml.XMLFilter; import org.omegat.util.OStrings; import org.omegat.util.StringUtil; import org.xml.sax.Attributes; /** * Filter for ResX files. * * @author Didier Briel */ public class ResXFilter extends XMLFilter { private String id = ""; private String entryText; private String comment; private String text; /** * Creates a new instance of ResXFilter */ public ResXFilter() { super(new ResXDialect()); } /** * Human-readable name of the File Format this filter supports. * * @return File format name */ public String getFileFormatName() { return OStrings.getString("RESX_FILTER_NAME"); } /** * The default list of filter instances that this filter class has. One filter class may have different * filter instances, different by source file mask, encoding of the source file etc. * <p> * Note that the user may change the instances freely. * * @return Default filter instances */ public Instance[] getDefaultInstances() { return new Instance[] { new Instance("*.resx", null, null), }; } /** * Either the encoding can be read, or it is UTF-8. * * @return <code>false</code> */ public boolean isSourceEncodingVariable() { return false; } /** * Yes, ResX may be written out in a variety of encodings. * * @return <code>true</code> */ public boolean isTargetEncodingVariable() { return true; } @Override public void tagStart(String path, Attributes atts) { if ("/root/data".equals(path)) { id = StringUtil.nvl(atts.getValue("name"), ""); comment = null; } } @Override public void tagEnd(String path) { if ("/root/data/comment".equals(path)) { comment = text; } else if ("/root/data".equals(path)) { - entryParseCallback.addEntry(id, entryText, null, false, comment, null, this); + if (entryParseCallback != null) { + entryParseCallback.addEntry(id, entryText, null, false, comment, null, this); + } id = null; entryText = null; comment = null; } } @Override public void text(String text) { this.text = text; } @Override public String translate(String entry) { if (entryParseCallback != null) { entryText = entry; return entry; } else { String trans = entryTranslateCallback.getTranslation(id, entry, null); return trans != null ? trans : entry; } } }
true
true
public void tagEnd(String path) { if ("/root/data/comment".equals(path)) { comment = text; } else if ("/root/data".equals(path)) { entryParseCallback.addEntry(id, entryText, null, false, comment, null, this); id = null; entryText = null; comment = null; } }
public void tagEnd(String path) { if ("/root/data/comment".equals(path)) { comment = text; } else if ("/root/data".equals(path)) { if (entryParseCallback != null) { entryParseCallback.addEntry(id, entryText, null, false, comment, null, this); } id = null; entryText = null; comment = null; } }
diff --git a/src/robot/PathPlanner.java b/src/robot/PathPlanner.java index 5eb2094..10c8775 100644 --- a/src/robot/PathPlanner.java +++ b/src/robot/PathPlanner.java @@ -1,85 +1,86 @@ package robot; import java.util.ArrayList; import java.util.LinkedList; import java.util.PriorityQueue; public class PathPlanner { public LinkedList<Point> dijkstra(Map map) { LinkedList<Point> path = new LinkedList<Point>(); ArrayList<Point> points = map.map; map.start.dist = 0.0; path.add(map.start); PriorityQueue<Point> pq = new PriorityQueue<Point>(points.size()); for(int i = 0; i < points.size(); i++) { pq.add(points.get(i)); } Point current; while((current = pq.poll()) != null) { ArrayList<Point> next = possibleNextPoints(current, map); Point adj = null; for(int i = 0; i < next.size(); i++) { adj = next.get(i); if(!adj.known) { //wrong - if(current.dist + map.adjacencyMatrix[i][i] < adj.dist) + int j = points.getIndex(current); + if(current.dist + map.adjacencyMatrix[j][i] < adj.dist) { //wrong - adj.dist = current.dist + map.adjacencyMatrix[i][i]; + adj.dist = current.dist + map.adjacencyMatrix[j][i]; adj.path = current; } pq.add(adj); } } } Point end = map.goal; double pathLength = end.dist; while(end.path != null) { path.add(end); end = end.path; } path.add(map.start); return path; } private ArrayList<Point> possibleNextPoints(Point current, Map map) { //to be implemented return new ArrayList<Point>(); } public static void main(String [] args) { // fast test Polygon pp = new Polygon(4); pp.add(new Point(-1,-1)); pp.add(new Point(-1,1)); pp.add(new Point(1,1)); pp.add(new Point(1,-1)); pp = pp.grow(1.0); System.out.println(pp); // open the map // Map map = new Map(args[0]); // grow obstacles // for(Polygon p : map.polygons) { // ? = p.grow(); // } // create visibility graph // use dijkstra's to get shortest path } }
false
true
public LinkedList<Point> dijkstra(Map map) { LinkedList<Point> path = new LinkedList<Point>(); ArrayList<Point> points = map.map; map.start.dist = 0.0; path.add(map.start); PriorityQueue<Point> pq = new PriorityQueue<Point>(points.size()); for(int i = 0; i < points.size(); i++) { pq.add(points.get(i)); } Point current; while((current = pq.poll()) != null) { ArrayList<Point> next = possibleNextPoints(current, map); Point adj = null; for(int i = 0; i < next.size(); i++) { adj = next.get(i); if(!adj.known) { //wrong if(current.dist + map.adjacencyMatrix[i][i] < adj.dist) { //wrong adj.dist = current.dist + map.adjacencyMatrix[i][i]; adj.path = current; } pq.add(adj); } } } Point end = map.goal; double pathLength = end.dist; while(end.path != null) { path.add(end); end = end.path; } path.add(map.start); return path; }
public LinkedList<Point> dijkstra(Map map) { LinkedList<Point> path = new LinkedList<Point>(); ArrayList<Point> points = map.map; map.start.dist = 0.0; path.add(map.start); PriorityQueue<Point> pq = new PriorityQueue<Point>(points.size()); for(int i = 0; i < points.size(); i++) { pq.add(points.get(i)); } Point current; while((current = pq.poll()) != null) { ArrayList<Point> next = possibleNextPoints(current, map); Point adj = null; for(int i = 0; i < next.size(); i++) { adj = next.get(i); if(!adj.known) { //wrong int j = points.getIndex(current); if(current.dist + map.adjacencyMatrix[j][i] < adj.dist) { //wrong adj.dist = current.dist + map.adjacencyMatrix[j][i]; adj.path = current; } pq.add(adj); } } } Point end = map.goal; double pathLength = end.dist; while(end.path != null) { path.add(end); end = end.path; } path.add(map.start); return path; }
diff --git a/src/main/java/com/developpez/skillbrowser/service/impl/UserServiceImpl.java b/src/main/java/com/developpez/skillbrowser/service/impl/UserServiceImpl.java index dd46bae..d57d680 100644 --- a/src/main/java/com/developpez/skillbrowser/service/impl/UserServiceImpl.java +++ b/src/main/java/com/developpez/skillbrowser/service/impl/UserServiceImpl.java @@ -1,123 +1,123 @@ package com.developpez.skillbrowser.service.impl; import com.developpez.skillbrowser.model.Comment; import com.developpez.skillbrowser.model.Message; import com.developpez.skillbrowser.model.Skill; import com.developpez.skillbrowser.model.User; import com.developpez.skillbrowser.repository.CommentRepo; import com.developpez.skillbrowser.repository.MessageRepo; import com.developpez.skillbrowser.repository.SkillRepository; import com.developpez.skillbrowser.repository.UserRepository; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Service implementation for the User entity. Use the UserRepository to give standard service about the Skill entity. <br/> * "@Service" trigger the Spring bean nature.<br/> * "@Transactionnal" trigger the transactionnal nature of all bean methods.<br/> * Implements not only the application's UserService but also:<br/> * UserDetailsService: to use the service as Spring Security authentication provider.<br/> * InitializingBean: to have a callback after Spring loading in order to insert the first user in db if there is none. * * @see org.springframework.security.core.userdetails.UserDetailsService * @see org.springframework.beans.factory.InitializingBean */ @Service // @Transactional public class UserServiceImpl implements UserDetailsService, InitializingBean { /** * Autowiring the repository implementation needed to do the job */ @Autowired private UserRepository userRepository; @Autowired private SkillRepository skillRepository; @Autowired private MessageRepo messageRepo; @Autowired private CommentRepo commentRepo; /** * This is the main (and only) method to implement to be a Spring Security authentication provider. It needs only to return the user corresponding * to the login in parameter or launch an exception if not exist. The password checking is fully managed by handling the UserDetails returned.<br/> * As the password checking is not our work, the password encoding can be configured in Spring Security. It's not done yet but it can be an * evolution of this tutorial. */ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByLogin(username); if (user == null) { throw new UsernameNotFoundException(username + " n'existe pas"); } else { return user; } } public User save(User user) { try { return userRepository.save(user); } catch(Exception e) { return new User(); } } public User getUser(String login) { return userRepository.findByLogin(login); } /** * By implementing InitializingBean in a Spring bean, this method will be launch after Spring wirings are finished.<br/> * It's used here to perform a check at the loading of the application on the content of the user table a adding the first user if it's empty. This * way, there is no need of SQL initialization script which is so boring to handle (and even more on CloudFoundry) */ public void afterPropertiesSet() throws Exception { System.out.println("kikoo"); if (skillRepository.count() == 0 && userRepository.count() == 0) { Skill skill1 = new Skill(); skill1.setName("toto 1"); skillRepository.save(skill1); Skill skill2 = new Skill(); skill2.setName("toto 2"); skillRepository.save(skill2); Skill skill3 = new Skill(); skill3.setName("toto 3"); skillRepository.save(skill3); Set<Skill> skills = new HashSet<Skill>(Arrays.asList(new Skill[]{skill1, skill2, skill3})); User user = new User(); user.setFullname("admin"); user.setLogin("admin"); user.setPassword("admin"); user.setSkills(skills); userRepository.save(user); for (int i = 0; i < 26; i++) { user = new User(); - user.setFullname("full name " + i); - user.setLogin("login " + i); - user.setPassword("password" + i); + user.setFullname("full name " + (30 - i)); + user.setLogin("login " + (30 - i)); + user.setPassword("password" + (30 - i)); user.setSkills(skills); Message m = new Message(); m.setUser(user); Comment c = new Comment(); c.setMessage(m); c.setUser(user); userRepository.save(user); messageRepo.save(m); commentRepo.save(c); } } } }
true
true
public void afterPropertiesSet() throws Exception { System.out.println("kikoo"); if (skillRepository.count() == 0 && userRepository.count() == 0) { Skill skill1 = new Skill(); skill1.setName("toto 1"); skillRepository.save(skill1); Skill skill2 = new Skill(); skill2.setName("toto 2"); skillRepository.save(skill2); Skill skill3 = new Skill(); skill3.setName("toto 3"); skillRepository.save(skill3); Set<Skill> skills = new HashSet<Skill>(Arrays.asList(new Skill[]{skill1, skill2, skill3})); User user = new User(); user.setFullname("admin"); user.setLogin("admin"); user.setPassword("admin"); user.setSkills(skills); userRepository.save(user); for (int i = 0; i < 26; i++) { user = new User(); user.setFullname("full name " + i); user.setLogin("login " + i); user.setPassword("password" + i); user.setSkills(skills); Message m = new Message(); m.setUser(user); Comment c = new Comment(); c.setMessage(m); c.setUser(user); userRepository.save(user); messageRepo.save(m); commentRepo.save(c); } } }
public void afterPropertiesSet() throws Exception { System.out.println("kikoo"); if (skillRepository.count() == 0 && userRepository.count() == 0) { Skill skill1 = new Skill(); skill1.setName("toto 1"); skillRepository.save(skill1); Skill skill2 = new Skill(); skill2.setName("toto 2"); skillRepository.save(skill2); Skill skill3 = new Skill(); skill3.setName("toto 3"); skillRepository.save(skill3); Set<Skill> skills = new HashSet<Skill>(Arrays.asList(new Skill[]{skill1, skill2, skill3})); User user = new User(); user.setFullname("admin"); user.setLogin("admin"); user.setPassword("admin"); user.setSkills(skills); userRepository.save(user); for (int i = 0; i < 26; i++) { user = new User(); user.setFullname("full name " + (30 - i)); user.setLogin("login " + (30 - i)); user.setPassword("password" + (30 - i)); user.setSkills(skills); Message m = new Message(); m.setUser(user); Comment c = new Comment(); c.setMessage(m); c.setUser(user); userRepository.save(user); messageRepo.save(m); commentRepo.save(c); } } }
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/DownloadJob.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/DownloadJob.java index 7b05b1f68..0001a2804 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/DownloadJob.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/DownloadJob.java @@ -1,72 +1,78 @@ /******************************************************************************* * Copyright (c) 2008 Genuitec, LLC 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: Genuitec, LLC - initial API and implementation * IBM Corporation - ongoing maintenance ******************************************************************************/ package org.eclipse.equinox.internal.p2.artifact.repository.simple; import java.util.LinkedList; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.equinox.internal.p2.artifact.repository.ArtifactRequest; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRequest; public class DownloadJob extends Job { static final Object FAMILY = new Object(); private LinkedList requestsPending; private SimpleArtifactRepository repository; private IProgressMonitor masterMonitor; private MultiStatus overallStatus; DownloadJob(String name) { super(name); setSystem(true); } void initialize(SimpleArtifactRepository repository, LinkedList requestsPending, IProgressMonitor masterMonitor, MultiStatus overallStatus) { this.repository = repository; this.requestsPending = requestsPending; this.masterMonitor = masterMonitor; this.overallStatus = overallStatus; } /* (non-Javadoc) * @see org.eclipse.core.runtime.jobs.Job#belongsTo(java.lang.Object) */ public boolean belongsTo(Object family) { return family == FAMILY; } /* (non-Javadoc) * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) */ protected IStatus run(IProgressMonitor jobMonitor) { jobMonitor.beginTask("Downloading software", IProgressMonitor.UNKNOWN); do { // get the request we are going to process IArtifactRequest request; synchronized (requestsPending) { if (requestsPending.isEmpty()) break; request = (IArtifactRequest) requestsPending.removeFirst(); } if (masterMonitor.isCanceled()) return Status.CANCEL_STATUS; // process the actual request - IStatus status = repository.getArtifact((ArtifactRequest) request, new SubProgressMonitor(masterMonitor, 1)); - if (!status.isOK()) { - synchronized (overallStatus) { - overallStatus.add(status); + SubProgressMonitor subMonitor = new SubProgressMonitor(masterMonitor, 1); + subMonitor.beginTask("", 1); //$NON-NLS-1$ + try { + IStatus status = repository.getArtifact((ArtifactRequest) request, subMonitor); + if (!status.isOK()) { + synchronized (overallStatus) { + overallStatus.add(status); + } } + } finally { + subMonitor.done(); } } while (true); jobMonitor.done(); return Status.OK_STATUS; } }
false
true
protected IStatus run(IProgressMonitor jobMonitor) { jobMonitor.beginTask("Downloading software", IProgressMonitor.UNKNOWN); do { // get the request we are going to process IArtifactRequest request; synchronized (requestsPending) { if (requestsPending.isEmpty()) break; request = (IArtifactRequest) requestsPending.removeFirst(); } if (masterMonitor.isCanceled()) return Status.CANCEL_STATUS; // process the actual request IStatus status = repository.getArtifact((ArtifactRequest) request, new SubProgressMonitor(masterMonitor, 1)); if (!status.isOK()) { synchronized (overallStatus) { overallStatus.add(status); } } } while (true); jobMonitor.done(); return Status.OK_STATUS; }
protected IStatus run(IProgressMonitor jobMonitor) { jobMonitor.beginTask("Downloading software", IProgressMonitor.UNKNOWN); do { // get the request we are going to process IArtifactRequest request; synchronized (requestsPending) { if (requestsPending.isEmpty()) break; request = (IArtifactRequest) requestsPending.removeFirst(); } if (masterMonitor.isCanceled()) return Status.CANCEL_STATUS; // process the actual request SubProgressMonitor subMonitor = new SubProgressMonitor(masterMonitor, 1); subMonitor.beginTask("", 1); //$NON-NLS-1$ try { IStatus status = repository.getArtifact((ArtifactRequest) request, subMonitor); if (!status.isOK()) { synchronized (overallStatus) { overallStatus.add(status); } } } finally { subMonitor.done(); } } while (true); jobMonitor.done(); return Status.OK_STATUS; }
diff --git a/src/org/ruhlendavis/mc/communitybridge/WebApplication.java b/src/org/ruhlendavis/mc/communitybridge/WebApplication.java index ee89e37..4e078ad 100644 --- a/src/org/ruhlendavis/mc/communitybridge/WebApplication.java +++ b/src/org/ruhlendavis/mc/communitybridge/WebApplication.java @@ -1,746 +1,750 @@ package org.ruhlendavis.mc.communitybridge; import java.io.File; import java.net.MalformedURLException; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import net.netmanagers.api.SQL; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.ruhlendavis.mc.utility.Log; import org.ruhlendavis.utility.StringUtilities; /** * Class representing the interface to the web application. * * @author Feaelin (Iain E. Davis) <[email protected]> */ public class WebApplication { private CommunityBridge plugin; private Configuration config; private Log log; private SQL sql; private int maxPlayers; private Map<String, String> playerUserIDs = new HashMap(); public WebApplication(CommunityBridge plugin, Configuration config, Log log, SQL sql) { this.config = config; this.plugin = plugin; this.log = log; setSQL(sql); this.maxPlayers = Bukkit.getMaxPlayers(); } /** * Returns a given player's web application user ID. * * @param String containing the player's name. * @return String containing the player's web application user ID. */ public String getUserID(String playerName) { if (playerUserIDs.containsKey(playerName)) {} else { loadUserIDfromDatabase(playerName); } return playerUserIDs.get(playerName); } /** * Returns true if the user's avatar column contains data. * * @param String The player's name. * @return boolean True if the user has an avatar. */ public boolean playerHasAvatar(String playerName) { final String errorBase = "Error during WebApplication.playerHasAvatar(): "; String query; query = "SELECT `" + config.requireAvatarTableName + "`.`" + config.requireAvatarAvatarColumn + "` " + "FROM `" + config.requireAvatarTableName + "` " + "WHERE `" + config.requireAvatarUserIDColumn + "` = '" + getUserID(playerName) + "'"; log.finest(query); try { String avatar = null; ResultSet result = sql.sqlQuery(query); if (result.next()) { avatar = result.getString(config.requireAvatarAvatarColumn); } if (avatar == null || avatar.isEmpty()) { return false; } else { return true; } } catch (SQLException error) { log.severe(errorBase + error.getMessage()); return false; } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); return false; } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); return false; } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); return false; } } /** * Fetches the user's post count from the web application. * * @param String The player's name. * @return int Number of posts. */ public int getUserPostCount(String playerName) { final String errorBase = "Error during WebApplication.playerHasAvatar(): "; String query; query = "SELECT `" + config.requirePostsTableName + "`.`" + config.requirePostsPostCountColumn + "` " + "FROM `" + config.requirePostsTableName + "` " + "WHERE `" + config.requirePostsUserIDColumn + "` = '" + getUserID(playerName) + "'"; log.finest(query); try { ResultSet result = sql.sqlQuery(query); if (result.next()) { return result.getInt(config.requirePostsPostCountColumn); } else { return 0; } } catch (SQLException error) { log.severe(errorBase + error.getMessage()); return 0; } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); return 0; } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); return 0; } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); return 0; } } /** * Returns a given player's web application user ID. * * @param String containing the player's name. * @return String containing the player's web application user ID. */ public int getUserIDint(String playerName) { if (playerUserIDs.get(playerName) == null) { return 0; } return Integer.parseInt(playerUserIDs.get(playerName)); } /** * Returns true if the player is registered on the web application. * @param String The name of the player. * @return boolean True if the player is registered. */ public boolean isPlayerRegistered(String playerName) { return !(getUserID(playerName) == null || getUserID(playerName).isEmpty()); } /** * Retrieves user IDs for all connected players, required after a cache * cleanup and after cb reload. */ public synchronized void loadOnlineUserIDsFromDatabase() { Player [] players = Bukkit.getOnlinePlayers(); for (Player player : players) { loadUserIDfromDatabase(player.getName()); } } /** * Performs the database query that should be done when a player connects. * * @param String containing the player's name. */ public synchronized void loadUserIDfromDatabase(String playerName) { if (playerUserIDs.size() >= (maxPlayers * 4)) { playerUserIDs.clear(); loadOnlineUserIDsFromDatabase(); } final String errorBase = "Error during WebApplication.onPreLogin(): "; String query = "SELECT `" + config.linkingTableName + "`.`" + config.linkingUserIDColumn + "` " + "FROM `" + config.linkingTableName + "`"; if (config.linkingUsesKey) { query = query + "WHERE `" + config.linkingKeyColumn + "` = '" + config.linkingKeyName + "' " + "AND `" + config.linkingValueColumn + "` = '" + playerName + "' "; } else { query = query + "WHERE LOWER(`" + config.linkingPlayerNameColumn + "`) = LOWER('" + playerName + "') "; } query = query + "ORDER BY `" + config.linkingUserIDColumn + "` DESC"; log.finest(query); try { String userID = null; ResultSet result = sql.sqlQuery(query); if (result.next()) { userID = result.getString(config.linkingUserIDColumn); } if (userID == null) { log.finest("User ID for " + playerName + " not found."); } else { log.finest("User ID '" + userID + "' associated with " + playerName + "."); playerUserIDs.put(playerName, userID); } } catch (SQLException error) { log.severe(errorBase + error.getMessage()); } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); } } // loadUserIDfromDatabase() /** * Performs operations when a player joins * * @param String The player who joined. */ public void onJoin(final Player player) { if (config.webappPrimaryGroupEnabled || config.webappSecondaryGroupEnabled) { runGroupSynchronizationTask(player); } runUpdateStatisticsTask(player, true); } /** * Performs operations when a player quits. * * @param String containing the player's name. */ public void onQuit(Player player) { runUpdateStatisticsTask(player, false); } /** * If statistics is enabled, this method sets up an update statistics task * for the given player. * * @param String The player's name. */ private void runGroupSynchronizationTask(final Player player) { Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { synchronizeGroups(player); } }); } /** * If statistics is enabled, this method sets up an update statistics task * for the given player. * * @param String The player's name. */ private void runUpdateStatisticsTask(final Player player, final boolean online) { if (config.statisticsEnabled) { Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { updateStatistics(player, online); } }); } } /** * Sets the SQL object. Typically used during a reload. * * @param SQL SQL object to set. */ public final void setSQL(SQL sql) { this.sql = sql; } private void synchronizeGroups(Player player) { File playerFolder = new File(plugin.getDataFolder(), "Players"); // 1. Retrieve previous group state for forum groups and permissions groups. PlayerGroupState previousState = new PlayerGroupState(player.getName(), playerFolder); previousState.load(); // 2. Capture current group state PlayerGroupState currentState = new PlayerGroupState(player.getName(), playerFolder); currentState.generate(); // 3. Compare current group state to previous, noting any additions or deletions. List additions = previousState.identifyAdditions(currentState); List removals = previousState.identifyRemovals(currentState); // 4. Process additions // 5. Process deletions // 6. Store current group state } /** * Update the player's statistical information on the forum. * * @param String Name of player to update * @param boolean Set to true if the player is currently online */ private void updateStatistics(Player player, boolean online) { String query; ResultSet result; String playerName = player.getName(); String userID = getUserID(playerName); int previousLastOnline = 0; int previousGameTime = 0; // If gametime is enabled, it depends on lastonline. Also, we need to // retrieve previously recorded lastonline time and the previously // recorded gametime to compute the new gametime. if (config.gametimeEnabled) { if (config.statisticsUsesKey) { query = "SELECT `" + config.statisticsKeyColumn + "`, `" + config.statisticsValueColumn + " FROM `" + config.statisticsTableName + "`" + " WHERE `" + config.statisticsUserIDColumn + "` = '" + userID + "'"; try { result = sql.sqlQuery(query); while (result.next()) { String key = result.getString(config.statisticsKeyColumn); if (key.equalsIgnoreCase(config.lastonlineColumnOrKey)) { previousLastOnline = result.getInt(config.statisticsValueColumn); } else if (key.equalsIgnoreCase(config.gametimeColumnOrKey)) { previousGameTime = result.getInt(config.statisticsValueColumn); } } } catch (SQLException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (MalformedURLException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (InstantiationException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (IllegalAccessException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } } else { query = "SELECT `" + config.lastonlineColumnOrKey + "`, `" + config.gametimeColumnOrKey + "`" + " FROM `" + config.statisticsTableName + "`" + " WHERE `" + config.statisticsUserIDColumn + "` = '" + userID + "'"; try { result = sql.sqlQuery(query); if (result.next()) { previousLastOnline = result.getInt(config.lastonlineColumnOrKey); previousGameTime = result.getInt(config.gametimeColumnOrKey); } } catch (SQLException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (MalformedURLException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (InstantiationException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (IllegalAccessException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } } } SimpleDateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss a"); String onlineStatus; if (online) { onlineStatus = config.onlineStatusValueOnline; } else { onlineStatus = config.onlineStatusValueOffline; } // last online int lastonlineTime = (int) (System.currentTimeMillis() / 1000L); String lastonlineTimeFormatted = dateFormat.format(new Date()); // game time (time played) int gametime = 0; if (previousLastOnline > 0) { gametime = previousGameTime + (lastonlineTime - previousLastOnline); } String gametimeFormatted = StringUtilities.timeElapsedtoString (gametime); int level = player.getLevel(); int totalxp = player.getTotalExperience(); float currentxp = player.getExp(); String currentxpFormatted = ((int)(currentxp * 100)) + "%"; int health = player.getHealth(); int lifeticks = player.getTicksLived(); String lifeticksFormatted = StringUtilities.timeElapsedtoString((int)(lifeticks / 20)); - double wallet = CommunityBridge.economy.getBalance(playerName); + double wallet = 0.0; + if (config.walletEnabled) + { + wallet = CommunityBridge.economy.getBalance(playerName); + } if (config.statisticsUsesKey) { updateStatisticsKeyStyle(userID, onlineStatus, lastonlineTime, lastonlineTimeFormatted, gametime, gametimeFormatted, level, totalxp, currentxp, currentxpFormatted, health, lifeticks, lifeticksFormatted, wallet); } else { updateStatisticsKeylessStyle(userID, onlineStatus, lastonlineTime, lastonlineTimeFormatted, gametime, gametimeFormatted, level, totalxp, currentxp, currentxpFormatted, health, lifeticks, lifeticksFormatted, wallet); } } /** * Called by updateStatistics() to update a statistics table that uses Key-Value Pairs. * * @param String Player's forum user ID. * @param String Set to the appropriate value representing player's online status. * @param int systime value for the last time the player was last online * @param String A formatted version of the systime value of when the player was last online. * @param int Amount of time the player has played in seconds. * @param String Amount of time the player has played formatted nicely. * @param int Level of the player * @param int Total amount of XP the player currently has. * @param float Amount of progress the player has towards the next level as a percentage. * @param String Readable version of the percentage the player has towards the next level. * @param int Player's current health level. * @param int Amount of time played since last death, in ticks. * @param String Formatted amount of time played since last death. * @param double Current balance of the player. */ private void updateStatisticsKeyStyle(String userID, String onlineStatus, int lastonlineTime, String lastonlineFormattedTime, int gameTime, String gameTimeFormatted, int level, int totalxp, float currentxp, String currentxpFormatted, int health, int lifeticks, String lifeticksFormatted, double wallet) { List<String> fields = new ArrayList(); String query = "UPDATE `" + config.statisticsTableName + "` " + "SET "; /* To collapse multiple MySQL queries into one query, we're using the * MySQL CASE operator. Recommended reading: * http://www.karlrixon.co.uk/writing/update-multiple-rows-with-different-values-and-a-single-sql-query/ * Prototype: * UPDATE tablename * SET valueColumn = CASE keycolumn * WHEN keyname THEN keyvalue * WHEN keyname THEN keyvalue * END * WHERE useridcolumn = userid; */ query = query + "`" + config.statisticsValueColumn + "` = CASE " + "`" + config.statisticsKeyColumn + "` "; if (config.onlineStatusEnabled) { fields.add("WHEN '" + config.onlineStatusColumnOrKey + "' THEN '" + onlineStatus + "' "); } if (config.lastonlineEnabled) { fields.add("WHEN '" + config.lastonlineColumnOrKey + "' THEN '" + lastonlineTime + "' "); if (config.lastonlineFormattedColumnOrKey.isEmpty()) {} else { fields.add("WHEN '" + config.lastonlineFormattedColumnOrKey + "' THEN '" + lastonlineFormattedTime + "' "); } } // Gametime actually relies on the prior lastonlineTime... if (config.gametimeEnabled && config.lastonlineEnabled) { fields.add("WHEN '" + config.gametimeColumnOrKey + "' THEN '" + gameTime + "' "); if (config.gametimeFormattedColumnOrKey.isEmpty()) {} else { fields.add("WHEN '" + config.gametimeFormattedColumnOrKey + "' THEN '" + gameTimeFormatted + "' "); } } if (config.levelEnabled) { fields.add("WHEN '" + config.levelColumnOrKey + "' THEN '" + level + "' "); } if (config.totalxpEnabled) { fields.add("WHEN '" + config.levelColumnOrKey + "' THEN '" + totalxp + "' "); } if (config.currentxpEnabled) { fields.add("WHEN '" + config.levelColumnOrKey + "' THEN '" + currentxp + "' "); if (config.currentxpFormattedColumnOrKey.isEmpty()) {} else { fields.add("WHEN '" + config.currentxpFormattedColumnOrKey + "' THEN '" + currentxpFormatted + "' "); } } if (config.healthEnabled) { fields.add("WHEN '" + config.healthColumnOrKey + "' THEN '" + health + "' "); } if (config.lifeticksEnabled) { fields.add("WHEN '" + config.lifeticksColumnOrKey + "' THEN '" + lifeticks + "' "); if (config.lifeticksFormattedColumnOrKey.isEmpty()) {} else { fields.add("WHEN '" + config.lifeticksFormattedColumnOrKey + "' THEN '" + lifeticksFormatted + "' "); } } if (config.walletEnabled) { fields.add("WHEN '" + config.walletColumnOrKey + "' THEN '" + wallet + "' "); } query = query + StringUtilities.joinStrings(fields, " "); query = query + "END"; query = query + " WHERE `" + config.statisticsUserIDColumn + "` = '" + userID + "'"; String errorBase = "Error during updateStatisticsKeyStyle(): "; log.finest(query); try { sql.updateQuery(query); } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); } } /** * Called by updateStatistics when updating a table that columns (instead of keyvalue pairs). * * @param String Player's forum user ID. * @param String Set to the appropriate value representing player's online status. * @param int systime value for the last time the player was last online * @param String A formatted version of the systime value of when the player was last online. * @param int Amount of time the player has played in seconds. * @param String Amount of time the player has played formatted nicely. * @param int Level of the player * @param int Total amount of XP the player currently has. * @param float Amount of progress the player has towards the next level as a percentage. * @param String Readable version of the percentage the player has towards the next level. * @param int Player's current health level. * @param int Amount of time played since last death, in ticks. * @param String Formatted amount of time played since last death. * @param double Current balance of the player. */ private void updateStatisticsKeylessStyle(String userID, String onlineStatus, int lastonlineTime, String lastonlineTimeFormatted, int gametime, String gametimeFormatted, int level, int totalxp, float currentxp, String currentxpFormatted, int health, int lifeticks, String lifeticksFormatted, double wallet) { String query; List<String> fields = new ArrayList(); query = "UPDATE `" + config.statisticsTableName + "` " + "SET "; if (config.onlineStatusEnabled) { fields.add("`" + config.onlineStatusColumnOrKey + "` = '" + onlineStatus + "'"); } if (config.lastonlineEnabled) { fields.add("`" + config.lastonlineColumnOrKey + "` = '" + lastonlineTime + "'"); if (config.lastonlineFormattedColumnOrKey.isEmpty()) {} else { fields.add("`" + config.lastonlineFormattedColumnOrKey + "` = '" + lastonlineTimeFormatted + "'"); } } if (config.gametimeEnabled) { fields.add("`" + config.gametimeColumnOrKey + "` = '" + gametime + "'"); if (config.gametimeFormattedColumnOrKey.isEmpty()) {} else { fields.add("`" + config.gametimeFormattedColumnOrKey + "` = '" + gametimeFormatted + "'"); } } if (config.levelEnabled) { fields.add("`" + config.levelColumnOrKey + "` = '" + level + "'"); } if (config.totalxpEnabled) { fields.add("`" + config.totalxpColumnOrKey + "` = '" + totalxp + "'"); } if (config.currentxpEnabled) { fields.add("`" + config.currentxpColumnOrKey + "` = '" + currentxp + "'"); if (config.currentxpFormattedColumnOrKey.isEmpty()) {} else { fields.add("`" + config.currentxpFormattedColumnOrKey + "` = '" + currentxpFormatted + "'"); } } if (config.healthEnabled) { fields.add("`" + config.healthColumnOrKey + "` = '" + health + "'"); } if (config.lifeticksEnabled) { fields.add("`" + config.lifeticksColumnOrKey + "` = '" + lifeticks + "'"); if (config.lifeticksFormattedColumnOrKey.isEmpty()) {} else { fields.add("`" + config.lifeticksFormattedColumnOrKey + "` = '" + lifeticksFormatted + "'"); } } if (config.walletEnabled) { fields.add("`" + config.walletColumnOrKey + "` = '" + wallet + "'"); } query = query + StringUtilities.joinStrings(fields, ", ") + " WHERE `" + config.statisticsUserIDColumn + "` = '" + userID + "'"; String errorBase = "Error during updateStatisticsKeylessStyle(): "; log.finest(query); try { sql.updateQuery(query); } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); } } } // WebApplication class
true
true
private void updateStatistics(Player player, boolean online) { String query; ResultSet result; String playerName = player.getName(); String userID = getUserID(playerName); int previousLastOnline = 0; int previousGameTime = 0; // If gametime is enabled, it depends on lastonline. Also, we need to // retrieve previously recorded lastonline time and the previously // recorded gametime to compute the new gametime. if (config.gametimeEnabled) { if (config.statisticsUsesKey) { query = "SELECT `" + config.statisticsKeyColumn + "`, `" + config.statisticsValueColumn + " FROM `" + config.statisticsTableName + "`" + " WHERE `" + config.statisticsUserIDColumn + "` = '" + userID + "'"; try { result = sql.sqlQuery(query); while (result.next()) { String key = result.getString(config.statisticsKeyColumn); if (key.equalsIgnoreCase(config.lastonlineColumnOrKey)) { previousLastOnline = result.getInt(config.statisticsValueColumn); } else if (key.equalsIgnoreCase(config.gametimeColumnOrKey)) { previousGameTime = result.getInt(config.statisticsValueColumn); } } } catch (SQLException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (MalformedURLException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (InstantiationException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (IllegalAccessException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } } else { query = "SELECT `" + config.lastonlineColumnOrKey + "`, `" + config.gametimeColumnOrKey + "`" + " FROM `" + config.statisticsTableName + "`" + " WHERE `" + config.statisticsUserIDColumn + "` = '" + userID + "'"; try { result = sql.sqlQuery(query); if (result.next()) { previousLastOnline = result.getInt(config.lastonlineColumnOrKey); previousGameTime = result.getInt(config.gametimeColumnOrKey); } } catch (SQLException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (MalformedURLException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (InstantiationException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (IllegalAccessException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } } } SimpleDateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss a"); String onlineStatus; if (online) { onlineStatus = config.onlineStatusValueOnline; } else { onlineStatus = config.onlineStatusValueOffline; } // last online int lastonlineTime = (int) (System.currentTimeMillis() / 1000L); String lastonlineTimeFormatted = dateFormat.format(new Date()); // game time (time played) int gametime = 0; if (previousLastOnline > 0) { gametime = previousGameTime + (lastonlineTime - previousLastOnline); } String gametimeFormatted = StringUtilities.timeElapsedtoString (gametime); int level = player.getLevel(); int totalxp = player.getTotalExperience(); float currentxp = player.getExp(); String currentxpFormatted = ((int)(currentxp * 100)) + "%"; int health = player.getHealth(); int lifeticks = player.getTicksLived(); String lifeticksFormatted = StringUtilities.timeElapsedtoString((int)(lifeticks / 20)); double wallet = CommunityBridge.economy.getBalance(playerName); if (config.statisticsUsesKey) { updateStatisticsKeyStyle(userID, onlineStatus, lastonlineTime, lastonlineTimeFormatted, gametime, gametimeFormatted, level, totalxp, currentxp, currentxpFormatted, health, lifeticks, lifeticksFormatted, wallet); } else { updateStatisticsKeylessStyle(userID, onlineStatus, lastonlineTime, lastonlineTimeFormatted, gametime, gametimeFormatted, level, totalxp, currentxp, currentxpFormatted, health, lifeticks, lifeticksFormatted, wallet); } }
private void updateStatistics(Player player, boolean online) { String query; ResultSet result; String playerName = player.getName(); String userID = getUserID(playerName); int previousLastOnline = 0; int previousGameTime = 0; // If gametime is enabled, it depends on lastonline. Also, we need to // retrieve previously recorded lastonline time and the previously // recorded gametime to compute the new gametime. if (config.gametimeEnabled) { if (config.statisticsUsesKey) { query = "SELECT `" + config.statisticsKeyColumn + "`, `" + config.statisticsValueColumn + " FROM `" + config.statisticsTableName + "`" + " WHERE `" + config.statisticsUserIDColumn + "` = '" + userID + "'"; try { result = sql.sqlQuery(query); while (result.next()) { String key = result.getString(config.statisticsKeyColumn); if (key.equalsIgnoreCase(config.lastonlineColumnOrKey)) { previousLastOnline = result.getInt(config.statisticsValueColumn); } else if (key.equalsIgnoreCase(config.gametimeColumnOrKey)) { previousGameTime = result.getInt(config.statisticsValueColumn); } } } catch (SQLException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (MalformedURLException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (InstantiationException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (IllegalAccessException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } } else { query = "SELECT `" + config.lastonlineColumnOrKey + "`, `" + config.gametimeColumnOrKey + "`" + " FROM `" + config.statisticsTableName + "`" + " WHERE `" + config.statisticsUserIDColumn + "` = '" + userID + "'"; try { result = sql.sqlQuery(query); if (result.next()) { previousLastOnline = result.getInt(config.lastonlineColumnOrKey); previousGameTime = result.getInt(config.gametimeColumnOrKey); } } catch (SQLException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (MalformedURLException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (InstantiationException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (IllegalAccessException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } } } SimpleDateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss a"); String onlineStatus; if (online) { onlineStatus = config.onlineStatusValueOnline; } else { onlineStatus = config.onlineStatusValueOffline; } // last online int lastonlineTime = (int) (System.currentTimeMillis() / 1000L); String lastonlineTimeFormatted = dateFormat.format(new Date()); // game time (time played) int gametime = 0; if (previousLastOnline > 0) { gametime = previousGameTime + (lastonlineTime - previousLastOnline); } String gametimeFormatted = StringUtilities.timeElapsedtoString (gametime); int level = player.getLevel(); int totalxp = player.getTotalExperience(); float currentxp = player.getExp(); String currentxpFormatted = ((int)(currentxp * 100)) + "%"; int health = player.getHealth(); int lifeticks = player.getTicksLived(); String lifeticksFormatted = StringUtilities.timeElapsedtoString((int)(lifeticks / 20)); double wallet = 0.0; if (config.walletEnabled) { wallet = CommunityBridge.economy.getBalance(playerName); } if (config.statisticsUsesKey) { updateStatisticsKeyStyle(userID, onlineStatus, lastonlineTime, lastonlineTimeFormatted, gametime, gametimeFormatted, level, totalxp, currentxp, currentxpFormatted, health, lifeticks, lifeticksFormatted, wallet); } else { updateStatisticsKeylessStyle(userID, onlineStatus, lastonlineTime, lastonlineTimeFormatted, gametime, gametimeFormatted, level, totalxp, currentxp, currentxpFormatted, health, lifeticks, lifeticksFormatted, wallet); } }
diff --git a/src/main/java/uk/ac/ebi/fgpt/sampletab/SampleTabcronBulk.java b/src/main/java/uk/ac/ebi/fgpt/sampletab/SampleTabcronBulk.java index 353cd7ef..6f978a22 100644 --- a/src/main/java/uk/ac/ebi/fgpt/sampletab/SampleTabcronBulk.java +++ b/src/main/java/uk/ac/ebi/fgpt/sampletab/SampleTabcronBulk.java @@ -1,270 +1,270 @@ package uk.ac.ebi.fgpt.sampletab; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.ebi.arrayexpress2.magetab.exception.ParseException; import uk.ac.ebi.fgpt.sampletab.utils.FileUtils; import uk.ac.ebi.fgpt.sampletab.utils.ProcessUtils; public class SampleTabcronBulk { @Option(name = "-h", aliases={"--help"}, usage = "display help") private boolean help; @Option(name = "-i", aliases={"--input"}, usage = "input directory or glob") private String inputFilename; @Option(name = "-s", aliases={"--scripts"}, usage = "script directory") private String scriptDirname; @Option(name = "--threaded", usage = "use multiple threads?") private boolean threaded = false; @Option(name = "-n", aliases={"--hostname"}, usage = "server hostname") private String hostname = "mysql-ae-autosubs-test.ebi.ac.uk"; @Option(name = "-t", aliases={"--port"}, usage = "server port") private int port = 4340; @Option(name = "-d", aliases={"--database"}, usage = "server database") private String database = "autosubs_test"; @Option(name = "-u", aliases={"--username"}, usage = "server username") private String username = "admin"; @Option(name = "-p", aliases={"--password"}, usage = "server password") private String password = "edsK6BV6"; private Logger log = LoggerFactory.getLogger(getClass()); public SampleTabcronBulk(){ } public SampleTabcronBulk(String hostname, int port, String database, String username, String password){ this.hostname = hostname; this.port = port; this.database = database; this.username = username; this.password = password; } public void process(File subdir, File scriptdir){ Runnable t = new DoProcessFile(subdir, scriptdir); t.run(); } private class DoProcessFile implements Runnable { private final File subdir; private final File scriptdir; private File sampletabpre; private File sampletab; private File sampletabtoload; private File agedir; private File agefile; public DoProcessFile(File subdir, File scriptdir){ this.subdir = subdir; this.scriptdir = scriptdir; sampletabpre = new File(subdir, "sampletab.pre.txt"); sampletab = new File(subdir, "sampletab.txt"); sampletabtoload = new File(subdir, "sampletab.toload.txt"); agedir = new File(subdir, "age"); agefile = new File(agedir, subdir.getName()+".age.txt"); } public void run() { File target; // accession sampletab.pre.txt to sampletab.txt target = sampletab; if (!target.exists() || sampletab.lastModified() < sampletabpre.lastModified()) { log.info("Processing " + target); try { SampleTabAccessioner c = new SampleTabAccessioner(hostname, port, database, username, password); c.convert(sampletabpre, sampletab); } catch (ClassNotFoundException e) { log.error("Problem processing "+sampletabpre); e.printStackTrace(); return; } catch (IOException e) { log.error("Problem processing "+sampletabpre); e.printStackTrace(); return; } catch (ParseException e) { log.error("Problem processing "+sampletabpre); e.printStackTrace(); return; } catch (SQLException e) { log.error("Problem processing "+sampletabpre); e.printStackTrace(); return; } catch (RuntimeException e){ log.error("Problem processing "+sampletabpre); e.printStackTrace(); return; } } // preprocess to load target = sampletabtoload; if (!target.exists() - || sampletabtoload.lastModified() < sampletabtoload.lastModified()) { + || sampletabtoload.lastModified() < sampletab.lastModified()) { log.info("Processing " + target); SampleTabToLoad c; try { c = new SampleTabToLoad(hostname, port, database, username, password); c.convert(sampletab, sampletabtoload); } catch (ClassNotFoundException e) { log.error("Problem processing "+sampletab); e.printStackTrace(); return; } catch (IOException e) { log.error("Problem processing "+sampletab); e.printStackTrace(); return; } catch (ParseException e) { log.error("Problem processing "+sampletab); e.printStackTrace(); return; } catch (RuntimeException e){ log.error("Problem processing "+sampletab); e.printStackTrace(); return; } catch (SQLException e) { log.error("Problem processing "+sampletab); e.printStackTrace(); return; } log.info("Finished " + target); } // convert to age target = agefile; if (!target.exists()) { //TODO check modification time log.info("Processing " + target); File script = new File(scriptdir, "SampleTab-to-AGETAB.sh"); if (!script.exists()) { log.error("Unable to find " + script); return; } String bashcom = script + " -o " + agedir + " " + sampletabtoload; SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyyMMdd_HHmmss"); File logfile = new File(subdir, "age_"+simpledateformat.format(new Date())+".log"); if (!ProcessUtils.doCommand(bashcom, logfile)) { log.error("Problem producing " + agedir); log.error("See logfile " + logfile); if (target.exists()){ for (File todel: target.listFiles()){ todel.delete(); } target.delete(); log.error("cleaning partly produced file"); } return; } log.info("Finished " + target); } //TODO load } } public void run(Collection<File> files, File scriptdir) { int nothreads = Runtime.getRuntime().availableProcessors(); ExecutorService pool = Executors.newFixedThreadPool(nothreads); for (File subdir : files) { if (!subdir.isDirectory()) { subdir = subdir.getParentFile(); } log.info("Processing "+subdir); Runnable t = new DoProcessFile(subdir, scriptdir); if (threaded) { pool.execute(t); } else { t.run(); } } // run the pool and then close it afterwards // must synchronize on the pool object synchronized (pool) { pool.shutdown(); try { // allow 24h to execute. Rather too much, but meh pool.awaitTermination(1, TimeUnit.DAYS); } catch (InterruptedException e) { log.error("Interuppted awaiting thread pool termination"); e.printStackTrace(); } } } public static void main(String[] args) { new SampleTabcronBulk().doMain(args); } public void doMain(String[] args) { CmdLineParser parser = new CmdLineParser(this); try { // parse the arguments. parser.parseArgument(args); // TODO check for extra arguments? } catch (CmdLineException e) { System.err.println(e.getMessage()); help = true; } if (help) { // print the list of available options parser.printUsage(System.err); System.err.println(); System.exit(1); return; } //TODO handle globs File scriptdir = new File(scriptDirname); if (!scriptdir.exists() && !scriptdir.isDirectory()) { log.error("Script directory missing or is not a directory"); System.exit(1); return; } Collection<File> files = FileUtils.getMatchesGlob(inputFilename); run(files, scriptdir); } }
true
true
public void run() { File target; // accession sampletab.pre.txt to sampletab.txt target = sampletab; if (!target.exists() || sampletab.lastModified() < sampletabpre.lastModified()) { log.info("Processing " + target); try { SampleTabAccessioner c = new SampleTabAccessioner(hostname, port, database, username, password); c.convert(sampletabpre, sampletab); } catch (ClassNotFoundException e) { log.error("Problem processing "+sampletabpre); e.printStackTrace(); return; } catch (IOException e) { log.error("Problem processing "+sampletabpre); e.printStackTrace(); return; } catch (ParseException e) { log.error("Problem processing "+sampletabpre); e.printStackTrace(); return; } catch (SQLException e) { log.error("Problem processing "+sampletabpre); e.printStackTrace(); return; } catch (RuntimeException e){ log.error("Problem processing "+sampletabpre); e.printStackTrace(); return; } } // preprocess to load target = sampletabtoload; if (!target.exists() || sampletabtoload.lastModified() < sampletabtoload.lastModified()) { log.info("Processing " + target); SampleTabToLoad c; try { c = new SampleTabToLoad(hostname, port, database, username, password); c.convert(sampletab, sampletabtoload); } catch (ClassNotFoundException e) { log.error("Problem processing "+sampletab); e.printStackTrace(); return; } catch (IOException e) { log.error("Problem processing "+sampletab); e.printStackTrace(); return; } catch (ParseException e) { log.error("Problem processing "+sampletab); e.printStackTrace(); return; } catch (RuntimeException e){ log.error("Problem processing "+sampletab); e.printStackTrace(); return; } catch (SQLException e) { log.error("Problem processing "+sampletab); e.printStackTrace(); return; } log.info("Finished " + target); } // convert to age target = agefile; if (!target.exists()) { //TODO check modification time log.info("Processing " + target); File script = new File(scriptdir, "SampleTab-to-AGETAB.sh"); if (!script.exists()) { log.error("Unable to find " + script); return; } String bashcom = script + " -o " + agedir + " " + sampletabtoload; SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyyMMdd_HHmmss"); File logfile = new File(subdir, "age_"+simpledateformat.format(new Date())+".log"); if (!ProcessUtils.doCommand(bashcom, logfile)) { log.error("Problem producing " + agedir); log.error("See logfile " + logfile); if (target.exists()){ for (File todel: target.listFiles()){ todel.delete(); } target.delete(); log.error("cleaning partly produced file"); } return; } log.info("Finished " + target); } //TODO load }
public void run() { File target; // accession sampletab.pre.txt to sampletab.txt target = sampletab; if (!target.exists() || sampletab.lastModified() < sampletabpre.lastModified()) { log.info("Processing " + target); try { SampleTabAccessioner c = new SampleTabAccessioner(hostname, port, database, username, password); c.convert(sampletabpre, sampletab); } catch (ClassNotFoundException e) { log.error("Problem processing "+sampletabpre); e.printStackTrace(); return; } catch (IOException e) { log.error("Problem processing "+sampletabpre); e.printStackTrace(); return; } catch (ParseException e) { log.error("Problem processing "+sampletabpre); e.printStackTrace(); return; } catch (SQLException e) { log.error("Problem processing "+sampletabpre); e.printStackTrace(); return; } catch (RuntimeException e){ log.error("Problem processing "+sampletabpre); e.printStackTrace(); return; } } // preprocess to load target = sampletabtoload; if (!target.exists() || sampletabtoload.lastModified() < sampletab.lastModified()) { log.info("Processing " + target); SampleTabToLoad c; try { c = new SampleTabToLoad(hostname, port, database, username, password); c.convert(sampletab, sampletabtoload); } catch (ClassNotFoundException e) { log.error("Problem processing "+sampletab); e.printStackTrace(); return; } catch (IOException e) { log.error("Problem processing "+sampletab); e.printStackTrace(); return; } catch (ParseException e) { log.error("Problem processing "+sampletab); e.printStackTrace(); return; } catch (RuntimeException e){ log.error("Problem processing "+sampletab); e.printStackTrace(); return; } catch (SQLException e) { log.error("Problem processing "+sampletab); e.printStackTrace(); return; } log.info("Finished " + target); } // convert to age target = agefile; if (!target.exists()) { //TODO check modification time log.info("Processing " + target); File script = new File(scriptdir, "SampleTab-to-AGETAB.sh"); if (!script.exists()) { log.error("Unable to find " + script); return; } String bashcom = script + " -o " + agedir + " " + sampletabtoload; SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyyMMdd_HHmmss"); File logfile = new File(subdir, "age_"+simpledateformat.format(new Date())+".log"); if (!ProcessUtils.doCommand(bashcom, logfile)) { log.error("Problem producing " + agedir); log.error("See logfile " + logfile); if (target.exists()){ for (File todel: target.listFiles()){ todel.delete(); } target.delete(); log.error("cleaning partly produced file"); } return; } log.info("Finished " + target); } //TODO load }
diff --git a/GAE/src/org/waterforpeople/mapping/app/web/SurveyRestServlet.java b/GAE/src/org/waterforpeople/mapping/app/web/SurveyRestServlet.java index f13c08b8a..7a94b3386 100644 --- a/GAE/src/org/waterforpeople/mapping/app/web/SurveyRestServlet.java +++ b/GAE/src/org/waterforpeople/mapping/app/web/SurveyRestServlet.java @@ -1,252 +1,257 @@ package org.waterforpeople.mapping.app.web; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import org.waterforpeople.mapping.app.web.dto.SurveyRestRequest; import com.gallatinsystems.framework.dao.BaseDAO; import com.gallatinsystems.framework.rest.AbstractRestApiServlet; import com.gallatinsystems.framework.rest.RestRequest; import com.gallatinsystems.framework.rest.RestResponse; import com.gallatinsystems.survey.dao.QuestionDao; import com.gallatinsystems.survey.dao.QuestionGroupDao; import com.gallatinsystems.survey.dao.SurveyDAO; import com.gallatinsystems.survey.dao.SurveyGroupDAO; import com.gallatinsystems.survey.domain.Question; import com.gallatinsystems.survey.domain.QuestionGroup; import com.gallatinsystems.survey.domain.QuestionOption; import com.gallatinsystems.survey.domain.Survey; import com.gallatinsystems.survey.domain.SurveyGroup; import com.gallatinsystems.survey.domain.Translation; import com.gallatinsystems.survey.domain.Question.Type; import com.gallatinsystems.survey.domain.Translation.ParentType; public class SurveyRestServlet extends AbstractRestApiServlet { private static final Logger log = Logger.getLogger(TaskServlet.class .getName()); /** * */ private static final long serialVersionUID = 1165507917062204859L; @Override protected RestRequest convertRequest() throws Exception { HttpServletRequest req = getRequest(); RestRequest restRequest = new SurveyRestRequest(); restRequest.populateFromHttpRequest(req); return restRequest; } @Override protected RestResponse handleRequest(RestRequest req) throws Exception { RestResponse response = new RestResponse(); SurveyRestRequest importReq = (SurveyRestRequest) req; Boolean questionSaved = null; if (SurveyRestRequest.SAVE_QUESTION_ACTION .equals(importReq.getAction())) { questionSaved = saveQuestion(importReq.getSurveyGroupName(), importReq.getSurveyName(), importReq.getQuestionGroupName(), importReq .getQuestionType(), importReq.getQuestionText(), importReq.getOptions(), importReq.getDependQuestion(), importReq.getAllowOtherFlag(), importReq .getAllowMultipleFlag(), importReq .getMandatoryFlag(), importReq.getQuestionId(), importReq.getQuestionGroupOrder()); } response.setCode("200"); response.setMessage("Record Saved status: " + questionSaved); return response; } @Override protected void writeOkResponse(RestResponse resp) throws Exception { // TODO Auto-generated method stub } private Boolean saveQuestion(String surveyGroupName, String surveyName, String questionGroupName, String questionType, String questionText, String options, String dependentQuestion, Boolean allowOtherFlag, Boolean allowMultipleFlag, Boolean mandatoryFlag, Integer questionOrder, Integer questionGroupOrder) throws UnsupportedEncodingException { // TODO:Change Impl Later if we support multiple langs surveyName = parseLangMap(surveyName).get("en"); questionGroupName = parseLangMap(questionGroupName).get("en"); SurveyGroupDAO sgDao = new SurveyGroupDAO(); SurveyDAO surveyDao = new SurveyDAO(); QuestionGroupDao qgDao = new QuestionGroupDao(); QuestionDao qDao = new QuestionDao(); BaseDAO<Translation> tDao = new BaseDAO<Translation>(Translation.class); SurveyGroup sg = null; if (surveyGroupName != null) { sg = sgDao.findBySurveyGroupName(surveyGroupName); } if (sg == null) { sg = new SurveyGroup(); sg.setCode(surveyGroupName); - sg = sgDao.save(sg); + sgDao.save(sg); } Survey survey = null; String surveyPath = surveyGroupName; survey = surveyDao.getByPath(surveyName, surveyPath); if (survey == null) { survey = new Survey(); survey.setName(surveyName); survey.setPath(surveyPath); survey.setCode(surveyName); + survey.setSurveyGroupId(sg.getKey().getId()); + surveyDao.save(survey); } QuestionGroup qg = null; String qgPath = surveyGroupName + "/" + surveyName; qg = qgDao.getByPath(questionGroupName, qgPath); if (qg == null) { qg = new QuestionGroup(); qg.setName(questionGroupName); qg.setCode(questionGroupName); qg.setPath(qgPath); survey.addQuestionGroup(questionGroupOrder, qg); + qg.setSurveyId(survey.getKey().getId()); + qgDao.save(qg); } Question q = new Question(); String questionPath = qgPath + "/" + questionGroupName; q.setText(parseLangMap(questionText).get("en")); q.setPath(questionPath); q.setOrder(questionOrder); q.setReferenceId(questionOrder.toString()); + q.setQuestionGroupId(qg.getKey().getId()); for (Map.Entry<String, String> qTextItem : parseLangMap(questionText) .entrySet()) { if (!qTextItem.getKey().equals("en")) { Translation t = new Translation(); t.setLanguageCode(qTextItem.getKey()); t.setText(qTextItem.getValue()); t.setParentType(ParentType.QUESTION_TEXT); q.addTranslation(t); } } if (questionType.equals("GEO")) q.setType(Question.Type.GEO); else if (questionType.equals("FREE_TEXT")) q.setType(Question.Type.FREE_TEXT); else if (questionType.equals("OPTION")) { q.setAllowMultipleFlag(allowMultipleFlag); q.setAllowOtherFlag(allowOtherFlag); q.setType(Type.OPTION); QuestionOption qo = new QuestionOption(); for(QuestionOptionContainer qoc:parseQuestionOption(options)){ if(qoc.getLangCode().equals("en")){ qo.setCode(qoc.getOption()); qo.setText(qoc.getOption()); }else{ Translation t = new Translation(); t.setLanguageCode(qoc.langCode); t.setText(qoc.getOption()); t.setParentType(ParentType.QUESTION_TEXT); qo.addTranslation(t); } } q.addQuestionOption(qo); } else if (questionType.equals("PHOTO")) q.setType(Question.Type.PHOTO); else if (questionType.equals("NUMBER")) q.setType(Question.Type.NUMBER); if (mandatoryFlag != null) q.setMandatoryFlag(mandatoryFlag); // deal with options and dependencies if (dependentQuestion != null && dependentQuestion.trim().length() > 1) { String[] parts = dependentQuestion.split("\\|"); Integer quesitonOrderId = new Integer(parts[0]); String answer = parts[1]; Question dependsOnQuestion = qDao.getByPath(quesitonOrderId, questionPath); if (dependsOnQuestion != null) { q.setDependentFlag(true); q.setDependentQuestionId(dependsOnQuestion.getKey().getId()); q.setDependentQuestionAnswer(answer); } }else{ q.setDependentFlag(false); } qDao.save(q); qg.addQuestion(questionOrder, q); qgDao.save(qg); surveyDao.save(survey); sgDao.save(sg); log.info("Just saved " + surveyGroupName + ":" + surveyName + ":" + questionGroupName + ":" + questionOrder); return true; } private HashMap<String, String> parseLangMap(String unparsedLangParam) { HashMap<String, String> langMap = new HashMap<String, String>(); String[] parts = unparsedLangParam.split(";"); for (String item : parts) { String[] langParts = item.split("\\|"); langMap.put(langParts[0], langParts[1]); } return langMap; } private ArrayList<QuestionOptionContainer> parseQuestionOption(String questionOption) { ArrayList<QuestionOptionContainer> qoList = new ArrayList<QuestionOptionContainer>(); String[] parts = questionOption.split("#"); for (String item : parts) { for (Map.Entry<String, String> entry : parseLangMap(item) .entrySet()) { qoList .add(new QuestionOptionContainer(entry.getKey(), entry .getValue())); } } return qoList; } private class QuestionOptionContainer { public QuestionOptionContainer(String langCode, String optionText) { this.setLangCode(langCode); this.setOption(optionText); } private String langCode = null; private String option = null; public void setLangCode(String langCode) { this.langCode = langCode; } public String getLangCode() { return langCode; } public void setOption(String option) { this.option = option; } public String getOption() { return option; } } }
false
true
private Boolean saveQuestion(String surveyGroupName, String surveyName, String questionGroupName, String questionType, String questionText, String options, String dependentQuestion, Boolean allowOtherFlag, Boolean allowMultipleFlag, Boolean mandatoryFlag, Integer questionOrder, Integer questionGroupOrder) throws UnsupportedEncodingException { // TODO:Change Impl Later if we support multiple langs surveyName = parseLangMap(surveyName).get("en"); questionGroupName = parseLangMap(questionGroupName).get("en"); SurveyGroupDAO sgDao = new SurveyGroupDAO(); SurveyDAO surveyDao = new SurveyDAO(); QuestionGroupDao qgDao = new QuestionGroupDao(); QuestionDao qDao = new QuestionDao(); BaseDAO<Translation> tDao = new BaseDAO<Translation>(Translation.class); SurveyGroup sg = null; if (surveyGroupName != null) { sg = sgDao.findBySurveyGroupName(surveyGroupName); } if (sg == null) { sg = new SurveyGroup(); sg.setCode(surveyGroupName); sg = sgDao.save(sg); } Survey survey = null; String surveyPath = surveyGroupName; survey = surveyDao.getByPath(surveyName, surveyPath); if (survey == null) { survey = new Survey(); survey.setName(surveyName); survey.setPath(surveyPath); survey.setCode(surveyName); } QuestionGroup qg = null; String qgPath = surveyGroupName + "/" + surveyName; qg = qgDao.getByPath(questionGroupName, qgPath); if (qg == null) { qg = new QuestionGroup(); qg.setName(questionGroupName); qg.setCode(questionGroupName); qg.setPath(qgPath); survey.addQuestionGroup(questionGroupOrder, qg); } Question q = new Question(); String questionPath = qgPath + "/" + questionGroupName; q.setText(parseLangMap(questionText).get("en")); q.setPath(questionPath); q.setOrder(questionOrder); q.setReferenceId(questionOrder.toString()); for (Map.Entry<String, String> qTextItem : parseLangMap(questionText) .entrySet()) { if (!qTextItem.getKey().equals("en")) { Translation t = new Translation(); t.setLanguageCode(qTextItem.getKey()); t.setText(qTextItem.getValue()); t.setParentType(ParentType.QUESTION_TEXT); q.addTranslation(t); } } if (questionType.equals("GEO")) q.setType(Question.Type.GEO); else if (questionType.equals("FREE_TEXT")) q.setType(Question.Type.FREE_TEXT); else if (questionType.equals("OPTION")) { q.setAllowMultipleFlag(allowMultipleFlag); q.setAllowOtherFlag(allowOtherFlag); q.setType(Type.OPTION); QuestionOption qo = new QuestionOption(); for(QuestionOptionContainer qoc:parseQuestionOption(options)){ if(qoc.getLangCode().equals("en")){ qo.setCode(qoc.getOption()); qo.setText(qoc.getOption()); }else{ Translation t = new Translation(); t.setLanguageCode(qoc.langCode); t.setText(qoc.getOption()); t.setParentType(ParentType.QUESTION_TEXT); qo.addTranslation(t); } } q.addQuestionOption(qo); } else if (questionType.equals("PHOTO")) q.setType(Question.Type.PHOTO); else if (questionType.equals("NUMBER")) q.setType(Question.Type.NUMBER); if (mandatoryFlag != null) q.setMandatoryFlag(mandatoryFlag); // deal with options and dependencies if (dependentQuestion != null && dependentQuestion.trim().length() > 1) { String[] parts = dependentQuestion.split("\\|"); Integer quesitonOrderId = new Integer(parts[0]); String answer = parts[1]; Question dependsOnQuestion = qDao.getByPath(quesitonOrderId, questionPath); if (dependsOnQuestion != null) { q.setDependentFlag(true); q.setDependentQuestionId(dependsOnQuestion.getKey().getId()); q.setDependentQuestionAnswer(answer); } }else{ q.setDependentFlag(false); } qDao.save(q); qg.addQuestion(questionOrder, q); qgDao.save(qg); surveyDao.save(survey); sgDao.save(sg); log.info("Just saved " + surveyGroupName + ":" + surveyName + ":" + questionGroupName + ":" + questionOrder); return true; }
private Boolean saveQuestion(String surveyGroupName, String surveyName, String questionGroupName, String questionType, String questionText, String options, String dependentQuestion, Boolean allowOtherFlag, Boolean allowMultipleFlag, Boolean mandatoryFlag, Integer questionOrder, Integer questionGroupOrder) throws UnsupportedEncodingException { // TODO:Change Impl Later if we support multiple langs surveyName = parseLangMap(surveyName).get("en"); questionGroupName = parseLangMap(questionGroupName).get("en"); SurveyGroupDAO sgDao = new SurveyGroupDAO(); SurveyDAO surveyDao = new SurveyDAO(); QuestionGroupDao qgDao = new QuestionGroupDao(); QuestionDao qDao = new QuestionDao(); BaseDAO<Translation> tDao = new BaseDAO<Translation>(Translation.class); SurveyGroup sg = null; if (surveyGroupName != null) { sg = sgDao.findBySurveyGroupName(surveyGroupName); } if (sg == null) { sg = new SurveyGroup(); sg.setCode(surveyGroupName); sgDao.save(sg); } Survey survey = null; String surveyPath = surveyGroupName; survey = surveyDao.getByPath(surveyName, surveyPath); if (survey == null) { survey = new Survey(); survey.setName(surveyName); survey.setPath(surveyPath); survey.setCode(surveyName); survey.setSurveyGroupId(sg.getKey().getId()); surveyDao.save(survey); } QuestionGroup qg = null; String qgPath = surveyGroupName + "/" + surveyName; qg = qgDao.getByPath(questionGroupName, qgPath); if (qg == null) { qg = new QuestionGroup(); qg.setName(questionGroupName); qg.setCode(questionGroupName); qg.setPath(qgPath); survey.addQuestionGroup(questionGroupOrder, qg); qg.setSurveyId(survey.getKey().getId()); qgDao.save(qg); } Question q = new Question(); String questionPath = qgPath + "/" + questionGroupName; q.setText(parseLangMap(questionText).get("en")); q.setPath(questionPath); q.setOrder(questionOrder); q.setReferenceId(questionOrder.toString()); q.setQuestionGroupId(qg.getKey().getId()); for (Map.Entry<String, String> qTextItem : parseLangMap(questionText) .entrySet()) { if (!qTextItem.getKey().equals("en")) { Translation t = new Translation(); t.setLanguageCode(qTextItem.getKey()); t.setText(qTextItem.getValue()); t.setParentType(ParentType.QUESTION_TEXT); q.addTranslation(t); } } if (questionType.equals("GEO")) q.setType(Question.Type.GEO); else if (questionType.equals("FREE_TEXT")) q.setType(Question.Type.FREE_TEXT); else if (questionType.equals("OPTION")) { q.setAllowMultipleFlag(allowMultipleFlag); q.setAllowOtherFlag(allowOtherFlag); q.setType(Type.OPTION); QuestionOption qo = new QuestionOption(); for(QuestionOptionContainer qoc:parseQuestionOption(options)){ if(qoc.getLangCode().equals("en")){ qo.setCode(qoc.getOption()); qo.setText(qoc.getOption()); }else{ Translation t = new Translation(); t.setLanguageCode(qoc.langCode); t.setText(qoc.getOption()); t.setParentType(ParentType.QUESTION_TEXT); qo.addTranslation(t); } } q.addQuestionOption(qo); } else if (questionType.equals("PHOTO")) q.setType(Question.Type.PHOTO); else if (questionType.equals("NUMBER")) q.setType(Question.Type.NUMBER); if (mandatoryFlag != null) q.setMandatoryFlag(mandatoryFlag); // deal with options and dependencies if (dependentQuestion != null && dependentQuestion.trim().length() > 1) { String[] parts = dependentQuestion.split("\\|"); Integer quesitonOrderId = new Integer(parts[0]); String answer = parts[1]; Question dependsOnQuestion = qDao.getByPath(quesitonOrderId, questionPath); if (dependsOnQuestion != null) { q.setDependentFlag(true); q.setDependentQuestionId(dependsOnQuestion.getKey().getId()); q.setDependentQuestionAnswer(answer); } }else{ q.setDependentFlag(false); } qDao.save(q); qg.addQuestion(questionOrder, q); qgDao.save(qg); surveyDao.save(survey); sgDao.save(sg); log.info("Just saved " + surveyGroupName + ":" + surveyName + ":" + questionGroupName + ":" + questionOrder); return true; }
diff --git a/org.eclipse.riena.tests/src/org/eclipse/riena/navigation/ui/swt/lnf/renderer/SubModuleTreeItemMarkerRendererTest.java b/org.eclipse.riena.tests/src/org/eclipse/riena/navigation/ui/swt/lnf/renderer/SubModuleTreeItemMarkerRendererTest.java index eb461492d..359674408 100644 --- a/org.eclipse.riena.tests/src/org/eclipse/riena/navigation/ui/swt/lnf/renderer/SubModuleTreeItemMarkerRendererTest.java +++ b/org.eclipse.riena.tests/src/org/eclipse/riena/navigation/ui/swt/lnf/renderer/SubModuleTreeItemMarkerRendererTest.java @@ -1,293 +1,295 @@ /******************************************************************************* * Copyright (c) 2007, 2008 compeople AG 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: * compeople AG - initial API and implementation *******************************************************************************/ package org.eclipse.riena.navigation.ui.swt.lnf.renderer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import junit.framework.TestCase; import org.eclipse.core.runtime.AssertionFailedException; import org.eclipse.riena.core.util.ReflectionUtils; import org.eclipse.riena.navigation.model.SubModuleNode; import org.eclipse.riena.ui.core.marker.ErrorMarker; import org.eclipse.riena.ui.core.marker.IIconizableMarker; import org.eclipse.riena.ui.core.marker.NegativeMarker; import org.eclipse.riena.ui.swt.lnf.LnfManager; import org.eclipse.riena.ui.swt.lnf.rienadefault.RienaDefaultLnf; import org.eclipse.riena.ui.swt.utils.SwtUtilities; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; /** * Tests of the class {@link SubModuleTreeItemMarkerRenderer}. */ public class SubModuleTreeItemMarkerRendererTest extends TestCase { private Shell shell; private GC gc; private TreeItem item; /** * @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); shell = new Shell(); Tree tree = new Tree(shell, SWT.NONE); item = new TreeItem(tree, SWT.NONE); gc = new GC(tree); LnfManager.setLnf(new MyLnf()); LnfManager.getLnf().initialize(); } /** * @see junit.framework.TestCase#tearDown() */ @Override protected void tearDown() throws Exception { super.tearDown(); gc.dispose(); gc = null; SwtUtilities.disposeWidget(shell); } /** * Tests the method {@code paint}. */ public void testPaint() { MockRenderer renderer = new MockRenderer(); renderer.setBounds(0, 0, 100, 100); try { renderer.paint(gc, null); fail("AssertionFailedException expected"); } catch (AssertionFailedException e) { // ok, expected } try { renderer.paint(gc, shell); fail("AssertionFailedException expected"); } catch (AssertionFailedException e) { // ok, expected } try { renderer.paint(null, item); fail("AssertionFailedException expected"); } catch (AssertionFailedException e) { // ok, expected } renderer.resetPaintMarkersCalled(); renderer.paint(gc, item); assertFalse(renderer.isPaintMarkersCalled()); SubModuleNode node = new SubModuleNode(); - item.setData(node); + renderer.setMarkers(node.getMarkers()); renderer.resetPaintMarkersCalled(); renderer.paint(gc, item); assertFalse(renderer.isPaintMarkersCalled()); node.addMarker(new ErrorMarker()); + renderer.setMarkers(node.getMarkers()); renderer.resetPaintMarkersCalled(); renderer.paint(gc, item); assertTrue(renderer.isPaintMarkersCalled()); node.removeAllMarkers(); node.addMarker(new NegativeMarker()); + renderer.setMarkers(node.getMarkers()); renderer.resetPaintMarkersCalled(); renderer.paint(gc, item); assertFalse(renderer.isPaintMarkersCalled()); renderer.dispose(); } /** * Tests the method {@code paintMarkers}. * * @throws Exception */ public void testPaintMarkers() throws Exception { item.setImage(createItemImage()); SubModuleTreeItemMarkerRenderer renderer = new SubModuleTreeItemMarkerRenderer(); renderer.setBounds(0, 0, 100, 25); // create image without markers Collection<IIconizableMarker> markers = new ArrayList<IIconizableMarker>(); Image noMarkersImage = new Image(shell.getDisplay(), new Rectangle(0, 0, 10, 10)); GC noMarkersGC = new GC(noMarkersImage); // renderer.paintMarkers(noMarkersGC, markers, item); ReflectionUtils.invokeHidden(renderer, "paintMarkers", noMarkersGC, markers, item); byte[] noMarkersBytes = noMarkersImage.getImageData().data; noMarkersGC.dispose(); SwtUtilities.disposeResource(noMarkersImage); // no marker -> no marker image is drawn Image paintImage = new Image(shell.getDisplay(), new Rectangle(0, 0, 10, 10)); GC paintGC = new GC(paintImage); ReflectionUtils.invokeHidden(renderer, "paintMarkers", paintGC, markers, item); byte[] paintBytes = paintImage.getImageData().data; paintGC.dispose(); SwtUtilities.disposeResource(paintImage); assertTrue(Arrays.equals(noMarkersBytes, paintBytes)); // one error marker -> error marker image is drawn markers.add(new ErrorMarker()); paintImage = new Image(shell.getDisplay(), new Rectangle(0, 0, 10, 10)); paintGC = new GC(paintImage); ReflectionUtils.invokeHidden(renderer, "paintMarkers", paintGC, markers, item); paintBytes = paintImage.getImageData().data; paintGC.dispose(); SwtUtilities.disposeResource(paintImage); assertFalse(Arrays.equals(noMarkersBytes, paintBytes)); // one error marker, but item has no image -> no marker image is drawn item.setImage((Image) null); paintImage = new Image(shell.getDisplay(), new Rectangle(0, 0, 10, 10)); paintGC = new GC(paintImage); ReflectionUtils.invokeHidden(renderer, "paintMarkers", paintGC, markers, item); paintBytes = paintImage.getImageData().data; paintGC.dispose(); SwtUtilities.disposeResource(paintImage); assertTrue(Arrays.equals(noMarkersBytes, paintBytes)); renderer.dispose(); } /** * Tests the method {@code calcMarkerCoordinates}. */ public void testCalcMarkerCoordinates() { SubModuleTreeItemMarkerRenderer renderer = new SubModuleTreeItemMarkerRenderer(); renderer.setBounds(2, 3, 100, 25); Image itemImage = createItemImage(); Image markerImage = createMarkerImage(); Point pos = ReflectionUtils.invokeHidden(renderer, "calcMarkerCoordinates", itemImage, markerImage, IIconizableMarker.MarkerPosition.TOP_LEFT); assertEquals(2, pos.x); assertEquals(3, pos.y); pos = ReflectionUtils.invokeHidden(renderer, "calcMarkerCoordinates", itemImage, markerImage, IIconizableMarker.MarkerPosition.TOP_RIGHT); assertEquals(2 + 5, pos.x); assertEquals(3, pos.y); pos = ReflectionUtils.invokeHidden(renderer, "calcMarkerCoordinates", itemImage, markerImage, IIconizableMarker.MarkerPosition.BOTTOM_LEFT); assertEquals(2, pos.x); assertEquals(3 + 5, pos.y); pos = ReflectionUtils.invokeHidden(renderer, "calcMarkerCoordinates", itemImage, markerImage, IIconizableMarker.MarkerPosition.BOTTOM_RIGHT); assertEquals(2 + 5, pos.x); assertEquals(3 + 5, pos.y); SwtUtilities.disposeResource(itemImage); SwtUtilities.disposeResource(markerImage); } /** * Creates a image with a small green rectangle. * * @return image */ private Image createItemImage() { Image image = new Image(shell.getDisplay(), new Rectangle(0, 0, 10, 10)); GC gc = new GC(image); gc.setForeground(LnfManager.getLnf().getColor("green")); gc.setBackground(LnfManager.getLnf().getColor("green")); gc.fillRectangle(0, 0, 5, 5); gc.dispose(); return image; } /** * Creates a image with a very small red rectangle. * * @return image */ private Image createMarkerImage() { Image image = new Image(shell.getDisplay(), new Rectangle(0, 0, 5, 5)); GC gc = new GC(image); gc.setForeground(LnfManager.getLnf().getColor("red")); gc.setBackground(LnfManager.getLnf().getColor("red")); gc.fillRectangle(0, 0, 2, 2); gc.dispose(); return image; } /** * This Look and Feel returns always the same image. */ private class MyLnf extends RienaDefaultLnf { private Image image; public MyLnf() { super(); image = createMarkerImage(); } @Override public Image getImage(String key) { return image; } } private class MockRenderer extends SubModuleTreeItemMarkerRenderer { private boolean paintMarkersCalled; public MockRenderer() { resetPaintMarkersCalled(); } public boolean isPaintMarkersCalled() { return paintMarkersCalled; } public void resetPaintMarkersCalled() { this.paintMarkersCalled = false; } /** * @see org.eclipse.riena.navigation.ui.swt.lnf.renderer.SubModuleTreeItemMarkerRenderer#paintMarkers(org.eclipse.swt.graphics.GC, * java.util.Collection, org.eclipse.swt.widgets.TreeItem) */ @Override protected void paintMarkers(GC gc, Collection<IIconizableMarker> markers, TreeItem item) { super.paintMarkers(gc, markers, item); this.paintMarkersCalled = true; } } }
false
true
public void testPaint() { MockRenderer renderer = new MockRenderer(); renderer.setBounds(0, 0, 100, 100); try { renderer.paint(gc, null); fail("AssertionFailedException expected"); } catch (AssertionFailedException e) { // ok, expected } try { renderer.paint(gc, shell); fail("AssertionFailedException expected"); } catch (AssertionFailedException e) { // ok, expected } try { renderer.paint(null, item); fail("AssertionFailedException expected"); } catch (AssertionFailedException e) { // ok, expected } renderer.resetPaintMarkersCalled(); renderer.paint(gc, item); assertFalse(renderer.isPaintMarkersCalled()); SubModuleNode node = new SubModuleNode(); item.setData(node); renderer.resetPaintMarkersCalled(); renderer.paint(gc, item); assertFalse(renderer.isPaintMarkersCalled()); node.addMarker(new ErrorMarker()); renderer.resetPaintMarkersCalled(); renderer.paint(gc, item); assertTrue(renderer.isPaintMarkersCalled()); node.removeAllMarkers(); node.addMarker(new NegativeMarker()); renderer.resetPaintMarkersCalled(); renderer.paint(gc, item); assertFalse(renderer.isPaintMarkersCalled()); renderer.dispose(); }
public void testPaint() { MockRenderer renderer = new MockRenderer(); renderer.setBounds(0, 0, 100, 100); try { renderer.paint(gc, null); fail("AssertionFailedException expected"); } catch (AssertionFailedException e) { // ok, expected } try { renderer.paint(gc, shell); fail("AssertionFailedException expected"); } catch (AssertionFailedException e) { // ok, expected } try { renderer.paint(null, item); fail("AssertionFailedException expected"); } catch (AssertionFailedException e) { // ok, expected } renderer.resetPaintMarkersCalled(); renderer.paint(gc, item); assertFalse(renderer.isPaintMarkersCalled()); SubModuleNode node = new SubModuleNode(); renderer.setMarkers(node.getMarkers()); renderer.resetPaintMarkersCalled(); renderer.paint(gc, item); assertFalse(renderer.isPaintMarkersCalled()); node.addMarker(new ErrorMarker()); renderer.setMarkers(node.getMarkers()); renderer.resetPaintMarkersCalled(); renderer.paint(gc, item); assertTrue(renderer.isPaintMarkersCalled()); node.removeAllMarkers(); node.addMarker(new NegativeMarker()); renderer.setMarkers(node.getMarkers()); renderer.resetPaintMarkersCalled(); renderer.paint(gc, item); assertFalse(renderer.isPaintMarkersCalled()); renderer.dispose(); }
diff --git a/src/numberConversionAlgoritme/SecondComplementBinaryConversion.java b/src/numberConversionAlgoritme/SecondComplementBinaryConversion.java index d44f7da..4856610 100644 --- a/src/numberConversionAlgoritme/SecondComplementBinaryConversion.java +++ b/src/numberConversionAlgoritme/SecondComplementBinaryConversion.java @@ -1,38 +1,39 @@ package numberConversionAlgoritme; public class SecondComplementBinaryConversion implements NumberConversionAlgoritmeInterface{ @Override public Object getSpecificNumber(double number) { double numberOfBits = 0; if(number != 0) numberOfBits = Math.log((int)Math.abs(number))/Math.log(2); String bits = Integer.toBinaryString((int)Math.abs(number)); int numberOfBitsInString = bits.length(); numberOfBits++; numberOfBits = Math.abs(numberOfBits); numberOfBits = Math.ceil((int) (Math.ceil(numberOfBits / 4d) * 4)); int bitsNeeded = (int) (numberOfBits-numberOfBitsInString); StringBuilder b = new StringBuilder(); for(int i = 0; i < bitsNeeded-1; i++){ b.append("0"); } if(number > 0){ b.insert(0, "0"); return b.toString() + bits; } number++; b.insert(0, "1"); - return b.toString() + " " + Integer.toBinaryString(~(int)Math.abs(number)); +// return b.toString() + " " + Integer.toBinaryString(~(int)Math.abs(number)); + return b.toString(); } @Override public double getDoubleNumber(Object number) { // TODO Auto-generated method stub return 0; } }
true
true
public Object getSpecificNumber(double number) { double numberOfBits = 0; if(number != 0) numberOfBits = Math.log((int)Math.abs(number))/Math.log(2); String bits = Integer.toBinaryString((int)Math.abs(number)); int numberOfBitsInString = bits.length(); numberOfBits++; numberOfBits = Math.abs(numberOfBits); numberOfBits = Math.ceil((int) (Math.ceil(numberOfBits / 4d) * 4)); int bitsNeeded = (int) (numberOfBits-numberOfBitsInString); StringBuilder b = new StringBuilder(); for(int i = 0; i < bitsNeeded-1; i++){ b.append("0"); } if(number > 0){ b.insert(0, "0"); return b.toString() + bits; } number++; b.insert(0, "1"); return b.toString() + " " + Integer.toBinaryString(~(int)Math.abs(number)); }
public Object getSpecificNumber(double number) { double numberOfBits = 0; if(number != 0) numberOfBits = Math.log((int)Math.abs(number))/Math.log(2); String bits = Integer.toBinaryString((int)Math.abs(number)); int numberOfBitsInString = bits.length(); numberOfBits++; numberOfBits = Math.abs(numberOfBits); numberOfBits = Math.ceil((int) (Math.ceil(numberOfBits / 4d) * 4)); int bitsNeeded = (int) (numberOfBits-numberOfBitsInString); StringBuilder b = new StringBuilder(); for(int i = 0; i < bitsNeeded-1; i++){ b.append("0"); } if(number > 0){ b.insert(0, "0"); return b.toString() + bits; } number++; b.insert(0, "1"); // return b.toString() + " " + Integer.toBinaryString(~(int)Math.abs(number)); return b.toString(); }
diff --git a/jetty/src/main/java/org/mortbay/jetty/handler/ErrorHandler.java b/jetty/src/main/java/org/mortbay/jetty/handler/ErrorHandler.java index dd626b0b7..392da0b33 100644 --- a/jetty/src/main/java/org/mortbay/jetty/handler/ErrorHandler.java +++ b/jetty/src/main/java/org/mortbay/jetty/handler/ErrorHandler.java @@ -1,137 +1,137 @@ // ======================================================================== // Copyright 1999-2005 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // 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.mortbay.jetty.handler; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.net.URLDecoder; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.mortbay.jetty.HttpConnection; import org.mortbay.jetty.HttpGenerator; import org.mortbay.jetty.MimeTypes; import org.mortbay.util.ByteArrayISO8859Writer; import org.mortbay.util.StringUtil; /* ------------------------------------------------------------ */ /** Handler for Error pages * A handler that is registered at the org.mortbay.http.ErrorHandler * context attributed and called by the HttpResponse.sendError method to write a * error page. * * @author Greg Wilkins (gregw) */ public class ErrorHandler extends AbstractHandler { boolean _showStacks=true; /* ------------------------------------------------------------ */ /* * @see org.mortbay.jetty.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int) */ public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException { HttpConnection.getCurrentConnection().getRequest().setHandled(true); response.setContentType(MimeTypes.TEXT_HTML); ByteArrayISO8859Writer writer= new ByteArrayISO8859Writer(2048); HttpConnection connection = HttpConnection.getCurrentConnection(); handleErrorPage(request, writer, connection.getResponse().getStatus(), connection.getResponse().getReason()); writer.flush(); response.setContentLength(writer.size()); writer.writeTo(response.getOutputStream()); writer.destroy(); } /* ------------------------------------------------------------ */ protected void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message) throws IOException { writeErrorPage(request, writer, code, message, _showStacks); } /* ------------------------------------------------------------ */ public static void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks) throws IOException { if (message != null) { message=URLDecoder.decode(message,"UTF-8"); message= StringUtil.replace(message, "<", "&lt;"); message= StringUtil.replace(message, ">", "&gt;"); } String uri= request.getRequestURI(); uri= StringUtil.replace(uri, "<", "&lt;"); uri= StringUtil.replace(uri, ">", "&gt;"); writer.write("<html>\n<head>\n<title>Error "); writer.write(Integer.toString(code)); writer.write(' '); if (message==null) message=HttpGenerator.getReason(code); writer.write(message); writer.write("</title>\n</head>\n<body>\n<h2>HTTP ERROR: "); writer.write(Integer.toString(code)); writer.write("</h2><pre>"); writer.write(message); writer.write("</pre>\n"); writer.write("<p>RequestURI="); writer.write(uri); writer.write( "</p>\n<p><i><small><a href=\"http://jetty.mortbay.org\">Powered by Jetty://</a></small></i></p>"); if (showStacks) { Throwable th = (Throwable)request.getAttribute("javax.servlet.error.exception"); while(th!=null) { - writer.write("<h3>Caused by:</h2><pre>"); + writer.write("<h3>Caused by:</h3><pre>"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); th.printStackTrace(pw); pw.flush(); writer.write(sw.getBuffer().toString()); writer.write("</pre>\n"); th =th.getCause(); } } for (int i= 0; i < 20; i++) writer.write("\n "); writer.write("\n</body>\n</html>\n"); } /* ------------------------------------------------------------ */ /** * @return True if stack traces are shown in the error pages */ public boolean isShowStacks() { return _showStacks; } /* ------------------------------------------------------------ */ /** * @param showStacks True if stack traces are shown in the error pages */ public void setShowStacks(boolean showStacks) { _showStacks = showStacks; } }
true
true
public static void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks) throws IOException { if (message != null) { message=URLDecoder.decode(message,"UTF-8"); message= StringUtil.replace(message, "<", "&lt;"); message= StringUtil.replace(message, ">", "&gt;"); } String uri= request.getRequestURI(); uri= StringUtil.replace(uri, "<", "&lt;"); uri= StringUtil.replace(uri, ">", "&gt;"); writer.write("<html>\n<head>\n<title>Error "); writer.write(Integer.toString(code)); writer.write(' '); if (message==null) message=HttpGenerator.getReason(code); writer.write(message); writer.write("</title>\n</head>\n<body>\n<h2>HTTP ERROR: "); writer.write(Integer.toString(code)); writer.write("</h2><pre>"); writer.write(message); writer.write("</pre>\n"); writer.write("<p>RequestURI="); writer.write(uri); writer.write( "</p>\n<p><i><small><a href=\"http://jetty.mortbay.org\">Powered by Jetty://</a></small></i></p>"); if (showStacks) { Throwable th = (Throwable)request.getAttribute("javax.servlet.error.exception"); while(th!=null) { writer.write("<h3>Caused by:</h2><pre>"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); th.printStackTrace(pw); pw.flush(); writer.write(sw.getBuffer().toString()); writer.write("</pre>\n"); th =th.getCause(); } } for (int i= 0; i < 20; i++) writer.write("\n "); writer.write("\n</body>\n</html>\n"); }
public static void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks) throws IOException { if (message != null) { message=URLDecoder.decode(message,"UTF-8"); message= StringUtil.replace(message, "<", "&lt;"); message= StringUtil.replace(message, ">", "&gt;"); } String uri= request.getRequestURI(); uri= StringUtil.replace(uri, "<", "&lt;"); uri= StringUtil.replace(uri, ">", "&gt;"); writer.write("<html>\n<head>\n<title>Error "); writer.write(Integer.toString(code)); writer.write(' '); if (message==null) message=HttpGenerator.getReason(code); writer.write(message); writer.write("</title>\n</head>\n<body>\n<h2>HTTP ERROR: "); writer.write(Integer.toString(code)); writer.write("</h2><pre>"); writer.write(message); writer.write("</pre>\n"); writer.write("<p>RequestURI="); writer.write(uri); writer.write( "</p>\n<p><i><small><a href=\"http://jetty.mortbay.org\">Powered by Jetty://</a></small></i></p>"); if (showStacks) { Throwable th = (Throwable)request.getAttribute("javax.servlet.error.exception"); while(th!=null) { writer.write("<h3>Caused by:</h3><pre>"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); th.printStackTrace(pw); pw.flush(); writer.write(sw.getBuffer().toString()); writer.write("</pre>\n"); th =th.getCause(); } } for (int i= 0; i < 20; i++) writer.write("\n "); writer.write("\n</body>\n</html>\n"); }
diff --git a/src/com/group7/dragonwars/engine/GameField.java b/src/com/group7/dragonwars/engine/GameField.java index 609ab0e..db7d45d 100644 --- a/src/com/group7/dragonwars/engine/GameField.java +++ b/src/com/group7/dragonwars/engine/GameField.java @@ -1,108 +1,108 @@ package com.group7.dragonwars.engine; public class GameField { private String fieldName; private Unit hostedUnit; private Building hostedBuilding; private Double movementModifier; private Double defenseModifier, attackModifier; private Boolean flightOnly, accessible; private String spriteLocation, spriteDir, spritePack; public Boolean doesAcceptUnit(Unit unit) { Boolean canStep = true; if (this.flightOnly) canStep = unit.isFlying(); return this.accessible && canStep; } public GameField(String fieldName, Double movementModifier, Double attackModifier, Double defenseModifier, Boolean accessible, Boolean flightOnly, String spriteLocation, String spriteDir, String spritePack) { this.fieldName = fieldName; this.movementModifier = movementModifier; - this.attackMedifier = attackModifier; + this.attackModifier = attackModifier; this.defenseModifier = defenseModifier; this.accessible = accessible; this.flightOnly = flightOnly; this.spriteLocation = spriteLocation; this.spriteDir = spriteDir; this.spritePack = spritePack; } public Double getDefenseModifier() { if (this.hostsBuilding()) { Double mod = this.hostedBuilding.getDefenseBonus(); mod += this.defenseModifier; return mod / 2; } return this.defenseModifier; } public Double getAttackModifier() { if (this.hostsBuilding()) { Double mod = this.hostedBuilding.getAttackBonus(); mod += this.attackModifier; return mod / 2; } return this.attackModifier; } public Double getMovementModifier() { return this.movementModifier; } public Boolean hostsUnit() { return this.hostedUnit != null; } public Boolean hostsBuilding() { /* Could be used by the drawing routine. */ return this.hostedBuilding != null; } public Unit getUnit() { return this.hostedUnit; } public Building getBuilding() { return this.hostedBuilding; } /* This will clobber old units/buildings as it is now. */ public void setBuilding(Building building) { this.hostedBuilding = building; } public void setUnit(Unit unit) { this.hostedUnit = unit; } public String toString() { return this.getFieldName(); } public String getFieldName() { return this.fieldName; } public String getSpriteLocation() { return this.spriteLocation; } public String getSpriteDir() { return this.spriteDir; } public String getSpritePack() { return this.spritePack; } }
true
true
public GameField(String fieldName, Double movementModifier, Double attackModifier, Double defenseModifier, Boolean accessible, Boolean flightOnly, String spriteLocation, String spriteDir, String spritePack) { this.fieldName = fieldName; this.movementModifier = movementModifier; this.attackMedifier = attackModifier; this.defenseModifier = defenseModifier; this.accessible = accessible; this.flightOnly = flightOnly; this.spriteLocation = spriteLocation; this.spriteDir = spriteDir; this.spritePack = spritePack; }
public GameField(String fieldName, Double movementModifier, Double attackModifier, Double defenseModifier, Boolean accessible, Boolean flightOnly, String spriteLocation, String spriteDir, String spritePack) { this.fieldName = fieldName; this.movementModifier = movementModifier; this.attackModifier = attackModifier; this.defenseModifier = defenseModifier; this.accessible = accessible; this.flightOnly = flightOnly; this.spriteLocation = spriteLocation; this.spriteDir = spriteDir; this.spritePack = spritePack; }
diff --git a/src/de/nomagic/test/pacemaker/SlotFactory.java b/src/de/nomagic/test/pacemaker/SlotFactory.java index b73ecaa..253bba6 100644 --- a/src/de/nomagic/test/pacemaker/SlotFactory.java +++ b/src/de/nomagic/test/pacemaker/SlotFactory.java @@ -1,28 +1,28 @@ package de.nomagic.test.pacemaker; import de.nomagic.printerController.pacemaker.Protocol; public final class SlotFactory { private SlotFactory() { } public static Slot getSlot(int type, int[] data) { switch(type) { - case Protocol.MOVEMENT_BLOCK_TYPE_COMMAND_WRAPPER: + case Protocol.MOVEMENT_BLOCK_TYPE_BASIC_LINEAR_MOVE: return new BasicLinearMoveSlot(data); + case Protocol.MOVEMENT_BLOCK_TYPE_COMMAND_WRAPPER: case Protocol.MOVEMENT_BLOCK_TYPE_DELAY: - case Protocol.MOVEMENT_BLOCK_TYPE_BASIC_LINEAR_MOVE: case Protocol.MOVEMENT_BLOCK_TYPE_SET_ACTIVE_TOOLHEAD: return new Slot(type, data); default: return null; } } }
false
true
public static Slot getSlot(int type, int[] data) { switch(type) { case Protocol.MOVEMENT_BLOCK_TYPE_COMMAND_WRAPPER: return new BasicLinearMoveSlot(data); case Protocol.MOVEMENT_BLOCK_TYPE_DELAY: case Protocol.MOVEMENT_BLOCK_TYPE_BASIC_LINEAR_MOVE: case Protocol.MOVEMENT_BLOCK_TYPE_SET_ACTIVE_TOOLHEAD: return new Slot(type, data); default: return null; } }
public static Slot getSlot(int type, int[] data) { switch(type) { case Protocol.MOVEMENT_BLOCK_TYPE_BASIC_LINEAR_MOVE: return new BasicLinearMoveSlot(data); case Protocol.MOVEMENT_BLOCK_TYPE_COMMAND_WRAPPER: case Protocol.MOVEMENT_BLOCK_TYPE_DELAY: case Protocol.MOVEMENT_BLOCK_TYPE_SET_ACTIVE_TOOLHEAD: return new Slot(type, data); default: return null; } }
diff --git a/hibernate-ogm-core/src/main/java/org/hibernate/ogm/type/descriptor/BasicGridBinder.java b/hibernate-ogm-core/src/main/java/org/hibernate/ogm/type/descriptor/BasicGridBinder.java index 900a79315..2fba16f13 100644 --- a/hibernate-ogm-core/src/main/java/org/hibernate/ogm/type/descriptor/BasicGridBinder.java +++ b/hibernate-ogm-core/src/main/java/org/hibernate/ogm/type/descriptor/BasicGridBinder.java @@ -1,93 +1,93 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * * JBoss, Home of Professional Open Source * Copyright 2010-2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.hibernate.ogm.type.descriptor; import java.sql.SQLException; import java.util.Arrays; import org.hibernate.engine.jdbc.LobCreator; import org.hibernate.engine.jdbc.NonContextualLobCreator; import org.hibernate.ogm.datastore.spi.Tuple; import org.hibernate.ogm.util.impl.Log; import org.hibernate.ogm.util.impl.LoggerFactory; import org.hibernate.type.descriptor.WrapperOptions; import org.hibernate.type.descriptor.java.JavaTypeDescriptor; import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; /** * @author Emmanuel Bernard */ public abstract class BasicGridBinder<X> implements GridValueBinder<X>{ private static final Log log = LoggerFactory.make(); private final JavaTypeDescriptor<X> javaDescriptor; private final GridTypeDescriptor gridDescriptor; private static final WrapperOptions DEFAULT_OPTIONS = new WrapperOptions() { @Override public boolean useStreamForLobBinding() { return false; } @Override public LobCreator getLobCreator() { return NonContextualLobCreator.INSTANCE; } @Override public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) { //OGM dialect don't remap types yet return sqlTypeDescriptor; } }; public BasicGridBinder(JavaTypeDescriptor<X> javaDescriptor, GridTypeDescriptor gridDescriptor) { this.javaDescriptor = javaDescriptor; this.gridDescriptor = gridDescriptor; } @Override public void bind(Tuple resultset, X value, String[] names) { if ( value == null ) { for ( String name : names ) { log.tracef( "binding [null] to parameter [%1$s]", name ); resultset.put( name, null ); } } else { if ( log.isTraceEnabled() ) { - log.tracef( "binding [%2$s] to parameter(s) %1$s", javaDescriptor.extractLoggableRepresentation( value ), Arrays.toString( names ) ); + log.tracef( "binding [%1$s] to parameter(s) %2$s", javaDescriptor.extractLoggableRepresentation( value ), Arrays.toString( names ) ); } doBind( resultset, value, names, DEFAULT_OPTIONS ); } } /** * Perform the binding. Safe to assume that value is not null. * * @param st The prepared statement * @param value The value to bind (not null). * @param index The index at which to bind * @param options The binding options * * @throws SQLException Indicates a problem binding to the prepared statement. */ protected abstract void doBind(Tuple resultset, X value, String[] names, WrapperOptions options); }
true
true
public void bind(Tuple resultset, X value, String[] names) { if ( value == null ) { for ( String name : names ) { log.tracef( "binding [null] to parameter [%1$s]", name ); resultset.put( name, null ); } } else { if ( log.isTraceEnabled() ) { log.tracef( "binding [%2$s] to parameter(s) %1$s", javaDescriptor.extractLoggableRepresentation( value ), Arrays.toString( names ) ); } doBind( resultset, value, names, DEFAULT_OPTIONS ); } }
public void bind(Tuple resultset, X value, String[] names) { if ( value == null ) { for ( String name : names ) { log.tracef( "binding [null] to parameter [%1$s]", name ); resultset.put( name, null ); } } else { if ( log.isTraceEnabled() ) { log.tracef( "binding [%1$s] to parameter(s) %2$s", javaDescriptor.extractLoggableRepresentation( value ), Arrays.toString( names ) ); } doBind( resultset, value, names, DEFAULT_OPTIONS ); } }
diff --git a/android/src/com/google/zxing/client/android/ResultHandler.java b/android/src/com/google/zxing/client/android/ResultHandler.java index 2489ceb9..0f20b2df 100755 --- a/android/src/com/google/zxing/client/android/ResultHandler.java +++ b/android/src/com/google/zxing/client/android/ResultHandler.java @@ -1,128 +1,128 @@ /* * Copyright (C) 2008 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.zxing.client.android; import android.content.Intent; import android.net.ContentURI; import android.os.Handler; import android.os.Message; import android.provider.Contacts; import com.google.zxing.client.result.AddressBookDoCoMoResult; import com.google.zxing.client.result.BookmarkDoCoMoResult; import com.google.zxing.client.result.EmailAddressResult; import com.google.zxing.client.result.EmailDoCoMoResult; import com.google.zxing.client.result.ParsedReaderResult; import com.google.zxing.client.result.ParsedReaderResultType; import com.google.zxing.client.result.UPCParsedResult; import com.google.zxing.client.result.URIParsedResult; import com.google.zxing.client.result.URLTOResult; import java.net.URISyntaxException; /** * Handles the result of barcode decoding in the context of the Android platform, * by dispatching the proper intents and so on. * * @author [email protected] (Sean Owen) * @author [email protected] (Daniel Switkin) */ final class ResultHandler extends Handler { private final ParsedReaderResult result; private final BarcodeReaderCaptureActivity captureActivity; ResultHandler(BarcodeReaderCaptureActivity captureActivity, ParsedReaderResult result) { this.captureActivity = captureActivity; this.result = result; } @Override public void handleMessage(Message message) { if (message.what == R.string.button_yes) { Intent intent = null; ParsedReaderResultType type = result.getType(); - if (type == ParsedReaderResultType.ADDRESSBOOK) { + if (type.equals(ParsedReaderResultType.ADDRESSBOOK)) { AddressBookDoCoMoResult addressResult = (AddressBookDoCoMoResult) result; intent = new Intent(Contacts.Intents.Insert.ACTION, Contacts.People.CONTENT_URI); putExtra(intent, Contacts.Intents.Insert.NAME, addressResult.getName()); putExtra(intent, Contacts.Intents.Insert.PHONE, addressResult.getPhoneNumbers()[0]); putExtra(intent, Contacts.Intents.Insert.EMAIL, addressResult.getEmail()); putExtra(intent, Contacts.Intents.Insert.NOTES, addressResult.getNote()); putExtra(intent, Contacts.Intents.Insert.POSTAL, addressResult.getAddress()); - } else if (type == ParsedReaderResultType.BOOKMARK) { + } else if (type.equals(ParsedReaderResultType.BOOKMARK)) { // For now, we can only open the browser, and not actually add a bookmark try { intent = new Intent(Intent.VIEW_ACTION, new ContentURI(((BookmarkDoCoMoResult) result).getURI())); } catch (URISyntaxException e) { return; } - } else if (type == ParsedReaderResultType.URLTO) { + } else if (type.equals(ParsedReaderResultType.URLTO)) { try { intent = new Intent(Intent.VIEW_ACTION, new ContentURI(((URLTOResult) result).getURI())); } catch (URISyntaxException e) { return; } - } else if (type == ParsedReaderResultType.EMAIL) { + } else if (type.equals(ParsedReaderResultType.EMAIL)) { EmailDoCoMoResult emailResult = (EmailDoCoMoResult) result; try { intent = new Intent(Intent.SENDTO_ACTION, new ContentURI(emailResult.getTo())); } catch (URISyntaxException e) { return; } putExtra(intent, "subject", emailResult.getSubject()); putExtra(intent, "body", emailResult.getBody()); - } else if (type == ParsedReaderResultType.EMAIL_ADDRESS) { + } else if (type.equals(ParsedReaderResultType.EMAIL_ADDRESS)) { EmailAddressResult emailResult = (EmailAddressResult) result; try { intent = new Intent(Intent.SENDTO_ACTION, new ContentURI(emailResult.getEmailAddress())); } catch (URISyntaxException e) { return; } - } else if (type == ParsedReaderResultType.UPC) { + } else if (type.equals(ParsedReaderResultType.UPC)) { UPCParsedResult upcResult = (UPCParsedResult) result; try { ContentURI uri = new ContentURI("http://www.upcdatabase.com/item.asp?upc=" + upcResult.getUPC()); intent = new Intent(Intent.VIEW_ACTION, uri); } catch (URISyntaxException e) { return; } - } else if (type == ParsedReaderResultType.URI) { + } else if (type.equals(ParsedReaderResultType.URI)) { URIParsedResult uriResult = (URIParsedResult) result; try { intent = new Intent(Intent.VIEW_ACTION, new ContentURI(uriResult.getURI())); } catch (URISyntaxException e) { return; } } if (intent != null) { captureActivity.startActivity(intent); } } else { captureActivity.restartPreview(); } } private static void putExtra(Intent intent, String key, String value) { if (key != null && key.length() > 0) { intent.putExtra(key, value); } } }
false
true
public void handleMessage(Message message) { if (message.what == R.string.button_yes) { Intent intent = null; ParsedReaderResultType type = result.getType(); if (type == ParsedReaderResultType.ADDRESSBOOK) { AddressBookDoCoMoResult addressResult = (AddressBookDoCoMoResult) result; intent = new Intent(Contacts.Intents.Insert.ACTION, Contacts.People.CONTENT_URI); putExtra(intent, Contacts.Intents.Insert.NAME, addressResult.getName()); putExtra(intent, Contacts.Intents.Insert.PHONE, addressResult.getPhoneNumbers()[0]); putExtra(intent, Contacts.Intents.Insert.EMAIL, addressResult.getEmail()); putExtra(intent, Contacts.Intents.Insert.NOTES, addressResult.getNote()); putExtra(intent, Contacts.Intents.Insert.POSTAL, addressResult.getAddress()); } else if (type == ParsedReaderResultType.BOOKMARK) { // For now, we can only open the browser, and not actually add a bookmark try { intent = new Intent(Intent.VIEW_ACTION, new ContentURI(((BookmarkDoCoMoResult) result).getURI())); } catch (URISyntaxException e) { return; } } else if (type == ParsedReaderResultType.URLTO) { try { intent = new Intent(Intent.VIEW_ACTION, new ContentURI(((URLTOResult) result).getURI())); } catch (URISyntaxException e) { return; } } else if (type == ParsedReaderResultType.EMAIL) { EmailDoCoMoResult emailResult = (EmailDoCoMoResult) result; try { intent = new Intent(Intent.SENDTO_ACTION, new ContentURI(emailResult.getTo())); } catch (URISyntaxException e) { return; } putExtra(intent, "subject", emailResult.getSubject()); putExtra(intent, "body", emailResult.getBody()); } else if (type == ParsedReaderResultType.EMAIL_ADDRESS) { EmailAddressResult emailResult = (EmailAddressResult) result; try { intent = new Intent(Intent.SENDTO_ACTION, new ContentURI(emailResult.getEmailAddress())); } catch (URISyntaxException e) { return; } } else if (type == ParsedReaderResultType.UPC) { UPCParsedResult upcResult = (UPCParsedResult) result; try { ContentURI uri = new ContentURI("http://www.upcdatabase.com/item.asp?upc=" + upcResult.getUPC()); intent = new Intent(Intent.VIEW_ACTION, uri); } catch (URISyntaxException e) { return; } } else if (type == ParsedReaderResultType.URI) { URIParsedResult uriResult = (URIParsedResult) result; try { intent = new Intent(Intent.VIEW_ACTION, new ContentURI(uriResult.getURI())); } catch (URISyntaxException e) { return; } } if (intent != null) { captureActivity.startActivity(intent); } } else { captureActivity.restartPreview(); } }
public void handleMessage(Message message) { if (message.what == R.string.button_yes) { Intent intent = null; ParsedReaderResultType type = result.getType(); if (type.equals(ParsedReaderResultType.ADDRESSBOOK)) { AddressBookDoCoMoResult addressResult = (AddressBookDoCoMoResult) result; intent = new Intent(Contacts.Intents.Insert.ACTION, Contacts.People.CONTENT_URI); putExtra(intent, Contacts.Intents.Insert.NAME, addressResult.getName()); putExtra(intent, Contacts.Intents.Insert.PHONE, addressResult.getPhoneNumbers()[0]); putExtra(intent, Contacts.Intents.Insert.EMAIL, addressResult.getEmail()); putExtra(intent, Contacts.Intents.Insert.NOTES, addressResult.getNote()); putExtra(intent, Contacts.Intents.Insert.POSTAL, addressResult.getAddress()); } else if (type.equals(ParsedReaderResultType.BOOKMARK)) { // For now, we can only open the browser, and not actually add a bookmark try { intent = new Intent(Intent.VIEW_ACTION, new ContentURI(((BookmarkDoCoMoResult) result).getURI())); } catch (URISyntaxException e) { return; } } else if (type.equals(ParsedReaderResultType.URLTO)) { try { intent = new Intent(Intent.VIEW_ACTION, new ContentURI(((URLTOResult) result).getURI())); } catch (URISyntaxException e) { return; } } else if (type.equals(ParsedReaderResultType.EMAIL)) { EmailDoCoMoResult emailResult = (EmailDoCoMoResult) result; try { intent = new Intent(Intent.SENDTO_ACTION, new ContentURI(emailResult.getTo())); } catch (URISyntaxException e) { return; } putExtra(intent, "subject", emailResult.getSubject()); putExtra(intent, "body", emailResult.getBody()); } else if (type.equals(ParsedReaderResultType.EMAIL_ADDRESS)) { EmailAddressResult emailResult = (EmailAddressResult) result; try { intent = new Intent(Intent.SENDTO_ACTION, new ContentURI(emailResult.getEmailAddress())); } catch (URISyntaxException e) { return; } } else if (type.equals(ParsedReaderResultType.UPC)) { UPCParsedResult upcResult = (UPCParsedResult) result; try { ContentURI uri = new ContentURI("http://www.upcdatabase.com/item.asp?upc=" + upcResult.getUPC()); intent = new Intent(Intent.VIEW_ACTION, uri); } catch (URISyntaxException e) { return; } } else if (type.equals(ParsedReaderResultType.URI)) { URIParsedResult uriResult = (URIParsedResult) result; try { intent = new Intent(Intent.VIEW_ACTION, new ContentURI(uriResult.getURI())); } catch (URISyntaxException e) { return; } } if (intent != null) { captureActivity.startActivity(intent); } } else { captureActivity.restartPreview(); } }
diff --git a/paranamer/src/java/com/thoughtworks/paranamer/BytecodeReadingParanamer.java b/paranamer/src/java/com/thoughtworks/paranamer/BytecodeReadingParanamer.java index 5820c49..6cbac66 100644 --- a/paranamer/src/java/com/thoughtworks/paranamer/BytecodeReadingParanamer.java +++ b/paranamer/src/java/com/thoughtworks/paranamer/BytecodeReadingParanamer.java @@ -1,1112 +1,1116 @@ /*** * * Portions Copyright (c) 2007 Paul Hammant * Portions copyright (c) 2000-2007 INRIA, France Telecom * 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. Neither the name of the copyright holders nor the names of its * 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 OWNER 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 com.thoughtworks.paranamer; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; /** * An ASM-based implementation of Paranamer. It relies on debug information compiled * with the "-g" javac option to retrieve parameter names. * * Portions of this source file are a fork of ASM. * * @author Guilherme Silveira * @author Paul Hammant */ public class BytecodeReadingParanamer implements Paranamer { public String[] lookupParameterNames(AccessibleObject methodOrCtor) { Class[] types = null; Class declaringClass = null; String name = null; if (methodOrCtor instanceof Method) { Method method = (Method) methodOrCtor; types = method.getParameterTypes(); name = method.getName(); declaringClass = method.getDeclaringClass(); } else { Constructor constructor = (Constructor) methodOrCtor; types = constructor.getParameterTypes(); declaringClass = constructor.getDeclaringClass(); name = "<init>"; } InputStream content = getClassAsStream(declaringClass); try { ClassReader reader = new ClassReader(content); TypeCollector visitor = new TypeCollector(name, types); reader.accept(visitor); return visitor.getParameterNamesForMethod(); } catch (IOException e) { return null; } } public int areParameterNamesAvailable(Class clazz, String constructorOrMethodName) { InputStream content = getClassAsStream(clazz.getClassLoader(), clazz.getName()); try { ClassReader reader = new ClassReader(content); //TODO - also for constructors List methods = getMatchingMethods(clazz.getClassLoader(), clazz.getName(), constructorOrMethodName); if (methods.size() == 0) { return Paranamer.NO_PARAMETER_NAMES_FOR_CLASS_AND_MEMBER; } TypeCollector visitor = new TypeCollector(constructorOrMethodName, ((Method) methods.get(0)).getParameterTypes()); reader.accept(visitor); if (visitor.isClassFound()) { if (!visitor.isMethodFound()) { return Paranamer.NO_PARAMETER_NAMES_FOR_CLASS_AND_MEMBER; } } else { return Paranamer.NO_PARAMETER_NAMES_FOR_CLASS; } return Paranamer.PARAMETER_NAMES_FOUND; } catch (IOException e) { return Paranamer.NO_PARAMETER_NAMES_LIST; } catch (ClassNotFoundException e) { e.printStackTrace(); } return 0; } private InputStream getClassAsStream(Class clazz) { ClassLoader classLoader = clazz.getClassLoader(); return getClassAsStream(classLoader, clazz.getName()); } private InputStream getClassAsStream(ClassLoader classLoader, String className) { String name = '/' + className.replace('.', '/') + ".class"; // better pre-cache all methods otherwise this content will be loaded // multiple times InputStream asStream = classLoader.getResourceAsStream(name); if (asStream == null) { asStream = BytecodeReadingParanamer.class.getResourceAsStream(name); } return asStream; } private List getMatchingMethods(ClassLoader classLoader, String className, String name) throws ClassNotFoundException { List list = new ArrayList(); Method[] methods = classLoader.loadClass(className).getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().equals(name)) { list.add(method); } } return list; } /** * The type collector waits for an specific method in order to start a method * collector. * * @author Guilherme Silveira */ private static class TypeCollector { private static final String COMMA = ","; private final String methodName; private final Class[] parameterTypes; private MethodCollector collector; private boolean methodFound = false; private boolean classFound = false; private TypeCollector(String methodName, Class[] parameterTypes) { this.methodName = methodName; this.parameterTypes = parameterTypes; this.collector = null; } public MethodCollector visitMethod(int access, String name, String desc) { // already found the method, skip any processing classFound = true; if (collector != null) { return null; } // not the same name if (!name.equals(methodName)) { return null; } methodFound = true; Type[] argumentTypes = Type.getArgumentTypes(desc); int longOrDoubleQuantity = 0; for (int i1 = 0; i1 < argumentTypes.length; i1++) { Type t = argumentTypes[i1]; if (t.getClassName().equals("long") || t.getClassName().equals("double")) { longOrDoubleQuantity++; } } int paramCount = argumentTypes.length; // not the same quantity of parameters if (paramCount != this.parameterTypes.length) { return null; } for (int i = 0; i < argumentTypes.length; i++) { if (!argumentTypes[i].getClassName().equals( this.parameterTypes[i].getName())) { return null; } } this.collector = new MethodCollector((Modifier.isStatic(access) ? 0 : 1), argumentTypes.length + longOrDoubleQuantity); return collector; } private String[] getParameterNamesForMethod() { if (collector == null) { return null; } if (!collector.isDebugInfoPresent()) { return null; } return collector.getResult().split(COMMA); } private boolean isMethodFound() { return methodFound; } private boolean isClassFound() { return classFound; } } /** * Objects of this class collects information from a specific method. * * @author Guilherme Silveira */ private static class MethodCollector { private final int paramCount; private final int ignoreCount; private int currentParameter; private final StringBuffer result; private boolean debugInfoPresent; private MethodCollector(int ignoreCount, int paramCount) { this.ignoreCount = ignoreCount; this.paramCount = paramCount; this.result = new StringBuffer(); this.currentParameter = 0; // if there are 0 parameters, there is no need for debug info this.debugInfoPresent = paramCount == 0 ? true : false; } public void visitLocalVariable(String name, int index) { if (index >= ignoreCount && index < ignoreCount + paramCount) { if (!name.equals("arg" + currentParameter)) { debugInfoPresent = true; } result.append(','); result.append(name); currentParameter++; } } private String getResult() { return result.length() != 0 ? result.substring(1) : ""; } private boolean isDebugInfoPresent() { return debugInfoPresent; } } /*** * Portions Copyright (c) 2007 Paul Hammant * Portions copyright (c) 2000-2007 INRIA, France Telecom * 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. Neither the name of the copyright holders nor the names of its * 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 OWNER 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. */ /** * A Java class parser to make a Class Visitor visit an existing class. * This class parses a byte array conforming to the Java class file format and * calls the appropriate visit methods of a given class visitor for each field, * method and bytecode instruction encountered. * * @author Eric Bruneton * @author Eugene Kuleshov */ private static class ClassReader { /** * The class to be parsed. <i>The content of this array must not be * modified. This field is intended for Attribute sub classes, and * is normally not needed by class generators or adapters.</i> */ public final byte[] b; /** * The start index of each constant pool item in {@link #b b}, plus one. * The one byte offset skips the constant pool item tag that indicates its * type. */ private final int[] items; /** * The String objects corresponding to the CONSTANT_Utf8 items. This cache * avoids multiple parsing of a given CONSTANT_Utf8 constant pool item, * which GREATLY improves performances (by a factor 2 to 3). This caching * strategy could be extended to all constant pool items, but its benefit * would not be so great for these items (because they are much less * expensive to parse than CONSTANT_Utf8 items). */ private final String[] strings; /** * Maximum length of the strings contained in the constant pool of the * class. */ private final int maxStringLength; /** * Start index of the class header information (access, name...) in * {@link #b b}. */ public final int header; /** * The type of CONSTANT_Fieldref constant pool items. */ final static int FIELD = 9; /** * The type of CONSTANT_Methodref constant pool items. */ final static int METH = 10; /** * The type of CONSTANT_InterfaceMethodref constant pool items. */ final static int IMETH = 11; /** * The type of CONSTANT_Integer constant pool items. */ final static int INT = 3; /** * The type of CONSTANT_Float constant pool items. */ final static int FLOAT = 4; /** * The type of CONSTANT_Long constant pool items. */ final static int LONG = 5; /** * The type of CONSTANT_Double constant pool items. */ final static int DOUBLE = 6; /** * The type of CONSTANT_NameAndType constant pool items. */ final static int NAME_TYPE = 12; /** * The type of CONSTANT_Utf8 constant pool items. */ final static int UTF8 = 1; // ------------------------------------------------------------------------ // Constructors // ------------------------------------------------------------------------ /** * Constructs a new {@link ClassReader} object. * * @param b the bytecode of the class to be read. */ private ClassReader(final byte[] b) { this(b, 0); } /** * Constructs a new {@link ClassReader} object. * * @param b the bytecode of the class to be read. * @param off the start offset of the class data. */ private ClassReader(final byte[] b, final int off) { this.b = b; // parses the constant pool items = new int[readUnsignedShort(off + 8)]; int n = items.length; strings = new String[n]; int max = 0; int index = off + 10; for (int i = 1; i < n; ++i) { items[i] = index + 1; int size; switch (b[index]) { case FIELD: case METH: case IMETH: case INT: case FLOAT: case NAME_TYPE: size = 5; break; case LONG: case DOUBLE: size = 9; ++i; break; case UTF8: size = 3 + readUnsignedShort(index + 1); if (size > max) { max = size; } break; // case HamConstants.CLASS: // case HamConstants.STR: default: size = 3; break; } index += size; } maxStringLength = max; // the class header information starts just after the constant pool header = index; } /** * Constructs a new {@link ClassReader} object. * * @param is an input stream from which to read the class. * @throws IOException if a problem occurs during reading. */ private ClassReader(final InputStream is) throws IOException { this(readClass(is)); } /** * Reads the bytecode of a class. * * @param is an input stream from which to read the class. * @return the bytecode read from the given input stream. * @throws IOException if a problem occurs during reading. */ private static byte[] readClass(final InputStream is) throws IOException { if (is == null) { throw new IOException("Class not found"); } byte[] b = new byte[is.available()]; int len = 0; while (true) { int n = is.read(b, len, b.length - len); if (n == -1) { if (len < b.length) { byte[] c = new byte[len]; System.arraycopy(b, 0, c, 0, len); b = c; } return b; } len += n; if (len == b.length) { byte[] c = new byte[b.length + 1000]; System.arraycopy(b, 0, c, 0, len); b = c; } } } // ------------------------------------------------------------------------ // Public methods // ------------------------------------------------------------------------ /** * Makes the given visitor visit the Java class of this {@link ClassReader}. * This class is the one specified in the constructor (see * {@link #ClassReader(byte[]) ClassReader}). * * @param classVisitor the visitor that must visit this class. */ private void accept(final TypeCollector classVisitor) { char[] c = new char[maxStringLength]; // buffer used to read strings int i, j, k; // loop variables int u, v, w; // indexes in b String attrName; int anns = 0; int ianns = 0; // visits the header u = header; v = items[readUnsignedShort(u + 4)]; int len = readUnsignedShort(u + 6); w = 0; u += 8; for (i = 0; i < len; ++i) { u += 2; } v = u; i = readUnsignedShort(v); v += 2; for (; i > 0; --i) { j = readUnsignedShort(v + 6); v += 8; for (; j > 0; --j) { v += 6 + readInt(v + 2); } } i = readUnsignedShort(v); v += 2; for (; i > 0; --i) { j = readUnsignedShort(v + 6); v += 8; for (; j > 0; --j) { v += 6 + readInt(v + 2); } } i = readUnsignedShort(v); v += 2; for (; i > 0; --i) { v += 6 + readInt(v + 2); } // visits the class annotations for (i = 1; i >= 0; --i) { v = i == 0 ? ianns : anns; if (v != 0) { v += 2; } } // visits the fields i = readUnsignedShort(u); u += 2; for (; i > 0; --i) { j = readUnsignedShort(u + 6); u += 8; for (; j > 0; --j) { u += 6 + readInt(u + 2); } } // visits the methods i = readUnsignedShort(u); u += 2; for (; i > 0; --i) { u = readMethod(classVisitor, c, u); } } private int readMethod(TypeCollector classVisitor, char[] c, int u) { int v; int w; int j; String attrName; int k; int access = readUnsignedShort(u); String name = readUTF8(u + 2, c); String desc = readUTF8(u + 4, c); v = 0; w = 0; // looks for Code and Exceptions attributes j = readUnsignedShort(u + 6); u += 8; for (; j > 0; --j) { attrName = readUTF8(u, c); int attrSize = readInt(u + 2); u += 6; // tests are sorted in decreasing frequency order // (based on frequencies observed on typical classes) if (attrName.equals("Code")) { v = u; } u += attrSize; } // reads declared exceptions if (w == 0) { } else { w += 2; for (j = 0; j < readUnsignedShort(w); ++j) { w += 2; } } // visits the method's code, if any MethodCollector mv = classVisitor.visitMethod(access, name, desc); if (mv != null && v != 0) { int codeLength = readInt(v + 4); v += 8; int codeStart = v; int codeEnd = v + codeLength; v = codeEnd; j = readUnsignedShort(v); v += 2; for (; j > 0; --j) { v += 8; } // parses the local variable, line number tables, and code // attributes int varTable = 0; int varTypeTable = 0; j = readUnsignedShort(v); v += 2; for (; j > 0; --j) { attrName = readUTF8(v, c); if (attrName.equals("LocalVariableTable")) { varTable = v + 6; } else if (attrName.equals("LocalVariableTypeTable")) { varTypeTable = v + 6; } v += 6 + readInt(v + 2); } v = codeStart; // visits the local variable tables if (varTable != 0) { if (varTypeTable != 0) { k = readUnsignedShort(varTypeTable) * 3; w = varTypeTable + 2; + int[] typeTable = new int[k]; while (k > 0) { + typeTable[--k] = w + 6; // signature + typeTable[--k] = readUnsignedShort(w + 8); // index + typeTable[--k] = readUnsignedShort(w); // start w += 10; } } k = readUnsignedShort(varTable); w = varTable + 2; for (; k > 0; --k) { int index = readUnsignedShort(w + 8); mv.visitLocalVariable(readUTF8(w + 4, c), index); w += 10; } } } return u; } /** * Reads an unsigned short value in {@link #b b}. <i>This method is * intended for Attribute sub classes, and is normally not needed by * class generators or adapters.</i> * * @param index the start index of the value to be read in {@link #b b}. * @return the read value. */ private int readUnsignedShort(final int index) { byte[] b = this.b; return ((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF); } /** * Reads a signed int value in {@link #b b}. <i>This method is intended for * Attribute sub classes, and is normally not needed by class * generators or adapters.</i> * * @param index the start index of the value to be read in {@link #b b}. * @return the read value. */ private int readInt(final int index) { byte[] b = this.b; return ((b[index] & 0xFF) << 24) | ((b[index + 1] & 0xFF) << 16) | ((b[index + 2] & 0xFF) << 8) | (b[index + 3] & 0xFF); } /** * Reads an UTF8 string constant pool item in {@link #b b}. <i>This method * is intended for Attribute sub classes, and is normally not needed * by class generators or adapters.</i> * * @param index the start index of an unsigned short value in {@link #b b}, * whose value is the index of an UTF8 constant pool item. * @param buf buffer to be used to read the item. This buffer must be * sufficiently large. It is not automatically resized. * @return the String corresponding to the specified UTF8 item. */ private String readUTF8(int index, final char[] buf) { int item = readUnsignedShort(index); String s = strings[item]; if (s != null) { return s; } index = items[item]; return strings[item] = readUTF(index + 2, readUnsignedShort(index), buf); } /** * Reads UTF8 string in {@link #b b}. * * @param index start offset of the UTF8 string to be read. * @param utfLen length of the UTF8 string to be read. * @param buf buffer to be used to read the string. This buffer must be * sufficiently large. It is not automatically resized. * @return the String corresponding to the specified UTF8 string. */ private String readUTF(int index, final int utfLen, final char[] buf) { int endIndex = index + utfLen; byte[] b = this.b; int strLen = 0; int c, d, e; while (index < endIndex) { c = b[index++] & 0xFF; switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: // 0xxxxxxx buf[strLen++] = (char) c; break; case 12: case 13: // 110x xxxx 10xx xxxx d = b[index++]; buf[strLen++] = (char) (((c & 0x1F) << 6) | (d & 0x3F)); break; default: // 1110 xxxx 10xx xxxx 10xx xxxx d = b[index++]; e = b[index++]; buf[strLen++] = (char) (((c & 0x0F) << 12) | ((d & 0x3F) << 6) | (e & 0x3F)); break; } } return new String(buf, 0, strLen); } } /*** * Portions Copyright (c) 2007 Paul Hammant * Portions copyright (c) 2000-2007 INRIA, France Telecom * 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. Neither the name of the copyright holders nor the names of its * 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 OWNER 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. */ /** * A Java type. This class can be used to make it easier to manipulate type and * method descriptors. * * @author Eric Bruneton * @author Chris Nokleberg */ private static class Type { /** * The sort of the <tt>void</tt> type. */ private final static int VOID = 0; /** * The sort of the <tt>boolean</tt> type. */ private final static int BOOLEAN = 1; /** * The sort of the <tt>char</tt> type. */ private final static int CHAR = 2; /** * The sort of the <tt>byte</tt> type. */ private final static int BYTE = 3; /** * The sort of the <tt>short</tt> type. */ private final static int SHORT = 4; /** * The sort of the <tt>int</tt> type. */ private final static int INT = 5; /** * The sort of the <tt>float</tt> type. */ private final static int FLOAT = 6; /** * The sort of the <tt>long</tt> type. */ private final static int LONG = 7; /** * The sort of the <tt>double</tt> type. */ private final static int DOUBLE = 8; /** * The sort of array reference types. */ private final static int ARRAY = 9; /** * The sort of object reference type. */ private final static int OBJECT = 10; /** * The <tt>void</tt> type. */ private final static Type VOID_TYPE = new Type(VOID); /** * The <tt>boolean</tt> type. */ private final static Type BOOLEAN_TYPE = new Type(BOOLEAN); /** * The <tt>char</tt> type. */ private final static Type CHAR_TYPE = new Type(CHAR); /** * The <tt>byte</tt> type. */ private final static Type BYTE_TYPE = new Type(BYTE); /** * The <tt>short</tt> type. */ private final static Type SHORT_TYPE = new Type(SHORT); /** * The <tt>int</tt> type. */ private final static Type INT_TYPE = new Type(INT); /** * The <tt>float</tt> type. */ private final static Type FLOAT_TYPE = new Type(FLOAT); /** * The <tt>long</tt> type. */ private final static Type LONG_TYPE = new Type(LONG); /** * The <tt>double</tt> type. */ private final static Type DOUBLE_TYPE = new Type(DOUBLE); // ------------------------------------------------------------------------ // Fields // ------------------------------------------------------------------------ /** * The sort of this Java type. */ private final int sort; /** * A buffer containing the internal name of this Java type. This field is * only used for reference types. */ private char[] buf; /** * The offset of the internal name of this Java type in {@link #buf buf}. * This field is only used for reference types. */ private int off; /** * The length of the internal name of this Java type. This field is only * used for reference types. */ private int len; // ------------------------------------------------------------------------ // Constructors // ------------------------------------------------------------------------ /** * Constructs a primitive type. * * @param sort the sort of the primitive type to be constructed. */ private Type(final int sort) { this.sort = sort; this.len = 1; } /** * Constructs a reference type. * * @param sort the sort of the reference type to be constructed. * @param buf a buffer containing the descriptor of the previous type. * @param off the offset of this descriptor in the previous buffer. * @param len the length of this descriptor. */ private Type(final int sort, final char[] buf, final int off, final int len) { this.sort = sort; this.buf = buf; this.off = off; this.len = len; } /** * Returns the Java types corresponding to the argument types of the given * method descriptor. * * @param methodDescriptor a method descriptor. * @return the Java types corresponding to the argument types of the given * method descriptor. */ private static Type[] getArgumentTypes(final String methodDescriptor) { char[] buf = methodDescriptor.toCharArray(); int off = 1; int size = 0; while (true) { char car = buf[off++]; if (car == ')') { break; } else if (car == 'L') { while (buf[off++] != ';') { } ++size; } else if (car != '[') { ++size; } } Type[] args = new Type[size]; off = 1; size = 0; while (buf[off] != ')') { args[size] = getType(buf, off); off += args[size].len + (args[size].sort == OBJECT ? 2 : 0); size += 1; } return args; } /** * Returns the Java type corresponding to the given type descriptor. * * @param buf a buffer containing a type descriptor. * @param off the offset of this descriptor in the previous buffer. * @return the Java type corresponding to the given type descriptor. */ private static Type getType(final char[] buf, final int off) { int len; switch (buf[off]) { case 'V': return VOID_TYPE; case 'Z': return BOOLEAN_TYPE; case 'C': return CHAR_TYPE; case 'B': return BYTE_TYPE; case 'S': return SHORT_TYPE; case 'I': return INT_TYPE; case 'F': return FLOAT_TYPE; case 'J': return LONG_TYPE; case 'D': return DOUBLE_TYPE; case '[': len = 1; while (buf[off + len] == '[') { ++len; } if (buf[off + len] == 'L') { ++len; while (buf[off + len] != ';') { ++len; } } return new Type(ARRAY, buf, off, len + 1); // case 'L': default: len = 1; while (buf[off + len] != ';') { ++len; } return new Type(OBJECT, buf, off + 1, len - 1); } } // ------------------------------------------------------------------------ // Accessors // ------------------------------------------------------------------------ /** * Returns the number of dimensions of this array type. This method should * only be used for an array type. * * @return the number of dimensions of this array type. */ private int getDimensions() { int i = 1; while (buf[off + i] == '[') { ++i; } return i; } /** * Returns the type of the elements of this array type. This method should * only be used for an array type. * * @return Returns the type of the elements of this array type. */ private Type getElementType() { return getType(buf, off + getDimensions()); } /** * Returns the name of the class corresponding to this type. * * @return the fully qualified name of the class corresponding to this type. */ private String getClassName() { switch (sort) { case VOID: return "void"; case BOOLEAN: return "boolean"; case CHAR: return "char"; case BYTE: return "byte"; case SHORT: return "short"; case INT: return "int"; case FLOAT: return "float"; case LONG: return "long"; case DOUBLE: return "double"; case ARRAY: StringBuffer b = new StringBuffer(getElementType().getClassName()); for (int i = getDimensions(); i > 0; --i) { b.append("[]"); } return b.toString(); // case OBJECT: default: return new String(buf, off, len).replace('/', '.'); } } } }
false
true
private int readMethod(TypeCollector classVisitor, char[] c, int u) { int v; int w; int j; String attrName; int k; int access = readUnsignedShort(u); String name = readUTF8(u + 2, c); String desc = readUTF8(u + 4, c); v = 0; w = 0; // looks for Code and Exceptions attributes j = readUnsignedShort(u + 6); u += 8; for (; j > 0; --j) { attrName = readUTF8(u, c); int attrSize = readInt(u + 2); u += 6; // tests are sorted in decreasing frequency order // (based on frequencies observed on typical classes) if (attrName.equals("Code")) { v = u; } u += attrSize; } // reads declared exceptions if (w == 0) { } else { w += 2; for (j = 0; j < readUnsignedShort(w); ++j) { w += 2; } } // visits the method's code, if any MethodCollector mv = classVisitor.visitMethod(access, name, desc); if (mv != null && v != 0) { int codeLength = readInt(v + 4); v += 8; int codeStart = v; int codeEnd = v + codeLength; v = codeEnd; j = readUnsignedShort(v); v += 2; for (; j > 0; --j) { v += 8; } // parses the local variable, line number tables, and code // attributes int varTable = 0; int varTypeTable = 0; j = readUnsignedShort(v); v += 2; for (; j > 0; --j) { attrName = readUTF8(v, c); if (attrName.equals("LocalVariableTable")) { varTable = v + 6; } else if (attrName.equals("LocalVariableTypeTable")) { varTypeTable = v + 6; } v += 6 + readInt(v + 2); } v = codeStart; // visits the local variable tables if (varTable != 0) { if (varTypeTable != 0) { k = readUnsignedShort(varTypeTable) * 3; w = varTypeTable + 2; while (k > 0) { w += 10; } } k = readUnsignedShort(varTable); w = varTable + 2; for (; k > 0; --k) { int index = readUnsignedShort(w + 8); mv.visitLocalVariable(readUTF8(w + 4, c), index); w += 10; } } } return u; }
private int readMethod(TypeCollector classVisitor, char[] c, int u) { int v; int w; int j; String attrName; int k; int access = readUnsignedShort(u); String name = readUTF8(u + 2, c); String desc = readUTF8(u + 4, c); v = 0; w = 0; // looks for Code and Exceptions attributes j = readUnsignedShort(u + 6); u += 8; for (; j > 0; --j) { attrName = readUTF8(u, c); int attrSize = readInt(u + 2); u += 6; // tests are sorted in decreasing frequency order // (based on frequencies observed on typical classes) if (attrName.equals("Code")) { v = u; } u += attrSize; } // reads declared exceptions if (w == 0) { } else { w += 2; for (j = 0; j < readUnsignedShort(w); ++j) { w += 2; } } // visits the method's code, if any MethodCollector mv = classVisitor.visitMethod(access, name, desc); if (mv != null && v != 0) { int codeLength = readInt(v + 4); v += 8; int codeStart = v; int codeEnd = v + codeLength; v = codeEnd; j = readUnsignedShort(v); v += 2; for (; j > 0; --j) { v += 8; } // parses the local variable, line number tables, and code // attributes int varTable = 0; int varTypeTable = 0; j = readUnsignedShort(v); v += 2; for (; j > 0; --j) { attrName = readUTF8(v, c); if (attrName.equals("LocalVariableTable")) { varTable = v + 6; } else if (attrName.equals("LocalVariableTypeTable")) { varTypeTable = v + 6; } v += 6 + readInt(v + 2); } v = codeStart; // visits the local variable tables if (varTable != 0) { if (varTypeTable != 0) { k = readUnsignedShort(varTypeTable) * 3; w = varTypeTable + 2; int[] typeTable = new int[k]; while (k > 0) { typeTable[--k] = w + 6; // signature typeTable[--k] = readUnsignedShort(w + 8); // index typeTable[--k] = readUnsignedShort(w); // start w += 10; } } k = readUnsignedShort(varTable); w = varTable + 2; for (; k > 0; --k) { int index = readUnsignedShort(w + 8); mv.visitLocalVariable(readUTF8(w + 4, c), index); w += 10; } } } return u; }
diff --git a/plugins/org.eclipse.jst.j2ee/j2eecreation/org/eclipse/jst/j2ee/componentcore/J2EEModuleVirtualComponent.java b/plugins/org.eclipse.jst.j2ee/j2eecreation/org/eclipse/jst/j2ee/componentcore/J2EEModuleVirtualComponent.java index aed33b2c9..59b74b106 100644 --- a/plugins/org.eclipse.jst.j2ee/j2eecreation/org/eclipse/jst/j2ee/componentcore/J2EEModuleVirtualComponent.java +++ b/plugins/org.eclipse.jst.j2ee/j2eecreation/org/eclipse/jst/j2ee/componentcore/J2EEModuleVirtualComponent.java @@ -1,408 +1,410 @@ /******************************************************************************* * Copyright (c) 2003, 2007 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.jst.j2ee.componentcore; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.IClasspathAttribute; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jst.common.jdt.internal.javalite.IJavaProjectLite; import org.eclipse.jst.common.jdt.internal.javalite.JavaCoreLite; import org.eclipse.jst.common.jdt.internal.javalite.JavaLiteUtilities; import org.eclipse.jst.j2ee.classpathdep.ClasspathDependencyUtil; import org.eclipse.jst.j2ee.commonarchivecore.internal.helpers.ArchiveManifest; import org.eclipse.jst.j2ee.commonarchivecore.internal.helpers.ArchiveManifestImpl; import org.eclipse.jst.j2ee.commonarchivecore.internal.util.ArchiveUtil; import org.eclipse.jst.j2ee.internal.J2EEConstants; import org.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyEnablement; import org.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyVirtualComponent; import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; import org.eclipse.jst.j2ee.project.EarUtilities; import org.eclipse.jst.j2ee.project.JavaEEProjectUtilities; import org.eclipse.wst.common.componentcore.ComponentCore; import org.eclipse.wst.common.componentcore.internal.resources.VirtualArchiveComponent; import org.eclipse.wst.common.componentcore.internal.resources.VirtualComponent; import org.eclipse.wst.common.componentcore.internal.resources.VirtualFolder; import org.eclipse.wst.common.componentcore.internal.resources.VirtualReference; import org.eclipse.wst.common.componentcore.internal.util.IComponentImplFactory; import org.eclipse.wst.common.componentcore.resources.IVirtualComponent; import org.eclipse.wst.common.componentcore.resources.IVirtualFile; import org.eclipse.wst.common.componentcore.resources.IVirtualFolder; import org.eclipse.wst.common.componentcore.resources.IVirtualReference; public class J2EEModuleVirtualComponent extends VirtualComponent implements IComponentImplFactory { public static String GET_JAVA_REFS = "GET_JAVA_REFS"; //$NON-NLS-1$ public static String GET_FUZZY_EAR_REFS = "GET_FUZZY_EAR_REFS"; //$NON-NLS-1$ public J2EEModuleVirtualComponent() { super(); } public J2EEModuleVirtualComponent(IProject aProject, IPath aRuntimePath) { super(aProject, aRuntimePath); } public IVirtualComponent createComponent(IProject aProject) { return new J2EEModuleVirtualComponent(aProject, new Path("/")); //$NON-NLS-1$ } public IVirtualComponent createArchiveComponent(IProject aProject, String archiveLocation, IPath aRuntimePath) { return new J2EEModuleVirtualArchiveComponent(aProject, archiveLocation, aRuntimePath); } public IVirtualFolder createFolder(IProject aProject, IPath aRuntimePath) { return new VirtualFolder(aProject, aRuntimePath); } /** * Retrieves all references except those computed dynamically from * tagged Java classpath entries. * @return IVirtualReferences for all non-Java classpath entry references. */ public IVirtualReference[] getNonJavaReferences() { return getReferences(false, false); } @Override public IVirtualReference[] getReferences(Map<String, Object> options) { Object ignoreDerived = options.get(IGNORE_DERIVED_REFERENCES); Object objGetJavaRefs = options.get(GET_JAVA_REFS); Object objGetFuzzyEarRefs = options.get(GET_FUZZY_EAR_REFS); boolean ignoreDerivedRefs = ignoreDerived != null ? ((Boolean)ignoreDerived).booleanValue() : false; boolean getJavaRefs = objGetJavaRefs != null ? ((Boolean)objGetJavaRefs).booleanValue() : true; boolean findFuzzyEARRefs = objGetFuzzyEarRefs != null ? ((Boolean)objGetFuzzyEarRefs).booleanValue() : false; if( ignoreDerivedRefs ) return getReferences(false, false); return getReferences(getJavaRefs, findFuzzyEARRefs); } @Override public IVirtualReference[] getReferences() { return getReferences(true, false); } public IVirtualReference[] getReferences(final boolean getJavaRefs, final boolean findFuzzyEARRefs) { IVirtualReference[] hardReferences = getNonManifestReferences(getJavaRefs); // retrieve the dynamic references specified via the MANIFEST.MF classpath List dynamicReferences = J2EEModuleVirtualComponent.getManifestReferences(this, hardReferences, findFuzzyEARRefs); IVirtualReference[] references = null; if (dynamicReferences == null) { references = hardReferences; } else { references = new IVirtualReference[hardReferences.length + dynamicReferences.size()]; System.arraycopy(hardReferences, 0, references, 0, hardReferences.length); for (int i = 0; i < dynamicReferences.size(); i++) { references[hardReferences.length + i] = (IVirtualReference) dynamicReferences.get(i); } } return references; } public IVirtualReference[] getNonManifestReferences() { return getNonManifestReferences(true); } public IVirtualReference[] getNonManifestReferences(final boolean getJavaRefs) { final List allRefs = new ArrayList(); // add component file references Map<String, Object> superMap = new HashMap<String,Object>(); superMap.put(IGNORE_DERIVED_REFERENCES, true); IVirtualReference[] hardReferences = super.getReferences(superMap); for (int i = 0; i < hardReferences.length; i++) { allRefs.add(hardReferences[i]); } // add the dynamic references specified via specially tagged JDT classpath entries if (getJavaRefs) { IVirtualReference[] cpRefs = getJavaClasspathReferences(hardReferences); for (int i = 0; i < cpRefs.length; i++) { allRefs.add(cpRefs[i]); } } return (IVirtualReference[]) allRefs.toArray(new IVirtualReference[allRefs.size()]); } public static String [] getManifestClasspath(IVirtualComponent moduleComponent) { String[] manifestClasspath = null; if(!moduleComponent.isBinary()){ IVirtualFile vManifest = moduleComponent.getRootFolder().getFile(J2EEConstants.MANIFEST_URI); if (vManifest.exists()) { IFile manifestFile = vManifest.getUnderlyingFile(); InputStream in = null; try { in = manifestFile.getContents(); ArchiveManifest manifest = new ArchiveManifestImpl(in); manifestClasspath = manifest.getClassPathTokenized(); } catch (IOException e) { J2EEPlugin.logError(e); } catch (CoreException e) { J2EEPlugin.logError(e); } finally { if (in != null) { try { in.close(); in = null; } catch (IOException e) { J2EEPlugin.logError(e); } } } } } else { manifestClasspath = ((J2EEModuleVirtualArchiveComponent)moduleComponent).getManifestClasspath(); } return manifestClasspath; } public IVirtualReference[] getJavaClasspathReferences() { return getJavaClasspathReferences(null); } private IVirtualReference[] getJavaClasspathReferences(IVirtualReference[] hardReferences) { final boolean isWebApp = JavaEEProjectUtilities.isDynamicWebComponent(this); if(!isWebApp && !ClasspathDependencyEnablement.isAllowClasspathComponentDependency()){ return new IVirtualReference[0]; } final IProject project = getProject(); final List cpRefs = new ArrayList(); try { if (project == null || !project.isAccessible() || !project.hasNature(JavaCoreLite.NATURE_ID)) { return new IVirtualReference[0]; } final IJavaProjectLite javaProjectLite = JavaCoreLite.create(project); if (javaProjectLite == null) { return new IVirtualReference[0]; } // retrieve all referenced classpath entries final Map referencedEntries = ClasspathDependencyUtil.getComponentClasspathDependencies(javaProjectLite, isWebApp); if (referencedEntries.isEmpty()) { return new IVirtualReference[0]; } IVirtualReference[] innerHardReferences = hardReferences; if (innerHardReferences == null) { // only compute this not set and if we have some cp dependencies - innerHardReferences = super.getReferences(); + HashMap<String, Object> map = new HashMap<String, Object>(); + map.put(IVirtualComponent.IGNORE_DERIVED_REFERENCES, new Boolean(true)); + innerHardReferences = super.getReferences(map); } final IPath[] hardRefPaths = new IPath[innerHardReferences.length]; for (int j = 0; j < innerHardReferences.length; j++) { final IVirtualComponent comp = innerHardReferences[j].getReferencedComponent(); if (comp.isBinary()) { final VirtualArchiveComponent archiveComp = (VirtualArchiveComponent) comp; final File diskFile = archiveComp.getUnderlyingDiskFile(); IPath diskPath = null; if (diskFile.exists()) { diskPath =new Path(diskFile.getAbsolutePath()); } else { final IFile iFile = archiveComp.getUnderlyingWorkbenchFile(); diskPath = iFile.getFullPath(); } hardRefPaths[j] = diskPath; } } IContainer[] mappedClassFolders = null; final Iterator i = referencedEntries.keySet().iterator(); while (i.hasNext()) { final IClasspathEntry entry = (IClasspathEntry) i.next(); final IClasspathAttribute attrib = (IClasspathAttribute) referencedEntries.get(entry); final boolean isClassFolder = ClasspathDependencyUtil.isClassFolderEntry(entry); final IPath runtimePath = ClasspathDependencyUtil.getRuntimePath(attrib, isWebApp, isClassFolder); boolean add = true; final IPath entryLocation = ClasspathDependencyUtil.getEntryLocation(entry); if (entryLocation == null) { // unable to retrieve location for cp entry, do not contribute as a virtual ref add = false; } else if (!isClassFolder) { // check hard archive refs for (int j = 0; j < hardRefPaths.length; j++) { if (entryLocation.equals(hardRefPaths[j])) { // entry resolves to same file as existing hard reference, can skip add = false; break; } } } else { // check class folders mapped in component file as class folders associated with mapped src folders if (mappedClassFolders == null) { List <IContainer> containers = JavaLiteUtilities.getJavaOutputContainers(this); mappedClassFolders = containers.toArray(new IContainer[containers.size()]); } for (int j = 0; j < mappedClassFolders.length; j++) { if (entryLocation.equals(mappedClassFolders[j].getFullPath())) { // entry resolves to same file as existing class folder mapping, skip add = false; break; } } } if (add && entryLocation != null) { String componentPath = null; ClasspathDependencyVirtualComponent entryComponent = null; /* if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { componentPath = VirtualArchiveComponent.CLASSPATHARCHIVETYPE; final IProject cpEntryProject = ResourcesPlugin.getWorkspace().getRoot().getProject(entry.getPath().lastSegment()); entryComponent = (VirtualArchiveComponent) ComponentCore.createArchiveComponent(cpEntryProject, componentPath); } else { */ componentPath = VirtualArchiveComponent.CLASSPATHARCHIVETYPE + IPath.SEPARATOR + entryLocation.toPortableString(); entryComponent = new ClasspathDependencyVirtualComponent(project, componentPath, isClassFolder); //} final IVirtualReference entryReference = ComponentCore.createReference(this, entryComponent, runtimePath); ((VirtualReference)entryReference).setDerived(true); entryReference.setArchiveName(ClasspathDependencyUtil.getArchiveName(entry)); cpRefs.add(entryReference); } } } catch (CoreException jme) { J2EEPlugin.logError(jme); } return (IVirtualReference[]) cpRefs.toArray(new IVirtualReference[cpRefs.size()]); } public static List getManifestReferences(IVirtualComponent moduleComponent, IVirtualReference[] hardReferences) { return getManifestReferences(moduleComponent, hardReferences, false); } public static List getManifestReferences(IVirtualComponent moduleComponent, IVirtualReference[] hardReferences, boolean findFuzzyEARRefs) { List dynamicReferences = null; String [] manifestClasspath = getManifestClasspath(moduleComponent); IVirtualReference foundRef = null; String earArchiveURI = null; //The URI for this archive in the EAR boolean simplePath = false; if (manifestClasspath != null && manifestClasspath.length > 0) { boolean [] foundRefAlready = findFuzzyEARRefs ? new boolean[manifestClasspath.length]: null; if(null != foundRefAlready){ for(int i=0; i<foundRefAlready.length; i++){ foundRefAlready[i] = false; } } IProject [] earProjects = EarUtilities.getReferencingEARProjects(moduleComponent.getProject()); for (IProject earProject : earProjects) { if(!JavaEEProjectUtilities.isEARProject(earProject)){ continue; } IVirtualReference[] earRefs = null; IVirtualComponent tempEARComponent = ComponentCore.createComponent(earProject); IVirtualReference[] tempEarRefs = tempEARComponent.getReferences(); for (int j = 0; j < tempEarRefs.length && earRefs == null; j++) { if (tempEarRefs[j].getReferencedComponent().equals(moduleComponent)) { earRefs = tempEarRefs; foundRef = tempEarRefs[j]; earArchiveURI = foundRef.getArchiveName(); simplePath = earArchiveURI != null ? earArchiveURI.lastIndexOf("/") == -1 : true; //$NON-NLS-1$ } } if (null != earRefs) { for (int manifestIndex = 0; manifestIndex < manifestClasspath.length; manifestIndex++) { boolean found = false; if(foundRefAlready != null && foundRefAlready[manifestIndex]){ continue; } for (int j = 0; j < earRefs.length && !found; j++) { if(foundRef != earRefs[j]){ String archiveName = earRefs[j].getArchiveName(); if (null != archiveName){ boolean shouldAdd = false; String manifestEntryString = manifestClasspath[manifestIndex]; if( manifestEntryString != null ){ IPath manifestPath = new Path(manifestEntryString); manifestEntryString = manifestPath.toPortableString(); } if(simplePath && manifestEntryString != null && manifestEntryString.lastIndexOf("/") == -1){ //$NON-NLS-1$ shouldAdd = archiveName.equals(manifestEntryString); } else { String earRelativeURI = ArchiveUtil.deriveEARRelativeURI(manifestEntryString, earArchiveURI); if(null != earRelativeURI){ shouldAdd = earRelativeURI.equals(archiveName); } } if(shouldAdd){ if(findFuzzyEARRefs && foundRefAlready != null){ foundRefAlready[manifestIndex] = true; } found = true; boolean shouldInclude = true; IVirtualComponent dynamicComponent = earRefs[j].getReferencedComponent(); if(null != hardReferences){ for (int k = 0; k < hardReferences.length && shouldInclude; k++) { if (hardReferences[k].getReferencedComponent().equals(dynamicComponent)) { shouldInclude = false; } } } if (shouldInclude) { IVirtualReference dynamicReference = ComponentCore.createReference(moduleComponent, dynamicComponent); ((VirtualReference)dynamicReference).setDerived(true); if (null == dynamicReferences) { dynamicReferences = new ArrayList(); } dynamicReferences.add(dynamicReference); } } } } } } if(!findFuzzyEARRefs){ break; } if(foundRefAlready != null){ boolean foundAll = true; for(int i = 0; i < foundRefAlready.length && foundAll; i++){ if(!foundRefAlready[i]){ foundAll = false; } } if(foundAll){ break; } } } } } return dynamicReferences; } }
true
true
private IVirtualReference[] getJavaClasspathReferences(IVirtualReference[] hardReferences) { final boolean isWebApp = JavaEEProjectUtilities.isDynamicWebComponent(this); if(!isWebApp && !ClasspathDependencyEnablement.isAllowClasspathComponentDependency()){ return new IVirtualReference[0]; } final IProject project = getProject(); final List cpRefs = new ArrayList(); try { if (project == null || !project.isAccessible() || !project.hasNature(JavaCoreLite.NATURE_ID)) { return new IVirtualReference[0]; } final IJavaProjectLite javaProjectLite = JavaCoreLite.create(project); if (javaProjectLite == null) { return new IVirtualReference[0]; } // retrieve all referenced classpath entries final Map referencedEntries = ClasspathDependencyUtil.getComponentClasspathDependencies(javaProjectLite, isWebApp); if (referencedEntries.isEmpty()) { return new IVirtualReference[0]; } IVirtualReference[] innerHardReferences = hardReferences; if (innerHardReferences == null) { // only compute this not set and if we have some cp dependencies innerHardReferences = super.getReferences(); } final IPath[] hardRefPaths = new IPath[innerHardReferences.length]; for (int j = 0; j < innerHardReferences.length; j++) { final IVirtualComponent comp = innerHardReferences[j].getReferencedComponent(); if (comp.isBinary()) { final VirtualArchiveComponent archiveComp = (VirtualArchiveComponent) comp; final File diskFile = archiveComp.getUnderlyingDiskFile(); IPath diskPath = null; if (diskFile.exists()) { diskPath =new Path(diskFile.getAbsolutePath()); } else { final IFile iFile = archiveComp.getUnderlyingWorkbenchFile(); diskPath = iFile.getFullPath(); } hardRefPaths[j] = diskPath; } } IContainer[] mappedClassFolders = null; final Iterator i = referencedEntries.keySet().iterator(); while (i.hasNext()) { final IClasspathEntry entry = (IClasspathEntry) i.next(); final IClasspathAttribute attrib = (IClasspathAttribute) referencedEntries.get(entry); final boolean isClassFolder = ClasspathDependencyUtil.isClassFolderEntry(entry); final IPath runtimePath = ClasspathDependencyUtil.getRuntimePath(attrib, isWebApp, isClassFolder); boolean add = true; final IPath entryLocation = ClasspathDependencyUtil.getEntryLocation(entry); if (entryLocation == null) { // unable to retrieve location for cp entry, do not contribute as a virtual ref add = false; } else if (!isClassFolder) { // check hard archive refs for (int j = 0; j < hardRefPaths.length; j++) { if (entryLocation.equals(hardRefPaths[j])) { // entry resolves to same file as existing hard reference, can skip add = false; break; } } } else { // check class folders mapped in component file as class folders associated with mapped src folders if (mappedClassFolders == null) { List <IContainer> containers = JavaLiteUtilities.getJavaOutputContainers(this); mappedClassFolders = containers.toArray(new IContainer[containers.size()]); } for (int j = 0; j < mappedClassFolders.length; j++) { if (entryLocation.equals(mappedClassFolders[j].getFullPath())) { // entry resolves to same file as existing class folder mapping, skip add = false; break; } } } if (add && entryLocation != null) { String componentPath = null; ClasspathDependencyVirtualComponent entryComponent = null; /* if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { componentPath = VirtualArchiveComponent.CLASSPATHARCHIVETYPE; final IProject cpEntryProject = ResourcesPlugin.getWorkspace().getRoot().getProject(entry.getPath().lastSegment()); entryComponent = (VirtualArchiveComponent) ComponentCore.createArchiveComponent(cpEntryProject, componentPath); } else { */ componentPath = VirtualArchiveComponent.CLASSPATHARCHIVETYPE + IPath.SEPARATOR + entryLocation.toPortableString(); entryComponent = new ClasspathDependencyVirtualComponent(project, componentPath, isClassFolder); //} final IVirtualReference entryReference = ComponentCore.createReference(this, entryComponent, runtimePath); ((VirtualReference)entryReference).setDerived(true); entryReference.setArchiveName(ClasspathDependencyUtil.getArchiveName(entry)); cpRefs.add(entryReference); } } } catch (CoreException jme) { J2EEPlugin.logError(jme); } return (IVirtualReference[]) cpRefs.toArray(new IVirtualReference[cpRefs.size()]); } public static List getManifestReferences(IVirtualComponent moduleComponent, IVirtualReference[] hardReferences) { return getManifestReferences(moduleComponent, hardReferences, false); } public static List getManifestReferences(IVirtualComponent moduleComponent, IVirtualReference[] hardReferences, boolean findFuzzyEARRefs) { List dynamicReferences = null; String [] manifestClasspath = getManifestClasspath(moduleComponent); IVirtualReference foundRef = null; String earArchiveURI = null; //The URI for this archive in the EAR boolean simplePath = false; if (manifestClasspath != null && manifestClasspath.length > 0) { boolean [] foundRefAlready = findFuzzyEARRefs ? new boolean[manifestClasspath.length]: null; if(null != foundRefAlready){ for(int i=0; i<foundRefAlready.length; i++){ foundRefAlready[i] = false; } } IProject [] earProjects = EarUtilities.getReferencingEARProjects(moduleComponent.getProject()); for (IProject earProject : earProjects) { if(!JavaEEProjectUtilities.isEARProject(earProject)){ continue; } IVirtualReference[] earRefs = null; IVirtualComponent tempEARComponent = ComponentCore.createComponent(earProject); IVirtualReference[] tempEarRefs = tempEARComponent.getReferences(); for (int j = 0; j < tempEarRefs.length && earRefs == null; j++) { if (tempEarRefs[j].getReferencedComponent().equals(moduleComponent)) { earRefs = tempEarRefs; foundRef = tempEarRefs[j]; earArchiveURI = foundRef.getArchiveName(); simplePath = earArchiveURI != null ? earArchiveURI.lastIndexOf("/") == -1 : true; //$NON-NLS-1$ } } if (null != earRefs) { for (int manifestIndex = 0; manifestIndex < manifestClasspath.length; manifestIndex++) { boolean found = false; if(foundRefAlready != null && foundRefAlready[manifestIndex]){ continue; } for (int j = 0; j < earRefs.length && !found; j++) { if(foundRef != earRefs[j]){ String archiveName = earRefs[j].getArchiveName(); if (null != archiveName){ boolean shouldAdd = false; String manifestEntryString = manifestClasspath[manifestIndex]; if( manifestEntryString != null ){ IPath manifestPath = new Path(manifestEntryString); manifestEntryString = manifestPath.toPortableString(); } if(simplePath && manifestEntryString != null && manifestEntryString.lastIndexOf("/") == -1){ //$NON-NLS-1$ shouldAdd = archiveName.equals(manifestEntryString); } else { String earRelativeURI = ArchiveUtil.deriveEARRelativeURI(manifestEntryString, earArchiveURI); if(null != earRelativeURI){ shouldAdd = earRelativeURI.equals(archiveName); } } if(shouldAdd){ if(findFuzzyEARRefs && foundRefAlready != null){ foundRefAlready[manifestIndex] = true; } found = true; boolean shouldInclude = true; IVirtualComponent dynamicComponent = earRefs[j].getReferencedComponent(); if(null != hardReferences){ for (int k = 0; k < hardReferences.length && shouldInclude; k++) { if (hardReferences[k].getReferencedComponent().equals(dynamicComponent)) { shouldInclude = false; } } } if (shouldInclude) { IVirtualReference dynamicReference = ComponentCore.createReference(moduleComponent, dynamicComponent); ((VirtualReference)dynamicReference).setDerived(true); if (null == dynamicReferences) { dynamicReferences = new ArrayList(); } dynamicReferences.add(dynamicReference); } } } } } } if(!findFuzzyEARRefs){ break; } if(foundRefAlready != null){ boolean foundAll = true; for(int i = 0; i < foundRefAlready.length && foundAll; i++){ if(!foundRefAlready[i]){ foundAll = false; } } if(foundAll){ break; } } } } } return dynamicReferences; } }
private IVirtualReference[] getJavaClasspathReferences(IVirtualReference[] hardReferences) { final boolean isWebApp = JavaEEProjectUtilities.isDynamicWebComponent(this); if(!isWebApp && !ClasspathDependencyEnablement.isAllowClasspathComponentDependency()){ return new IVirtualReference[0]; } final IProject project = getProject(); final List cpRefs = new ArrayList(); try { if (project == null || !project.isAccessible() || !project.hasNature(JavaCoreLite.NATURE_ID)) { return new IVirtualReference[0]; } final IJavaProjectLite javaProjectLite = JavaCoreLite.create(project); if (javaProjectLite == null) { return new IVirtualReference[0]; } // retrieve all referenced classpath entries final Map referencedEntries = ClasspathDependencyUtil.getComponentClasspathDependencies(javaProjectLite, isWebApp); if (referencedEntries.isEmpty()) { return new IVirtualReference[0]; } IVirtualReference[] innerHardReferences = hardReferences; if (innerHardReferences == null) { // only compute this not set and if we have some cp dependencies HashMap<String, Object> map = new HashMap<String, Object>(); map.put(IVirtualComponent.IGNORE_DERIVED_REFERENCES, new Boolean(true)); innerHardReferences = super.getReferences(map); } final IPath[] hardRefPaths = new IPath[innerHardReferences.length]; for (int j = 0; j < innerHardReferences.length; j++) { final IVirtualComponent comp = innerHardReferences[j].getReferencedComponent(); if (comp.isBinary()) { final VirtualArchiveComponent archiveComp = (VirtualArchiveComponent) comp; final File diskFile = archiveComp.getUnderlyingDiskFile(); IPath diskPath = null; if (diskFile.exists()) { diskPath =new Path(diskFile.getAbsolutePath()); } else { final IFile iFile = archiveComp.getUnderlyingWorkbenchFile(); diskPath = iFile.getFullPath(); } hardRefPaths[j] = diskPath; } } IContainer[] mappedClassFolders = null; final Iterator i = referencedEntries.keySet().iterator(); while (i.hasNext()) { final IClasspathEntry entry = (IClasspathEntry) i.next(); final IClasspathAttribute attrib = (IClasspathAttribute) referencedEntries.get(entry); final boolean isClassFolder = ClasspathDependencyUtil.isClassFolderEntry(entry); final IPath runtimePath = ClasspathDependencyUtil.getRuntimePath(attrib, isWebApp, isClassFolder); boolean add = true; final IPath entryLocation = ClasspathDependencyUtil.getEntryLocation(entry); if (entryLocation == null) { // unable to retrieve location for cp entry, do not contribute as a virtual ref add = false; } else if (!isClassFolder) { // check hard archive refs for (int j = 0; j < hardRefPaths.length; j++) { if (entryLocation.equals(hardRefPaths[j])) { // entry resolves to same file as existing hard reference, can skip add = false; break; } } } else { // check class folders mapped in component file as class folders associated with mapped src folders if (mappedClassFolders == null) { List <IContainer> containers = JavaLiteUtilities.getJavaOutputContainers(this); mappedClassFolders = containers.toArray(new IContainer[containers.size()]); } for (int j = 0; j < mappedClassFolders.length; j++) { if (entryLocation.equals(mappedClassFolders[j].getFullPath())) { // entry resolves to same file as existing class folder mapping, skip add = false; break; } } } if (add && entryLocation != null) { String componentPath = null; ClasspathDependencyVirtualComponent entryComponent = null; /* if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { componentPath = VirtualArchiveComponent.CLASSPATHARCHIVETYPE; final IProject cpEntryProject = ResourcesPlugin.getWorkspace().getRoot().getProject(entry.getPath().lastSegment()); entryComponent = (VirtualArchiveComponent) ComponentCore.createArchiveComponent(cpEntryProject, componentPath); } else { */ componentPath = VirtualArchiveComponent.CLASSPATHARCHIVETYPE + IPath.SEPARATOR + entryLocation.toPortableString(); entryComponent = new ClasspathDependencyVirtualComponent(project, componentPath, isClassFolder); //} final IVirtualReference entryReference = ComponentCore.createReference(this, entryComponent, runtimePath); ((VirtualReference)entryReference).setDerived(true); entryReference.setArchiveName(ClasspathDependencyUtil.getArchiveName(entry)); cpRefs.add(entryReference); } } } catch (CoreException jme) { J2EEPlugin.logError(jme); } return (IVirtualReference[]) cpRefs.toArray(new IVirtualReference[cpRefs.size()]); } public static List getManifestReferences(IVirtualComponent moduleComponent, IVirtualReference[] hardReferences) { return getManifestReferences(moduleComponent, hardReferences, false); } public static List getManifestReferences(IVirtualComponent moduleComponent, IVirtualReference[] hardReferences, boolean findFuzzyEARRefs) { List dynamicReferences = null; String [] manifestClasspath = getManifestClasspath(moduleComponent); IVirtualReference foundRef = null; String earArchiveURI = null; //The URI for this archive in the EAR boolean simplePath = false; if (manifestClasspath != null && manifestClasspath.length > 0) { boolean [] foundRefAlready = findFuzzyEARRefs ? new boolean[manifestClasspath.length]: null; if(null != foundRefAlready){ for(int i=0; i<foundRefAlready.length; i++){ foundRefAlready[i] = false; } } IProject [] earProjects = EarUtilities.getReferencingEARProjects(moduleComponent.getProject()); for (IProject earProject : earProjects) { if(!JavaEEProjectUtilities.isEARProject(earProject)){ continue; } IVirtualReference[] earRefs = null; IVirtualComponent tempEARComponent = ComponentCore.createComponent(earProject); IVirtualReference[] tempEarRefs = tempEARComponent.getReferences(); for (int j = 0; j < tempEarRefs.length && earRefs == null; j++) { if (tempEarRefs[j].getReferencedComponent().equals(moduleComponent)) { earRefs = tempEarRefs; foundRef = tempEarRefs[j]; earArchiveURI = foundRef.getArchiveName(); simplePath = earArchiveURI != null ? earArchiveURI.lastIndexOf("/") == -1 : true; //$NON-NLS-1$ } } if (null != earRefs) { for (int manifestIndex = 0; manifestIndex < manifestClasspath.length; manifestIndex++) { boolean found = false; if(foundRefAlready != null && foundRefAlready[manifestIndex]){ continue; } for (int j = 0; j < earRefs.length && !found; j++) { if(foundRef != earRefs[j]){ String archiveName = earRefs[j].getArchiveName(); if (null != archiveName){ boolean shouldAdd = false; String manifestEntryString = manifestClasspath[manifestIndex]; if( manifestEntryString != null ){ IPath manifestPath = new Path(manifestEntryString); manifestEntryString = manifestPath.toPortableString(); } if(simplePath && manifestEntryString != null && manifestEntryString.lastIndexOf("/") == -1){ //$NON-NLS-1$ shouldAdd = archiveName.equals(manifestEntryString); } else { String earRelativeURI = ArchiveUtil.deriveEARRelativeURI(manifestEntryString, earArchiveURI); if(null != earRelativeURI){ shouldAdd = earRelativeURI.equals(archiveName); } } if(shouldAdd){ if(findFuzzyEARRefs && foundRefAlready != null){ foundRefAlready[manifestIndex] = true; } found = true; boolean shouldInclude = true; IVirtualComponent dynamicComponent = earRefs[j].getReferencedComponent(); if(null != hardReferences){ for (int k = 0; k < hardReferences.length && shouldInclude; k++) { if (hardReferences[k].getReferencedComponent().equals(dynamicComponent)) { shouldInclude = false; } } } if (shouldInclude) { IVirtualReference dynamicReference = ComponentCore.createReference(moduleComponent, dynamicComponent); ((VirtualReference)dynamicReference).setDerived(true); if (null == dynamicReferences) { dynamicReferences = new ArrayList(); } dynamicReferences.add(dynamicReference); } } } } } } if(!findFuzzyEARRefs){ break; } if(foundRefAlready != null){ boolean foundAll = true; for(int i = 0; i < foundRefAlready.length && foundAll; i++){ if(!foundRefAlready[i]){ foundAll = false; } } if(foundAll){ break; } } } } } return dynamicReferences; } }
diff --git a/src/me/DDoS/MCCasino/bet/MCCItemBetProvider.java b/src/me/DDoS/MCCasino/bet/MCCItemBetProvider.java index b5d44e3..5c50a3c 100644 --- a/src/me/DDoS/MCCasino/bet/MCCItemBetProvider.java +++ b/src/me/DDoS/MCCasino/bet/MCCItemBetProvider.java @@ -1,97 +1,97 @@ package me.DDoS.MCCasino.bet; import java.util.List; import me.DDoS.MCCasino.util.MCCUtil; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; /** * * @author DDoS */ public class MCCItemBetProvider implements MCCBetProvider { private List<ItemStack> limits; public MCCItemBetProvider(List<ItemStack> limits) { this.limits = limits; } @Override public MCCBet getBet(Player player) { ItemStack bet = player.getItemInHand(); if (bet.getType().equals(Material.AIR)) { MCCUtil.tell(player, "You can't bet nothing!"); return null; } if (bet.getType().equals(Material.DIAMOND_SWORD) || bet.getType().equals(Material.IRON_SWORD) || bet.getType().equals(Material.STONE_SWORD) || bet.getType().equals(Material.GOLD_SWORD) || bet.getType().equals(Material.WOOD_SWORD)) { return null; } if (limits.isEmpty()) { - player.getInventory().remove(bet); + player.getInventory().removeItem(bet); return new MCCItemBet(bet); } boolean notEnough = false; int smallest = Integer.MAX_VALUE; for (ItemStack limit : limits) { if (bet.getType() != limit.getType()) { continue; } int amount = limit.getAmount(); if (bet.getAmount() < amount) { notEnough = true; if (amount < smallest) { smallest = amount; } continue; } player.getInventory().removeItem(limit); player.updateInventory(); return new MCCItemBet(limit); } if (notEnough) { MCCUtil.tell(player, "You need to increase your bet of '" + bet.getType().toString().toLowerCase() + "' to " + smallest + " items"); } else { MCCUtil.tell(player, "This machine does not accept item '" + bet.getType().toString().toLowerCase() + "' as a bet."); } return null; } }
true
true
public MCCBet getBet(Player player) { ItemStack bet = player.getItemInHand(); if (bet.getType().equals(Material.AIR)) { MCCUtil.tell(player, "You can't bet nothing!"); return null; } if (bet.getType().equals(Material.DIAMOND_SWORD) || bet.getType().equals(Material.IRON_SWORD) || bet.getType().equals(Material.STONE_SWORD) || bet.getType().equals(Material.GOLD_SWORD) || bet.getType().equals(Material.WOOD_SWORD)) { return null; } if (limits.isEmpty()) { player.getInventory().remove(bet); return new MCCItemBet(bet); } boolean notEnough = false; int smallest = Integer.MAX_VALUE; for (ItemStack limit : limits) { if (bet.getType() != limit.getType()) { continue; } int amount = limit.getAmount(); if (bet.getAmount() < amount) { notEnough = true; if (amount < smallest) { smallest = amount; } continue; } player.getInventory().removeItem(limit); player.updateInventory(); return new MCCItemBet(limit); } if (notEnough) { MCCUtil.tell(player, "You need to increase your bet of '" + bet.getType().toString().toLowerCase() + "' to " + smallest + " items"); } else { MCCUtil.tell(player, "This machine does not accept item '" + bet.getType().toString().toLowerCase() + "' as a bet."); } return null; }
public MCCBet getBet(Player player) { ItemStack bet = player.getItemInHand(); if (bet.getType().equals(Material.AIR)) { MCCUtil.tell(player, "You can't bet nothing!"); return null; } if (bet.getType().equals(Material.DIAMOND_SWORD) || bet.getType().equals(Material.IRON_SWORD) || bet.getType().equals(Material.STONE_SWORD) || bet.getType().equals(Material.GOLD_SWORD) || bet.getType().equals(Material.WOOD_SWORD)) { return null; } if (limits.isEmpty()) { player.getInventory().removeItem(bet); return new MCCItemBet(bet); } boolean notEnough = false; int smallest = Integer.MAX_VALUE; for (ItemStack limit : limits) { if (bet.getType() != limit.getType()) { continue; } int amount = limit.getAmount(); if (bet.getAmount() < amount) { notEnough = true; if (amount < smallest) { smallest = amount; } continue; } player.getInventory().removeItem(limit); player.updateInventory(); return new MCCItemBet(limit); } if (notEnough) { MCCUtil.tell(player, "You need to increase your bet of '" + bet.getType().toString().toLowerCase() + "' to " + smallest + " items"); } else { MCCUtil.tell(player, "This machine does not accept item '" + bet.getType().toString().toLowerCase() + "' as a bet."); } return null; }
diff --git a/src/main/java/com/github/zhongl/util/Md5.java b/src/main/java/com/github/zhongl/util/Md5.java index 9910b00..1651be7 100644 --- a/src/main/java/com/github/zhongl/util/Md5.java +++ b/src/main/java/com/github/zhongl/util/Md5.java @@ -1,51 +1,51 @@ /* * Copyright 2012 zhongl * 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.github.zhongl.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** @author <a href="mailto:[email protected]">zhongl<a> */ public class Md5 { private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; private Md5() { } public static byte[] md5(byte[] bytes) { return messageDigest().digest(bytes); } public static MessageDigest messageDigest() { try { return MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public static String toHex(byte[] bytes) { - char[] chars = new char[HEX_DIGITS.length * 2]; + char[] chars = new char[bytes.length * 2]; for (int i = 0; i < bytes.length; i++) { chars[i * 2] = HEX_DIGITS[bytes[i] >>> 4 & 0xf]; chars[i * 2 + 1] = HEX_DIGITS[bytes[i] & 0xf]; } return new String(chars); } }
true
true
public static String toHex(byte[] bytes) { char[] chars = new char[HEX_DIGITS.length * 2]; for (int i = 0; i < bytes.length; i++) { chars[i * 2] = HEX_DIGITS[bytes[i] >>> 4 & 0xf]; chars[i * 2 + 1] = HEX_DIGITS[bytes[i] & 0xf]; } return new String(chars); }
public static String toHex(byte[] bytes) { char[] chars = new char[bytes.length * 2]; for (int i = 0; i < bytes.length; i++) { chars[i * 2] = HEX_DIGITS[bytes[i] >>> 4 & 0xf]; chars[i * 2 + 1] = HEX_DIGITS[bytes[i] & 0xf]; } return new String(chars); }
diff --git a/Assembly/app/com/afforess/assembly/DumpUpdateTask.java b/Assembly/app/com/afforess/assembly/DumpUpdateTask.java index 805ae5b..a6f0fa3 100644 --- a/Assembly/app/com/afforess/assembly/DumpUpdateTask.java +++ b/Assembly/app/com/afforess/assembly/DumpUpdateTask.java @@ -1,313 +1,313 @@ package com.afforess.assembly; import java.io.File; import java.io.FileNotFoundException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.concurrent.ExecutionException; import org.apache.commons.dbutils.DbUtils; import play.Logger; import com.afforess.assembly.util.DatabaseAccess; import com.afforess.assembly.util.Utils; import com.afforess.nsdump.NationsDump; import com.afforess.nsdump.RegionsDump; import com.mchange.v2.c3p0.ComboPooledDataSource; public class DumpUpdateTask implements Runnable { private final File regionDump; private final File nationDump; private final ComboPooledDataSource pool; private final DatabaseAccess access; public DumpUpdateTask(DatabaseAccess access, File regionDump, File nationDump) { this.pool = access.getPool(); this.access = access; this.regionDump = regionDump; this.nationDump = nationDump; } @Override public void run() { try { Logger.info("Starting daily dumps update task with [" + regionDump.getName() + " & " + nationDump.getName() + "]"); RegionsDump regions = new RegionsDump(regionDump); regions.parse(); updateRegions(regions); NationsDump nations = new NationsDump(nationDump); nations.parse(); updateNations(nations); Logger.info("Finished daily dumps update task"); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } private void updateRegions(RegionsDump dump) { Connection conn = null; Connection assembly = null; try { conn = dump.getDatabaseConnection(); PreparedStatement statement = conn.prepareStatement("SELECT name FROM regions"); ResultSet result = statement.executeQuery(); final HashSet<String> set = new HashSet<String>(20000); while (result.next()) { set.add(result.getString(1)); } DbUtils.closeQuietly(result); Logger.info("Updating " + set.size() + " regions from daily dump"); PreparedStatement select = conn.prepareStatement("SELECT title, flag, delegate, founder, numnations FROM regions WHERE name = ?"); int newRegions = 0; for (String region : set) { select.setString(1, region); result = select.executeQuery(); result.next(); newRegions += updateRegion(region, result.getString(1), result.getString(2), result.getString(3), result.getString(4), result.getInt(5)); DbUtils.closeQuietly(result); try { Thread.sleep(1); } catch (InterruptedException e) { } } Logger.info("Added " + newRegions + " regions to the database"); assembly = pool.getConnection(); HashSet<String> allRegions = new HashSet<String>(20000); select = assembly.prepareStatement("SELECT name FROM assembly.region WHERE alive = 1"); result = select.executeQuery(); while (result.next()) { allRegions.add(result.getString(1)); } DbUtils.closeQuietly(result); allRegions.removeAll(set); Logger.info("Marking " + allRegions.size() + " regions as dead"); PreparedStatement markDead = assembly.prepareStatement("UPDATE assembly.region SET alive = 0 WHERE name = ?"); for (String region : allRegions) { markDead.setString(1, region); markDead.addBatch(); } markDead.executeBatch(); conn.prepareStatement("DROP TABLE regions").execute(); conn.prepareStatement("SHUTDOWN COMPACT").execute(); } catch (Exception e) { Logger.error("unable to update region dumps", e); } finally { DbUtils.closeQuietly(conn); DbUtils.closeQuietly(assembly); } } private int updateRegion(String region, String title, String flag, String delegate, String founder, int numNations) throws SQLException { Connection conn = pool.getConnection(); try { PreparedStatement select = conn.prepareStatement("SELECT id FROM assembly.region WHERE name = ?"); select.setString(1, region); ResultSet result = select.executeQuery(); int regionId = -1; if (result.next()) { regionId = result.getInt(1); } Logger.info("Updating region [" + region + "] from the daily dump [numnations: " + numNations + "]"); PreparedStatement insert = null; insert = conn.prepareStatement("INSERT INTO assembly.region_populations (region, population, timestamp) VALUES (?, ?, ?)"); insert.setString(1, region); insert.setInt(2, numNations); insert.setLong(3, System.currentTimeMillis()); insert.executeUpdate(); DbUtils.closeQuietly(insert); PreparedStatement update = null; if (regionId == -1) { update = conn.prepareStatement("INSERT INTO assembly.region (name, title, flag, delegate, founder, alive) VALUES (?, ?, ?, ?, ?, 1)"); update.setString(1, region); update.setString(2, title); update.setString(3, flag); update.setString(4, delegate); update.setString(5, founder); update.executeUpdate(); DbUtils.closeQuietly(update); return 1; } else { update = conn.prepareStatement("UPDATE assembly.region SET alive = 1, title = ?, flag = ?, delegate = ?, founder = ? WHERE id = ?"); update.setString(1, title); update.setString(2, flag); update.setString(3, delegate); update.setString(4, founder); update.setInt(5, regionId); update.executeUpdate(); DbUtils.closeQuietly(update); return 0; } } finally { DbUtils.closeQuietly(conn); } } private static String[] NATION_FIELDS = new String[] {"motto", "currency", "animal", "capital", "leader", "religion", "category", "civilrights", "economy", "politicalfreedom", "population", "tax", "majorindustry", "governmentpriority", "environment", "socialequality", "education", "lawandorder", "administration", "welfare", "spirituality", "defence", "publictransport", "healthcare", "commerce", "civilrightscore", "economyscore", "politicalfreedomscore", "publicsector"}; private void updateNations(NationsDump dump) { Connection conn = null; Connection assembly = null; try { conn = dump.getDatabaseConnection(); PreparedStatement statement = conn.prepareStatement("SELECT name FROM nations"); ResultSet result = statement.executeQuery(); final HashSet<String> set = new HashSet<String>(150000); while (result.next()) { set.add(result.getString(1)); } DbUtils.closeQuietly(result); Logger.info("Updating " + set.size() + " nations from daily dump"); PreparedStatement select = conn.prepareStatement("SELECT title, fullname, unstatus, influence, lastlogin, flag, region, motto," + "currency, animal, capital, leader, religion, category, civilrights, economy, politicalfreedom, population, tax, majorindustry," + - "governmentpriority, enivornment, socialequality, education, lawandorder, administration, welfare, spirituality, defence," + + "governmentpriority, environment, socialequality, education, lawandorder, administration, welfare, spirituality, defence," + "publictransport, healthcare, commerce, civilrightscore, economyscore, politicalfreedomscore, publicsector FROM nations WHERE name = ?"); int newNations = 0; assembly = pool.getConnection(); Map<String, Integer> columnMapping = null; for (String nation : set) { select.setString(1, nation); result = select.executeQuery(); result.next(); newNations += updateNation(assembly, nation, result.getString("title"), result.getString("fullname"), !result.getString("unstatus").toLowerCase().equals("non-member"), result.getString("influence"), result.getInt("lastlogin"), result.getString("flag"), result.getString("region")); ResultSetMetaData metaData = result.getMetaData(); int columns = metaData.getColumnCount(); if (columnMapping == null) { columnMapping = new HashMap<String, Integer>(); for (int i = 1; i <= columns; i++) { - columnMapping.put(metaData.getColumnName(i), i); + columnMapping.put(metaData.getColumnName(i).toLowerCase(), i); } } //update extra nation fields StringBuilder fields = new StringBuilder("UPDATE assembly.nation SET "); for (int i = 0; i < NATION_FIELDS.length; i++) { fields.append(NATION_FIELDS[i]).append(" = ?"); if (i != NATION_FIELDS.length - 1) fields.append(", "); } fields.append(" WHERE name = ?"); PreparedStatement updateFields = assembly.prepareStatement(fields.toString()); for (int i = 0; i < NATION_FIELDS.length; i++) { updateFields.setObject(i + 1, result.getObject(columnMapping.get(NATION_FIELDS[i])), metaData.getColumnType(columnMapping.get(NATION_FIELDS[i]))); } updateFields.setString(NATION_FIELDS.length + 1, nation); updateFields.executeUpdate(); DbUtils.closeQuietly(updateFields); DbUtils.closeQuietly(result); try { Thread.sleep(1); } catch (InterruptedException e) { } } Logger.info("Added " + newNations + " nations to the database"); HashSet<String> allNations = new HashSet<String>(150000); select = assembly.prepareStatement("SELECT name FROM assembly.nation WHERE alive = 1"); result = select.executeQuery(); while (result.next()) { allNations.add(result.getString(1)); } DbUtils.closeQuietly(result); allNations.removeAll(set); Logger.info("Marking " + allNations.size() + " nations as dead"); for (String nation : allNations) { try { access.markNationDead(nation, assembly); } catch (ExecutionException e) { Logger.warn("Unknown nation: " + nation, e); } } conn.prepareStatement("DROP TABLE nations").execute(); conn.prepareStatement("SHUTDOWN COMPACT").execute(); int cleanupNations = 0; result = assembly.prepareStatement("SELECT id FROM assembly.nation WHERE alive = 0 AND wa_member = 1").executeQuery(); while(result.next()) { access.markNationDead(result.getInt(1), assembly); cleanupNations++; } DbUtils.closeQuietly(result); Logger.info("Cleaned up " + cleanupNations + " who were dead World Assembly Member nations!"); } catch (SQLException e) { Logger.error("unable to update nation dumps", e); } finally { DbUtils.closeQuietly(conn); DbUtils.closeQuietly(assembly); } } private int updateNation(Connection conn, String nation, String title, String fullName, boolean waMember, String influence, int lastLogin, String flag, String region) throws SQLException { int id = -1; PreparedStatement select = conn.prepareStatement("SELECT id, wa_member, region FROM assembly.nation WHERE name = ?"); select.setString(1, nation); ResultSet result = select.executeQuery(); int prevRegion = -1; boolean wasWA = false; if (result.next()) { id = result.getInt(1); wasWA = result.getBoolean(2); prevRegion = result.getInt(3); } select = conn.prepareStatement("SELECT id FROM assembly.region WHERE name = ?"); select.setString(1, Utils.sanitizeName(region)); result = select.executeQuery(); int regionId = -1; if (result.next()) { regionId = result.getInt(1); } Logger.info("Updating nation [" + nation + "] from the daily dump"); PreparedStatement insert = null; if (id == -1) { insert = conn.prepareStatement("INSERT INTO assembly.nation (name, title, full_name, flag, region, influence_desc, last_login, wa_member, alive, first_seen) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); insert.setString(1, nation); insert.setString(2, title); insert.setString(3, fullName); insert.setString(4, flag); insert.setInt(5, regionId); insert.setString(6, influence); insert.setInt(7, lastLogin); insert.setByte(8, (byte)(waMember ? 1 : 0)); insert.setByte(9, (byte)1); insert.setLong(10, System.currentTimeMillis() / 1000L); insert.executeUpdate(); DbUtils.closeQuietly(insert); return 1; } else { insert = conn.prepareStatement("UPDATE assembly.nation SET alive = 1, full_name = ?, title = ?, flag = ?, region = ?, influence_desc = ?, last_login = ?, wa_member = ? WHERE id = ?"); insert.setString(1, fullName); insert.setString(2, title); insert.setString(3, flag); insert.setInt(4, regionId); insert.setString(5, influence); insert.setInt(6, lastLogin); if (prevRegion != regionId && wasWA) { insert.setByte(7, (byte)(2)); } else { insert.setByte(7, (byte)(waMember ? 1 : 0)); } insert.setInt(8, id); insert.executeUpdate(); DbUtils.closeQuietly(insert); return 0; } } }
false
true
private void updateNations(NationsDump dump) { Connection conn = null; Connection assembly = null; try { conn = dump.getDatabaseConnection(); PreparedStatement statement = conn.prepareStatement("SELECT name FROM nations"); ResultSet result = statement.executeQuery(); final HashSet<String> set = new HashSet<String>(150000); while (result.next()) { set.add(result.getString(1)); } DbUtils.closeQuietly(result); Logger.info("Updating " + set.size() + " nations from daily dump"); PreparedStatement select = conn.prepareStatement("SELECT title, fullname, unstatus, influence, lastlogin, flag, region, motto," + "currency, animal, capital, leader, religion, category, civilrights, economy, politicalfreedom, population, tax, majorindustry," + "governmentpriority, enivornment, socialequality, education, lawandorder, administration, welfare, spirituality, defence," + "publictransport, healthcare, commerce, civilrightscore, economyscore, politicalfreedomscore, publicsector FROM nations WHERE name = ?"); int newNations = 0; assembly = pool.getConnection(); Map<String, Integer> columnMapping = null; for (String nation : set) { select.setString(1, nation); result = select.executeQuery(); result.next(); newNations += updateNation(assembly, nation, result.getString("title"), result.getString("fullname"), !result.getString("unstatus").toLowerCase().equals("non-member"), result.getString("influence"), result.getInt("lastlogin"), result.getString("flag"), result.getString("region")); ResultSetMetaData metaData = result.getMetaData(); int columns = metaData.getColumnCount(); if (columnMapping == null) { columnMapping = new HashMap<String, Integer>(); for (int i = 1; i <= columns; i++) { columnMapping.put(metaData.getColumnName(i), i); } } //update extra nation fields StringBuilder fields = new StringBuilder("UPDATE assembly.nation SET "); for (int i = 0; i < NATION_FIELDS.length; i++) { fields.append(NATION_FIELDS[i]).append(" = ?"); if (i != NATION_FIELDS.length - 1) fields.append(", "); } fields.append(" WHERE name = ?"); PreparedStatement updateFields = assembly.prepareStatement(fields.toString()); for (int i = 0; i < NATION_FIELDS.length; i++) { updateFields.setObject(i + 1, result.getObject(columnMapping.get(NATION_FIELDS[i])), metaData.getColumnType(columnMapping.get(NATION_FIELDS[i]))); } updateFields.setString(NATION_FIELDS.length + 1, nation); updateFields.executeUpdate(); DbUtils.closeQuietly(updateFields); DbUtils.closeQuietly(result); try { Thread.sleep(1); } catch (InterruptedException e) { } } Logger.info("Added " + newNations + " nations to the database"); HashSet<String> allNations = new HashSet<String>(150000); select = assembly.prepareStatement("SELECT name FROM assembly.nation WHERE alive = 1"); result = select.executeQuery(); while (result.next()) { allNations.add(result.getString(1)); } DbUtils.closeQuietly(result); allNations.removeAll(set); Logger.info("Marking " + allNations.size() + " nations as dead"); for (String nation : allNations) { try { access.markNationDead(nation, assembly); } catch (ExecutionException e) { Logger.warn("Unknown nation: " + nation, e); } } conn.prepareStatement("DROP TABLE nations").execute(); conn.prepareStatement("SHUTDOWN COMPACT").execute(); int cleanupNations = 0; result = assembly.prepareStatement("SELECT id FROM assembly.nation WHERE alive = 0 AND wa_member = 1").executeQuery(); while(result.next()) { access.markNationDead(result.getInt(1), assembly); cleanupNations++; } DbUtils.closeQuietly(result); Logger.info("Cleaned up " + cleanupNations + " who were dead World Assembly Member nations!"); } catch (SQLException e) { Logger.error("unable to update nation dumps", e); } finally { DbUtils.closeQuietly(conn); DbUtils.closeQuietly(assembly); } }
private void updateNations(NationsDump dump) { Connection conn = null; Connection assembly = null; try { conn = dump.getDatabaseConnection(); PreparedStatement statement = conn.prepareStatement("SELECT name FROM nations"); ResultSet result = statement.executeQuery(); final HashSet<String> set = new HashSet<String>(150000); while (result.next()) { set.add(result.getString(1)); } DbUtils.closeQuietly(result); Logger.info("Updating " + set.size() + " nations from daily dump"); PreparedStatement select = conn.prepareStatement("SELECT title, fullname, unstatus, influence, lastlogin, flag, region, motto," + "currency, animal, capital, leader, religion, category, civilrights, economy, politicalfreedom, population, tax, majorindustry," + "governmentpriority, environment, socialequality, education, lawandorder, administration, welfare, spirituality, defence," + "publictransport, healthcare, commerce, civilrightscore, economyscore, politicalfreedomscore, publicsector FROM nations WHERE name = ?"); int newNations = 0; assembly = pool.getConnection(); Map<String, Integer> columnMapping = null; for (String nation : set) { select.setString(1, nation); result = select.executeQuery(); result.next(); newNations += updateNation(assembly, nation, result.getString("title"), result.getString("fullname"), !result.getString("unstatus").toLowerCase().equals("non-member"), result.getString("influence"), result.getInt("lastlogin"), result.getString("flag"), result.getString("region")); ResultSetMetaData metaData = result.getMetaData(); int columns = metaData.getColumnCount(); if (columnMapping == null) { columnMapping = new HashMap<String, Integer>(); for (int i = 1; i <= columns; i++) { columnMapping.put(metaData.getColumnName(i).toLowerCase(), i); } } //update extra nation fields StringBuilder fields = new StringBuilder("UPDATE assembly.nation SET "); for (int i = 0; i < NATION_FIELDS.length; i++) { fields.append(NATION_FIELDS[i]).append(" = ?"); if (i != NATION_FIELDS.length - 1) fields.append(", "); } fields.append(" WHERE name = ?"); PreparedStatement updateFields = assembly.prepareStatement(fields.toString()); for (int i = 0; i < NATION_FIELDS.length; i++) { updateFields.setObject(i + 1, result.getObject(columnMapping.get(NATION_FIELDS[i])), metaData.getColumnType(columnMapping.get(NATION_FIELDS[i]))); } updateFields.setString(NATION_FIELDS.length + 1, nation); updateFields.executeUpdate(); DbUtils.closeQuietly(updateFields); DbUtils.closeQuietly(result); try { Thread.sleep(1); } catch (InterruptedException e) { } } Logger.info("Added " + newNations + " nations to the database"); HashSet<String> allNations = new HashSet<String>(150000); select = assembly.prepareStatement("SELECT name FROM assembly.nation WHERE alive = 1"); result = select.executeQuery(); while (result.next()) { allNations.add(result.getString(1)); } DbUtils.closeQuietly(result); allNations.removeAll(set); Logger.info("Marking " + allNations.size() + " nations as dead"); for (String nation : allNations) { try { access.markNationDead(nation, assembly); } catch (ExecutionException e) { Logger.warn("Unknown nation: " + nation, e); } } conn.prepareStatement("DROP TABLE nations").execute(); conn.prepareStatement("SHUTDOWN COMPACT").execute(); int cleanupNations = 0; result = assembly.prepareStatement("SELECT id FROM assembly.nation WHERE alive = 0 AND wa_member = 1").executeQuery(); while(result.next()) { access.markNationDead(result.getInt(1), assembly); cleanupNations++; } DbUtils.closeQuietly(result); Logger.info("Cleaned up " + cleanupNations + " who were dead World Assembly Member nations!"); } catch (SQLException e) { Logger.error("unable to update nation dumps", e); } finally { DbUtils.closeQuietly(conn); DbUtils.closeQuietly(assembly); } }
diff --git a/src/main/java/greed/code/transform/BlockCleaner.java b/src/main/java/greed/code/transform/BlockCleaner.java index d1c135a..1e7e466 100644 --- a/src/main/java/greed/code/transform/BlockCleaner.java +++ b/src/main/java/greed/code/transform/BlockCleaner.java @@ -1,52 +1,54 @@ package greed.code.transform; import greed.code.CodeByLine; import greed.code.CodeTransformer; import java.util.ArrayList; /** * @author WuCY */ public class BlockCleaner implements CodeTransformer { private String startTag; private String endTag; public BlockCleaner(String startTag, String endTag) { this.startTag = startTag; this.endTag = endTag; } @Override public CodeByLine transform(CodeByLine input) { CodeByLine res = new CodeByLine(); ArrayList<String> buffer = new ArrayList<String>(); int totalLen = 0; boolean inBlock = false; for (String line: input.getLines()) { if (line.trim().equals(startTag)) { inBlock = true; + buffer.add(line); } else if (line.trim().equals(endTag)) { + buffer.add(line); if (totalLen > 0) res.getLines().addAll(buffer); inBlock = false; buffer.clear(); totalLen = 0; } else { if (inBlock) { buffer.add(line); totalLen += line.trim().length(); } else res.getLines().add(line); } } return res; } }
false
true
public CodeByLine transform(CodeByLine input) { CodeByLine res = new CodeByLine(); ArrayList<String> buffer = new ArrayList<String>(); int totalLen = 0; boolean inBlock = false; for (String line: input.getLines()) { if (line.trim().equals(startTag)) { inBlock = true; } else if (line.trim().equals(endTag)) { if (totalLen > 0) res.getLines().addAll(buffer); inBlock = false; buffer.clear(); totalLen = 0; } else { if (inBlock) { buffer.add(line); totalLen += line.trim().length(); } else res.getLines().add(line); } } return res; }
public CodeByLine transform(CodeByLine input) { CodeByLine res = new CodeByLine(); ArrayList<String> buffer = new ArrayList<String>(); int totalLen = 0; boolean inBlock = false; for (String line: input.getLines()) { if (line.trim().equals(startTag)) { inBlock = true; buffer.add(line); } else if (line.trim().equals(endTag)) { buffer.add(line); if (totalLen > 0) res.getLines().addAll(buffer); inBlock = false; buffer.clear(); totalLen = 0; } else { if (inBlock) { buffer.add(line); totalLen += line.trim().length(); } else res.getLines().add(line); } } return res; }
diff --git a/java/testing/org/apache/derbyTesting/junit/JDBCDataSource.java b/java/testing/org/apache/derbyTesting/junit/JDBCDataSource.java index a82d58032..19fa5830f 100644 --- a/java/testing/org/apache/derbyTesting/junit/JDBCDataSource.java +++ b/java/testing/org/apache/derbyTesting/junit/JDBCDataSource.java @@ -1,297 +1,301 @@ /* * * Derby - Class org.apache.derbyTesting.junit.JDBCDataSource * * 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.derbyTesting.junit; import java.lang.reflect.Method; import java.security.AccessController; import java.sql.SQLException; import java.util.HashMap; import java.util.Iterator; import javax.sql.DataSource; import junit.framework.Assert; /** * Utility methods related to JDBC DataSource objects. * J2EEDataSource exists to return XA and connection pooling data sources. * * @see J2EEDataSource */ public class JDBCDataSource { /** * Return a new DataSource corresponding to the current * configuration. The getConnection() method will return * a connection identical to TestConfiguration.openDefaultConnection(). */ public static javax.sql.DataSource getDataSource() { return getDataSource(TestConfiguration.getCurrent(), (HashMap) null); } /** * Return a new DataSource corresponding to the current * configuration except that the database name is different. */ public static javax.sql.DataSource getDataSource(String dbName) { // default DataSource javax.sql.DataSource ds = getDataSource(); // Override the database name setBeanProperty(ds, "databaseName", dbName); return ds; } /** * Return a DataSource corresponding to one * of the logical databases in the current configuration. */ public static javax.sql.DataSource getDataSourceLogical(String logicalDatabasename) { // default DataSource javax.sql.DataSource ds = getDataSource(); TestConfiguration current = TestConfiguration.getCurrent(); String physicalName = current.getPhysicalDatabaseName(logicalDatabasename); // Override the database name setBeanProperty(ds, "databaseName", physicalName); return ds; } /** * Create a new DataSource object setup from the passed in TestConfiguration. * The getConnection() method will return a connection identical to * TestConfiguration.openDefaultConnection(). */ static javax.sql.DataSource getDataSource(TestConfiguration config, HashMap beanProperties) { return (javax.sql.DataSource) getDataSource(config, beanProperties, config.getJDBCClient().getDataSourceClassName()); } /** * Create a new DataSource object setup from the passed in * TestConfiguration using the received properties and data * source class name. */ static Object getDataSource(TestConfiguration config, HashMap beanProperties, String dsClassName) { if (beanProperties == null) beanProperties = getDataSourceProperties(config); return getDataSourceObject(dsClassName, beanProperties); } /** * Create a HashMap with the set of Derby DataSource * Java bean properties corresponding to the configuration. */ static HashMap getDataSourceProperties(TestConfiguration config) { HashMap beanProperties = new HashMap(); if (!config.getJDBCClient().isEmbedded()) { beanProperties.put("serverName", config.getHostName()); beanProperties.put("portNumber", new Integer(config.getPort())); } beanProperties.put("databaseName", config.getDefaultDatabaseName()); beanProperties.put("user", config.getUserName()); beanProperties.put("password", config.getUserPassword()); String attributes = config.getConnectionAttributesString(); if (attributes != null) { beanProperties.put("connectionAttributes", attributes); } return beanProperties; } /** * Return a DataSource object of the passed in type * configured with the passed in Java bean properties. * This will actually work with any object that has Java bean * setter methods. * <BR> * If a thread context class loader exists then it is used * to try and load the class. */ static javax.sql.DataSource getDataSourceObject(String classname, HashMap beanProperties) { ClassLoader contextLoader = (ClassLoader) AccessController.doPrivileged (new java.security.PrivilegedAction(){ public Object run() { return Thread.currentThread().getContextClassLoader(); } }); try { javax.sql.DataSource ds = null; if (contextLoader != null) { try { ds = (javax.sql.DataSource) Class.forName(classname, true, contextLoader).newInstance(); } catch (Exception e) { // context loader may not be correctly hooked up // with parent, try without it. } } if (ds == null) { ds = (javax.sql.DataSource) Class.forName(classname).newInstance(); } for (Iterator i = beanProperties.keySet().iterator(); i.hasNext(); ) { String property = (String) i.next(); Object value = beanProperties.get(property); setBeanProperty(ds, property, value); } - ds.setLoginTimeout( TestConfiguration.getCurrent().getLoginTimeout() ); + if ( !BaseTestCase.isJ9Platform() && !BaseTestCase.isCVM() ) + { + ds.setLoginTimeout( TestConfiguration.getCurrent().getLoginTimeout() ); + } return ds; } catch (Exception e) { - BaseTestCase.fail("unexpected error", e); + BaseTestCase.printStackTrace( e ); + BaseTestCase.fail("unexpected error: " + e.getMessage(), e); return null; } } /** * Set a bean property for a data source. This code can be used * on any data source type. * @param ds DataSource to have property set * @param property name of property. * @param value Value, type is derived from value's class. */ public static void setBeanProperty(Object ds, String property, Object value) { String setterName = getSetterName(property); // Base the type of the setter method from the value's class. Class clazz = value.getClass(); if (Integer.class.equals(clazz)) clazz = Integer.TYPE; else if (Boolean.class.equals(clazz)) clazz = Boolean.TYPE; else if (Short.class.equals(clazz)) clazz = Short.TYPE; try { Method setter = ds.getClass().getMethod(setterName, new Class[] {clazz}); setter.invoke(ds, new Object[] {value}); } catch (Exception e) { Assert.fail(e.getMessage()); } } /** * Get a bean property for a data source. This code can be used * on any data source type. * @param ds DataSource to fetch property from * @param property name of property. */ public static Object getBeanProperty(Object ds, String property) throws Exception { String getterName = getGetterName(property); Method getter = ds.getClass().getMethod(getterName, new Class[0]); return getter.invoke(ds, new Object[0]); } /** * Clear a String Java bean property by setting it to null. * @param ds DataSource to have property cleared * @param property name of property. */ public static void clearStringBeanProperty(Object ds, String property) { String setterName = getSetterName(property); try { Method setter = ds.getClass().getMethod(setterName, new Class[] {String.class}); setter.invoke(ds, new Object[] {null}); } catch (Exception e) { Assert.fail(e.getMessage()); } } private static String getSetterName(String attribute) { return "set" + Character.toUpperCase(attribute.charAt(0)) + attribute.substring(1); } private static String getGetterName(String attribute) { return "get" + Character.toUpperCase(attribute.charAt(0)) + attribute.substring(1); } /** * Shutdown the database described by this data source. * The shutdownDatabase property is cleared by this method. */ public static void shutdownDatabase(javax.sql.DataSource ds) { setBeanProperty(ds, "shutdownDatabase", "shutdown"); try { ds.getConnection(); Assert.fail("Database failed to shut down"); } catch (SQLException e) { BaseJDBCTestCase.assertSQLState("Database shutdown", "08006", e); } finally { clearStringBeanProperty(ds, "shutdownDatabase"); } } /** * Shutdown the engine described by this data source. * The shutdownDatabase property is cleared by this method. */ public static void shutEngine(javax.sql.DataSource ds) throws SQLException { setBeanProperty(ds, "shutdownDatabase", "shutdown"); JDBCDataSource.setBeanProperty(ds, "databaseName", ""); try { ds.getConnection(); Assert.fail("Engine failed to shut down"); } catch (SQLException e) { BaseJDBCTestCase.assertSQLState("Engine shutdown", "XJ015", e); } finally { clearStringBeanProperty(ds, "shutdownDatabase"); } } }
false
true
static javax.sql.DataSource getDataSourceObject(String classname, HashMap beanProperties) { ClassLoader contextLoader = (ClassLoader) AccessController.doPrivileged (new java.security.PrivilegedAction(){ public Object run() { return Thread.currentThread().getContextClassLoader(); } }); try { javax.sql.DataSource ds = null; if (contextLoader != null) { try { ds = (javax.sql.DataSource) Class.forName(classname, true, contextLoader).newInstance(); } catch (Exception e) { // context loader may not be correctly hooked up // with parent, try without it. } } if (ds == null) { ds = (javax.sql.DataSource) Class.forName(classname).newInstance(); } for (Iterator i = beanProperties.keySet().iterator(); i.hasNext(); ) { String property = (String) i.next(); Object value = beanProperties.get(property); setBeanProperty(ds, property, value); } ds.setLoginTimeout( TestConfiguration.getCurrent().getLoginTimeout() ); return ds; } catch (Exception e) { BaseTestCase.fail("unexpected error", e); return null; } }
static javax.sql.DataSource getDataSourceObject(String classname, HashMap beanProperties) { ClassLoader contextLoader = (ClassLoader) AccessController.doPrivileged (new java.security.PrivilegedAction(){ public Object run() { return Thread.currentThread().getContextClassLoader(); } }); try { javax.sql.DataSource ds = null; if (contextLoader != null) { try { ds = (javax.sql.DataSource) Class.forName(classname, true, contextLoader).newInstance(); } catch (Exception e) { // context loader may not be correctly hooked up // with parent, try without it. } } if (ds == null) { ds = (javax.sql.DataSource) Class.forName(classname).newInstance(); } for (Iterator i = beanProperties.keySet().iterator(); i.hasNext(); ) { String property = (String) i.next(); Object value = beanProperties.get(property); setBeanProperty(ds, property, value); } if ( !BaseTestCase.isJ9Platform() && !BaseTestCase.isCVM() ) { ds.setLoginTimeout( TestConfiguration.getCurrent().getLoginTimeout() ); } return ds; } catch (Exception e) { BaseTestCase.printStackTrace( e ); BaseTestCase.fail("unexpected error: " + e.getMessage(), e); return null; } }
diff --git a/servlet/src/main/java/com/redshape/servlet/form/impl/support/TimeForm.java b/servlet/src/main/java/com/redshape/servlet/form/impl/support/TimeForm.java index 5ccc5220..6b257b3a 100644 --- a/servlet/src/main/java/com/redshape/servlet/form/impl/support/TimeForm.java +++ b/servlet/src/main/java/com/redshape/servlet/form/impl/support/TimeForm.java @@ -1,114 +1,114 @@ package com.redshape.servlet.form.impl.support; import com.redshape.servlet.form.builders.BuildersFacade; import com.redshape.servlet.form.fields.InputField; import com.redshape.utils.range.IRange; import com.redshape.utils.range.IntervalRange; import com.redshape.utils.range.RangeBuilder; import com.redshape.validators.impl.common.LengthValidator; import com.redshape.validators.impl.common.NumericStringValidator; import com.redshape.validators.impl.common.RangeValidator; import java.util.Calendar; import java.util.Date; /** * @author Cyril A. Karpenko <[email protected]> * @package com.redshape.servlet.form.impl.support * @date 8/16/11 8:46 PM */ public class TimeForm extends DateForm { private IRange<Integer> timeRange; public TimeForm() { super(); } public TimeForm(String id) { this(id, null); } public TimeForm(String id, String name) { super(id, name); } @Override protected void buildForm() { super.buildForm(); - this.timeRange = RangeBuilder.createInterval(IntervalRange.Type.INCLUSIVE, 1, 60); + this.timeRange = RangeBuilder.createInterval(IntervalRange.Type.INCLUSIVE, 0, 59); this.addField( BuildersFacade.newFieldBuilder() .withValidator(new NumericStringValidator()) .withValidator(new LengthValidator(0, 2)) .withValidator(new RangeValidator(this.timeRange)) .withName("hour") .withAttribute("class", "hour-element") .asFieldBuilder() .newInputField(InputField.Type.TEXT) ); this.addField( BuildersFacade.newFieldBuilder() .withValidator(new NumericStringValidator()) .withValidator( new LengthValidator( 0, 2 ) ) .withValidator( new RangeValidator( this.timeRange ) ) .withName("minute") .withAttribute("class", "minute-element") .asFieldBuilder() .newInputField( InputField.Type.TEXT ) ); this.addField( BuildersFacade.newFieldBuilder() .withValidator(new NumericStringValidator()) .withValidator( new LengthValidator( 0, 2 ) ) .withValidator( new RangeValidator( this.timeRange ) ) .withName("second") .withAttribute("class", "second-element") .asFieldBuilder() .newInputField( InputField.Type.TEXT ) ); } public Integer getHour() { String hour = this.getValue("hour"); if ( hour == null || hour.isEmpty() ) { return Calendar.getInstance().get( Calendar.HOUR_OF_DAY ); } return Integer.valueOf( hour ); } public Integer getMinute() { String minute = this.getValue("minute"); if ( minute == null || minute.isEmpty() ) { return Calendar.getInstance().get( Calendar.MINUTE ); } return Integer.valueOf( minute ); } public Integer getSecond() { String second = this.getValue("second"); if ( second == null || second.isEmpty() ) { return Calendar.getInstance().get( Calendar.SECOND ); } return Integer.valueOf( second ); } @Override public Date prepareDate() { Calendar calendar = Calendar.getInstance(); calendar.set( Calendar.YEAR, this.getYear() ); calendar.set( Calendar.MONTH, this.getMonth() ); calendar.set( Calendar.DAY_OF_MONTH, this.getDay() ); calendar.set( Calendar.HOUR, this.getHour() ); calendar.set( Calendar.MINUTE, this.getMinute() ); calendar.set( Calendar.SECOND, this.getSecond() ); return calendar.getTime(); } }
true
true
protected void buildForm() { super.buildForm(); this.timeRange = RangeBuilder.createInterval(IntervalRange.Type.INCLUSIVE, 1, 60); this.addField( BuildersFacade.newFieldBuilder() .withValidator(new NumericStringValidator()) .withValidator(new LengthValidator(0, 2)) .withValidator(new RangeValidator(this.timeRange)) .withName("hour") .withAttribute("class", "hour-element") .asFieldBuilder() .newInputField(InputField.Type.TEXT) ); this.addField( BuildersFacade.newFieldBuilder() .withValidator(new NumericStringValidator()) .withValidator( new LengthValidator( 0, 2 ) ) .withValidator( new RangeValidator( this.timeRange ) ) .withName("minute") .withAttribute("class", "minute-element") .asFieldBuilder() .newInputField( InputField.Type.TEXT ) ); this.addField( BuildersFacade.newFieldBuilder() .withValidator(new NumericStringValidator()) .withValidator( new LengthValidator( 0, 2 ) ) .withValidator( new RangeValidator( this.timeRange ) ) .withName("second") .withAttribute("class", "second-element") .asFieldBuilder() .newInputField( InputField.Type.TEXT ) ); }
protected void buildForm() { super.buildForm(); this.timeRange = RangeBuilder.createInterval(IntervalRange.Type.INCLUSIVE, 0, 59); this.addField( BuildersFacade.newFieldBuilder() .withValidator(new NumericStringValidator()) .withValidator(new LengthValidator(0, 2)) .withValidator(new RangeValidator(this.timeRange)) .withName("hour") .withAttribute("class", "hour-element") .asFieldBuilder() .newInputField(InputField.Type.TEXT) ); this.addField( BuildersFacade.newFieldBuilder() .withValidator(new NumericStringValidator()) .withValidator( new LengthValidator( 0, 2 ) ) .withValidator( new RangeValidator( this.timeRange ) ) .withName("minute") .withAttribute("class", "minute-element") .asFieldBuilder() .newInputField( InputField.Type.TEXT ) ); this.addField( BuildersFacade.newFieldBuilder() .withValidator(new NumericStringValidator()) .withValidator( new LengthValidator( 0, 2 ) ) .withValidator( new RangeValidator( this.timeRange ) ) .withName("second") .withAttribute("class", "second-element") .asFieldBuilder() .newInputField( InputField.Type.TEXT ) ); }
diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/persistence/XMLWriter.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/persistence/XMLWriter.java index 52ab4cf02..993a32603 100644 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/persistence/XMLWriter.java +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/persistence/XMLWriter.java @@ -1,298 +1,307 @@ /******************************************************************************* * Copyright (c) 2007 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.equinox.internal.p2.persistence; import java.io.*; import java.util.*; import org.osgi.framework.Version; public class XMLWriter implements XMLConstants { public static class ProcessingInstruction { private String target; private String[] data; // The standard UTF-8 processing instruction public static final String XML_UTF8 = "<?xml version='1.0' encoding='UTF-8'?>"; //$NON-NLS-1$ public ProcessingInstruction(String target, String[] attrs, String[] values) { // Lengths of attributes and values must be the same this.target = target; this.data = new String[attrs.length]; for (int i = 0; i < attrs.length; i++) { data[i] = attributeImage(attrs[i], values[i]); } } public static ProcessingInstruction makeClassVersionInstruction(String target, Class clazz, Version version) { return new ProcessingInstruction(target, new String[] {PI_CLASS_ATTRIBUTE, PI_VERSION_ATTRIBUTE}, new String[] {clazz.getName(), version.toString()}); } public String toString() { StringBuffer sb = new StringBuffer("<?"); //$NON-NLS-1$ sb.append(this.target).append(' '); for (int i = 0; i < data.length; i++) { sb.append(this.data[i]); if (i < data.length - 1) { sb.append(' '); } } sb.append("?>"); //$NON-NLS-1$ return sb.toString(); } } private Stack elements; // XML elements that have not yet been closed private boolean open; // Can attributes be added to the current element? private String indent; // used for each level of indentation private PrintWriter pw; public XMLWriter(OutputStream output, ProcessingInstruction[] piElements) throws UnsupportedEncodingException { this.pw = new PrintWriter(new OutputStreamWriter(output, "UTF8"), false); //$NON-NLS-1$ println(ProcessingInstruction.XML_UTF8); this.elements = new Stack(); this.open = false; this.indent = " "; //$NON-NLS-1$ if (piElements != null) { for (int i = 0; i < piElements.length; i++) { println(piElements[i].toString()); } } } // start a new element public void start(String name) { if (this.open) { println('>'); } indent(); print('<'); print(name); this.elements.push(name); this.open = true; } // end the most recent element with this name public void end(String name) { if (this.elements.empty()) { throw new EndWithoutStartError(); } int index = this.elements.search(name); if (index == -1) { throw new EndWithoutStartError(name); } for (int i = 0; i < index; i += 1) { end(); } } // end the current element public void end() { if (this.elements.empty()) { throw new EndWithoutStartError(); } String name = (String) this.elements.pop(); if (this.open) { println("/>"); //$NON-NLS-1$ } else { printlnIndented("</" + name + '>', false); //$NON-NLS-1$ } this.open = false; } public static String escape(String txt) { StringBuffer buffer = null; for (int i = 0; i < txt.length(); ++i) { String replace; char c = txt.charAt(i); switch (c) { case '<' : replace = "&lt;"; //$NON-NLS-1$ break; case '>' : replace = "&gt;"; //$NON-NLS-1$ break; case '"' : replace = "&quot;"; //$NON-NLS-1$ break; case '\'' : replace = "&apos;"; //$NON-NLS-1$ break; case '&' : replace = "&amp;"; //$NON-NLS-1$ break; + case '\t' : + replace = "&#x9;"; //$NON-NLS-1$ + break; + case '\n' : + replace = "&#xA;"; //$NON-NLS-1$ + break; + case '\r' : + replace = "&#xD;"; //$NON-NLS-1$ + break; default : - // this is the set of legal xml characters in unicode excluding high surrogates since they cannot be represented with a char + // this is the set of legal xml scharacters in unicode excluding high surrogates since they cannot be represented with a char // see http://www.w3.org/TR/REC-xml/#charsets - if ((c >= '\u0020' && c <= '\uD7FF') || c == '\t' || c == '\n' || c == '\r' || (c >= '\uE000' && c <= '\uFFFD')) { + if ((c >= '\u0020' && c <= '\uD7FF') || (c >= '\uE000' && c <= '\uFFFD')) { if (buffer != null) buffer.append(c); continue; } replace = Character.isWhitespace(c) ? " " : null; //$NON-NLS-1$ } if (buffer == null) { buffer = new StringBuffer(txt.length() + 16); buffer.append(txt.substring(0, i)); } if (replace != null) buffer.append(replace); } if (buffer == null) return txt; return buffer.toString(); } // write a boolean attribute if it doesn't have the default value public void attribute(String name, boolean value, boolean defaultValue) { if (value != defaultValue) { attribute(name, value); } } public void attribute(String name, boolean value) { attribute(name, Boolean.toString(value)); } public void attribute(String name, int value) { attribute(name, Integer.toString(value)); } public void attributeOptional(String name, String value) { if (value != null && value.length() > 0) { attribute(name, value); } } public void attribute(String name, Object value) { if (!this.open) { throw new AttributeAfterNestedContentError(); } if (value == null) { return; // optional attribute with no value } print(' '); print(name); print("='"); //$NON-NLS-1$ print(escape(value.toString())); print('\''); } public void cdata(String data) { cdata(data, true); } public void cdata(String data, boolean escape) { if (this.open) { println('>'); this.open = false; } if (data != null) { printlnIndented(data, escape); } } public void flush() { this.pw.flush(); } public void writeProperties(Map properties) { writeProperties(PROPERTIES_ELEMENT, properties); } public void writeProperties(String propertiesElement, Map properties) { if (properties != null && properties.size() > 0) { start(propertiesElement); attribute(COLLECTION_SIZE_ATTRIBUTE, properties.size()); for (Iterator iter = properties.keySet().iterator(); iter.hasNext();) { String name = (String) iter.next(); writeProperty(name, (String) properties.get(name)); } end(propertiesElement); } } public void writeProperty(String name, String value) { start(PROPERTY_ELEMENT); attribute(PROPERTY_NAME_ATTRIBUTE, name); attribute(PROPERTY_VALUE_ATTRIBUTE, value); end(); } protected static String attributeImage(String name, String value) { if (value == null) { return ""; // optional attribute with no value } return name + "='" + escape(value) + '\''; //$NON-NLS-1$ } private void println(char c) { this.pw.println(c); } private void println(String s) { this.pw.println(s); } private void println() { this.pw.println(); } private void print(char c) { this.pw.print(c); } private void print(String s) { this.pw.print(s); } private void printlnIndented(String s, boolean escape) { if (s.length() == 0) { println(); } else { indent(); println(escape ? escape(s) : s); } } private void indent() { for (int i = this.elements.size(); i > 0; i -= 1) { print(this.indent); } } public static class AttributeAfterNestedContentError extends Error { private static final long serialVersionUID = 1L; // not serialized } public static class EndWithoutStartError extends Error { private static final long serialVersionUID = 1L; // not serialized private String name; public EndWithoutStartError() { super(); } public EndWithoutStartError(String name) { super(); this.name = name; } public String getName() { return this.name; } } }
false
true
public static String escape(String txt) { StringBuffer buffer = null; for (int i = 0; i < txt.length(); ++i) { String replace; char c = txt.charAt(i); switch (c) { case '<' : replace = "&lt;"; //$NON-NLS-1$ break; case '>' : replace = "&gt;"; //$NON-NLS-1$ break; case '"' : replace = "&quot;"; //$NON-NLS-1$ break; case '\'' : replace = "&apos;"; //$NON-NLS-1$ break; case '&' : replace = "&amp;"; //$NON-NLS-1$ break; default : // this is the set of legal xml characters in unicode excluding high surrogates since they cannot be represented with a char // see http://www.w3.org/TR/REC-xml/#charsets if ((c >= '\u0020' && c <= '\uD7FF') || c == '\t' || c == '\n' || c == '\r' || (c >= '\uE000' && c <= '\uFFFD')) { if (buffer != null) buffer.append(c); continue; } replace = Character.isWhitespace(c) ? " " : null; //$NON-NLS-1$ } if (buffer == null) { buffer = new StringBuffer(txt.length() + 16); buffer.append(txt.substring(0, i)); } if (replace != null) buffer.append(replace); } if (buffer == null) return txt; return buffer.toString(); }
public static String escape(String txt) { StringBuffer buffer = null; for (int i = 0; i < txt.length(); ++i) { String replace; char c = txt.charAt(i); switch (c) { case '<' : replace = "&lt;"; //$NON-NLS-1$ break; case '>' : replace = "&gt;"; //$NON-NLS-1$ break; case '"' : replace = "&quot;"; //$NON-NLS-1$ break; case '\'' : replace = "&apos;"; //$NON-NLS-1$ break; case '&' : replace = "&amp;"; //$NON-NLS-1$ break; case '\t' : replace = "&#x9;"; //$NON-NLS-1$ break; case '\n' : replace = "&#xA;"; //$NON-NLS-1$ break; case '\r' : replace = "&#xD;"; //$NON-NLS-1$ break; default : // this is the set of legal xml scharacters in unicode excluding high surrogates since they cannot be represented with a char // see http://www.w3.org/TR/REC-xml/#charsets if ((c >= '\u0020' && c <= '\uD7FF') || (c >= '\uE000' && c <= '\uFFFD')) { if (buffer != null) buffer.append(c); continue; } replace = Character.isWhitespace(c) ? " " : null; //$NON-NLS-1$ } if (buffer == null) { buffer = new StringBuffer(txt.length() + 16); buffer.append(txt.substring(0, i)); } if (replace != null) buffer.append(replace); } if (buffer == null) return txt; return buffer.toString(); }
diff --git a/ContentConnectorAPI/src/com/gentics/cr/CRRequest.java b/ContentConnectorAPI/src/com/gentics/cr/CRRequest.java index f08a6b9a..85d32f91 100644 --- a/ContentConnectorAPI/src/com/gentics/cr/CRRequest.java +++ b/ContentConnectorAPI/src/com/gentics/cr/CRRequest.java @@ -1,547 +1,547 @@ package com.gentics.cr; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import com.gentics.api.lib.datasource.Datasource.Sorting; import com.gentics.api.lib.exception.ParserException; import com.gentics.api.lib.expressionparser.Expression; import com.gentics.api.lib.expressionparser.ExpressionParserException; import com.gentics.api.lib.expressionparser.filtergenerator.DatasourceFilter; import com.gentics.api.lib.resolving.Resolvable; import com.gentics.api.portalnode.connector.PortalConnectorFactory; import com.gentics.cr.util.CRUtil; /** * * Last changed: $Date$ * @version $Revision$ * @author $Author$ * */ public class CRRequest implements Cloneable, Serializable { private static final long serialVersionUID = 1L; private HashMap<String,Resolvable> objectsToDeploy = new HashMap<String,Resolvable>(); private HashMap<String,Object> params = new HashMap<String,Object>(); /** * Create a new instance of CRRequest * @param requestFilter - Rule to fetch the objects * @param startString - Number of start element * @param countString - Count of elements from start element * @param sortArray - sorting array e.g. String[]{"contentid:asc","name:desc"} * @param attributeArray - Attributes to fetch * @param plinkAttributeArray - Attributes to perform plink replacement within */ public CRRequest(String requestFilter, String startString, String countString, String[] sortArray, String[] attributeArray, String[] plinkAttributeArray) { this.setRequestFilter(requestFilter); this.setStartString(startString); this.setCountString(countString); this.setSortArray(sortArray); this.setAttributeArray(attributeArray); this.setPlinkAttributeArray(plinkAttributeArray); } /** * Create a new instance of CRRequest * @param requestFilter - Rule to fetch the objects * @param startString - Number of start element * @param countString - Count of elements from start element * @param sortArray - sorting array e.g. String[]{"contentid:asc","name:desc"} * @param attributeArray - Attributes to fetch * @param plinkAttributeArray * @param childFilter - Rule to fetch the child elements (Navigation) */ public CRRequest(String requestFilter, String startString, String countString, String[] sortArray, String[] attributeArray, String[] plinkAttributeArray, String childFilter) { this.setRequestFilter(requestFilter); this.setStartString(startString); this.setCountString(countString); this.setSortArray(sortArray); this.setAttributeArray(attributeArray); this.setPlinkAttributeArray(plinkAttributeArray); this.setChildFilter(childFilter); } /** * Create new instance of CRRequest */ public CRRequest() { } /** * Gets the configures request object * @return request */ public Object getRequest() { return this.get("request"); } /** * Gets the configured response object * @return response */ public Object getResponse() { return this.get("response"); } /** * Set the request object * @param request */ public void setRequest(Object request) { this.set("request", request); } /** * Set the response object * @param response */ public void setResponse(Object response) { this.set("response", response); } /** * Add one object to the filter that can be accessed in the rule using the given name * @param name * @param object */ public void addObjectForFilterDeployment(String name, Resolvable object) { this.objectsToDeploy.put(name,object); } /** * Set the request filter. This filter is the rule that is used to fetch the objects. * You can deploy custom objects to this rule using addObjectForFilterDeployment * @param requestFilter */ public void setRequestFilter(String requestFilter) { this.set("requestFilter", requestFilter); } /** * Get the configured request filter. This filter is the rule that is used to fetch the objects. * You can deploy custom objects to this rule using addObjectForFilterDeployment * @return requestFilter */ public String getRequestFilter() { return (String)this.get("requestFilter"); } /** * Sets the object number to start from as String e.g. "2" gets <count> objects starting from object nr. 2 * @param startString */ public void setStartString(String startString) { Integer start = new Integer((startString != null) ? startString : "0"); this.set("start", start); } /** * Gets the object number to start from as String e.g. "2" gets <count> objects starting from object nr. 2 * @return start number */ public String getStartString() { Integer start = (Integer)this.get("start"); if(start!=null) { return(start.toString()); } else { return("0"); } } /** * Sets the number of objects to request as String e.g. "5" gets 5 objects starting from <start>, defaults to "-1" and gets all objects * @param countString */ public void setCountString(String countString) { Integer count = new Integer((countString != null) ? countString : "-1"); this.set("count", count); } /** * Get the number of objects to request as String e.g. "5" gets 5 objects starting from <start>, defaults to "-1" and gets all objects * @return countString */ public String getCountString() { Integer count = (Integer)this.get("count"); if(count!=null) { return(count.toString()); } else { return("-1"); } } /** * The sortArray defines the sort order of the returned objects. You can sort by multiple parameters. e.g. String[]{"object.name:asc","object.contentid:desc"} * @param sortArray */ public void setSortArray(String[] sortArray) { this.set("sortArray", sortArray); } /** * The sortArray defines the sort order of the returned objects. You can sort by multiple parameters. e.g. String[]{"object.name:asc","object.contentid:desc"} * @return sortArray */ public String[] getSortArray() { return (String[])this.get("sortArray"); } /** * Sets an array of attribute names that are to be prefilled for the requested objects. * @param attributeArray */ public void setAttributeArray(String[] attributeArray) { this.set("attributeArray", attributeArray); } /** * Gets an array of attribute names that are to be prefilled for the requested objects. Defaults to String[] { "contentid" } * @param attributeArray * @return */ public String[] getAttributeArray() { String[] attributeArray = (String[])this.get("attributeArray"); if(attributeArray==null) return new String[] { "contentid" }; return attributeArray; } /** * Sets an array of attribute names wherein plinks are to be replaced * @param plinkAttributeArray */ public void setPlinkAttributeArray(String[] plinkAttributeArray) { this.set("plinkAttributeArray",plinkAttributeArray); } /** * Gets an array of attribute names wherein plinks are to be replaced * @return plinkAttributeArray, returns null if array is not set => no plinks are to be replaced */ public String[] getPlinkAttributeArray() { return (String[])this.get("plinkAttributeArray"); } /** * Sets the child filter rule that is used to fetch sub elements. This is only to be set for getNavigation * For detailed description see <setRequestFilter> * @param childFilter */ public void setChildFilter(String childFilter) { this.set("childFilter",childFilter); } /** * Gets the child filter rule that is used to fetch sub elements. This is only to be set for getNavigation * For detailed description see <setRequestFilter> * @return childFilter */ public String getChildFilter() { return (String)this.get("childFilter"); } /** * Set a HashMap of objects to deploy to the filter. See <addObjectForFilterDeployment> for detailed description. * @param objectsToDeploy */ public void setObjectsToDeploy(HashMap<String,Resolvable> objectsToDeploy) { this.objectsToDeploy = objectsToDeploy; } /** * Get a HashMap of objects to deploy to the filter. See <addObjectForFilterDeployment> for detailed description. * @return objectsToDeploy */ public HashMap<String,Resolvable> getObjectsToDeploy() { return objectsToDeploy; } /** * Gets the object number to start from as Integer e.g. 2 gets <count> objects starting from object nr. 2 * @return start */ public Integer getStart() { Integer start = (Integer)this.get("start"); if(start==null)return(new Integer(0)); return start; } /** * Get the number of objects to request as Integer e.g. 5 gets 5 objects starting from <start>, defaults to -1 and gets all objects * @return count */ public Integer getCount() { Integer count = (Integer)this.get("count"); if(count==null)return(new Integer(-1)); return count; } /** * Returns the configured sort array prepared as Datasource Sorting array * @return sorting */ public Sorting[] getSorting() { return CRUtil.convertSorting(this.getSortArray()); } /** * Clone current instance * @return cloned instance of CRRequest */ public CRRequest Clone() { CRRequest ret = new CRRequest(); Iterator<String> it_p = this.params.keySet().iterator(); while(it_p.hasNext()) { String key = it_p.next(); ret.set(key, this.params.get(key)); } Iterator<String> it = this.objectsToDeploy.keySet().iterator(); while(it.hasNext()) { String key = it.next(); ret.addObjectForFilterDeployment(key,this.getObjectsToDeploy().get(key)); } return(ret); } /** * Get a prepared and checked instance of DatasourceFilter. The filter is checked for sanity before it is merged with the application rule defined in the given CRConfig. * @param config * @return DatasourceFilter * @throws ParserException * @throws ExpressionParserException */ public DatasourceFilter getPreparedFilter(CRConfig config) throws ParserException, ExpressionParserException { DatasourceFilter dsFilter; String filter =""; if((this.getRequestFilter()==null || this.getRequestFilter().equals("")) && this.getContentid()!=null && !this.getContentid().equals("")) { - this.setRequestFilter("object.contentid=="+this.getContentid()); + this.setRequestFilter("object.contentid=='"+this.getContentid()+"'"); } //TEST IF REQUEST FILTER IS SAVE Expression expression = PortalConnectorFactory.createExpression(this.getRequestFilter()); //IF NO EXCEPTION IS THROWN IN THE ABOVE STATEMENT, FILTER IS CONSIDERED TO BE SAVE //ADD APPLICATION RULE IF IT IS SET if(config.getApplicationRule()==null || config.getApplicationRule().equals("")) { filter=this.getRequestFilter(); }else if(config.getApplicationRule()!=null && !config.getApplicationRule().equals("") && this.getRequestFilter()!=null && !this.getRequestFilter().equals("")) { filter="("+this.getRequestFilter()+") AND "+config.getApplicationRule(); } else if(config.getApplicationRule()!=null && !config.getApplicationRule().equals("") && (this.getRequestFilter()==null || this.getRequestFilter().equals(""))) { filter=config.getApplicationRule(); } expression = PortalConnectorFactory.createExpression(filter); dsFilter = config.getDatasource().createDatasourceFilter(expression); Iterator<String> it = this.getObjectsToDeploy().keySet().iterator(); while(it.hasNext()) { String key = it.next(); dsFilter.addBaseResolvable(key,this.getObjectsToDeploy().get(key)); } return(dsFilter); } /** * Sets if the RequestProcessor is to replace plinks in the configured attributes (plink attributes). * @param doreplaceplinks */ public void setDoReplacePlinks(boolean doreplaceplinks) { this.set("doreplaceplinks", new Boolean(doreplaceplinks)); } /** * Gets if the RequestProcessor is to replace plinks in the configured attributes (plink attributes). * @return boolean doreplaceplinks */ public boolean getDoReplacePlinks() { Boolean doR = (Boolean)this.get("doreplaceplinks"); if(doR==null)return(false); return(doR.booleanValue()); } /** * Sets if the RequestProcessor is to render velocity. * @param dovelocity */ public void setDoVelocity(boolean dovelocity) { this.set("dovelocity",new Boolean(dovelocity)); } /** * Gets if the RequestProcessor is to render velocity. * @return dovelocity */ public boolean getDoVelocity() { Boolean doV = (Boolean)this.get("dovelocity"); if(doV==null)return(false); return(doV.booleanValue()); } /** * Sets the request URL. Setting the request URL makes this request an URL-Request if a more specific key (contentid) is not set. * @param url */ public void setUrl(String url) { this.set("url",url); } /** * Gets the configured URL and returns it as String. Returns null if URL is not set. * @return URL */ public String getUrl() { return (String)this.get("url"); } /** * Sets the encoding that is used to render the responses that need a encoding to render. * @param encoding */ public void setEncoding(String encoding) { this.set("encoding",encoding); } /** * Returns true if this request instance is configured as URL request (RequestFilter parameter not is set and contentid is not set and URL is set) * @return boolean */ public boolean isUrlRequest() { boolean urlrequest=false; if((this.getContentid()==null || this.getContentid().equals("")) && (this.getRequestFilter()==null || this.getRequestFilter().equals("")) && (this.getUrl()!=null && !this.getUrl().equals(""))) urlrequest=true; return urlrequest; } /** * Get configured encoding. Defaults to UTF-8. * @return encoding */ public String getEncoding() { String encoding = (String)this.get("encoding"); if(encoding!=null && !encoding.equals("")) { return encoding; } else { return("UTF-8"); } } /** * Sets the contentid which can be used to request one object per contentid (object.contentid==x) * @param contentid */ public void setContentid(String contentid) { this.set("contentid", contentid); } /** * Gets the configured contentid and returns it as String. Returns null if contentid is not set. * @return contentid */ public String getContentid() { return (String)this.get("contentid"); } /** * Returns a String that can be used as cache key and identifies this request by requestFilter AND/OR contentid * Requested attributes will not be added to the key * @return cachekey * returns null if neither a contentid nor a requestfilter was found */ public String getCacheKeyFromFilter() { String contentid=this.getContentid(); if(contentid!=null)return(contentid); String filter = this.getRequestFilter(); if(filter!=null)return(filter); return null; } /** * Set custom parameter. * Keep in mind that the other variables are stored in this map as well. So x.set("contentid",contentid) is the same as x.setContentid(contentid) * @param key * @param value */ public void set(String key, Object value) { this.params.put(key, value); } /** * Gets a parameter using the given key. * @param key * @return value */ public Object get(String key) { return(this.params.get(key)); } @Override public int hashCode() { // shamelessly copied from List#hashCode() return 31*this.params.hashCode() + this.objectsToDeploy.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof CRRequest)) { return false; } CRRequest req = (CRRequest) obj; return this.params.equals(req.params) && this.objectsToDeploy.equals(req.objectsToDeploy); } }
true
true
public DatasourceFilter getPreparedFilter(CRConfig config) throws ParserException, ExpressionParserException { DatasourceFilter dsFilter; String filter =""; if((this.getRequestFilter()==null || this.getRequestFilter().equals("")) && this.getContentid()!=null && !this.getContentid().equals("")) { this.setRequestFilter("object.contentid=="+this.getContentid()); } //TEST IF REQUEST FILTER IS SAVE Expression expression = PortalConnectorFactory.createExpression(this.getRequestFilter()); //IF NO EXCEPTION IS THROWN IN THE ABOVE STATEMENT, FILTER IS CONSIDERED TO BE SAVE //ADD APPLICATION RULE IF IT IS SET if(config.getApplicationRule()==null || config.getApplicationRule().equals("")) { filter=this.getRequestFilter(); }else if(config.getApplicationRule()!=null && !config.getApplicationRule().equals("") && this.getRequestFilter()!=null && !this.getRequestFilter().equals("")) { filter="("+this.getRequestFilter()+") AND "+config.getApplicationRule(); } else if(config.getApplicationRule()!=null && !config.getApplicationRule().equals("") && (this.getRequestFilter()==null || this.getRequestFilter().equals(""))) { filter=config.getApplicationRule(); } expression = PortalConnectorFactory.createExpression(filter); dsFilter = config.getDatasource().createDatasourceFilter(expression); Iterator<String> it = this.getObjectsToDeploy().keySet().iterator(); while(it.hasNext()) { String key = it.next(); dsFilter.addBaseResolvable(key,this.getObjectsToDeploy().get(key)); } return(dsFilter); }
public DatasourceFilter getPreparedFilter(CRConfig config) throws ParserException, ExpressionParserException { DatasourceFilter dsFilter; String filter =""; if((this.getRequestFilter()==null || this.getRequestFilter().equals("")) && this.getContentid()!=null && !this.getContentid().equals("")) { this.setRequestFilter("object.contentid=='"+this.getContentid()+"'"); } //TEST IF REQUEST FILTER IS SAVE Expression expression = PortalConnectorFactory.createExpression(this.getRequestFilter()); //IF NO EXCEPTION IS THROWN IN THE ABOVE STATEMENT, FILTER IS CONSIDERED TO BE SAVE //ADD APPLICATION RULE IF IT IS SET if(config.getApplicationRule()==null || config.getApplicationRule().equals("")) { filter=this.getRequestFilter(); }else if(config.getApplicationRule()!=null && !config.getApplicationRule().equals("") && this.getRequestFilter()!=null && !this.getRequestFilter().equals("")) { filter="("+this.getRequestFilter()+") AND "+config.getApplicationRule(); } else if(config.getApplicationRule()!=null && !config.getApplicationRule().equals("") && (this.getRequestFilter()==null || this.getRequestFilter().equals(""))) { filter=config.getApplicationRule(); } expression = PortalConnectorFactory.createExpression(filter); dsFilter = config.getDatasource().createDatasourceFilter(expression); Iterator<String> it = this.getObjectsToDeploy().keySet().iterator(); while(it.hasNext()) { String key = it.next(); dsFilter.addBaseResolvable(key,this.getObjectsToDeploy().get(key)); } return(dsFilter); }
diff --git a/src/main/java/org/dynjs/parser/ast/AbstractForStatement.java b/src/main/java/org/dynjs/parser/ast/AbstractForStatement.java index 890ecd61..3d300ace 100644 --- a/src/main/java/org/dynjs/parser/ast/AbstractForStatement.java +++ b/src/main/java/org/dynjs/parser/ast/AbstractForStatement.java @@ -1,192 +1,194 @@ /** * Copyright 2012 Douglas Campos, and individual 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.dynjs.parser.ast; import static me.qmx.jitescript.util.CodegenUtils.*; import java.util.List; import me.qmx.jitescript.CodeBlock; import org.antlr.runtime.tree.Tree; import org.dynjs.compiler.CodeBlockUtils; import org.dynjs.parser.Statement; import org.dynjs.runtime.BlockManager; import org.dynjs.runtime.Completion; import org.objectweb.asm.tree.LabelNode; public abstract class AbstractForStatement extends AbstractIteratingStatement { private final Expression test; private final Expression increment; private final Statement block; public AbstractForStatement(final Tree tree, final BlockManager blockManager, final Expression test, final Expression increment, final Statement block) { super(tree, blockManager); this.test = test; this.increment = increment; this.block = block; } public abstract CodeBlock getFirstChunkCodeBlock(); protected Expression getTest() { return this.test; } protected Expression getIncrement() { return this.increment; } protected Statement getBlock() { return this.block; } public List<VariableDeclaration> getVariableDeclarations() { return this.block.getVariableDeclarations(); } @Override public CodeBlock getCodeBlock() { return new CodeBlock() { { LabelNode begin = new LabelNode(); LabelNode bringForward = new LabelNode(); LabelNode hasValue = new LabelNode(); LabelNode checkCompletion = new LabelNode(); LabelNode doIncrement = new LabelNode(); LabelNode doBreak = new LabelNode(); LabelNode doContinue = new LabelNode(); LabelNode end = new LabelNode(); append(getFirstChunkCodeBlock()); // <empty> append(normalCompletion()); // completion label(begin); if (test != null) { append(test.getCodeBlock()); append(jsGetValue()); append(jsToBoolean()); invokevirtual(p(Boolean.class), "booleanValue", sig(boolean.class)); // completion bool iffalse(end); // completion } // completion(prev) append(CodeBlockUtils.invokeCompiledStatementBlock(getBlockManager(), "For", block)); // completion(prev) completion(cur) dup(); // completion(prev) completion(cur) completion(cur) append(jsCompletionValue()); // completion(prev) completion(cur) val(cur) ifnull(bringForward); // completion(prev) completion(cur) go_to(hasValue); // ---------------------------------------- // bring previous forward label(bringForward); // completion(prev) completion(cur) dup_x1(); // completion(cur) completion(prev) completion(cur) swap(); // completion(cur) completion(cur) completion(prev) append(jsCompletionValue()); // completion(cur) completion(cur) val(prev) putfield(p(Completion.class), "value", ci(Object.class)); // completion(cur) go_to(checkCompletion); // ---------------------------------------- // has value label(hasValue); // completion(prev) completion(cur) swap(); // completion(cur) completion(prev) pop(); // completion(cur) // ---------------------------------------- // handle current completion label(checkCompletion); // completion dup(); // completion completion append(handleCompletion(doIncrement, /*break*/doBreak, /*continue*/doContinue, /*return*/end)); // ---------------------------------------- // do increment label(doIncrement); // completion if (increment != null) { append(increment.getCodeBlock()); append(jsGetValue()); pop(); } // completion go_to(begin); // ---------------------------------------- // BREAK label(doBreak); // completion(block,BREAK) dup(); // completion completion append( jsCompletionTarget() ); // completion target append( isInLabelSet() ); // completion bool iffalse(end); // completion append(convertToNormal()); // completion(block,NORMAL) go_to( end ); // ---------------------------------------- // CONTINUE label( doContinue ); // completion(block,CONTINUE) dup(); // completion completion append( jsCompletionTarget() ); // completion target append( isInLabelSet() ); // completion bool iffalse(end); // completion + append(convertToNormal()); + // completion(block,NORMAL) go_to( doIncrement ); label(end); // completion } }; } }
true
true
public CodeBlock getCodeBlock() { return new CodeBlock() { { LabelNode begin = new LabelNode(); LabelNode bringForward = new LabelNode(); LabelNode hasValue = new LabelNode(); LabelNode checkCompletion = new LabelNode(); LabelNode doIncrement = new LabelNode(); LabelNode doBreak = new LabelNode(); LabelNode doContinue = new LabelNode(); LabelNode end = new LabelNode(); append(getFirstChunkCodeBlock()); // <empty> append(normalCompletion()); // completion label(begin); if (test != null) { append(test.getCodeBlock()); append(jsGetValue()); append(jsToBoolean()); invokevirtual(p(Boolean.class), "booleanValue", sig(boolean.class)); // completion bool iffalse(end); // completion } // completion(prev) append(CodeBlockUtils.invokeCompiledStatementBlock(getBlockManager(), "For", block)); // completion(prev) completion(cur) dup(); // completion(prev) completion(cur) completion(cur) append(jsCompletionValue()); // completion(prev) completion(cur) val(cur) ifnull(bringForward); // completion(prev) completion(cur) go_to(hasValue); // ---------------------------------------- // bring previous forward label(bringForward); // completion(prev) completion(cur) dup_x1(); // completion(cur) completion(prev) completion(cur) swap(); // completion(cur) completion(cur) completion(prev) append(jsCompletionValue()); // completion(cur) completion(cur) val(prev) putfield(p(Completion.class), "value", ci(Object.class)); // completion(cur) go_to(checkCompletion); // ---------------------------------------- // has value label(hasValue); // completion(prev) completion(cur) swap(); // completion(cur) completion(prev) pop(); // completion(cur) // ---------------------------------------- // handle current completion label(checkCompletion); // completion dup(); // completion completion append(handleCompletion(doIncrement, /*break*/doBreak, /*continue*/doContinue, /*return*/end)); // ---------------------------------------- // do increment label(doIncrement); // completion if (increment != null) { append(increment.getCodeBlock()); append(jsGetValue()); pop(); } // completion go_to(begin); // ---------------------------------------- // BREAK label(doBreak); // completion(block,BREAK) dup(); // completion completion append( jsCompletionTarget() ); // completion target append( isInLabelSet() ); // completion bool iffalse(end); // completion append(convertToNormal()); // completion(block,NORMAL) go_to( end ); // ---------------------------------------- // CONTINUE label( doContinue ); // completion(block,CONTINUE) dup(); // completion completion append( jsCompletionTarget() ); // completion target append( isInLabelSet() ); // completion bool iffalse(end); // completion go_to( doIncrement ); label(end); // completion } }; }
public CodeBlock getCodeBlock() { return new CodeBlock() { { LabelNode begin = new LabelNode(); LabelNode bringForward = new LabelNode(); LabelNode hasValue = new LabelNode(); LabelNode checkCompletion = new LabelNode(); LabelNode doIncrement = new LabelNode(); LabelNode doBreak = new LabelNode(); LabelNode doContinue = new LabelNode(); LabelNode end = new LabelNode(); append(getFirstChunkCodeBlock()); // <empty> append(normalCompletion()); // completion label(begin); if (test != null) { append(test.getCodeBlock()); append(jsGetValue()); append(jsToBoolean()); invokevirtual(p(Boolean.class), "booleanValue", sig(boolean.class)); // completion bool iffalse(end); // completion } // completion(prev) append(CodeBlockUtils.invokeCompiledStatementBlock(getBlockManager(), "For", block)); // completion(prev) completion(cur) dup(); // completion(prev) completion(cur) completion(cur) append(jsCompletionValue()); // completion(prev) completion(cur) val(cur) ifnull(bringForward); // completion(prev) completion(cur) go_to(hasValue); // ---------------------------------------- // bring previous forward label(bringForward); // completion(prev) completion(cur) dup_x1(); // completion(cur) completion(prev) completion(cur) swap(); // completion(cur) completion(cur) completion(prev) append(jsCompletionValue()); // completion(cur) completion(cur) val(prev) putfield(p(Completion.class), "value", ci(Object.class)); // completion(cur) go_to(checkCompletion); // ---------------------------------------- // has value label(hasValue); // completion(prev) completion(cur) swap(); // completion(cur) completion(prev) pop(); // completion(cur) // ---------------------------------------- // handle current completion label(checkCompletion); // completion dup(); // completion completion append(handleCompletion(doIncrement, /*break*/doBreak, /*continue*/doContinue, /*return*/end)); // ---------------------------------------- // do increment label(doIncrement); // completion if (increment != null) { append(increment.getCodeBlock()); append(jsGetValue()); pop(); } // completion go_to(begin); // ---------------------------------------- // BREAK label(doBreak); // completion(block,BREAK) dup(); // completion completion append( jsCompletionTarget() ); // completion target append( isInLabelSet() ); // completion bool iffalse(end); // completion append(convertToNormal()); // completion(block,NORMAL) go_to( end ); // ---------------------------------------- // CONTINUE label( doContinue ); // completion(block,CONTINUE) dup(); // completion completion append( jsCompletionTarget() ); // completion target append( isInLabelSet() ); // completion bool iffalse(end); // completion append(convertToNormal()); // completion(block,NORMAL) go_to( doIncrement ); label(end); // completion } }; }
diff --git a/src/main/java/com/ppedregal/typescript/maven/TscMojo.java b/src/main/java/com/ppedregal/typescript/maven/TscMojo.java index 703a219..0d49c27 100644 --- a/src/main/java/com/ppedregal/typescript/maven/TscMojo.java +++ b/src/main/java/com/ppedregal/typescript/maven/TscMojo.java @@ -1,409 +1,409 @@ package com.ppedregal.typescript.maven; /* * Copyright 2001-2005 The Apache Software Foundation. * * 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. */ import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.mozilla.javascript.Context; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.NativeArray; import org.mozilla.javascript.NativeJavaObject; import org.mozilla.javascript.NativeObject; import org.mozilla.javascript.RhinoException; import org.mozilla.javascript.Script; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.commonjs.module.RequireBuilder; import org.mozilla.javascript.commonjs.module.provider.SoftCachingModuleScriptProvider; /** * Goal which compiles a set of TypeScript files * * @goal tsc * * @phase compile */ public class TscMojo extends AbstractMojo { /** * Output directory for .js compiled files * @parameter expression="${ts.targetDirectory}" default-value="target/ts" * @required */ private File targetDirectory; /** * Source directory for .ts source files * @parameter expression="${ts.sourceDirectory}" default-value="src/main/ts" */ private File sourceDirectory; /** * Source directory for .d.ts source files * @parameter expression="${ts.libraryDirectory}" default-value="src/main/d.ts" */ private File libraryDirectory; /** * The lib.d.ts file used to pass into the compiler if required * * @parameter expression="${ts.libDTS}" default-value="src/main/tsc/lib.d.ts" */ private File libDTS; /** * Encoding for files * @parameter expression="${project.build.sourceEncoding} */ private String encoding = "utf-8"; /** * Set to true to watch for changes to files and re-compile them on the fly. * * @parameter expression="${ts.watch}" */ private boolean watch = false; /** * Set to true to use the command line 'tsc' executable if its on the PATH * * @parameter expression="${ts.useTsc}" */ private boolean useTsc = false; /** * Set to true to ignore the lib.d.ts by default * * @parameter expression="${ts.nolib}" */ private boolean noStandardLib = true; /** * The amount of millis to wait before polling the source files for changes * * @parameter expression="${ts.pollTime}" */ private long pollTime = 100; private Script nodeScript; private Script tscScript; private ScriptableObject globalScope; private boolean watching; public void execute() throws MojoExecutionException { sourceDirectory.mkdirs(); targetDirectory.mkdirs(); try { compileScripts(); } catch (IOException e) { throw createMojoExecutionException(e); } doCompileFiles(false); if (watch) { watching = true; getLog().info("Waiting for changes to " + sourceDirectory + " polling every " + pollTime + " millis"); checkForChangesEvery(pollTime); } } private void checkForChangesEvery(long ms) throws MojoExecutionException { FileSetChangeMonitor monitor = new FileSetChangeMonitor(sourceDirectory, "**/*.ts"); try { while (true) { Thread.sleep(ms); List<String> modified = monitor.getModifiedFilesSinceLastTimeIAsked(); if (modified.size() > 0) { // TODO ideally we'd just pass in the files to compile here... doCompileFiles(true); } } } catch (InterruptedException e) { getLog().info("Caught interrupt, quitting."); } } private void doCompileFiles(boolean checkTimestamp) throws MojoExecutionException { Collection<File> files = FileUtils.listFiles(sourceDirectory, new String[] {"ts"}, true); doCompileFiles(checkTimestamp, files); } private void doCompileFiles(boolean checkTimestamp, Collection<File> files) throws MojoExecutionException { try { int compiledFiles = 0; if (!watching) { getLog().info("Searching directory " + sourceDirectory.getCanonicalPath()); } for (File file : files) { try { String path = file.getPath().substring(sourceDirectory.getPath().length()); String sourcePath = path; String targetPath = FilenameUtils.removeExtension(path) + ".js"; File sourceFile = new File(sourceDirectory, sourcePath).getAbsoluteFile(); File targetFile = new File(targetDirectory, targetPath).getAbsoluteFile(); if (!targetFile.exists() || !checkTimestamp || sourceFile.lastModified() > targetFile.lastModified()) { String sourceFilePath = sourceFile.getPath(); getLog().info(String.format("Compiling: %s", sourceFilePath)); String generatePath = targetFile.getPath(); tsc("--out", generatePath, sourceFilePath); getLog().info(String.format("Generated: %s", generatePath)); compiledFiles++; } } catch (TscInvocationException e) { getLog().error(e.getMessage()); if (getLog().isDebugEnabled()) { getLog().debug(e); } } } if (compiledFiles == 0) { getLog().info("Nothing to compile"); } else { getLog().info(String.format("Compiled %s file(s)", compiledFiles)); } } catch (IOException e) { throw createMojoExecutionException(e); } } private void compileScripts() throws IOException { try { Context.enter(); Context ctx = Context.getCurrentContext(); ctx.setOptimizationLevel(9); globalScope = ctx.initStandardObjects(); RequireBuilder require = new RequireBuilder(); require.setSandboxed(false); require.setModuleScriptProvider(new SoftCachingModuleScriptProvider(new ClasspathModuleSourceProvider())); require.createRequire(ctx, globalScope).install(globalScope); nodeScript = compile(ctx,"node.js"); tscScript = compile(ctx,"tsc.js"); } finally { Context.exit(); } Context.enter(); } private Script compile(Context context,String resource) throws IOException { InputStream stream = TscMojo.class.getClassLoader().getResourceAsStream(resource); if (stream==null){ throw new FileNotFoundException("Resource open error: "+resource); } try { return context.compileReader(new InputStreamReader(stream), resource, 1, null); } catch (IOException e){ throw new IOException("Resource read error: "+resource); } finally { try { stream.close(); } catch (IOException e){ throw new IOException("Resource close error: "+resource); } stream = null; } } private void tsc(String...args) throws TscInvocationException, MojoExecutionException { if (useBinary(args)) { return; } try { Context.enter(); Context ctx = Context.getCurrentContext(); nodeScript.exec(ctx, globalScope); NativeObject proc = (NativeObject)globalScope.get("process"); NativeArray argv = (NativeArray)proc.get("argv"); argv.defineProperty("length", 0, ScriptableObject.EMPTY); int i = 0; argv.put(i++, argv, "node"); argv.put(i++, argv, "tsc.js"); if (noStandardLib) { argv.put(i++, argv, "--nolib"); } - if (libDTS.exists()) { + if (libDTS!=null && libDTS.exists()) { if (!watching) { getLog().info("Adding standard library file " + libDTS); } argv.put(i++, argv, libDTS.getAbsolutePath()); } - if (libraryDirectory.exists()) { + if (libraryDirectory!=null && libraryDirectory.exists()) { File[] libFiles = libraryDirectory.listFiles(); if (libFiles != null) { for (File libFile : libFiles) { if (libFile.getName().endsWith(".d.ts") && libFile.exists()) { if (!watching) { getLog().info("Adding library file " + libFile); } argv.put(i++, argv, libFile.getAbsolutePath()); } } } } for (String s:args){ argv.put(i++, argv, s); } proc.defineProperty("encoding", encoding, ScriptableObject.READONLY); NativeObject mainModule = (NativeObject)proc.get("mainModule"); mainModule.defineProperty("filename", new File("tsc.js").getAbsolutePath(),ScriptableObject.READONLY); tscScript.exec(ctx,globalScope); } catch (JavaScriptException e){ if (e.getValue() instanceof NativeJavaObject){ NativeJavaObject njo = (NativeJavaObject)e.getValue(); Object o = njo.unwrap(); if (o instanceof ProcessExit){ ProcessExit pe = (ProcessExit)o; if (pe.getStatus()!=0){ throw new TscInvocationException("Process Error: "+pe.getStatus()); } } else { throw new TscInvocationException("Javascript Error",e); } } else { throw new TscInvocationException("Javascript Error",e); } } catch (RhinoException e){ getLog().error(e.getMessage()); throw new TscInvocationException("Rhino Error",e); } finally { org.mozilla.javascript.Context.exit(); } } private boolean useBinary(String[] args) throws MojoExecutionException { if (useTsc) { // lets try execute the 'tsc' executable directly List<String> arguments = new ArrayList<String>(); arguments.add("tsc"); if (libraryDirectory.exists()) { File[] libFiles = libraryDirectory.listFiles(); if (libFiles != null) { for (File libFile : libFiles) { if (libFile.getName().endsWith(".d.ts") && libFile.exists()) { String path = libFile.getAbsolutePath(); if (!watching) { getLog().info("Adding library file " + libFile); } arguments.add(path); } } } } for (String arg : args) { arguments.add(arg); } getLog().debug("About to execute command: " + arguments); ProcessBuilder builder = new ProcessBuilder(arguments); try { Process process = builder.start(); redirectOutput(process.getInputStream(), false); redirectOutput(process.getErrorStream(), true); int value = process.waitFor(); if (value != 0) { getLog().error("Failed to execute tsc. Return code: " + value); } else { getLog().debug("Compiled file successfully"); } } catch (IOException e) { getLog().error("Failed to execute tsc: " + e); throw createMojoExecutionException(e); } catch (InterruptedException e) { throw new MojoExecutionException(e.getMessage()); } return true; } return false; } private void redirectOutput(InputStream is, boolean error) throws IOException { try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while (true) { String line = br.readLine(); if (line == null) { break; } if (error) { getLog().error(line); } else { getLog().info(line); } } } finally { is.close(); } } private MojoExecutionException createMojoExecutionException(IOException e) { return new MojoExecutionException(e.getMessage()); } public File getTargetDirectory() { return targetDirectory; } public void setTargetDirectory(File targetDirectory) { this.targetDirectory = targetDirectory; } public File getSourceDirectory() { return sourceDirectory; } public void setSourceDirectory(File sourceDirectory) { this.sourceDirectory = sourceDirectory; } public String getEncoding() { return encoding; } public void setEncoding(String encoding) { this.encoding = encoding; } }
false
true
private void tsc(String...args) throws TscInvocationException, MojoExecutionException { if (useBinary(args)) { return; } try { Context.enter(); Context ctx = Context.getCurrentContext(); nodeScript.exec(ctx, globalScope); NativeObject proc = (NativeObject)globalScope.get("process"); NativeArray argv = (NativeArray)proc.get("argv"); argv.defineProperty("length", 0, ScriptableObject.EMPTY); int i = 0; argv.put(i++, argv, "node"); argv.put(i++, argv, "tsc.js"); if (noStandardLib) { argv.put(i++, argv, "--nolib"); } if (libDTS.exists()) { if (!watching) { getLog().info("Adding standard library file " + libDTS); } argv.put(i++, argv, libDTS.getAbsolutePath()); } if (libraryDirectory.exists()) { File[] libFiles = libraryDirectory.listFiles(); if (libFiles != null) { for (File libFile : libFiles) { if (libFile.getName().endsWith(".d.ts") && libFile.exists()) { if (!watching) { getLog().info("Adding library file " + libFile); } argv.put(i++, argv, libFile.getAbsolutePath()); } } } } for (String s:args){ argv.put(i++, argv, s); } proc.defineProperty("encoding", encoding, ScriptableObject.READONLY); NativeObject mainModule = (NativeObject)proc.get("mainModule"); mainModule.defineProperty("filename", new File("tsc.js").getAbsolutePath(),ScriptableObject.READONLY); tscScript.exec(ctx,globalScope); } catch (JavaScriptException e){ if (e.getValue() instanceof NativeJavaObject){ NativeJavaObject njo = (NativeJavaObject)e.getValue(); Object o = njo.unwrap(); if (o instanceof ProcessExit){ ProcessExit pe = (ProcessExit)o; if (pe.getStatus()!=0){ throw new TscInvocationException("Process Error: "+pe.getStatus()); } } else { throw new TscInvocationException("Javascript Error",e); } } else { throw new TscInvocationException("Javascript Error",e); } } catch (RhinoException e){ getLog().error(e.getMessage()); throw new TscInvocationException("Rhino Error",e); } finally { org.mozilla.javascript.Context.exit(); } }
private void tsc(String...args) throws TscInvocationException, MojoExecutionException { if (useBinary(args)) { return; } try { Context.enter(); Context ctx = Context.getCurrentContext(); nodeScript.exec(ctx, globalScope); NativeObject proc = (NativeObject)globalScope.get("process"); NativeArray argv = (NativeArray)proc.get("argv"); argv.defineProperty("length", 0, ScriptableObject.EMPTY); int i = 0; argv.put(i++, argv, "node"); argv.put(i++, argv, "tsc.js"); if (noStandardLib) { argv.put(i++, argv, "--nolib"); } if (libDTS!=null && libDTS.exists()) { if (!watching) { getLog().info("Adding standard library file " + libDTS); } argv.put(i++, argv, libDTS.getAbsolutePath()); } if (libraryDirectory!=null && libraryDirectory.exists()) { File[] libFiles = libraryDirectory.listFiles(); if (libFiles != null) { for (File libFile : libFiles) { if (libFile.getName().endsWith(".d.ts") && libFile.exists()) { if (!watching) { getLog().info("Adding library file " + libFile); } argv.put(i++, argv, libFile.getAbsolutePath()); } } } } for (String s:args){ argv.put(i++, argv, s); } proc.defineProperty("encoding", encoding, ScriptableObject.READONLY); NativeObject mainModule = (NativeObject)proc.get("mainModule"); mainModule.defineProperty("filename", new File("tsc.js").getAbsolutePath(),ScriptableObject.READONLY); tscScript.exec(ctx,globalScope); } catch (JavaScriptException e){ if (e.getValue() instanceof NativeJavaObject){ NativeJavaObject njo = (NativeJavaObject)e.getValue(); Object o = njo.unwrap(); if (o instanceof ProcessExit){ ProcessExit pe = (ProcessExit)o; if (pe.getStatus()!=0){ throw new TscInvocationException("Process Error: "+pe.getStatus()); } } else { throw new TscInvocationException("Javascript Error",e); } } else { throw new TscInvocationException("Javascript Error",e); } } catch (RhinoException e){ getLog().error(e.getMessage()); throw new TscInvocationException("Rhino Error",e); } finally { org.mozilla.javascript.Context.exit(); } }
diff --git a/src/org/servalproject/LogActivity.java b/src/org/servalproject/LogActivity.java index 5a91f868..325ec976 100644 --- a/src/org/servalproject/LogActivity.java +++ b/src/org/servalproject/LogActivity.java @@ -1,188 +1,187 @@ /** * Copyright (C) 2011 The Serval Project * * This file is part of Serval Software (http://www.servalproject.org) * * Serval Software 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. * * This source code 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 source code; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** * 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 3 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, see <http://www.gnu.org/licenses/>. * Use this application at your own risk. * * Copyright (c) 2009 by Harald Mueller and Seth Lemons. */ package org.servalproject; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import org.servalproject.system.ChipsetDetection; import android.app.Activity; import android.os.Bundle; import android.webkit.WebSettings; import android.webkit.WebView; public class LogActivity extends Activity { public static final String MSG_TAG = "ADHOC -> AccessControlActivity"; private static final String HEADER = "<html><head><title>background-color</title> "+ "<style type=\"text/css\"> "+ "body { background-color:#181818; font-family:Arial; font-size:100%; color: #ffffff } "+ ".date { font-family:Arial; font-size:80%; font-weight:bold} "+ ".done { font-family:Arial; font-size:80%; color: #2ff425} "+ ".failed { font-family:Arial; font-size:80%; color: #ff3636} "+ ".heading { font-family:Arial; text-decoration: underline; font-size:100%; font-weight: bold; color: #ffffff} " + ".skipped { font-family:Arial; font-size:80%; color: #6268e5} "+ "</style> "+ "</head><body>"; private static final String FOOTER = "</body></html>"; private WebView webView = null; private ServalBatPhoneApplication application; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.logview); // Init Application this.application = (ServalBatPhoneApplication)this.getApplication(); this.webView = (WebView) findViewById(R.id.webviewLog); this.webView.getSettings().setJavaScriptEnabled(false); this.webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); this.webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); this.webView.getSettings().setPluginsEnabled(false); this.webView.getSettings().setSupportMultipleWindows(false); this.webView.getSettings().setSupportZoom(false); this.setWebViewContent(); } private void setWebViewContent() { this.webView.loadDataWithBaseURL("fake://fakeme",HEADER+this.readLogfile()+FOOTER , "text/html", "UTF-8", "fake://fakeme"); } private String readLogfile(){ FileInputStream fis = null; InputStreamReader isr = null; String data = ""; List<String> logfiles = ChipsetDetection .getList("/data/data/org.servalproject/conf/logfiles.list"); for (String l : logfiles) { if (l.indexOf(":") == -1) continue; String logfile = l.substring(1, l.indexOf(":") - 1); String description = l.substring(l.indexOf(":") + 1, l.length()); data = data + "<div class=\"heading\">"+description+"</div>\n"; try { - File file = new File(application.coretask.DATA_FILE_PATH - + "/var/" + logfile + ".log"); + File file = new File("/data/data/org.servalproject/var/" + + logfile + ".log"); fis = new FileInputStream(file); isr = new InputStreamReader(fis, "utf-8"); char[] buff = new char[(int) file.length()]; isr.read(buff); data = data + new String(buff); } catch (Exception e) { // We don't need to display anything, just put a message in the // log - data = data - + "<div class=\"failed\">No ad-hoc wifi control messages</div>"; + data = data + "<div class=\"failed\">No messages</div>"; // this.application.displayToastMessage("Unable to open log-File!"); } finally { try { if (isr != null) isr.close(); if (fis != null) fis.close(); } catch (Exception e) { // nothing } } } return data; } public static void logMessage(String logname, String message, boolean failedP) { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter( "/data/data/org.servalproject/var/" + logname + ".log", true), 256); Calendar currentDate = Calendar.getInstance(); SimpleDateFormat formatter = new SimpleDateFormat( "yyyy/MMM/dd HH:mm:ss"); String dateNow = formatter.format(currentDate.getTime()); writer.write("<div class=\"date\">" + dateNow + "</div>\n"); writer.write("<div class=\"action\">" + message + "</div>\n"); writer.write("<div class=\""); if (failedP) writer.write("failed\">failed"); else writer.write("done\">done"); writer.write("</div>\n"); writer.close(); } catch (IOException e) { // Should we do something here? try { if (writer != null) writer.close(); } catch (IOException e2) { } } return; } public static void logErase(String logname) { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter( "/data/data/org.servalproject/var/" + logname + ".log", true), 256); writer.close(); } catch (IOException e) { // Should we do something here? try { if (writer != null) writer.close(); } catch (IOException e2) { } } return; } }
false
true
private String readLogfile(){ FileInputStream fis = null; InputStreamReader isr = null; String data = ""; List<String> logfiles = ChipsetDetection .getList("/data/data/org.servalproject/conf/logfiles.list"); for (String l : logfiles) { if (l.indexOf(":") == -1) continue; String logfile = l.substring(1, l.indexOf(":") - 1); String description = l.substring(l.indexOf(":") + 1, l.length()); data = data + "<div class=\"heading\">"+description+"</div>\n"; try { File file = new File(application.coretask.DATA_FILE_PATH + "/var/" + logfile + ".log"); fis = new FileInputStream(file); isr = new InputStreamReader(fis, "utf-8"); char[] buff = new char[(int) file.length()]; isr.read(buff); data = data + new String(buff); } catch (Exception e) { // We don't need to display anything, just put a message in the // log data = data + "<div class=\"failed\">No ad-hoc wifi control messages</div>"; // this.application.displayToastMessage("Unable to open log-File!"); } finally { try { if (isr != null) isr.close(); if (fis != null) fis.close(); } catch (Exception e) { // nothing } } } return data; }
private String readLogfile(){ FileInputStream fis = null; InputStreamReader isr = null; String data = ""; List<String> logfiles = ChipsetDetection .getList("/data/data/org.servalproject/conf/logfiles.list"); for (String l : logfiles) { if (l.indexOf(":") == -1) continue; String logfile = l.substring(1, l.indexOf(":") - 1); String description = l.substring(l.indexOf(":") + 1, l.length()); data = data + "<div class=\"heading\">"+description+"</div>\n"; try { File file = new File("/data/data/org.servalproject/var/" + logfile + ".log"); fis = new FileInputStream(file); isr = new InputStreamReader(fis, "utf-8"); char[] buff = new char[(int) file.length()]; isr.read(buff); data = data + new String(buff); } catch (Exception e) { // We don't need to display anything, just put a message in the // log data = data + "<div class=\"failed\">No messages</div>"; // this.application.displayToastMessage("Unable to open log-File!"); } finally { try { if (isr != null) isr.close(); if (fis != null) fis.close(); } catch (Exception e) { // nothing } } } return data; }
diff --git a/server-unit/src/test/java/org/apache/directory/server/IllegalModificationITest.java b/server-unit/src/test/java/org/apache/directory/server/IllegalModificationITest.java index a4e626ef1c..d6af620d52 100644 --- a/server-unit/src/test/java/org/apache/directory/server/IllegalModificationITest.java +++ b/server-unit/src/test/java/org/apache/directory/server/IllegalModificationITest.java @@ -1,133 +1,133 @@ /* * Copyright 2004 The Apache Software Foundation * * 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.apache.directory.server; import org.apache.directory.server.unit.AbstractServerTest; import netscape.ldap.LDAPAttribute; import netscape.ldap.LDAPAttributeSet; import netscape.ldap.LDAPConnection; import netscape.ldap.LDAPEntry; import netscape.ldap.LDAPException; import netscape.ldap.LDAPModification; /** * A test taken from DIRSERVER-630: If one tries to add an attribute to an * entry, and does not provide a value, it is assumed that the server does * not modify the entry. We have a situation here using Sun ONE Directory * SDK for Java, where adding a description attribute without value to a * person entry like this, * <code> * dn: cn=Kate Bush,dc=example,dc=com * objectclass: person * objectclass: top * sn: Bush * cn: Kate Bush * </code> * does not fail (modify call does not result in an exception). Instead, a * description attribute is created within the entry. At least the new * attribute is readable with Netscape SDK (it is not visible to most UIs, * because it is invalid ...). * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev: $ */ public class IllegalModificationITest extends AbstractServerTest { static final String DN = "cn=Kate Bush,ou=system"; static final String USER = "uid=admin,ou=system"; static final String PASSWORD = "secret"; static final String HOST = "localhost"; private LDAPConnection con = null; protected void setUp() throws Exception { super.setUp(); con = new LDAPConnection(); con.connect( 3, HOST, super.port, USER, PASSWORD ); // Create a person entry LDAPAttributeSet attrs = new LDAPAttributeSet(); attrs.add( new LDAPAttribute( "sn", "Bush" ) ); attrs.add( new LDAPAttribute( "cn", "Kate Bush" ) ); LDAPAttribute oc = new LDAPAttribute( "objectClass" ); oc.addValue( "top" ); oc.addValue( "person" ); attrs.add( oc ); LDAPEntry entry = new LDAPEntry( DN, attrs ); con.add( entry ); } protected void tearDown() throws Exception { // Remove the person entry and disconnect con.delete( DN ); con.disconnect(); super.tearDown(); } public void testIllegalModification() throws LDAPException { LDAPAttribute attr = new LDAPAttribute( "description" ); LDAPModification mod = new LDAPModification( LDAPModification.ADD, attr ); try { con.modify( "cn=Kate Bush,ou=system", mod ); fail( "error expected due to empty attribute value" ); } catch ( LDAPException e ) { // expected } // Check whether entry is unmodified, i.e. no description LDAPEntry entry = con.read( DN ); assertEquals( "description exists?", null, entry.getAttribute( "description" ) ); } public void testIllegalModification2() throws LDAPException { // first a valid attribute LDAPAttribute attr = new LDAPAttribute( "description", "The description" ); LDAPModification mod = new LDAPModification( LDAPModification.ADD, attr ); // then an invalid one without any value attr = new LDAPAttribute( "displayName" ); LDAPModification mod2 = new LDAPModification( LDAPModification.ADD, attr ); try { con.modify( "cn=Kate Bush,ou=system", new LDAPModification[] { mod, mod2 } ); fail( "error expected due to empty attribute value" ); } catch ( LDAPException e ) { // expected } - // Check whether entry is unmodified, i.e. no description + // Check whether entry is unmodified, i.e. no displayName LDAPEntry entry = con.read( DN ); assertEquals( "displayName exists?", null, entry.getAttribute( "displayName" ) ); } }
true
true
public void testIllegalModification2() throws LDAPException { // first a valid attribute LDAPAttribute attr = new LDAPAttribute( "description", "The description" ); LDAPModification mod = new LDAPModification( LDAPModification.ADD, attr ); // then an invalid one without any value attr = new LDAPAttribute( "displayName" ); LDAPModification mod2 = new LDAPModification( LDAPModification.ADD, attr ); try { con.modify( "cn=Kate Bush,ou=system", new LDAPModification[] { mod, mod2 } ); fail( "error expected due to empty attribute value" ); } catch ( LDAPException e ) { // expected } // Check whether entry is unmodified, i.e. no description LDAPEntry entry = con.read( DN ); assertEquals( "displayName exists?", null, entry.getAttribute( "displayName" ) ); }
public void testIllegalModification2() throws LDAPException { // first a valid attribute LDAPAttribute attr = new LDAPAttribute( "description", "The description" ); LDAPModification mod = new LDAPModification( LDAPModification.ADD, attr ); // then an invalid one without any value attr = new LDAPAttribute( "displayName" ); LDAPModification mod2 = new LDAPModification( LDAPModification.ADD, attr ); try { con.modify( "cn=Kate Bush,ou=system", new LDAPModification[] { mod, mod2 } ); fail( "error expected due to empty attribute value" ); } catch ( LDAPException e ) { // expected } // Check whether entry is unmodified, i.e. no displayName LDAPEntry entry = con.read( DN ); assertEquals( "displayName exists?", null, entry.getAttribute( "displayName" ) ); }
diff --git a/src/Core/org/objectweb/proactive/core/component/controller/ProActiveBindingControllerImpl.java b/src/Core/org/objectweb/proactive/core/component/controller/ProActiveBindingControllerImpl.java index a395f3413..306cc36dd 100644 --- a/src/Core/org/objectweb/proactive/core/component/controller/ProActiveBindingControllerImpl.java +++ b/src/Core/org/objectweb/proactive/core/component/controller/ProActiveBindingControllerImpl.java @@ -1,684 +1,684 @@ /* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis * Contact: [email protected] * * This library 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 any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ */ package org.objectweb.proactive.core.component.controller; import java.io.Serializable; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.objectweb.fractal.api.Component; import org.objectweb.fractal.api.Interface; import org.objectweb.fractal.api.NoSuchInterfaceException; import org.objectweb.fractal.api.control.BindingController; import org.objectweb.fractal.api.control.IllegalBindingException; import org.objectweb.fractal.api.control.IllegalLifeCycleException; import org.objectweb.fractal.api.control.LifeCycleController; import org.objectweb.fractal.api.factory.InstantiationException; import org.objectweb.fractal.api.type.ComponentType; import org.objectweb.fractal.api.type.InterfaceType; import org.objectweb.fractal.api.type.TypeFactory; import org.objectweb.fractal.util.Fractal; import org.objectweb.proactive.api.PAFuture; import org.objectweb.proactive.api.PAGroup; import org.objectweb.proactive.core.ProActiveRuntimeException; import org.objectweb.proactive.core.component.Binding; import org.objectweb.proactive.core.component.Bindings; import org.objectweb.proactive.core.component.Constants; import org.objectweb.proactive.core.component.Fractive; import org.objectweb.proactive.core.component.ItfStubObject; import org.objectweb.proactive.core.component.ProActiveInterface; import org.objectweb.proactive.core.component.Utils; import org.objectweb.proactive.core.component.exceptions.InterfaceGenerationFailedException; import org.objectweb.proactive.core.component.gen.GatherItfAdapterProxy; import org.objectweb.proactive.core.component.gen.OutputInterceptorClassGenerator; import org.objectweb.proactive.core.component.identity.ProActiveComponent; import org.objectweb.proactive.core.component.identity.ProActiveComponentImpl; import org.objectweb.proactive.core.component.representative.ItfID; import org.objectweb.proactive.core.component.type.ProActiveInterfaceType; import org.objectweb.proactive.core.component.type.ProActiveInterfaceTypeImpl; import org.objectweb.proactive.core.component.type.ProActiveTypeFactoryImpl; /** * Implementation of the * {@link org.objectweb.fractal.api.control.BindingController BindingController} interface. * * @author The ProActive Team * */ public class ProActiveBindingControllerImpl extends AbstractProActiveController implements ProActiveBindingController, Serializable, ControllerStateDuplication { protected Bindings bindings; // key = clientInterfaceName ; value = Binding // private Map<String, Map<ProActiveComponent, List<String>>> bindingsOnServerItfs = new HashMap<String, Map<ProActiveComponent,List<String>>>(0); // Map(serverItfName, Map(owner, clientItfName)) public ProActiveBindingControllerImpl(Component owner) { super(owner); bindings = new Bindings(); } @Override protected void setControllerItfType() { try { setItfType(ProActiveTypeFactoryImpl.instance().createFcItfType(Constants.BINDING_CONTROLLER, ProActiveBindingController.class.getName(), TypeFactory.SERVER, TypeFactory.MANDATORY, TypeFactory.SINGLE)); } catch (InstantiationException e) { throw new ProActiveRuntimeException("cannot create controller type for controller " + this.getClass().getName()); } } public void addBinding(Binding binding) { bindings.add(binding); } protected void checkBindability(String clientItfName, Interface serverItf) throws NoSuchInterfaceException, IllegalBindingException, IllegalLifeCycleException { if (!(serverItf instanceof ProActiveInterface)) { throw new IllegalBindingException("Can only bind interfaces of type ProActiveInterface"); } // if (((InterfaceType) serverItf.getFcItfType()).isFcClientItf()) // throw new IllegalBindingException("The provided server interface is a client interface"); ProActiveInterfaceType clientItfType = (ProActiveInterfaceType) Utils .getItfType(clientItfName, owner); // TODO_M handle internal interfaces // if (server_itf_type.isFcClientItf()) { // throw new IllegalBindingException("cannot bind client interface " + // clientItfName + " to other client interface " // +server_itf_type.getFcItfName() ); // } // if (!client_itf_type.isFcClientItf()) { // throw new IllegalBindingException("cannot bind client interface " + // clientItfName + " to other client interface " // +server_itf_type.getFcItfName() ); // } if (!(Fractal.getLifeCycleController(getFcItfOwner())).getFcState().equals( LifeCycleController.STOPPED)) { throw new IllegalLifeCycleException("component has to be stopped to perform binding operations"); } // multicast interfaces : interfaces must be compatible // (rem : itf is null when it is a single itf not yet bound if (Utils.isMulticastItf(clientItfName, getFcItfOwner())) { Fractive.getMulticastController(owner).ensureCompatibility(clientItfType, (ProActiveInterface) serverItf); // ensure multicast interface of primitive component is initialized if (isPrimitive()) { BindingController userBindingController = (BindingController) (owner) .getReferenceOnBaseObject(); if ((userBindingController.lookupFc(clientItfName) == null) || !(PAGroup.isGroup(userBindingController.lookupFc(clientItfName)))) { userBindingController.bindFc(clientItfName, owner.getFcInterface(clientItfName)); } } } if (Utils.isGathercastItf(serverItf)) { Fractive.getGathercastController(owner).ensureCompatibility(clientItfType, (ProActiveInterface) serverItf); } // TODO type checkings for other cardinalities else if (Utils.isSingletonItf(clientItfName, getFcItfOwner())) { InterfaceType sType = (InterfaceType) serverItf.getFcItfType(); //InterfaceType cType = (InterfaceType)((ProActiveInterface)owner.getFcInterface(clientItfName)).getFcItfType(); InterfaceType cType = ((ComponentType) owner.getFcType()).getFcInterfaceType(clientItfName); try { Class<?> s = Class.forName(sType.getFcItfSignature()); Class<?> c = Class.forName(cType.getFcItfSignature()); if (!c.isAssignableFrom(s)) { throw new IllegalBindingException("The server interface type " + s.getName() + " is not a subtype of the client interface type " + c.getName()); } } catch (ClassNotFoundException e) { IllegalBindingException ibe = new IllegalBindingException("Cannot find type of interface : " + e.getMessage()); ibe.initCause(e); throw ibe; } } // check for binding primitive component can only be performed in the // primitive component if (!isPrimitive()) { // removed the following checkings as they did not consider composite server itfs // checkClientInterfaceName(clientItfName); if (existsBinding(clientItfName)) { if (!((ProActiveInterfaceTypeImpl) ((Interface) getFcItfOwner().getFcInterface(clientItfName)) .getFcItfType()).isFcCollectionItf()) { // binding from a single client interface : only 1 binding // is allowed controllerLogger.warn(Fractal.getNameController(getFcItfOwner()).getFcName() + "." + clientItfName + " is already bound"); throw new IllegalBindingException(clientItfName + " is already bound"); } else { // binding from a collection interface if (((InterfaceType) serverItf.getFcItfType()).isFcClientItf()) { // binding to a client(external) interface --> not OK throw new IllegalBindingException(serverItf.getFcItfName() + " is not a server interface"); } } } } // TODO_M : check bindings between external client interfaces // see next, but need to consider internal interfaces (i.e. valid if // server AND internal) // TODO_M : check bindings crossing composite membranes } protected void checkUnbindability(String clientItfName) throws NoSuchInterfaceException, IllegalBindingException, IllegalLifeCycleException { checkLifeCycleIsStopped(); checkClientInterfaceName(clientItfName); if (Utils.getItfType(clientItfName, owner).isFcCollectionItf()) { throw new IllegalBindingException( "In this implementation, for coherency reasons, it is not possible to unbind members of a collection interface"); } } /** * * @param clientItfName * the name of the client interface * @return a Binding object if single binding, List of Binding objects * otherwise */ public Object removeBinding(String clientItfName) { return bindings.remove(clientItfName); } /** * * @param clientItfName * the name of the client interface * @return a Binding object if single binding, List of Binding objects * otherwise */ public Object getBinding(String clientItfName) { return bindings.get(clientItfName); } /** * see * * @link org.objectweb.fractal.api.control.BindingController#lookupFc(String) */ public Object lookupFc(String clientItfName) throws NoSuchInterfaceException { Object itf = null; if (isPrimitive()) { itf = ((BindingController) ((ProActiveComponent) getFcItfOwner()).getReferenceOnBaseObject()) .lookupFc(clientItfName); } else if (existsBinding(clientItfName)) { itf = ((Binding) getBinding(clientItfName)).getServerInterface(); } if (itf == null) { //check if the interface name exist, if not we must throw a NoSuchInterfaceException checkClientInterfaceExist(clientItfName); } return itf; } /** * implementation of the interface BindingController see * {@link BindingController#bindFc(java.lang.String, java.lang.Object)} */ public void bindFc(String clientItfName, Object serverItf) throws NoSuchInterfaceException, IllegalBindingException, IllegalLifeCycleException { // get value of (eventual) future before casting serverItf = PAFuture.getFutureValue(serverItf); ProActiveInterface sItf = (ProActiveInterface) serverItf; // if (controllerLogger.isDebugEnabled()) { // String serverComponentName; // // if (PAGroup.isGroup(serverItf)) { // serverComponentName = "a group of components "; // } else { // serverComponentName = Fractal.getNameController((sItf).getFcItfOwner()).getFcName(); // } // // controllerLogger.debug("binding " + Fractal.getNameController(getFcItfOwner()).getFcName() + "." + // clientItfName + " to " + serverComponentName + "." + (sItf).getFcItfName()); // } checkBindability(clientItfName, (Interface) serverItf); ((ItfStubObject) serverItf).setSenderItfID(new ItfID(clientItfName, ((ProActiveComponent) getFcItfOwner()).getID())); // if output interceptors are defined // TODO_M check with groups : interception is here done at the beginning // of the group invocation, // not for each element of the group List<Interface> outputInterceptors = ((ProActiveComponentImpl) getFcItfOwner()) .getOutputInterceptors(); if (!outputInterceptors.isEmpty()) { try { // replace server itf with an interface of the same type+same proxy, but with interception code sItf = OutputInterceptorClassGenerator.instance().generateInterface(sItf, outputInterceptors); } catch (InterfaceGenerationFailedException e) { controllerLogger.error("could not generate output interceptor for client interface " + clientItfName + " : " + e.getMessage()); IllegalBindingException ibe = new IllegalBindingException( "could not generate output interceptor for client interface " + clientItfName + " : " + e.getMessage()); ibe.initCause(e); throw ibe; } } // Multicast bindings are handled here if (Utils.isMulticastItf(clientItfName, owner)) { if (Utils.isGathercastItf(sItf)) { // Fractive.getMulticastController(owner) // .bindFcMulticast(clientItfName, getGathercastAdaptor(clientItfName, serverItf, sItf)); // no adaptor here - ((MulticastControllerImpl) Fractive.getMulticastController(owner)) - .bindFc(clientItfName, sItf); + ((MulticastControllerImpl) ((ProActiveInterface) Fractive.getMulticastController(owner)) + .getFcItfImpl()).bindFc(clientItfName, sItf); // add a callback ref in the server gather interface // TODO should throw a binding event try { if (Fractive.getMembraneController((sItf).getFcItfOwner()).getMembraneState().equals( MembraneController.MEMBRANE_STOPPED)) { throw new IllegalLifeCycleException( "The membrane of the owner of the server interface should be started"); } } catch (NoSuchInterfaceException e) { //If the component doesn't have a MembraneController, it won't have any impact on the rest of the method. } Fractive.getGathercastController((sItf).getFcItfOwner()).addedBindingOnServerItf( sItf.getFcItfName(), (owner).getRepresentativeOnThis(), clientItfName); } else { MulticastController mc = Fractive.getMulticastController(owner); ProActiveInterface pitf = (ProActiveInterface) mc; MulticastControllerImpl impl = (MulticastControllerImpl) pitf.getFcItfImpl(); impl.bindFc(clientItfName, sItf); //((MulticastControllerImpl) Fractive.getMulticastController(owner)) // .bindFc(clientItfName, sItf); } return; } if (isPrimitive()) { checkClientInterfaceExist(clientItfName); // binding operation is delegated if (Utils.isGathercastItf(sItf)) { primitiveBindFc(clientItfName, getGathercastAdaptor(clientItfName, serverItf, sItf)); // add a callback ref in the server gather interface // TODO should throw a binding event try { if (Fractive.getMembraneController((sItf).getFcItfOwner()).getMembraneState().equals( MembraneController.MEMBRANE_STOPPED)) { throw new IllegalLifeCycleException( "The membrane of the owner of the server interface should be started"); } } catch (NoSuchInterfaceException e) { //If the component doesn't have a MembraneController, it won't have any impact on the rest of the method. } Fractive.getGathercastController((sItf).getFcItfOwner()).addedBindingOnServerItf( sItf.getFcItfName(), (owner).getRepresentativeOnThis(), clientItfName); } else { primitiveBindFc(clientItfName, sItf); } return; } // composite or parallel InterfaceType client_itf_type; client_itf_type = Utils.getItfType(clientItfName, owner); if (isComposite()) { if (Utils.isGathercastItf(sItf)) { compositeBindFc(clientItfName, client_itf_type, getGathercastAdaptor(clientItfName, serverItf, sItf)); // add a callback ref in the server gather interface // TODO should throw a binding event try { if (Fractive.getMembraneController((sItf).getFcItfOwner()).getMembraneState().equals( MembraneController.MEMBRANE_STOPPED)) { throw new IllegalLifeCycleException( "The membrane of the owner of the server interface should be started"); } } catch (NoSuchInterfaceException e) { //If the component doesn't have a MembraneController, it won't have any impact on the rest of the method. } Fractive.getGathercastController(sItf.getFcItfOwner()).addedBindingOnServerItf( sItf.getFcItfName(), owner.getRepresentativeOnThis(), clientItfName); } else { compositeBindFc(clientItfName, client_itf_type, sItf); } } } private ProActiveInterface getGathercastAdaptor(String clientItfName, Object serverItf, ProActiveInterface sItf) throws NoSuchInterfaceException { // add an adaptor proxy for matching interface types Class<?> clientItfClass = null; try { InterfaceType[] cItfTypes = ((ComponentType) owner.getFcType()).getFcInterfaceTypes(); for (int i = 0; i < cItfTypes.length; i++) { if (clientItfName.equals(cItfTypes[i].getFcItfName()) || (cItfTypes[i].isFcCollectionItf() && clientItfName .startsWith(cItfTypes[i].getFcItfName()))) { clientItfClass = Class.forName(cItfTypes[i].getFcItfSignature()); } } if (clientItfClass == null) { throw new ProActiveRuntimeException("could not find type of client interface " + clientItfName); } } catch (ClassNotFoundException e) { throw new ProActiveRuntimeException("cannot find client interface class for client interface : " + clientItfName); } ProActiveInterface itfProxy = (ProActiveInterface) Proxy.newProxyInstance(Thread.currentThread() .getContextClassLoader(), new Class<?>[] { ProActiveInterface.class, clientItfClass }, new GatherItfAdapterProxy(serverItf)); return itfProxy; } private void primitiveBindFc(String clientItfName, ProActiveInterface serverItf) throws NoSuchInterfaceException, IllegalBindingException, IllegalLifeCycleException { // delegate binding operation to the reified object BindingController user_binding_controller = (BindingController) ((ProActiveComponent) getFcItfOwner()) .getReferenceOnBaseObject(); // serverItf cannot be a Future (because it has to be casted) => make // sure if binding to a composite's internal interface serverItf = (ProActiveInterface) PAFuture.getFutureValue(serverItf); //if not already bound if (user_binding_controller.lookupFc(clientItfName) == null || ((ProActiveInterfaceType) ((Interface) user_binding_controller.lookupFc(clientItfName)) .getFcItfType()).isFcMulticastItf()) { user_binding_controller.bindFc(clientItfName, serverItf); // addBinding(new Binding(clientItf, clientItfName, serverItf)); } else { throw new IllegalBindingException("The client interface '" + serverItf + "' is already bound!"); } } /* * binding method enforcing Interface type for the server interface, for composite components */ private void compositeBindFc(String clientItfName, InterfaceType clientItfType, Interface serverItf) throws NoSuchInterfaceException, IllegalBindingException, IllegalLifeCycleException { ProActiveInterface clientItf = null; clientItf = (ProActiveInterface) getFcItfOwner().getFcInterface(clientItfName); // TODO remove this as we should now use multicast interfaces for this purpose // if we have a collection interface, the impl object is actually a // group of references to interfaces // Thus we have to add the link to the new interface in this group // same for client interfaces of parallel components if (clientItfType.getFcItfName().equals(clientItfName)) { // if ((isParallel() && !clientItfType.isFcClientItf())) { // // collective binding, unnamed interface // // TODO provide a default name? // Group itf_group = ProActiveGroup.getGroup(clientItf.getFcItfImpl()); // itf_group.add(serverItf); // } else { // single binding clientItf.setFcItfImpl(serverItf); // } } else { if (Utils.getItfType(clientItfName, owner).isFcCollectionItf()) { clientItf.setFcItfImpl(serverItf); } else { // if ((isParallel() && !clientItfType.isFcClientItf())) { // // Group itf_group = ProActiveGroup.getGroup(clientItf.getFcItfImpl()); // itf_group.addNamedElement(clientItfName, serverItf); // } else { throw new NoSuchInterfaceException("Cannot bind interface " + clientItfName + " because it does not correspond to the specified type"); } } // } addBinding(new Binding(clientItf, clientItfName, serverItf)); } /* * @see org.objectweb.fractal.api.control.BindingController#unbindFc(String) * * CAREFUL : unbinding action on collective interfaces will remove all the bindings to this * interface. This is also the case when removing bindings from the server interface of a * parallel component (yes you can do unbindFc(parallelServerItfName) !) */ public void unbindFc(String clientItfName) throws NoSuchInterfaceException, IllegalBindingException, IllegalLifeCycleException { if (!existsBinding(clientItfName)) { throw new IllegalBindingException(clientItfName + " is not yet bound"); } // remove from bindings and set impl object to null if (isPrimitive()) { // delegate to primitive component BindingController user_binding_controller = (BindingController) ((ProActiveComponent) getFcItfOwner()) .getReferenceOnBaseObject(); if (Utils.isGathercastItf((Interface) user_binding_controller.lookupFc(clientItfName))) { ProActiveInterface sItf = (ProActiveInterface) user_binding_controller .lookupFc(clientItfName); try { if (Fractive.getMembraneController((sItf).getFcItfOwner()).getMembraneState().equals( MembraneController.MEMBRANE_STOPPED)) { throw new IllegalLifeCycleException( "The client interface is bound to a component that has its membrane in a stopped state. It should be strated, as this method could interact with its controllers."); } } catch (NoSuchInterfaceException e) { //If the component doesn't have a MembraneController, it won't have any impact on the rest of the method. } Fractive.getGathercastController(sItf.getFcItfOwner()).removedBindingOnServerItf( sItf.getFcItfName(), (ProActiveComponent) sItf.getFcItfOwner(), clientItfName); } user_binding_controller.unbindFc(clientItfName); } else { checkUnbindability(clientItfName); } removeBinding(clientItfName); } /** * @see org.objectweb.fractal.api.control.BindingController#listFc() In case * of a client collection interface, only the interfaces generated at * runtime and members of the collection are returned (a reference on * the collection interface itself is not returned, because it is just * a typing artifact and does not exist at runtime). */ public String[] listFc() { if (isPrimitive()) { return ((BindingController) ((ProActiveComponent) getFcItfOwner()).getReferenceOnBaseObject()) .listFc(); } InterfaceType[] itfs_types = ((ComponentType) getFcItfOwner().getFcType()).getFcInterfaceTypes(); List<String> client_itfs_names = new ArrayList<String>(); for (int i = 0; i < itfs_types.length; i++) { if (itfs_types[i].isFcClientItf()) { if (itfs_types[i].isFcCollectionItf()) { List<Interface> collection_itfs = (List<Interface>) bindings.get(itfs_types[i] .getFcItfName()); if (collection_itfs != null) { Iterator<Interface> it = collection_itfs.iterator(); while (it.hasNext()) { client_itfs_names.add(((Interface) it.next()).getFcItfName()); } } } else { client_itfs_names.add(itfs_types[i].getFcItfName()); } } } return client_itfs_names.toArray(new String[client_itfs_names.size()]); } protected boolean existsBinding(String clientItfName) throws NoSuchInterfaceException { if (isPrimitive() && !(((ProActiveInterfaceType) ((ComponentType) owner.getFcType()).getFcInterfaceType(clientItfName)) .isFcMulticastItf())) { return (((BindingController) ((ProActiveComponent) getFcItfOwner()).getReferenceOnBaseObject()) .lookupFc(clientItfName) != null); } else { return bindings.containsBindingOn(clientItfName); } } protected void checkClientInterfaceName(String clientItfName) throws NoSuchInterfaceException { if (Utils.hasSingleCardinality(clientItfName, owner)) { return; } if (Utils.pertainsToACollectionInterface(clientItfName, owner) != null) { return; } if (Utils.isMulticastItf(clientItfName, owner)) { return; } throw new NoSuchInterfaceException(clientItfName + " does not correspond to a single nor a collective interface"); } /** * Throws a NoSuchInterfaceException exception if there is no client interface with this name * defined in the owner component type. It's applicable only on primitive. * * @throws NoSuchInterfaceException */ private void checkClientInterfaceExist(String clientItfName) throws NoSuchInterfaceException { InterfaceType[] itfTypes = ((ComponentType) getFcItfOwner().getFcType()).getFcInterfaceTypes(); for (InterfaceType interfaceType : itfTypes) { if (clientItfName.startsWith(interfaceType.getFcItfName())) { return; } } throw new NoSuchInterfaceException(clientItfName); } public Boolean isBound() { String[] client_itf_names = listFc(); for (int i = 0; i < client_itf_names.length; i++) { try { if (existsBinding(client_itf_names[i])) { return true; } } catch (NoSuchInterfaceException logged) { controllerLogger.error("cannot find interface " + client_itf_names[i] + " : " + logged.getMessage()); } } return new Boolean(false); } public Bindings getBindings() { return bindings; } public void duplicateController(Object c) { if (c instanceof Bindings) { bindings = (Bindings) c; } else { throw new ProActiveRuntimeException( "ProActiveBindingControllerImpl : Impossible to duplicate the controller " + this + " from the controller" + c); } } public ControllerState getState() { return new ControllerState(bindings); } private Interface[] filterServerItfs(Object[] itfs) { ArrayList<Interface> newListItfs = new ArrayList<Interface>(); for (int i = 0; i < itfs.length; i++) { Interface curItf = (Interface) itfs[i]; if (!((ProActiveInterfaceType) curItf.getFcItfType()).isFcClientItf()) newListItfs.add(curItf); } return newListItfs.toArray(new Interface[] {}); } public Boolean isBoundTo(Component component) { Interface[] serverItfsComponent = filterServerItfs(component.getFcInterfaces()); Object[] itfs = getFcItfOwner().getFcInterfaces(); for (int i = 0; i < itfs.length; i++) { Interface curItf = (Interface) itfs[i]; if (!((ProActiveInterfaceType) curItf.getFcItfType()).isFcMulticastItf()) { for (int j = 0; j < serverItfsComponent.length; j++) { Interface curServerItf = serverItfsComponent[j]; Binding binding = (Binding) getBinding(curItf.getFcItfName()); if ((binding != null) && binding.getServerInterface().getFcItfOwner().equals(curServerItf.getFcItfOwner()) && binding.getServerInterface().getFcItfType().equals(curServerItf.getFcItfType())) { return new Boolean(true); } } } else { try { MulticastController mc = (MulticastController) getFcItfOwner().getFcInterface( Constants.MULTICAST_CONTROLLER); if (mc.isBoundTo(curItf, serverItfsComponent)) return new Boolean(true); } catch (NoSuchInterfaceException e) { // TODO: handle exception } } } return new Boolean(false); } }
true
true
public void bindFc(String clientItfName, Object serverItf) throws NoSuchInterfaceException, IllegalBindingException, IllegalLifeCycleException { // get value of (eventual) future before casting serverItf = PAFuture.getFutureValue(serverItf); ProActiveInterface sItf = (ProActiveInterface) serverItf; // if (controllerLogger.isDebugEnabled()) { // String serverComponentName; // // if (PAGroup.isGroup(serverItf)) { // serverComponentName = "a group of components "; // } else { // serverComponentName = Fractal.getNameController((sItf).getFcItfOwner()).getFcName(); // } // // controllerLogger.debug("binding " + Fractal.getNameController(getFcItfOwner()).getFcName() + "." + // clientItfName + " to " + serverComponentName + "." + (sItf).getFcItfName()); // } checkBindability(clientItfName, (Interface) serverItf); ((ItfStubObject) serverItf).setSenderItfID(new ItfID(clientItfName, ((ProActiveComponent) getFcItfOwner()).getID())); // if output interceptors are defined // TODO_M check with groups : interception is here done at the beginning // of the group invocation, // not for each element of the group List<Interface> outputInterceptors = ((ProActiveComponentImpl) getFcItfOwner()) .getOutputInterceptors(); if (!outputInterceptors.isEmpty()) { try { // replace server itf with an interface of the same type+same proxy, but with interception code sItf = OutputInterceptorClassGenerator.instance().generateInterface(sItf, outputInterceptors); } catch (InterfaceGenerationFailedException e) { controllerLogger.error("could not generate output interceptor for client interface " + clientItfName + " : " + e.getMessage()); IllegalBindingException ibe = new IllegalBindingException( "could not generate output interceptor for client interface " + clientItfName + " : " + e.getMessage()); ibe.initCause(e); throw ibe; } } // Multicast bindings are handled here if (Utils.isMulticastItf(clientItfName, owner)) { if (Utils.isGathercastItf(sItf)) { // Fractive.getMulticastController(owner) // .bindFcMulticast(clientItfName, getGathercastAdaptor(clientItfName, serverItf, sItf)); // no adaptor here ((MulticastControllerImpl) Fractive.getMulticastController(owner)) .bindFc(clientItfName, sItf); // add a callback ref in the server gather interface // TODO should throw a binding event try { if (Fractive.getMembraneController((sItf).getFcItfOwner()).getMembraneState().equals( MembraneController.MEMBRANE_STOPPED)) { throw new IllegalLifeCycleException( "The membrane of the owner of the server interface should be started"); } } catch (NoSuchInterfaceException e) { //If the component doesn't have a MembraneController, it won't have any impact on the rest of the method. } Fractive.getGathercastController((sItf).getFcItfOwner()).addedBindingOnServerItf( sItf.getFcItfName(), (owner).getRepresentativeOnThis(), clientItfName); } else { MulticastController mc = Fractive.getMulticastController(owner); ProActiveInterface pitf = (ProActiveInterface) mc; MulticastControllerImpl impl = (MulticastControllerImpl) pitf.getFcItfImpl(); impl.bindFc(clientItfName, sItf); //((MulticastControllerImpl) Fractive.getMulticastController(owner)) // .bindFc(clientItfName, sItf); } return; } if (isPrimitive()) { checkClientInterfaceExist(clientItfName); // binding operation is delegated if (Utils.isGathercastItf(sItf)) { primitiveBindFc(clientItfName, getGathercastAdaptor(clientItfName, serverItf, sItf)); // add a callback ref in the server gather interface // TODO should throw a binding event try { if (Fractive.getMembraneController((sItf).getFcItfOwner()).getMembraneState().equals( MembraneController.MEMBRANE_STOPPED)) { throw new IllegalLifeCycleException( "The membrane of the owner of the server interface should be started"); } } catch (NoSuchInterfaceException e) { //If the component doesn't have a MembraneController, it won't have any impact on the rest of the method. } Fractive.getGathercastController((sItf).getFcItfOwner()).addedBindingOnServerItf( sItf.getFcItfName(), (owner).getRepresentativeOnThis(), clientItfName); } else { primitiveBindFc(clientItfName, sItf); } return; } // composite or parallel InterfaceType client_itf_type; client_itf_type = Utils.getItfType(clientItfName, owner); if (isComposite()) { if (Utils.isGathercastItf(sItf)) { compositeBindFc(clientItfName, client_itf_type, getGathercastAdaptor(clientItfName, serverItf, sItf)); // add a callback ref in the server gather interface // TODO should throw a binding event try { if (Fractive.getMembraneController((sItf).getFcItfOwner()).getMembraneState().equals( MembraneController.MEMBRANE_STOPPED)) { throw new IllegalLifeCycleException( "The membrane of the owner of the server interface should be started"); } } catch (NoSuchInterfaceException e) { //If the component doesn't have a MembraneController, it won't have any impact on the rest of the method. } Fractive.getGathercastController(sItf.getFcItfOwner()).addedBindingOnServerItf( sItf.getFcItfName(), owner.getRepresentativeOnThis(), clientItfName); } else { compositeBindFc(clientItfName, client_itf_type, sItf); } } }
public void bindFc(String clientItfName, Object serverItf) throws NoSuchInterfaceException, IllegalBindingException, IllegalLifeCycleException { // get value of (eventual) future before casting serverItf = PAFuture.getFutureValue(serverItf); ProActiveInterface sItf = (ProActiveInterface) serverItf; // if (controllerLogger.isDebugEnabled()) { // String serverComponentName; // // if (PAGroup.isGroup(serverItf)) { // serverComponentName = "a group of components "; // } else { // serverComponentName = Fractal.getNameController((sItf).getFcItfOwner()).getFcName(); // } // // controllerLogger.debug("binding " + Fractal.getNameController(getFcItfOwner()).getFcName() + "." + // clientItfName + " to " + serverComponentName + "." + (sItf).getFcItfName()); // } checkBindability(clientItfName, (Interface) serverItf); ((ItfStubObject) serverItf).setSenderItfID(new ItfID(clientItfName, ((ProActiveComponent) getFcItfOwner()).getID())); // if output interceptors are defined // TODO_M check with groups : interception is here done at the beginning // of the group invocation, // not for each element of the group List<Interface> outputInterceptors = ((ProActiveComponentImpl) getFcItfOwner()) .getOutputInterceptors(); if (!outputInterceptors.isEmpty()) { try { // replace server itf with an interface of the same type+same proxy, but with interception code sItf = OutputInterceptorClassGenerator.instance().generateInterface(sItf, outputInterceptors); } catch (InterfaceGenerationFailedException e) { controllerLogger.error("could not generate output interceptor for client interface " + clientItfName + " : " + e.getMessage()); IllegalBindingException ibe = new IllegalBindingException( "could not generate output interceptor for client interface " + clientItfName + " : " + e.getMessage()); ibe.initCause(e); throw ibe; } } // Multicast bindings are handled here if (Utils.isMulticastItf(clientItfName, owner)) { if (Utils.isGathercastItf(sItf)) { // Fractive.getMulticastController(owner) // .bindFcMulticast(clientItfName, getGathercastAdaptor(clientItfName, serverItf, sItf)); // no adaptor here ((MulticastControllerImpl) ((ProActiveInterface) Fractive.getMulticastController(owner)) .getFcItfImpl()).bindFc(clientItfName, sItf); // add a callback ref in the server gather interface // TODO should throw a binding event try { if (Fractive.getMembraneController((sItf).getFcItfOwner()).getMembraneState().equals( MembraneController.MEMBRANE_STOPPED)) { throw new IllegalLifeCycleException( "The membrane of the owner of the server interface should be started"); } } catch (NoSuchInterfaceException e) { //If the component doesn't have a MembraneController, it won't have any impact on the rest of the method. } Fractive.getGathercastController((sItf).getFcItfOwner()).addedBindingOnServerItf( sItf.getFcItfName(), (owner).getRepresentativeOnThis(), clientItfName); } else { MulticastController mc = Fractive.getMulticastController(owner); ProActiveInterface pitf = (ProActiveInterface) mc; MulticastControllerImpl impl = (MulticastControllerImpl) pitf.getFcItfImpl(); impl.bindFc(clientItfName, sItf); //((MulticastControllerImpl) Fractive.getMulticastController(owner)) // .bindFc(clientItfName, sItf); } return; } if (isPrimitive()) { checkClientInterfaceExist(clientItfName); // binding operation is delegated if (Utils.isGathercastItf(sItf)) { primitiveBindFc(clientItfName, getGathercastAdaptor(clientItfName, serverItf, sItf)); // add a callback ref in the server gather interface // TODO should throw a binding event try { if (Fractive.getMembraneController((sItf).getFcItfOwner()).getMembraneState().equals( MembraneController.MEMBRANE_STOPPED)) { throw new IllegalLifeCycleException( "The membrane of the owner of the server interface should be started"); } } catch (NoSuchInterfaceException e) { //If the component doesn't have a MembraneController, it won't have any impact on the rest of the method. } Fractive.getGathercastController((sItf).getFcItfOwner()).addedBindingOnServerItf( sItf.getFcItfName(), (owner).getRepresentativeOnThis(), clientItfName); } else { primitiveBindFc(clientItfName, sItf); } return; } // composite or parallel InterfaceType client_itf_type; client_itf_type = Utils.getItfType(clientItfName, owner); if (isComposite()) { if (Utils.isGathercastItf(sItf)) { compositeBindFc(clientItfName, client_itf_type, getGathercastAdaptor(clientItfName, serverItf, sItf)); // add a callback ref in the server gather interface // TODO should throw a binding event try { if (Fractive.getMembraneController((sItf).getFcItfOwner()).getMembraneState().equals( MembraneController.MEMBRANE_STOPPED)) { throw new IllegalLifeCycleException( "The membrane of the owner of the server interface should be started"); } } catch (NoSuchInterfaceException e) { //If the component doesn't have a MembraneController, it won't have any impact on the rest of the method. } Fractive.getGathercastController(sItf.getFcItfOwner()).addedBindingOnServerItf( sItf.getFcItfName(), owner.getRepresentativeOnThis(), clientItfName); } else { compositeBindFc(clientItfName, client_itf_type, sItf); } } }
diff --git a/core/src/classes/org/jdesktop/wonderland/client/cell/utils/CellUtils.java b/core/src/classes/org/jdesktop/wonderland/client/cell/utils/CellUtils.java index 65d8e4d4c..206d0ca67 100644 --- a/core/src/classes/org/jdesktop/wonderland/client/cell/utils/CellUtils.java +++ b/core/src/classes/org/jdesktop/wonderland/client/cell/utils/CellUtils.java @@ -1,179 +1,182 @@ /** * Project Wonderland * * Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied * this code. */ package org.jdesktop.wonderland.client.cell.utils; import com.jme.bounding.BoundingSphere; import com.jme.bounding.BoundingVolume; import com.jme.math.Vector3f; import java.util.logging.Logger; import org.jdesktop.wonderland.client.cell.CellEditChannelConnection; import org.jdesktop.wonderland.client.cell.view.ViewCell; import org.jdesktop.wonderland.client.comms.WonderlandSession; import org.jdesktop.wonderland.client.jme.ViewManager; import org.jdesktop.wonderland.common.cell.CellEditConnectionType; import org.jdesktop.wonderland.common.cell.messages.CellCreateMessage; import org.jdesktop.wonderland.common.cell.state.CellServerState; import org.jdesktop.wonderland.common.cell.state.PositionComponentServerState; import org.jdesktop.wonderland.client.cell.Cell; import org.jdesktop.wonderland.client.login.ServerSessionManager; import org.jdesktop.wonderland.common.cell.CellTransform; import org.jdesktop.wonderland.common.cell.CellID; import org.jdesktop.wonderland.common.cell.messages.CellDeleteMessage; import org.jdesktop.wonderland.common.cell.state.BoundingVolumeHint; import org.jdesktop.wonderland.common.cell.state.ViewComponentServerState; /** * A collection of useful utility routines pertaining to Cells. * * @author Jordan Slott <[email protected]> */ public class CellUtils { private static Logger logger = Logger.getLogger(CellUtils.class.getName()); /** The default bounds radius to use if no hint is given */ private static final float DEFAULT_RADIUS = 1.0f; /** * Creates a cell in the world given the CellServerState of the cell. If the * given CellServerState is null, this method simply does not create a Cell. * This method attempts to position the Cell "optimally" so that the avatar * can see it, based upon "hints" about the Cell bounds given to it in the * CellServerState. * * @param state The cell server state for the new cell * @throw CellCreationException Upon error creating the cell */ public static void createCell(CellServerState state) throws CellCreationException { // Check to see if the Cell server state is null, and fail quietly if // so if (state == null) { logger.fine("Creating cell with null server state. Returning."); return; } // Fetch the transform of the view (avatar) Cell and its "look at" // direction. ViewManager vm = ViewManager.getViewManager(); ViewCell viewCell = vm.getPrimaryViewCell(); CellTransform viewTransform = viewCell.getWorldTransform(); ServerSessionManager manager = viewCell.getCellCache().getSession().getSessionManager(); // The Cell Transform to apply to the Cell CellTransform transform = null; // Look for the "bounds hint" provided by the Cell. There are three // possible cases: // // (1) There is a hint and the Cell wants us to do the optimal layout // so go ahead and do it. // // (2) There is no hint, so use the default bounds radius and do the // optimal layout // // (3) There is a hint that says do not do the optimal layout, so we // will just put the Cell right on top of the avatar. BoundingVolumeHint hint = state.getBoundingVolumeHint(); logger.info("Using bounding volume hint " + hint.getBoundsHint() + ", do placement=" + hint.isDoSystemPlacement()); if (hint != null && hint.isDoSystemPlacement() == true) { // Case (1): We have a bounds hint and we want to do the layout, // so we find the distance away from the avatar and also the height // above the ground. BoundingVolume boundsHint = hint.getBoundsHint(); transform = CellPlacementUtils.getCellTransform(manager, boundsHint, viewTransform); } else if (hint == null) { // Case (2): Do the optimal placement using the default radius. BoundingVolume boundsHint = new BoundingSphere(DEFAULT_RADIUS, Vector3f.ZERO); transform = CellPlacementUtils.getCellTransform(manager, boundsHint, viewTransform); } else if (hint != null && hint.isDoSystemPlacement() == false) { // Case (3): The Cell will take care of its own placement, use // the origin of the avatar as the initial placement transform = new CellTransform(); } // find the parent cell for this creation (may be null) CellID parentID = null; Cell parent = CellCreationParentRegistry.getCellCreationParent(); if (parent != null) { parentID = parent.getCellID(); logger.info("Using parent with Cell ID " + parentID.toString()); } // We also need to convert the initial origin of the Cell (in world // coordinates to the coordinates of the parent Cell (if non-null) if (parentID != null) { CellTransform worldTransform = new CellTransform(null, null); CellTransform parentTransform = parent.getWorldTransform(); logger.info("Transform of the parent cell: translation=" + parentTransform.getTranslation(null).toString() + ", rotation=" + parentTransform.getRotation(null).toString()); transform = CellPlacementUtils.transform(transform, worldTransform, parentTransform); } logger.info("Final adjusted origin " + transform.getTranslation(null).toString()); // Create a position component that will set the initial origin - PositionComponentServerState position = new PositionComponentServerState(); + PositionComponentServerState position = (PositionComponentServerState) state.getComponentServerState(PositionComponentServerState.class); + if (position==null) { + position = new PositionComponentServerState(); + state.addComponentServerState(position); + } position.setTranslation(transform.getTranslation(null)); position.setRotation(transform.getRotation(null)); position.setScaling(transform.getScaling(null)); - state.addComponentServerState(position); // Always pass in the view transform to the Cell's server state state.addComponentServerState(new ViewComponentServerState(viewTransform)); // Send the message to the server WonderlandSession session = manager.getPrimarySession(); CellEditChannelConnection connection = (CellEditChannelConnection) session.getConnection(CellEditConnectionType.CLIENT_TYPE); CellCreateMessage msg = new CellCreateMessage(parentID, state); connection.send(msg); } /** * Requests the server to delete the given cell from the world * of the primary session. Returns true if the deletion succeeds. * <br><br> * Note: currently always returns true because the server doesn't send * any response to the cell delete message. */ public static boolean deleteCell (Cell cell) { WonderlandSession session = cell.getCellCache().getSession(); CellEditChannelConnection connection = (CellEditChannelConnection) session.getConnection(CellEditConnectionType.CLIENT_TYPE); CellDeleteMessage msg = new CellDeleteMessage(cell.getCellID()); connection.send(msg); // TODO: there really really should be an OK/Error response from the server! return true; } }
false
true
public static void createCell(CellServerState state) throws CellCreationException { // Check to see if the Cell server state is null, and fail quietly if // so if (state == null) { logger.fine("Creating cell with null server state. Returning."); return; } // Fetch the transform of the view (avatar) Cell and its "look at" // direction. ViewManager vm = ViewManager.getViewManager(); ViewCell viewCell = vm.getPrimaryViewCell(); CellTransform viewTransform = viewCell.getWorldTransform(); ServerSessionManager manager = viewCell.getCellCache().getSession().getSessionManager(); // The Cell Transform to apply to the Cell CellTransform transform = null; // Look for the "bounds hint" provided by the Cell. There are three // possible cases: // // (1) There is a hint and the Cell wants us to do the optimal layout // so go ahead and do it. // // (2) There is no hint, so use the default bounds radius and do the // optimal layout // // (3) There is a hint that says do not do the optimal layout, so we // will just put the Cell right on top of the avatar. BoundingVolumeHint hint = state.getBoundingVolumeHint(); logger.info("Using bounding volume hint " + hint.getBoundsHint() + ", do placement=" + hint.isDoSystemPlacement()); if (hint != null && hint.isDoSystemPlacement() == true) { // Case (1): We have a bounds hint and we want to do the layout, // so we find the distance away from the avatar and also the height // above the ground. BoundingVolume boundsHint = hint.getBoundsHint(); transform = CellPlacementUtils.getCellTransform(manager, boundsHint, viewTransform); } else if (hint == null) { // Case (2): Do the optimal placement using the default radius. BoundingVolume boundsHint = new BoundingSphere(DEFAULT_RADIUS, Vector3f.ZERO); transform = CellPlacementUtils.getCellTransform(manager, boundsHint, viewTransform); } else if (hint != null && hint.isDoSystemPlacement() == false) { // Case (3): The Cell will take care of its own placement, use // the origin of the avatar as the initial placement transform = new CellTransform(); } // find the parent cell for this creation (may be null) CellID parentID = null; Cell parent = CellCreationParentRegistry.getCellCreationParent(); if (parent != null) { parentID = parent.getCellID(); logger.info("Using parent with Cell ID " + parentID.toString()); } // We also need to convert the initial origin of the Cell (in world // coordinates to the coordinates of the parent Cell (if non-null) if (parentID != null) { CellTransform worldTransform = new CellTransform(null, null); CellTransform parentTransform = parent.getWorldTransform(); logger.info("Transform of the parent cell: translation=" + parentTransform.getTranslation(null).toString() + ", rotation=" + parentTransform.getRotation(null).toString()); transform = CellPlacementUtils.transform(transform, worldTransform, parentTransform); } logger.info("Final adjusted origin " + transform.getTranslation(null).toString()); // Create a position component that will set the initial origin PositionComponentServerState position = new PositionComponentServerState(); position.setTranslation(transform.getTranslation(null)); position.setRotation(transform.getRotation(null)); position.setScaling(transform.getScaling(null)); state.addComponentServerState(position); // Always pass in the view transform to the Cell's server state state.addComponentServerState(new ViewComponentServerState(viewTransform)); // Send the message to the server WonderlandSession session = manager.getPrimarySession(); CellEditChannelConnection connection = (CellEditChannelConnection) session.getConnection(CellEditConnectionType.CLIENT_TYPE); CellCreateMessage msg = new CellCreateMessage(parentID, state); connection.send(msg); }
public static void createCell(CellServerState state) throws CellCreationException { // Check to see if the Cell server state is null, and fail quietly if // so if (state == null) { logger.fine("Creating cell with null server state. Returning."); return; } // Fetch the transform of the view (avatar) Cell and its "look at" // direction. ViewManager vm = ViewManager.getViewManager(); ViewCell viewCell = vm.getPrimaryViewCell(); CellTransform viewTransform = viewCell.getWorldTransform(); ServerSessionManager manager = viewCell.getCellCache().getSession().getSessionManager(); // The Cell Transform to apply to the Cell CellTransform transform = null; // Look for the "bounds hint" provided by the Cell. There are three // possible cases: // // (1) There is a hint and the Cell wants us to do the optimal layout // so go ahead and do it. // // (2) There is no hint, so use the default bounds radius and do the // optimal layout // // (3) There is a hint that says do not do the optimal layout, so we // will just put the Cell right on top of the avatar. BoundingVolumeHint hint = state.getBoundingVolumeHint(); logger.info("Using bounding volume hint " + hint.getBoundsHint() + ", do placement=" + hint.isDoSystemPlacement()); if (hint != null && hint.isDoSystemPlacement() == true) { // Case (1): We have a bounds hint and we want to do the layout, // so we find the distance away from the avatar and also the height // above the ground. BoundingVolume boundsHint = hint.getBoundsHint(); transform = CellPlacementUtils.getCellTransform(manager, boundsHint, viewTransform); } else if (hint == null) { // Case (2): Do the optimal placement using the default radius. BoundingVolume boundsHint = new BoundingSphere(DEFAULT_RADIUS, Vector3f.ZERO); transform = CellPlacementUtils.getCellTransform(manager, boundsHint, viewTransform); } else if (hint != null && hint.isDoSystemPlacement() == false) { // Case (3): The Cell will take care of its own placement, use // the origin of the avatar as the initial placement transform = new CellTransform(); } // find the parent cell for this creation (may be null) CellID parentID = null; Cell parent = CellCreationParentRegistry.getCellCreationParent(); if (parent != null) { parentID = parent.getCellID(); logger.info("Using parent with Cell ID " + parentID.toString()); } // We also need to convert the initial origin of the Cell (in world // coordinates to the coordinates of the parent Cell (if non-null) if (parentID != null) { CellTransform worldTransform = new CellTransform(null, null); CellTransform parentTransform = parent.getWorldTransform(); logger.info("Transform of the parent cell: translation=" + parentTransform.getTranslation(null).toString() + ", rotation=" + parentTransform.getRotation(null).toString()); transform = CellPlacementUtils.transform(transform, worldTransform, parentTransform); } logger.info("Final adjusted origin " + transform.getTranslation(null).toString()); // Create a position component that will set the initial origin PositionComponentServerState position = (PositionComponentServerState) state.getComponentServerState(PositionComponentServerState.class); if (position==null) { position = new PositionComponentServerState(); state.addComponentServerState(position); } position.setTranslation(transform.getTranslation(null)); position.setRotation(transform.getRotation(null)); position.setScaling(transform.getScaling(null)); // Always pass in the view transform to the Cell's server state state.addComponentServerState(new ViewComponentServerState(viewTransform)); // Send the message to the server WonderlandSession session = manager.getPrimarySession(); CellEditChannelConnection connection = (CellEditChannelConnection) session.getConnection(CellEditConnectionType.CLIENT_TYPE); CellCreateMessage msg = new CellCreateMessage(parentID, state); connection.send(msg); }
diff --git a/src/org/pentaho/amazon/emr/ui/AmazonElasticMapReduceJobExecutorDialog.java b/src/org/pentaho/amazon/emr/ui/AmazonElasticMapReduceJobExecutorDialog.java index 81919960..62b7c3ec 100644 --- a/src/org/pentaho/amazon/emr/ui/AmazonElasticMapReduceJobExecutorDialog.java +++ b/src/org/pentaho/amazon/emr/ui/AmazonElasticMapReduceJobExecutorDialog.java @@ -1,142 +1,142 @@ /* Copyright (c) 2011 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is Pentaho Corporation. * * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ package org.pentaho.amazon.emr.ui; import java.util.Enumeration; import java.util.ResourceBundle; import org.dom4j.DocumentException; import org.eclipse.swt.widgets.Shell; import org.pentaho.amazon.emr.job.AmazonElasticMapReduceJobExecutor; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entry.JobEntryDialogInterface; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.repository.Repository; import org.pentaho.di.ui.core.database.dialog.tags.ExtTextbox; import org.pentaho.di.ui.job.entry.JobEntryDialog; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.XulException; import org.pentaho.ui.xul.XulRunner; import org.pentaho.ui.xul.binding.Binding.Type; import org.pentaho.ui.xul.binding.BindingConvertor; import org.pentaho.ui.xul.binding.BindingFactory; import org.pentaho.ui.xul.binding.DefaultBindingFactory; import org.pentaho.ui.xul.components.XulMenuList; import org.pentaho.ui.xul.components.XulTextbox; import org.pentaho.ui.xul.containers.XulDialog; import org.pentaho.ui.xul.swt.SwtXulLoader; import org.pentaho.ui.xul.swt.SwtXulRunner; public class AmazonElasticMapReduceJobExecutorDialog extends JobEntryDialog implements JobEntryDialogInterface { private static final Class<?> CLZ = AmazonElasticMapReduceJobExecutor.class; private AmazonElasticMapReduceJobExecutor jobEntry; private AmazonElasticMapReduceJobExecutorController controller = new AmazonElasticMapReduceJobExecutorController(); private XulDomContainer container; private BindingFactory bf; private ResourceBundle bundle = new ResourceBundle() { @Override public Enumeration<String> getKeys() { return null; } @Override protected Object handleGetObject(String key) { return BaseMessages.getString(CLZ, key); } }; public AmazonElasticMapReduceJobExecutorDialog(Shell parent, JobEntryInterface jobEntry, Repository rep, JobMeta jobMeta) throws XulException, DocumentException { super(parent, jobEntry, rep, jobMeta); final BindingConvertor<String, Integer> bindingConverter = new BindingConvertor<String, Integer>() { public Integer sourceToTarget(String value) { return Integer.parseInt(value); } public String targetToSource(Integer value) { return value.toString(); } }; this.jobEntry = (AmazonElasticMapReduceJobExecutor) jobEntry; SwtXulLoader swtXulLoader = new SwtXulLoader(); swtXulLoader.registerClassLoader(getClass().getClassLoader()); swtXulLoader.register("VARIABLETEXTBOX", "org.pentaho.di.ui.core.database.dialog.tags.ExtTextbox"); swtXulLoader.setOuterContext(shell); - container = swtXulLoader.loadXul("com/pentaho/amazon/emr/ui/AmazonElasticMapReduceJobExecutorDialog.xul", bundle); //$NON-NLS-1$ + container = swtXulLoader.loadXul("org/pentaho/amazon/emr/ui/AmazonElasticMapReduceJobExecutorDialog.xul", bundle); //$NON-NLS-1$ final XulRunner runner = new SwtXulRunner(); runner.addContainer(container); container.addEventHandler(controller); bf = new DefaultBindingFactory(); bf.setDocument(container.getDocumentRoot()); bf.setBindingType(Type.BI_DIRECTIONAL); bf.createBinding("jobentry-name", "value", controller, AmazonElasticMapReduceJobExecutorController.JOB_ENTRY_NAME); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("jobentry-hadoopjob-name", "value", controller, AmazonElasticMapReduceJobExecutorController.HADOOP_JOB_NAME); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("jobentry-hadoopjob-flow-id", "value", controller, AmazonElasticMapReduceJobExecutorController.HADOOP_JOB_FLOW_ID); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("jar-url", "value", controller, AmazonElasticMapReduceJobExecutorController.JAR_URL); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("access-key", "value", controller, AmazonElasticMapReduceJobExecutorController.ACCESS_KEY); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("secret-key", "value", controller, AmazonElasticMapReduceJobExecutorController.SECRET_KEY); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("s3-staging-directory", "value", controller, AmazonElasticMapReduceJobExecutorController.STAGING_DIR); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("num-instances", "value", controller, AmazonElasticMapReduceJobExecutorController.NUM_INSTANCES, bindingConverter); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("master-instance-type", "selectedItem", controller, AmazonElasticMapReduceJobExecutorController.MASTER_INSTANCE_TYPE); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("slave-instance-type", "selectedItem", controller, AmazonElasticMapReduceJobExecutorController.SLAVE_INSTANCE_TYPE); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("command-line-arguments", "value", controller, AmazonElasticMapReduceJobExecutorController.CMD_LINE_ARGS); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ XulTextbox numInstances = (XulTextbox) container.getDocumentRoot().getElementById("num-instances"); numInstances.setValue("" + controller.getNumInstances()); XulMenuList<String> masterInstanceType = (XulMenuList<String>) container.getDocumentRoot().getElementById("master-instance-type"); masterInstanceType.setSelectedItem("" + controller.getMasterInstanceType()); XulMenuList<String> slaveInstanceType = (XulMenuList<String>) container.getDocumentRoot().getElementById("slave-instance-type"); slaveInstanceType.setSelectedItem("" + controller.getSlaveInstanceType()); bf.createBinding("blocking", "selected", controller, AmazonElasticMapReduceJobExecutorController.BLOCKING); //$NON-NLS-1$ //$NON-NLS-2$ bf.createBinding("logging-interval", "value", controller, AmazonElasticMapReduceJobExecutorController.LOGGING_INTERVAL, bindingConverter); //$NON-NLS-1$ //$NON-NLS-2$ XulTextbox loggingInterval = (XulTextbox) container.getDocumentRoot().getElementById("logging-interval"); loggingInterval.setValue("" + controller.getLoggingInterval()); ExtTextbox accessKeyTB = (ExtTextbox) container.getDocumentRoot().getElementById("access-key"); accessKeyTB.setVariableSpace(controller.getVariableSpace()); ExtTextbox secretKeyTB = (ExtTextbox) container.getDocumentRoot().getElementById("secret-key"); secretKeyTB.setVariableSpace(controller.getVariableSpace()); bf.setBindingType(Type.BI_DIRECTIONAL); controller.setJobEntry((AmazonElasticMapReduceJobExecutor) jobEntry); controller.init(); } public JobEntryInterface open() { XulDialog dialog = (XulDialog) container.getDocumentRoot().getElementById("amazon-emr-job-entry-dialog"); //$NON-NLS-1$ dialog.show(); return jobEntry; } }
true
true
public AmazonElasticMapReduceJobExecutorDialog(Shell parent, JobEntryInterface jobEntry, Repository rep, JobMeta jobMeta) throws XulException, DocumentException { super(parent, jobEntry, rep, jobMeta); final BindingConvertor<String, Integer> bindingConverter = new BindingConvertor<String, Integer>() { public Integer sourceToTarget(String value) { return Integer.parseInt(value); } public String targetToSource(Integer value) { return value.toString(); } }; this.jobEntry = (AmazonElasticMapReduceJobExecutor) jobEntry; SwtXulLoader swtXulLoader = new SwtXulLoader(); swtXulLoader.registerClassLoader(getClass().getClassLoader()); swtXulLoader.register("VARIABLETEXTBOX", "org.pentaho.di.ui.core.database.dialog.tags.ExtTextbox"); swtXulLoader.setOuterContext(shell); container = swtXulLoader.loadXul("com/pentaho/amazon/emr/ui/AmazonElasticMapReduceJobExecutorDialog.xul", bundle); //$NON-NLS-1$ final XulRunner runner = new SwtXulRunner(); runner.addContainer(container); container.addEventHandler(controller); bf = new DefaultBindingFactory(); bf.setDocument(container.getDocumentRoot()); bf.setBindingType(Type.BI_DIRECTIONAL); bf.createBinding("jobentry-name", "value", controller, AmazonElasticMapReduceJobExecutorController.JOB_ENTRY_NAME); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("jobentry-hadoopjob-name", "value", controller, AmazonElasticMapReduceJobExecutorController.HADOOP_JOB_NAME); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("jobentry-hadoopjob-flow-id", "value", controller, AmazonElasticMapReduceJobExecutorController.HADOOP_JOB_FLOW_ID); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("jar-url", "value", controller, AmazonElasticMapReduceJobExecutorController.JAR_URL); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("access-key", "value", controller, AmazonElasticMapReduceJobExecutorController.ACCESS_KEY); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("secret-key", "value", controller, AmazonElasticMapReduceJobExecutorController.SECRET_KEY); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("s3-staging-directory", "value", controller, AmazonElasticMapReduceJobExecutorController.STAGING_DIR); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("num-instances", "value", controller, AmazonElasticMapReduceJobExecutorController.NUM_INSTANCES, bindingConverter); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("master-instance-type", "selectedItem", controller, AmazonElasticMapReduceJobExecutorController.MASTER_INSTANCE_TYPE); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("slave-instance-type", "selectedItem", controller, AmazonElasticMapReduceJobExecutorController.SLAVE_INSTANCE_TYPE); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("command-line-arguments", "value", controller, AmazonElasticMapReduceJobExecutorController.CMD_LINE_ARGS); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ XulTextbox numInstances = (XulTextbox) container.getDocumentRoot().getElementById("num-instances"); numInstances.setValue("" + controller.getNumInstances()); XulMenuList<String> masterInstanceType = (XulMenuList<String>) container.getDocumentRoot().getElementById("master-instance-type"); masterInstanceType.setSelectedItem("" + controller.getMasterInstanceType()); XulMenuList<String> slaveInstanceType = (XulMenuList<String>) container.getDocumentRoot().getElementById("slave-instance-type"); slaveInstanceType.setSelectedItem("" + controller.getSlaveInstanceType()); bf.createBinding("blocking", "selected", controller, AmazonElasticMapReduceJobExecutorController.BLOCKING); //$NON-NLS-1$ //$NON-NLS-2$ bf.createBinding("logging-interval", "value", controller, AmazonElasticMapReduceJobExecutorController.LOGGING_INTERVAL, bindingConverter); //$NON-NLS-1$ //$NON-NLS-2$ XulTextbox loggingInterval = (XulTextbox) container.getDocumentRoot().getElementById("logging-interval"); loggingInterval.setValue("" + controller.getLoggingInterval()); ExtTextbox accessKeyTB = (ExtTextbox) container.getDocumentRoot().getElementById("access-key"); accessKeyTB.setVariableSpace(controller.getVariableSpace()); ExtTextbox secretKeyTB = (ExtTextbox) container.getDocumentRoot().getElementById("secret-key"); secretKeyTB.setVariableSpace(controller.getVariableSpace()); bf.setBindingType(Type.BI_DIRECTIONAL); controller.setJobEntry((AmazonElasticMapReduceJobExecutor) jobEntry); controller.init(); }
public AmazonElasticMapReduceJobExecutorDialog(Shell parent, JobEntryInterface jobEntry, Repository rep, JobMeta jobMeta) throws XulException, DocumentException { super(parent, jobEntry, rep, jobMeta); final BindingConvertor<String, Integer> bindingConverter = new BindingConvertor<String, Integer>() { public Integer sourceToTarget(String value) { return Integer.parseInt(value); } public String targetToSource(Integer value) { return value.toString(); } }; this.jobEntry = (AmazonElasticMapReduceJobExecutor) jobEntry; SwtXulLoader swtXulLoader = new SwtXulLoader(); swtXulLoader.registerClassLoader(getClass().getClassLoader()); swtXulLoader.register("VARIABLETEXTBOX", "org.pentaho.di.ui.core.database.dialog.tags.ExtTextbox"); swtXulLoader.setOuterContext(shell); container = swtXulLoader.loadXul("org/pentaho/amazon/emr/ui/AmazonElasticMapReduceJobExecutorDialog.xul", bundle); //$NON-NLS-1$ final XulRunner runner = new SwtXulRunner(); runner.addContainer(container); container.addEventHandler(controller); bf = new DefaultBindingFactory(); bf.setDocument(container.getDocumentRoot()); bf.setBindingType(Type.BI_DIRECTIONAL); bf.createBinding("jobentry-name", "value", controller, AmazonElasticMapReduceJobExecutorController.JOB_ENTRY_NAME); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("jobentry-hadoopjob-name", "value", controller, AmazonElasticMapReduceJobExecutorController.HADOOP_JOB_NAME); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("jobentry-hadoopjob-flow-id", "value", controller, AmazonElasticMapReduceJobExecutorController.HADOOP_JOB_FLOW_ID); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("jar-url", "value", controller, AmazonElasticMapReduceJobExecutorController.JAR_URL); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("access-key", "value", controller, AmazonElasticMapReduceJobExecutorController.ACCESS_KEY); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("secret-key", "value", controller, AmazonElasticMapReduceJobExecutorController.SECRET_KEY); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("s3-staging-directory", "value", controller, AmazonElasticMapReduceJobExecutorController.STAGING_DIR); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("num-instances", "value", controller, AmazonElasticMapReduceJobExecutorController.NUM_INSTANCES, bindingConverter); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("master-instance-type", "selectedItem", controller, AmazonElasticMapReduceJobExecutorController.MASTER_INSTANCE_TYPE); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("slave-instance-type", "selectedItem", controller, AmazonElasticMapReduceJobExecutorController.SLAVE_INSTANCE_TYPE); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ bf.createBinding("command-line-arguments", "value", controller, AmazonElasticMapReduceJobExecutorController.CMD_LINE_ARGS); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ XulTextbox numInstances = (XulTextbox) container.getDocumentRoot().getElementById("num-instances"); numInstances.setValue("" + controller.getNumInstances()); XulMenuList<String> masterInstanceType = (XulMenuList<String>) container.getDocumentRoot().getElementById("master-instance-type"); masterInstanceType.setSelectedItem("" + controller.getMasterInstanceType()); XulMenuList<String> slaveInstanceType = (XulMenuList<String>) container.getDocumentRoot().getElementById("slave-instance-type"); slaveInstanceType.setSelectedItem("" + controller.getSlaveInstanceType()); bf.createBinding("blocking", "selected", controller, AmazonElasticMapReduceJobExecutorController.BLOCKING); //$NON-NLS-1$ //$NON-NLS-2$ bf.createBinding("logging-interval", "value", controller, AmazonElasticMapReduceJobExecutorController.LOGGING_INTERVAL, bindingConverter); //$NON-NLS-1$ //$NON-NLS-2$ XulTextbox loggingInterval = (XulTextbox) container.getDocumentRoot().getElementById("logging-interval"); loggingInterval.setValue("" + controller.getLoggingInterval()); ExtTextbox accessKeyTB = (ExtTextbox) container.getDocumentRoot().getElementById("access-key"); accessKeyTB.setVariableSpace(controller.getVariableSpace()); ExtTextbox secretKeyTB = (ExtTextbox) container.getDocumentRoot().getElementById("secret-key"); secretKeyTB.setVariableSpace(controller.getVariableSpace()); bf.setBindingType(Type.BI_DIRECTIONAL); controller.setJobEntry((AmazonElasticMapReduceJobExecutor) jobEntry); controller.init(); }
diff --git a/gov.va.med.iss.meditor/src/org/mumps/meditor/SaveRoutine.java b/gov.va.med.iss.meditor/src/org/mumps/meditor/SaveRoutine.java index 25ee65b..fb9fcd7 100644 --- a/gov.va.med.iss.meditor/src/org/mumps/meditor/SaveRoutine.java +++ b/gov.va.med.iss.meditor/src/org/mumps/meditor/SaveRoutine.java @@ -1,137 +1,137 @@ package org.mumps.meditor; import gov.va.med.iss.meditor.utils.MEditorMessageConsole; import gov.va.med.iss.meditor.utils.MEditorUtilities; import gov.va.med.iss.meditor.utils.RoutineChangedDialog; import gov.va.med.iss.meditor.utils.RoutineChangedDialogData; import java.io.FileNotFoundException; import java.io.IOException; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; public class SaveRoutine { private MEditorRPC rpc; public SaveRoutine(MEditorRPC rpc) { this.rpc = rpc; } public void save(String routineName, String projectName, String fileCode) throws ServerSaveFailure { //Load routine from server String serverCode = null; boolean isNewRoutine = false; try { //attempt Load routine into a string serverCode = rpc.getRoutineFromServer(routineName); } catch (RoutineNotFoundException e) { //save the routine as a new file. isNewRoutine = true; } String backupCode = null; try { if (!isNewRoutine) backupCode = MEditorUtils.getBackupFileContents(projectName, routineName); } catch (FileNotFoundException e1) { //inform backup file cannot be found and ask whether or not to proceed with a dialog // MessageDialog dialog = new MessageDialog(null, "MEditor", null, // "This routine exists on the server, but no backup file exists in this project. Therefore it is not known if the editor and the server are in sync.", MessageDialog.QUESTION, // new String[] { "Yes", "No" }, // 1); // No is the default // int result = dialog.open(); if (!MEditorUtils.compareRoutines(fileCode, serverCode)) { RoutineChangedDialog dialog = new RoutineChangedDialog(Display.getDefault().getActiveShell()); RoutineChangedDialogData userInput = dialog.open(routineName, serverCode, fileCode, false, false, "This routine exists on the server, but no backup file exists"); //TODO: fix this dialog so it display wrapped text messages. "in this project. Therefore it is not known if the editor and the server are in sync."); if (!userInput.getReturnValue()) { throw new ServerSaveFailure("User cancelled, no previous backup file was found."); // super.doSave(monitor); // return; } } } catch (CoreException | IOException e1) { e1.printStackTrace(); String message = "Failed to save routine onto the server. Error occured while loading the backup file: " +e1.getMessage(); MessageDialog.openError(PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(), "MEditor", message ); throw new ServerSaveFailure(message, e1); // super.doSave(monitor); // return; } //First compare contents of editor to contents on server to see if there is even a proposed change boolean isCopy = false; if (!isNewRoutine && MEditorUtils.compareRoutines(fileCode, serverCode)) { //show prompt asking about whether to cancel because they are same, or to continue thereby updating the routine header on server and client // MessageDialog.openError(PlatformUI.getWorkbench() // .getActiveWorkbenchWindow().getShell(), "MEditor", // "Rotine on server is identical to the local routine. Nothing new to deploy to server."); MessageDialog dialog = new MessageDialog(null, "MEditor", null, "Routines are the same on the client and in this project. Would " + "you like to continue by updating the date in the routine header" + " on both the client and server?", MessageDialog.QUESTION, new String[] { "OK", "Cancel" }, 1); // Cancel is the default if (dialog.open() != 0) { throw new ServerSaveFailure("User cancelled, files are the same on client and server."); // super.doSave(monitor); // return; } else isCopy = true; } //Next compare contents of server to contents of backup to see if MEditor was the last to touch the server - if (!isNewRoutine && backupCode != null && MEditorUtils.compareRoutines(backupCode, serverCode)) { + if (!isNewRoutine && backupCode != null && !MEditorUtils.compareRoutines(backupCode, serverCode)) { RoutineChangedDialog dialog = new RoutineChangedDialog(Display.getDefault().getActiveShell()); RoutineChangedDialogData userInput = dialog.open(routineName, serverCode, backupCode, true, false); if (!userInput.getReturnValue()) { throw new ServerSaveFailure("User cancelled, backup file differs from what is on server."); // super.doSave(monitor); // return; } } //Save to server and display XINDEX results String saveResults = ""; try { saveResults = rpc.saveRoutineToServer(routineName, fileCode, isCopy); } catch (Throwable t) { saveResults = "Unable to save routine " +routineName+ " to server"; // return; throw new ServerSaveFailure("RPC failed.", t); } finally { try { MEditorMessageConsole.writeToConsole(saveResults); } catch (Exception e) { MessageDialog.openError( MEditorUtilities.getIWorkbenchWindow().getShell(), "Meditor Plug-in Routine Save", saveResults); } } //Sync the latest on server to the backup try { MEditorUtils.syncBackup(projectName, routineName, fileCode); } catch (CoreException e) { // show warning only e.printStackTrace(); MessageDialog.openWarning(PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(), "MEditor", "Routine Saved on server, but error occured while syncing the local backup file: " +e.getMessage()); } } }
true
true
public void save(String routineName, String projectName, String fileCode) throws ServerSaveFailure { //Load routine from server String serverCode = null; boolean isNewRoutine = false; try { //attempt Load routine into a string serverCode = rpc.getRoutineFromServer(routineName); } catch (RoutineNotFoundException e) { //save the routine as a new file. isNewRoutine = true; } String backupCode = null; try { if (!isNewRoutine) backupCode = MEditorUtils.getBackupFileContents(projectName, routineName); } catch (FileNotFoundException e1) { //inform backup file cannot be found and ask whether or not to proceed with a dialog // MessageDialog dialog = new MessageDialog(null, "MEditor", null, // "This routine exists on the server, but no backup file exists in this project. Therefore it is not known if the editor and the server are in sync.", MessageDialog.QUESTION, // new String[] { "Yes", "No" }, // 1); // No is the default // int result = dialog.open(); if (!MEditorUtils.compareRoutines(fileCode, serverCode)) { RoutineChangedDialog dialog = new RoutineChangedDialog(Display.getDefault().getActiveShell()); RoutineChangedDialogData userInput = dialog.open(routineName, serverCode, fileCode, false, false, "This routine exists on the server, but no backup file exists"); //TODO: fix this dialog so it display wrapped text messages. "in this project. Therefore it is not known if the editor and the server are in sync."); if (!userInput.getReturnValue()) { throw new ServerSaveFailure("User cancelled, no previous backup file was found."); // super.doSave(monitor); // return; } } } catch (CoreException | IOException e1) { e1.printStackTrace(); String message = "Failed to save routine onto the server. Error occured while loading the backup file: " +e1.getMessage(); MessageDialog.openError(PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(), "MEditor", message ); throw new ServerSaveFailure(message, e1); // super.doSave(monitor); // return; } //First compare contents of editor to contents on server to see if there is even a proposed change boolean isCopy = false; if (!isNewRoutine && MEditorUtils.compareRoutines(fileCode, serverCode)) { //show prompt asking about whether to cancel because they are same, or to continue thereby updating the routine header on server and client // MessageDialog.openError(PlatformUI.getWorkbench() // .getActiveWorkbenchWindow().getShell(), "MEditor", // "Rotine on server is identical to the local routine. Nothing new to deploy to server."); MessageDialog dialog = new MessageDialog(null, "MEditor", null, "Routines are the same on the client and in this project. Would " + "you like to continue by updating the date in the routine header" + " on both the client and server?", MessageDialog.QUESTION, new String[] { "OK", "Cancel" }, 1); // Cancel is the default if (dialog.open() != 0) { throw new ServerSaveFailure("User cancelled, files are the same on client and server."); // super.doSave(monitor); // return; } else isCopy = true; } //Next compare contents of server to contents of backup to see if MEditor was the last to touch the server if (!isNewRoutine && backupCode != null && MEditorUtils.compareRoutines(backupCode, serverCode)) { RoutineChangedDialog dialog = new RoutineChangedDialog(Display.getDefault().getActiveShell()); RoutineChangedDialogData userInput = dialog.open(routineName, serverCode, backupCode, true, false); if (!userInput.getReturnValue()) { throw new ServerSaveFailure("User cancelled, backup file differs from what is on server."); // super.doSave(monitor); // return; } } //Save to server and display XINDEX results String saveResults = ""; try { saveResults = rpc.saveRoutineToServer(routineName, fileCode, isCopy); } catch (Throwable t) { saveResults = "Unable to save routine " +routineName+ " to server"; // return; throw new ServerSaveFailure("RPC failed.", t); } finally { try { MEditorMessageConsole.writeToConsole(saveResults); } catch (Exception e) { MessageDialog.openError( MEditorUtilities.getIWorkbenchWindow().getShell(), "Meditor Plug-in Routine Save", saveResults); } } //Sync the latest on server to the backup try { MEditorUtils.syncBackup(projectName, routineName, fileCode); } catch (CoreException e) { // show warning only e.printStackTrace(); MessageDialog.openWarning(PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(), "MEditor", "Routine Saved on server, but error occured while syncing the local backup file: " +e.getMessage()); } }
public void save(String routineName, String projectName, String fileCode) throws ServerSaveFailure { //Load routine from server String serverCode = null; boolean isNewRoutine = false; try { //attempt Load routine into a string serverCode = rpc.getRoutineFromServer(routineName); } catch (RoutineNotFoundException e) { //save the routine as a new file. isNewRoutine = true; } String backupCode = null; try { if (!isNewRoutine) backupCode = MEditorUtils.getBackupFileContents(projectName, routineName); } catch (FileNotFoundException e1) { //inform backup file cannot be found and ask whether or not to proceed with a dialog // MessageDialog dialog = new MessageDialog(null, "MEditor", null, // "This routine exists on the server, but no backup file exists in this project. Therefore it is not known if the editor and the server are in sync.", MessageDialog.QUESTION, // new String[] { "Yes", "No" }, // 1); // No is the default // int result = dialog.open(); if (!MEditorUtils.compareRoutines(fileCode, serverCode)) { RoutineChangedDialog dialog = new RoutineChangedDialog(Display.getDefault().getActiveShell()); RoutineChangedDialogData userInput = dialog.open(routineName, serverCode, fileCode, false, false, "This routine exists on the server, but no backup file exists"); //TODO: fix this dialog so it display wrapped text messages. "in this project. Therefore it is not known if the editor and the server are in sync."); if (!userInput.getReturnValue()) { throw new ServerSaveFailure("User cancelled, no previous backup file was found."); // super.doSave(monitor); // return; } } } catch (CoreException | IOException e1) { e1.printStackTrace(); String message = "Failed to save routine onto the server. Error occured while loading the backup file: " +e1.getMessage(); MessageDialog.openError(PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(), "MEditor", message ); throw new ServerSaveFailure(message, e1); // super.doSave(monitor); // return; } //First compare contents of editor to contents on server to see if there is even a proposed change boolean isCopy = false; if (!isNewRoutine && MEditorUtils.compareRoutines(fileCode, serverCode)) { //show prompt asking about whether to cancel because they are same, or to continue thereby updating the routine header on server and client // MessageDialog.openError(PlatformUI.getWorkbench() // .getActiveWorkbenchWindow().getShell(), "MEditor", // "Rotine on server is identical to the local routine. Nothing new to deploy to server."); MessageDialog dialog = new MessageDialog(null, "MEditor", null, "Routines are the same on the client and in this project. Would " + "you like to continue by updating the date in the routine header" + " on both the client and server?", MessageDialog.QUESTION, new String[] { "OK", "Cancel" }, 1); // Cancel is the default if (dialog.open() != 0) { throw new ServerSaveFailure("User cancelled, files are the same on client and server."); // super.doSave(monitor); // return; } else isCopy = true; } //Next compare contents of server to contents of backup to see if MEditor was the last to touch the server if (!isNewRoutine && backupCode != null && !MEditorUtils.compareRoutines(backupCode, serverCode)) { RoutineChangedDialog dialog = new RoutineChangedDialog(Display.getDefault().getActiveShell()); RoutineChangedDialogData userInput = dialog.open(routineName, serverCode, backupCode, true, false); if (!userInput.getReturnValue()) { throw new ServerSaveFailure("User cancelled, backup file differs from what is on server."); // super.doSave(monitor); // return; } } //Save to server and display XINDEX results String saveResults = ""; try { saveResults = rpc.saveRoutineToServer(routineName, fileCode, isCopy); } catch (Throwable t) { saveResults = "Unable to save routine " +routineName+ " to server"; // return; throw new ServerSaveFailure("RPC failed.", t); } finally { try { MEditorMessageConsole.writeToConsole(saveResults); } catch (Exception e) { MessageDialog.openError( MEditorUtilities.getIWorkbenchWindow().getShell(), "Meditor Plug-in Routine Save", saveResults); } } //Sync the latest on server to the backup try { MEditorUtils.syncBackup(projectName, routineName, fileCode); } catch (CoreException e) { // show warning only e.printStackTrace(); MessageDialog.openWarning(PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(), "MEditor", "Routine Saved on server, but error occured while syncing the local backup file: " +e.getMessage()); } }
diff --git a/processing/app/Editor.java b/processing/app/Editor.java index f9df66e..c98943c 100644 --- a/processing/app/Editor.java +++ b/processing/app/Editor.java @@ -1,2942 +1,2941 @@ /* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Editor - main editor panel for the processing development environment Part of the Processing project - http://processing.org Copyright (c) 2004-05 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology 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 $Id: Editor.java 370 2008-01-19 16:37:19Z mellis $ */ package processing.app; import processing.app.syntax.*; import processing.app.tools.*; import processing.core.*; import java.awt.*; import java.awt.datatransfer.*; import java.awt.dnd.*; import java.awt.event.*; import java.awt.print.*; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.util.*; import java.util.zip.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import javax.swing.text.*; import javax.swing.undo.*; import antipasto.*; import antipasto.GUI.GadgetListView.*; import antipasto.GUI.GadgetListView.GadgetPanelEvents.*; import antipasto.GUI.ImageListView.ImageListPanel; import antipasto.Interfaces.*; import antipasto.ModuleRules.IMessage; import antipasto.ModuleRules.IOkListener; import com.apple.mrj.*; import com.oroinc.text.regex.*; //import de.hunsicker.jalopy.*; import com.apple.mrj.*; import gnu.io.*; public class Editor extends JFrame implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler, MRJOpenDocumentHandler, IActiveGadgetChangedEventListener //, MRJOpenApplicationHandler { // yeah static final String WINDOW_TITLE = "Antipasto Arduino"; // p5 icon for the window Image icon; // otherwise, if the window is resized with the message label // set to blank, it's preferredSize() will be fukered static public final String EMPTY = " " + " " + " "; static public final KeyStroke WINDOW_CLOSE_KEYSTROKE = KeyStroke.getKeyStroke('W', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); static final String CODEEDITOR = "CODEPANEL"; static final String FILELIST = "FILELIST"; static final String TEST = "TEST"; static final int HANDLE_NEW = 1; static final int HANDLE_OPEN = 2; static final int HANDLE_QUIT = 3; int checkModifiedMode; String handleOpenPath; boolean handleNewShift; boolean handleNewLibrary; PageFormat pageFormat; PrinterJob printerJob; EditorButtons buttons; EditorHeader header; EditorStatus status; EditorConsole console; Serial serialPort; JSplitPane splitPane; JPanel consolePanel; JLabel lineNumberComponent; JPanel leftWing; JLabel leftExpandLabel; // currently opened program public Sketch sketch; public String lastActiveGadgetPath; EditorLineStatus lineStatus; String curBoard; public JEditTextArea textarea; EditorListener listener; // runtime information and window placement Point appletLocation; //Point presentLocation; //Window presentationWindow; RunButtonWatcher watcher; //Runner runtime; JMenuItem exportAppItem; JMenuItem saveMenuItem; JMenuItem saveAsMenuItem; public JPanel centerPanel; JMenuItem burnBootloader8Item = null; JMenuItem burnBootloader8ParallelItem = null; JMenuItem burnBootloader168DiecimilaItem = null; JMenuItem burnBootloader168DiecimilaParallelItem = null; JMenuItem burnBootloader168NGItem = null; JMenuItem burnBootloader168NGParallelItem = null; JMenu serialMenu; JMenu serialRateMenu; JMenu mcuMenu; ImageListPanel imageListPanel; SerialMenuListener serialMenuListener; boolean running; boolean presenting; boolean debugging; boolean isExporting = false; // undo fellers JMenuItem undoItem, redoItem; protected UndoAction undoAction; protected RedoAction redoAction; UndoManager undo; // used internally, and only briefly CompoundEdit compoundEdit; //Used specifically for the board files history File originalBoardsFile; File newBoardsFile; //SketchHistory history; // TODO re-enable history Sketchbook sketchbook; //Preferences preferences; FindReplace find; public JFrame _frame; public GadgetPanel gadgetPanel ; //static Properties keywords; // keyword -> reference html lookup public Editor() { super(); _frame = this; this.setTitle(WINDOW_TITLE); // #@$*(@#$ apple.. always gotta think different MRJApplicationUtils.registerAboutHandler(this); MRJApplicationUtils.registerPrefsHandler(this); MRJApplicationUtils.registerQuitHandler(this); MRJApplicationUtils.registerOpenDocumentHandler(this); // run static initialization that grabs all the prefs Preferences.init(); // set the window icon try { icon = Base.getImage("icon.gif", this); _frame.setIconImage(icon); } catch (Exception e) { } // fail silently, no big whup // add listener to handle window close box hit event _frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { handleQuitInternal(); } }); // don't close the window when clicked, the app will take care // of that via the handleQuitInternal() methods // http://dev.processing.org/bugs/show_bug.cgi?id=440 _frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); PdeKeywords keywords = new PdeKeywords(); sketchbook = new Sketchbook(this); JMenuBar menubar = new JMenuBar(); menubar.add(buildFileMenu()); menubar.add(buildEditMenu()); menubar.add(buildSketchMenu()); menubar.add(buildToolsMenu()); // what platform has their help menu way on the right? motif? //menubar.add(Box.createHorizontalGlue()); menubar.add(buildHelpMenu()); _frame.setJMenuBar(menubar); // doesn't matter when this is created, just make it happen at some point //find = new FindReplace(Editor.this); //Container pain = getContentPane(); //pain.setLayout(new BorderLayout()); // for rev 0120, placing things inside a JPanel because //Container contentPain = getContentPane(); this.getContentPane().setLayout(new BorderLayout()); JPanel pain = new JPanel(); pain.setLayout(new BorderLayout()); this.getContentPane().add(pain, BorderLayout.CENTER); Box box = Box.createVerticalBox(); Box upper = Box.createVerticalBox(); JPanel editorSection = new JPanel(new BorderLayout()); buttons = new EditorButtons(this); upper.add(buttons); header = new EditorHeader(this); //header.setBorder(null); upper.add(header); textarea = new JEditTextArea(new PdeTextAreaDefaults()); textarea.setRightClickPopup(new TextAreaPopup()); //textarea.setTokenMarker(new PdeKeywords()); textarea.setHorizontalOffset(6); // assemble console panel, consisting of status area and the console itself consolePanel = new JPanel(); consolePanel.setLayout(new BorderLayout()); status = new EditorStatus(this); consolePanel.add(status, BorderLayout.NORTH); console = new EditorConsole(this); // windows puts an ugly border on this guy console.setBorder(null); consolePanel.add(console, BorderLayout.CENTER); lineStatus = new EditorLineStatus(textarea); consolePanel.add(lineStatus, BorderLayout.SOUTH); leftExpandLabel = new JLabel("<"); leftWing = new JPanel(); leftWing.setBackground(new Color(0x54, 0x91, 0x9e)); leftWing.setOpaque(true); leftWing.setSize(15, 0); leftWing.setPreferredSize(new Dimension(10, 0)); leftWing.setLayout(new BorderLayout()); leftWing.add(leftExpandLabel, BorderLayout.CENTER); leftWing.addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent arg0) { gadgetPanel.setVisible(!gadgetPanel.isVisible()); /* Handle the expand icon */ if (gadgetPanel.isVisible()){ leftExpandLabel.setText(">"); } else { leftExpandLabel.setText("<"); } } public void mouseEntered(MouseEvent arg0) { } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }); JPanel rightWing = new JPanel(); rightWing.setBackground(new Color(0x54, 0x91, 0x9e)); rightWing.setOpaque(true); rightWing.setSize(15, 0); rightWing.setPreferredSize(new Dimension(10, 0)); imageListPanel = new ImageListPanel(this.gadgetPanel, new FlashTransfer()); this.getContentPane().validate(); JPanel testPanel = new JPanel(); JLabel lbl = new JLabel("THIS IS A TEST STRING"); lbl.setVisible(true); lbl.setBackground(Color.BLUE); centerPanel = new JPanel(); Dimension dim = textarea.getSize(); System.out.println("The dimensions...." + dim); centerPanel.setLayout(new CardLayout()); centerPanel.setVisible(true); centerPanel.add(textarea, CODEEDITOR); centerPanel.add(imageListPanel, FILELIST); centerPanel.add(lbl, TEST); CardLayout cl = (CardLayout) centerPanel.getLayout(); cl.show(centerPanel, CODEEDITOR); editorSection.add(leftWing, BorderLayout.WEST); editorSection.add(centerPanel, BorderLayout.CENTER); editorSection.add(rightWing, BorderLayout.EAST); upper.add(editorSection); String libraryDirectory = System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "OpenHardware" + File.separator + "Modules"; gadgetPanel = new GadgetPanel("", this, libraryDirectory); gadgetPanel.addActiveGadgetChangedEventListener(this); leftWing.setVisible(true); //upper.add(gadgetPanel); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upper, consolePanel); //textarea, consolePanel); splitPane.setOneTouchExpandable(true); // repaint child panes while resizing splitPane.setContinuousLayout(true); // if window increases in size, give all of increase to // the textarea in the uppper pane splitPane.setResizeWeight(1D); // to fix ugliness.. normally macosx java 1.3 puts an // ugly white border around this object, so turn it off. splitPane.setBorder(null); // the default size on windows is too small and kinda ugly int dividerSize = Preferences.getInteger("editor.divider.size"); if (dividerSize != 0) { splitPane.setDividerSize(dividerSize); } splitPane.setMinimumSize(new Dimension(this.getWidth(), 300)); box.add(splitPane); // hopefully these are no longer needed w/ swing // (har har har.. that was wishful thinking) listener = new EditorListener(this, textarea); pain.add(box); pain.setTransferHandler(new TransferHandler() { public boolean canImport(JComponent dest, DataFlavor[] flavors) { // claim that we can import everything return true; } public boolean importData(JComponent src, Transferable transferable) { DataFlavor[] flavors = transferable.getTransferDataFlavors(); /* DropTarget dt = new DropTarget(this, new DropTargetListener() { public void dragEnter(DropTargetDragEvent event) { // debug messages for diagnostics //System.out.println("dragEnter " + event); event.acceptDrag(DnDConstants.ACTION_COPY); } public void dragExit(DropTargetEvent event) { //System.out.println("dragExit " + event); } public void dragOver(DropTargetDragEvent event) { //System.out.println("dragOver " + event); event.acceptDrag(DnDConstants.ACTION_COPY); } public void dropActionChanged(DropTargetDragEvent event) { //System.out.println("dropActionChanged " + event); } public void drop(DropTargetDropEvent event) { //System.out.println("drop " + event); event.acceptDrop(DnDConstants.ACTION_COPY); Transferable transferable = event.getTransferable(); DataFlavor flavors[] = transferable.getTransferDataFlavors(); */ int successful = 0; for (int i = 0; i < flavors.length; i++) { try { //System.out.println(flavors[i]); //System.out.println(transferable.getTransferData(flavors[i])); Object stuff = transferable.getTransferData(flavors[i]); if (!(stuff instanceof java.util.List)) continue; java.util.List list = (java.util.List) stuff; for (int j = 0; j < list.size(); j++) { Object item = list.get(j); if (item instanceof File) { File file = (File) item; // see if this is a .pde file to be opened String filename = file.getName(); if (filename.endsWith(".pde")) { String name = filename.substring(0, filename.length() - 4); File parent = file.getParentFile(); if (name.equals(parent.getName())) { handleOpenFile(file); return true; } } if (sketch.addFile(file)) { successful++; } } } } catch (Exception e) { e.printStackTrace(); return false; } } if (successful == 0) { error("No files were added to the sketch."); } else if (successful == 1) { message("One file added to the sketch."); } else { message(successful + " files added to the sketch."); } return true; } }); } /** * Hack for #@#)$(* Mac OS X 10.2. * <p/> * This appears to only be required on OS X 10.2, and is not * even being called on later versions of OS X or Windows. */ public Dimension getMinimumSize() { //System.out.println("getting minimum size"); return new Dimension(500, 550); } // ................................................................... /** * Builds any unbuilt buildable libraries * Adds syntax coloring from those libraries (if exists) * Rebuilds sketchbook menu with library examples (if they exist) */ public void prepareLibraries() { // build any unbuilt libraries try { LibraryManager libraryManager = new LibraryManager(); libraryManager.buildAllUnbuilt(); // update syntax coloring table libraryManager.addSyntaxColoring(new PdeKeywords()); } catch (RunnerException re) { message("Error compiling library ..."); error(re); } catch (Exception ex) { ex.printStackTrace(); } // update sketchbook menu, this adds examples of any built libs sketchbook.rebuildMenus(); } // ................................................................... /** * Post-constructor setup for the editor area. Loads the last * sketch that was used (if any), and restores other Editor settings. * The complement to "storePreferences", this is called when the * application is first launched. */ public void restorePreferences() { // figure out window placement Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); boolean windowPositionValid = true; if (Preferences.get("last.screen.height") != null) { // if screen size has changed, the window coordinates no longer // make sense, so don't use them unless they're identical int screenW = Preferences.getInteger("last.screen.width"); int screenH = Preferences.getInteger("last.screen.height"); if ((screen.width != screenW) || (screen.height != screenH)) { windowPositionValid = false; } int windowX = Preferences.getInteger("last.window.x"); int windowY = Preferences.getInteger("last.window.y"); if ((windowX < 0) || (windowY < 0) || (windowX > screenW) || (windowY > screenH)) { windowPositionValid = false; } } else { windowPositionValid = false; } if (!windowPositionValid) { //System.out.println("using default size"); int windowH = Preferences.getInteger("default.window.height"); int windowW = Preferences.getInteger("default.window.width"); setBounds((screen.width - windowW) / 2, (screen.height - windowH) / 2, windowW, windowH); // this will be invalid as well, so grab the new value Preferences.setInteger("last.divider.location", splitPane.getDividerLocation()); } else { setBounds(Preferences.getInteger("last.window.x"), Preferences.getInteger("last.window.y"), Preferences.getInteger("last.window.width"), Preferences.getInteger("last.window.height")); } // last sketch that was in use, or used to launch the app if (Base.openedAtStartup != null) { handleOpen2(Base.openedAtStartup); } else { //String sketchName = Preferences.get("last.sketch.name"); String sketchPath = null/*Preferences.get("last.sketch.path")*/; //Sketch sketchTemp = new Sketch(sketchPath); if ((sketchPath != null) && (new File(sketchPath)).exists()) { // don't check modified because nothing is open yet handleOpen2(sketchPath); } else { handleNew2(true); this.header.rebuild(); } } // location for the console/editor area divider int location = Preferences.getInteger("last.divider.location"); splitPane.setDividerLocation(location); // read the preferences that are settable in the preferences window applyPreferences(); } /** * Read and apply new values from the preferences, either because * the app is just starting up, or the user just finished messing * with things in the Preferences window. */ public void applyPreferences() { // apply the setting for 'use external editor' boolean external = Preferences.getBoolean("editor.external"); textarea.setEditable(!external); saveMenuItem.setEnabled(!external); saveAsMenuItem.setEnabled(!external); //beautifyMenuItem.setEnabled(!external); TextAreaPainter painter = textarea.getPainter(); if (external) { // disable line highlight and turn off the caret when disabling Color color = Preferences.getColor("editor.external.bgcolor"); painter.setBackground(color); painter.setLineHighlightEnabled(false); textarea.setCaretVisible(false); } else { Color color = Preferences.getColor("editor.bgcolor"); painter.setBackground(color); boolean highlight = Preferences.getBoolean("editor.linehighlight"); painter.setLineHighlightEnabled(highlight); textarea.setCaretVisible(true); } // apply changes to the font size for the editor //TextAreaPainter painter = textarea.getPainter(); painter.setFont(Preferences.getFont("editor.font")); //Font font = painter.getFont(); //textarea.getPainter().setFont(new Font("Courier", Font.PLAIN, 36)); // in case tab expansion stuff has changed listener.applyPreferences(); // in case moved to a new location // For 0125, changing to async version (to be implemented later) //sketchbook.rebuildMenus(); sketchbook.rebuildMenusAsync(); } /** * Store preferences about the editor's current state. * Called when the application is quitting. */ public void storePreferences() { //System.out.println("storing preferences"); // window location information Rectangle bounds = getBounds(); Preferences.setInteger("last.window.x", bounds.x); Preferences.setInteger("last.window.y", bounds.y); Preferences.setInteger("last.window.width", bounds.width); Preferences.setInteger("last.window.height", bounds.height); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Preferences.setInteger("last.screen.width", screen.width); Preferences.setInteger("last.screen.height", screen.height); // last sketch that was in use //Preferences.set("last.sketch.name", sketchName); //Preferences.set("last.sketch.name", sketch.name); Preferences.set("last.sketch.path", sketch.getMainFilePath()); // location for the console/editor area divider int location = splitPane.getDividerLocation(); Preferences.setInteger("last.divider.location", location); } // ................................................................... protected JMenu buildFileMenu() { JMenuItem item; JMenu menu = new JMenu("File"); item = newJMenuItem("New", 'N'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleNew(false); } }); menu.add(item); menu.add(sketchbook.getOpenMenu()); saveMenuItem = newJMenuItem("Save", 'S'); saveMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSave(false); } }); menu.add(saveMenuItem); saveAsMenuItem = newJMenuItem("Save As...", 'S', true); saveAsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSaveAs(); } }); menu.add(saveAsMenuItem); item = newJMenuItem("Upload to I/O Board", 'U'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleExport(); } }); menu.add(item); /*exportAppItem = newJMenuItem("Export Application", 'E', true); exportAppItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //buttons.activate(EditorButtons.EXPORT); //SwingUtilities.invokeLater(new Runnable() { //public void run() { handleExportApplication(); //}}); } }); menu.add(exportAppItem); */ menu.addSeparator(); item = newJMenuItem("Page Setup", 'P', true); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePageSetup(); } }); menu.add(item); item = newJMenuItem("Print", 'P'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePrint(); } }); menu.add(item); // macosx already has its own preferences and quit menu if (!Base.isMacOS()) { menu.addSeparator(); item = newJMenuItem("Preferences", ','); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePrefs(); } }); menu.add(item); menu.addSeparator(); item = newJMenuItem("Quit", 'Q'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleQuitInternal(); } }); menu.add(item); } return menu; } protected JMenu buildSketchMenu() { JMenuItem item; JMenu menu = new JMenu("Sketch"); item = newJMenuItem("Verify/Compile", 'R'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { handleRun(false); } catch (IOException ex) { ex.printStackTrace(); } } }); menu.add(item); /*item = newJMenuItem("Present", 'R', true); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleRun(true); } }); menu.add(item); */ item = new JMenuItem("Stop"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleStop(); } }); menu.add(item); menu.addSeparator(); menu.add(sketchbook.getImportMenu()); //if (Base.isWindows() || Base.isMacOS()) { // no way to do an 'open in file browser' on other platforms // since there isn't any sort of standard item = newJMenuItem("Show Sketch Folder", 'K', false); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //Base.openFolder(sketchDir); Base.openFolder(sketch.folder); } }); menu.add(item); if (!Base.openFolderAvailable()) { item.setEnabled(false); } //menu.addSeparator(); item = new JMenuItem("Add File..."); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sketch.addFile(); } }); menu.add(item); // TODO re-enable history //history.attachMenu(menu); return menu; } protected JMenu buildToolsMenu() { JMenuItem item; JMenuItem rbMenuItem; JMenuItem cbMenuItem; serialMenuListener = new SerialMenuListener(); JMenu menu = new JMenu("Tools"); item = newJMenuItem("Auto Format", 'T', false); item.addActionListener(new ActionListener() { synchronized public void actionPerformed(ActionEvent e) { new AutoFormat(Editor.this).show(); /* Jalopy jalopy = new Jalopy(); jalopy.setInput(getText(), sketch.current.file.getAbsolutePath()); StringBuffer buffer = new StringBuffer(); jalopy.setOutput(buffer); jalopy.setInspect(false); jalopy.format(); setText(buffer.toString(), 0, 0); if (jalopy.getState() == Jalopy.State.OK) System.out.println("successfully formatted"); else if (jalopy.getState() == Jalopy.State.WARN) System.out.println(" formatted with warnings"); else if (jalopy.getState() == Jalopy.State.ERROR) System.out.println(" could not be formatted"); */ } }); menu.add(item); item = new JMenuItem("Copy for Forum"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { new DiscourseFormat(Editor.this).show(); } }); } }); menu.add(item); item = new JMenuItem("Archive Sketch"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new Archiver(Editor.this).show(); //Archiver archiver = new Archiver(); //archiver.setup(Editor.this); //archiver.show(); } }); menu.add(item); /* item = new JMenuItem("Export Folder..."); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { new ExportFolder(Editor.this).show(); } }); menu.add(item); */ menu.addSeparator(); JMenu boardsMenu = new JMenu("Board"); ButtonGroup boardGroup = new ButtonGroup(); for (Iterator i = Preferences.getSubKeys("boards"); i.hasNext(); ) { String board = (String) i.next(); Action action = new BoardMenuAction(board); item = new JRadioButtonMenuItem(action); String selectedBoard = Preferences.get("board"); if (board.equals(Preferences.get("board"))) item.setSelected(true); boardGroup.add(item); boardsMenu.add(item); } menu.add(boardsMenu); serialMenu = new JMenu("Serial Port"); populateSerialMenu(); menu.add(serialMenu); menu.addSeparator(); JMenu bootloaderMenu = new JMenu("Burn Bootloader"); for (Iterator i = Preferences.getSubKeys("programmers"); i.hasNext(); ) { String programmer = (String) i.next(); Action action = new BootloaderMenuAction(programmer); item = new JMenuItem(action); bootloaderMenu.add(item); } menu.add(bootloaderMenu); menu.addMenuListener(new MenuListener() { public void menuCanceled(MenuEvent e) {} public void menuDeselected(MenuEvent e) {} public void menuSelected(MenuEvent e) { //System.out.println("Tools menu selected."); populateSerialMenu(); } }); return menu; } class SerialMenuListener implements ActionListener { //public SerialMenuListener() { } public void actionPerformed(ActionEvent e) { if(serialMenu == null) { System.out.println("serialMenu is null"); return; } int count = serialMenu.getItemCount(); for (int i = 0; i < count; i++) { ((JCheckBoxMenuItem)serialMenu.getItem(i)).setState(false); } JCheckBoxMenuItem item = (JCheckBoxMenuItem)e.getSource(); item.setState(true); String name = item.getText(); //System.out.println(item.getLabel()); Preferences.set("serial.port", name); //System.out.println("set to " + get("serial.port")); } /* public void actionPerformed(ActionEvent e) { System.out.println(e.getSource()); String name = e.getActionCommand(); PdeBase.properties.put("serial.port", name); System.out.println("set to " + get("serial.port")); //editor.skOpen(path + File.separator + name, name); // need to push "serial.port" into PdeBase.properties } */ } class BoardMenuAction extends AbstractAction { private String board; public BoardMenuAction(String board) { super(Preferences.get("boards." + board + ".name")); this.board = board; } public void actionPerformed(ActionEvent actionevent) { System.out.println("Switching to " + board); Preferences.set("board", board); try { //LibraryManager libraryManager = new LibraryManager(); //libraryManager.rebuildAllBuilt(); } catch (Exception e) { e.printStackTrace(); //} catch (RunnerException e) { // message("Error rebuilding libraries..."); // error(e); } } } class BootloaderMenuAction extends AbstractAction { private String programmer; public BootloaderMenuAction(String programmer) { super("w/ " + Preferences.get("programmers." + programmer + ".name")); this.programmer = programmer; } public void actionPerformed(ActionEvent actionevent) { handleBurnBootloader(programmer); } } protected void populateSerialMenu() { // getting list of ports JMenuItem rbMenuItem; //System.out.println("Clearing serial port menu."); serialMenu.removeAll(); boolean empty = true; try { for (Enumeration enumeration = CommPortIdentifier.getPortIdentifiers(); enumeration.hasMoreElements();) { CommPortIdentifier commportidentifier = (CommPortIdentifier)enumeration.nextElement(); //System.out.println("Found communication port: " + commportidentifier); if (commportidentifier.getPortType() == CommPortIdentifier.PORT_SERIAL) { //System.out.println("Adding port to serial port menu: " + commportidentifier); String curr_port = commportidentifier.getName(); rbMenuItem = new JCheckBoxMenuItem(curr_port, curr_port.equals(Preferences.get("serial.port"))); rbMenuItem.addActionListener(serialMenuListener); //serialGroup.add(rbMenuItem); serialMenu.add(rbMenuItem); empty = false; } } if (!empty) { //System.out.println("enabling the serialMenu"); serialMenu.setEnabled(true); } } catch (Exception exception) { System.out.println("error retrieving port list"); exception.printStackTrace(); } if (serialMenu.getItemCount() == 0) { serialMenu.setEnabled(false); } //serialMenu.addSeparator(); //serialMenu.add(item); } protected JMenu buildHelpMenu() { JMenu menu = new JMenu("Help"); JMenuItem item; if (!Base.isLinux()) { item = new JMenuItem("Getting Started"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (Base.isWindows()) Base.openURL(System.getProperty("user.dir") + File.separator + "reference" + File.separator + "Guide_Windows.html"); else Base.openURL(System.getProperty("user.dir") + File.separator + "reference" + File.separator + "Guide_MacOSX.html"); } }); menu.add(item); } item = new JMenuItem("Environment"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showEnvironment(); } }); menu.add(item); item = new JMenuItem("Troubleshooting"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showTroubleshooting(); } }); menu.add(item); item = new JMenuItem("Reference"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference(); } }); menu.add(item); item = newJMenuItem("Find in Reference", 'F', true); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (textarea.isSelectionActive()) { handleReference(); } } }); menu.add(item); item = new JMenuItem("Frequently Asked Questions"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showFAQ(); } }); menu.add(item); item = newJMenuItem("Visit www.arduino.cc", '5'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL("http://www.arduino.cc/"); } }); menu.add(item); // macosx already has its own about menu if (!Base.isMacOS()) { menu.addSeparator(); item = new JMenuItem("About Arduino"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleAbout(); } }); menu.add(item); } return menu; } public JMenu buildEditMenu() { JMenu menu = new JMenu("Edit"); JMenuItem item; undoItem = newJMenuItem("Undo", 'Z'); undoItem.addActionListener(undoAction = new UndoAction()); menu.add(undoItem); redoItem = newJMenuItem("Redo", 'Y'); redoItem.addActionListener(redoAction = new RedoAction()); menu.add(redoItem); menu.addSeparator(); // TODO "cut" and "copy" should really only be enabled // if some text is currently selected item = newJMenuItem("Cut", 'X'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.cut(); sketch.setModified(true); } }); menu.add(item); item = newJMenuItem("Copy", 'C'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.copy(); } }); menu.add(item); item = newJMenuItem("Paste", 'V'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.paste(); sketch.setModified(true); } }); menu.add(item); item = newJMenuItem("Select All", 'A'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.selectAll(); } }); menu.add(item); menu.addSeparator(); item = newJMenuItem("Find...", 'F'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find == null) { find = new FindReplace(Editor.this); } //new FindReplace(Editor.this).show(); find.show(); //find.setVisible(true); } }); menu.add(item); // TODO find next should only be enabled after a // search has actually taken place item = newJMenuItem("Find Next", 'G'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find != null) { //find.find(true); //FindReplace find = new FindReplace(Editor.this); //.show(); find.find(true); } } }); menu.add(item); return menu; } /** * Convenience method, see below. */ static public JMenuItem newJMenuItem(String title, int what) { return newJMenuItem(title, what, false); } /** * A software engineer, somewhere, needs to have his abstraction * taken away. In some countries they jail or beat people for writing * the sort of API that would require a five line helper function * just to set the command key for a menu item. */ static public JMenuItem newJMenuItem(String title, int what, boolean shift) { JMenuItem menuItem = new JMenuItem(title); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); if (shift) modifiers |= ActionEvent.SHIFT_MASK; menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); return menuItem; } // ................................................................... class UndoAction extends AbstractAction { public UndoAction() { super("Undo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undo.undo(); } catch (CannotUndoException ex) { //System.out.println("Unable to undo: " + ex); //ex.printStackTrace(); } updateUndoState(); redoAction.updateRedoState(); } protected void updateUndoState() { if (undo.canUndo()) { this.setEnabled(true); undoItem.setEnabled(true); undoItem.setText(undo.getUndoPresentationName()); putValue(Action.NAME, undo.getUndoPresentationName()); if (sketch != null) { sketch.setModified(true); // 0107 } } else { this.setEnabled(false); undoItem.setEnabled(false); undoItem.setText("Undo"); putValue(Action.NAME, "Undo"); if (sketch != null) { sketch.setModified(false); // 0107 } } } } class RedoAction extends AbstractAction { public RedoAction() { super("Redo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undo.redo(); } catch (CannotRedoException ex) { //System.out.println("Unable to redo: " + ex); //ex.printStackTrace(); } updateRedoState(); undoAction.updateUndoState(); } protected void updateRedoState() { if (undo.canRedo()) { redoItem.setEnabled(true); redoItem.setText(undo.getRedoPresentationName()); putValue(Action.NAME, undo.getRedoPresentationName()); } else { this.setEnabled(false); redoItem.setEnabled(false); redoItem.setText("Redo"); putValue(Action.NAME, "Redo"); } } } // ................................................................... // interfaces for MRJ Handlers, but naming is fine // so used internally for everything else public void handleAbout() { final Image image = Base.getImage("about.jpg", this); int w = image.getWidth(this); int h = image.getHeight(this); final Window window = new Window(_frame) { public void paint(Graphics g) { g.drawImage(image, 0, 0, null); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); g.setFont(new Font("SansSerif", Font.PLAIN, 11)); g.setColor(Color.white); g.drawString(Base.DIST_NAME + " v" + Base.VERSION_NAME, 50, 30); } }; window.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { window.dispose(); } }); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); window.setBounds((screen.width-w)/2, (screen.height-h)/2, w, h); window.show(); } /** * Show the preferences window. */ public void handlePrefs() { Preferences preferences = new Preferences(); preferences.showFrame(this); // since this can't actually block, it'll hide // the editor window while the prefs are open //preferences.showFrame(this); // and then call applyPreferences if 'ok' is hit // and then unhide // may need to rebuild sketch and other menus //applyPreferences(); // next have editor do its thing //editor.appyPreferences(); } // ................................................................... /** * Get the contents of the current buffer. Used by the Sketch class. */ public String getText() { return textarea.getText(); } /** * Called to update the text but not switch to a different * set of code (which would affect the undo manager). */ public void setText(String what, int selectionStart, int selectionEnd) { beginCompoundEdit(); textarea.setText(what); endCompoundEdit(); // make sure that a tool isn't asking for a bad location selectionStart = Math.max(0, Math.min(selectionStart, textarea.getDocumentLength())); selectionEnd = Math.max(0, Math.min(selectionStart, textarea.getDocumentLength())); textarea.select(selectionStart, selectionEnd); textarea.requestFocus(); // get the caret blinking } /** * Switch between tabs, this swaps out the Document object * that's currently being manipulated. */ public void setCode(SketchCode code) { if (code.document == null) { // this document not yet inited code.document = new SyntaxDocument(); // turn on syntax highlighting code.document.setTokenMarker(new PdeKeywords()); // insert the program text into the document object try { code.document.insertString(0, code.program, null); } catch (BadLocationException bl) { bl.printStackTrace(); } // set up this guy's own undo manager code.undo = new UndoManager(); // connect the undo listener to the editor code.document.addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent e) { if (compoundEdit != null) { compoundEdit.addEdit(e.getEdit()); } else if (undo != null) { undo.addEdit(e.getEdit()); undoAction.updateUndoState(); redoAction.updateRedoState(); } } }); } //switch to a code card try{ CardLayout cl = (CardLayout)this.getLayout(); cl.show(textarea, CODEEDITOR); }catch(Exception ex){ } //set the card layout to give focus to the textarea CardLayout layout = (CardLayout)this.centerPanel.getLayout(); layout.show(this.centerPanel, CODEEDITOR); // update the document object that's in use textarea.setDocument(code.document, code.selectionStart, code.selectionStop, code.scrollPosition); textarea.requestFocus(); // get the caret blinking this.undo = code.undo; undoAction.updateUndoState(); redoAction.updateRedoState(); } public void beginCompoundEdit() { compoundEdit = new CompoundEdit(); } public void endCompoundEdit() { compoundEdit.end(); undo.addEdit(compoundEdit); undoAction.updateUndoState(); redoAction.updateRedoState(); compoundEdit = null; } // ................................................................... public void handleRun(final boolean present) throws IOException { System.out.println("handling the run"); doClose(); running = true; this.isExporting = false; buttons.activate(EditorButtons.RUN); message("Compiling..."); // do this for the terminal window / dos prompt / etc for (int i = 0; i < 10; i++) System.out.println(); // clear the console on each run, unless the user doesn't want to //if (Base.getBoolean("console.auto_clear", true)) { //if (Preferences.getBoolean("console.auto_clear", true)) { if (Preferences.getBoolean("console.auto_clear")) { console.clear(); } presenting = present; if (presenting && Base.isMacOS()) { // check to see if osx 10.2, if so, show a warning String osver = System.getProperty("os.version").substring(0, 4); if (osver.equals("10.2")) { Base.showWarning("Time for an OS Upgrade", "The \"Present\" feature may not be available on\n" + "Mac OS X 10.2, because of what appears to be\n" + "a bug in the Java 1.4 implementation on 10.2.\n" + "In case it works on your machine, present mode\n" + "will start, but if you get a flickering white\n" + "window, using Command-Q to quit the sketch", null); } } this.saveSketches(); if(gadgetPanel.getActiveGadget() != null){ if(gadgetPanel.getActiveModule().getRules() != null){ IMessage message = gadgetPanel.getActiveModule().getRules().getMessages()[0]; if(message != null && this.isExporting){ IOkListener ourListener = new IOkListener(){ private String msg; public void OkButton() { compile(); } public String getMessage() { return msg; } public void setMessage(String message) { msg = message; } }; status.CreateOkDialog(ourListener, message.getMessage()); }else{ this.compile(); //no message just compile } }else{ this.compile(); } }else{ this.compile(); } // this doesn't seem to help much or at all /* final SwingWorker worker = new SwingWorker() { public Object construct() { try { if (!sketch.handleRun()) return null; runtime = new Runner(sketch, Editor.this); runtime.start(presenting ? presentLocation : appletLocation); watcher = new RunButtonWatcher(); message("Done compiling."); } catch (RunnerException e) { message("Error compiling..."); error(e); } catch (Exception e) { e.printStackTrace(); } return null; // needn't return anything } }; worker.start(); */ //sketch.cleanup(); // where does this go? buttons.clear(); } private void compile(){ final Sketch sketch = this.sketch; SwingUtilities.invokeLater(new Runnable() { public void run() { try { if(gadgetPanel != null){ if(gadgetPanel.getActiveModule() != null){ IGadget book = gadgetPanel.getActiveGadget(); IModule[] gadgets = book.getModules(); IModule gadget = gadgetPanel.getActiveModule(); File sketchFile = gadget.getSketchFile(); Sketch currentSketch = new Sketch(new Editor(), sketchFile.getPath()); String target = gadget.getTarget(); System.out.println("Running file with target : " + target); String boardName = Preferences.get("board"); System.out.println(boardName); if(!currentSketch.handleRun(new Target(System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores", Preferences.get("boards." + target + ".build.core")))){ System.out.println("Error compiling file"); } }else{ //There is no active gadget; we should do a classic run String boardName = Preferences.get("board"); if(!sketch.handleRun(new Target(System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores", Preferences.get("boards." + boardName + ".build.core")))){ System.out.println("Error compiling file"); } } }else{ System.out.println("error getting the gadget panel"); } /* if (!sketch.handleRun(new Target( System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores", Preferences.get("boards." + Preferences.get("board") + ".build.core")))) return; */ //runtime = new Runner(sketch, Editor.this); //runtime.start(appletLocation); watcher = new RunButtonWatcher(); message("Done compiling."); if(watcher != null) watcher.stop(); } catch (RunnerException e) { message("Error compiling..."); error(e); } catch (Exception e) { e.printStackTrace(); } }}); } class RunButtonWatcher implements Runnable { Thread thread; public RunButtonWatcher() { thread = new Thread(this, "run button watcher"); thread.setPriority(Thread.MIN_PRIORITY); thread.start(); } public void run() { while (Thread.currentThread() == thread) { /*if (runtime == null) { stop(); } else { if (runtime.applet != null) { if (runtime.applet.finished) { stop(); } //buttons.running(!runtime.applet.finished); } else if (runtime.process != null) { //buttons.running(true); // ?? } else { stop(); } }*/ try { Thread.sleep(250); } catch (InterruptedException e) { } //System.out.println("still inside runner thread"); } } public void stop() { buttons.running(false); thread = null; } } public void handleSerial() { if (!debugging) { try { ImageListPanel.killActiveTransfer(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } serialPort = new Serial(true); this.gadgetPanel.setSerial(serialPort); console.clear(); buttons.activate(EditorButtons.SERIAL); debugging = true; status.serial(); } catch(SerialException e) { error(e); } } else { doStop(); } } public void handleStop() { // called by menu or buttons if (presenting) { doClose(); } else { doStop(); } buttons.clear(); } /** * Stop the applet but don't kill its window. */ public void doStop() { //if (runtime != null) runtime.stop(); if (debugging) { status.unserial(); serialPort.dispose(); debugging = false; } if (watcher != null) watcher.stop(); message(EMPTY); // the buttons are sometimes still null during the constructor // is this still true? are people still hitting this error? /*if (buttons != null)*/ buttons.clear(); running = false; } /** * Stop the applet and kill its window. When running in presentation * mode, this will always be called instead of doStop(). */ public void doClose() { //if (presenting) { //presentationWindow.hide(); //} else { //try { // the window will also be null the process was running // externally. so don't even try setting if window is null // since Runner will set the appletLocation when an // external process is in use. // if (runtime.window != null) { // appletLocation = runtime.window.getLocation(); // } //} catch (NullPointerException e) { } //} //if (running) doStop(); doStop(); // need to stop if runtime error //try { /*if (runtime != null) { runtime.close(); // kills the window runtime = null; // will this help? }*/ //} catch (Exception e) { } //buttons.clear(); // done by doStop sketch.cleanup(); // [toxi 030903] // focus the PDE again after quitting presentation mode _frame.toFront(); if(this.gadgetPanel.isActive()){ this.gadgetPanel.saveCurrentGadget(); Preferences.set("gadget.active", "true"); try{ Preferences.set("last.active.gadget", ((IPackedFile)this.gadgetPanel.getActiveGadget()).getPackedFile().getPath()); }catch(Exception ex){ //there is no gadget } } } /** * Check to see if there have been changes. If so, prompt user * whether or not to save first. If the user cancels, just ignore. * Otherwise, one of the other methods will handle calling * checkModified2() which will get on with business. */ protected void checkModified(int checkModifiedMode) { this.checkModifiedMode = checkModifiedMode; if (!sketch.modified) { checkModified2(); return; } String prompt = "Save changes to " + sketch.name + "? "; if (checkModifiedMode != HANDLE_QUIT) { // if the user is not quitting, then use simpler nicer // dialog that's actually inside the p5 window. status.prompt(prompt); } else { if (!Base.isMacOS() || PApplet.javaVersion < 1.5f) { int result = JOptionPane.showConfirmDialog(this, prompt, "Quit", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { handleSave(true); checkModified2(); } else if (result == JOptionPane.NO_OPTION) { checkModified2(); } // cancel is ignored altogether } else { // This code is disabled unless Java 1.5 is being used on Mac OS X // because of a Java bug that prevents the initial value of the // dialog from being set properly (at least on my MacBook Pro). // The bug causes the "Don't Save" option to be the highlighted, // blinking, default. This sucks. But I'll tell you what doesn't // suck--workarounds for the Mac and Apple's snobby attitude about it! // adapted from the quaqua guide // http://www.randelshofer.ch/quaqua/guide/joptionpane.html JOptionPane pane = new JOptionPane("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Do you want to save changes to this sketch<BR>" + " before closing?</b>" + "<p>If you don't save, your changes will be lost.", JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { "Save", "Cancel", "Don't Save" }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); // on macosx, setting the destructive property places this option // away from the others at the lefthand side pane.putClientProperty("Quaqua.OptionPane.destructiveOption", new Integer(2)); JDialog dialog = pane.createDialog(this, null); dialog.show(); Object result = pane.getValue(); if (result == options[0]) { // save (and quit) handleSave(true); checkModified2(); } else if (result == options[2]) { // don't save (still quit) checkModified2(); } } } } /** * Called by EditorStatus to complete the job and re-dispatch * to handleNew, handleOpen, handleQuit. */ public void checkModified2() { switch (checkModifiedMode) { case HANDLE_NEW: handleNew2(false); break; case HANDLE_OPEN: handleOpen2(handleOpenPath); break; case HANDLE_QUIT: handleQuit2(); break; } checkModifiedMode = 0; } /** * New was called (by buttons or by menu), first check modified * and if things work out ok, handleNew2() will be called. * <p/> * If shift is pressed when clicking the toolbar button, then * force the opposite behavior from sketchbook.prompt's setting */ public void handleNew(final boolean shift) { buttons.activate(EditorButtons.NEW); SwingUtilities.invokeLater(new Runnable() { public void run() { doStop(); handleNewShift = shift; handleNewLibrary = false; checkModified(HANDLE_NEW); }}); this.header.paintComponents(this.getGraphics()); } /** * Extra public method so that Sketch can call this when a sketch * is selected to be deleted, and it won't call checkModified() * to prompt for save as. */ public void handleNewUnchecked() { doStop(); handleNewShift = false; handleNewLibrary = false; handleNew2(true); } /** * User selected "New Library", this will act just like handleNew * but internally set a flag that the new guy is a library, * meaning that a "library" subfolder will be added. */ public void handleNewLibrary() { doStop(); handleNewShift = false; handleNewLibrary = true; checkModified(HANDLE_NEW); } /** * Does all the plumbing to create a new project * then calls handleOpen to load it up. * * @param noPrompt true to disable prompting for the sketch * name, used when the app is starting (auto-create a sketch) */ protected void handleNew2(boolean noPrompt) { try { String pdePath = sketchbook.handleNew(noPrompt, handleNewShift, handleNewLibrary); if (pdePath != null) handleOpen2(pdePath); this.header.rebuild(); } catch (IOException e) { // not sure why this would happen, but since there's no way to // recover (outside of creating another new setkch, which might // just cause more trouble), then they've gotta quit. Base.showError("Problem creating a new sketch", "An error occurred while creating\n" + "a new sketch. Arduino must now quit.", e); } buttons.clear(); } /** * This is the implementation of the MRJ open document event, * and the Windows XP open document will be routed through this too. */ public void handleOpenFile(File file) { //System.out.println("handling open file: " + file); handleOpen(file.getAbsolutePath()); } /** * Open a sketch given the full path to the .pde file. * Pass in 'null' to prompt the user for the name of the sketch. */ public void handleOpen(final String ipath) { // haven't run across a case where i can verify that this works // because open is usually very fast. buttons.activate(EditorButtons.OPEN); SwingUtilities.invokeLater(new Runnable() { public void run() { String path = ipath; if (path == null) { // "open..." selected from the menu path = sketchbook.handleOpen(); if (path == null) return; } doClose(); handleOpenPath = path; checkModified(HANDLE_OPEN); }}); } /** * Open a sketch from a particular path, but don't check to save changes. * Used by Sketch.saveAs() to re-open a sketch after the "Save As" */ public void handleOpenUnchecked(String path, int codeIndex, int selStart, int selStop, int scrollPos) { doClose(); handleOpen2(path); sketch.setCurrent(codeIndex); textarea.select(selStart, selStop); //textarea.updateScrollBars(); textarea.setScrollPosition(scrollPos); } /** * Second stage of open, occurs after having checked to * see if the modifications (if any) to the previous sketch * need to be saved. */ protected void handleOpen2(String path) { if (sketch != null) { // if leaving an empty sketch (i.e. the default) do an // auto-clean right away try { // don't clean if we're re-opening the same file String oldPath = sketch.code[0].file.getPath(); String newPath = new File(path).getPath(); if (!oldPath.equals(newPath)) { if (Base.calcFolderSize(sketch.folder) == 0) { Base.removeDir(sketch.folder); //sketchbook.rebuildMenus(); sketchbook.rebuildMenusAsync(); } } } catch (Exception e) { } // oh well } try { // check to make sure that this .pde file is // in a folder of the same name File file = new File(path); File parentFile = new File(file.getParent()); String parentName = parentFile.getName(); String pdeName = parentName + ".pde"; File altFile = new File(file.getParent(), pdeName); boolean isGadgetFile = false; //System.out.println("path = " + file.getParent()); //System.out.println("name = " + file.getName()); //System.out.println("pname = " + parentName); if (pdeName.equals(file.getName())) { // no beef with this guy } else if (altFile.exists()) { // user selected a .java from the same sketch, // but open the .pde instead path = altFile.getAbsolutePath(); //System.out.println("found alt file in same folder"); } else if (!path.endsWith(".pde")) { Base.showWarning("Bad file selected", "Arduino can only open its own sketches\n" + "and other files ending in .pde", null); return; } else if (path.endsWith(".gadget")){ this.gadgetPanel.loadGadget(new File(path)); path = this.gadgetPanel.getActiveModule().getSketchFile().getPath(); this.loadGadget(this.gadgetPanel.getActiveGadget()); isGadgetFile = true; this.lastActiveGadgetPath = path; }else { try{ this.gadgetPanel.loadGadget(new File(path)); IModule module = this.gadgetPanel.getActiveModule(); File sketchFile = module.getSketchFile(); path = sketchFile.getPath(); this.loadGadget(this.gadgetPanel.getActiveGadget()); isGadgetFile = true; this.lastActiveGadgetPath = path; }catch(Exception ex){ ex.printStackTrace(); isGadgetFile = false; String properParent = file.getName().substring(0, file.getName().length() - 4); Object[] options = { "OK", "Cancel" }; String prompt = "The file \"" + file.getName() + "\" needs to be inside\n" + "a sketch folder named \"" + properParent + "\".\n" + "Create this folder, move the file, and continue?"; int result = JOptionPane.showOptionDialog(this, prompt, "Moving", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.YES_OPTION) { // create properly named folder File properFolder = new File(file.getParent(), properParent); if (properFolder.exists()) { Base.showWarning("Error", "A folder named \"" + properParent + "\" " + "already exists. Can't open sketch.", null); return; } if (!properFolder.mkdirs()) { throw new IOException("Couldn't create sketch folder"); } // copy the sketch inside File properPdeFile = new File(properFolder, file.getName()); File origPdeFile = new File(path); Base.copyFile(origPdeFile, properPdeFile); // remove the original file, so user doesn't get confused origPdeFile.delete(); // update with the new path path = properPdeFile.getAbsolutePath(); } else if (result == JOptionPane.NO_OPTION) { return; } } } //do one last check if(this.gadgetPanel.getActiveGadget() != null){ for(int i = 0; i < gadgetPanel.getActiveGadget().getModules().length; i++){ if(gadgetPanel.getActiveGadget().getModules()[i].getSketchFile().getPath().equalsIgnoreCase(path)){ isGadgetFile = true; break; } } } this.gadgetPanel.setVisible(isGadgetFile); if(isGadgetFile){ gadgetPanel.show(); /* The Boards menu doesn't * make sense with a gadget .pde file, so disable it */ _frame.getJMenuBar().getMenu(3).getItem(4).setEnabled(false); leftExpandLabel.setText(">"); }else{ this.gadgetPanel.Unload(); //remove the gadget list and unload active module /* Use the Boards menu with a std .pde file */ _frame.getJMenuBar().getMenu(3).getItem(4).setEnabled(true); gadgetPanel.hide(); } sketch = new Sketch(this, path); if(isGadgetFile){ System.out.println(path); } // TODO re-enable this once export application works //exportAppItem.setEnabled(false); //exportAppItem.setEnabled(false && !sketch.isLibrary()); //buttons.disableRun(sketch.isLibrary()); header.rebuild(); if (Preferences.getBoolean("console.auto_clear")) { console.clear(); } } catch (Exception e) { error(e); } } // there is no handleSave1 since there's never a need to prompt /** * Actually handle the save command. If 'force' is set to false, * this will happen in another thread so that the message area * will update and the save button will stay highlighted while the * save is happening. If 'force' is true, then it will happen * immediately. This is used during a quit, because invokeLater() * won't run properly while a quit is happening. This fixes * <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=276">Bug 276</A>. */ public void handleSave(boolean force) { doStop(); buttons.activate(EditorButtons.SAVE); if (force) { handleSave2(); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { handleSave2(); } }); } } public void handleSave2() { message("Saving..."); try { sketch.save(); if (saveSketches()) { message("Done Saving."); } else { message(EMPTY); } if(this.gadgetPanel.getActiveGadget()!= null){ this.gadgetPanel.saveCurrentGadget(); System.out.println("saved gadget"); } // rebuild sketch menu in case a save-as was forced // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenus(); //sketchbook.rebuildMenusAsync(); } catch (Exception e) { // show the error as a message in the window error(e); // zero out the current action, // so that checkModified2 will just do nothing checkModifiedMode = 0; // this is used when another operation calls a save } buttons.clear(); } public void handleSaveAs() { doStop(); buttons.activate(EditorButtons.SAVE); final GadgetPanel gp = this.gadgetPanel; final Editor edit = this; SwingUtilities.invokeLater(new Runnable() { public void run() { message("Saving..."); try { sketch.save(); } catch (IOException e1) { e1.printStackTrace(); } try { if(gp.getActiveGadget() != null){ FileDialog fd = new FileDialog(edit._frame, "Save gadget file as...", FileDialog.SAVE); File packedDirectory = ((IPackedFile)gp.getActiveGadget()).getPackedFile().getParentFile(); fd.setDirectory(packedDirectory.getPath()); fd.setFile(gp.getActiveGadget().getName()); fd.show(); String newParentDir = fd.getDirectory(); String newName = fd.getFile(); if (newName != null){ String fileName; if(newName.endsWith(".pde")){ fileName = newName; newName = newName.substring(0, newName.length() - 4); }else{ fileName = newName + ".pde"; } //save the gadget file GadgetFactory fact = new GadgetFactory(); /* IPackedFile file = ((IPackedFile)gp.getActiveGadget()); File newGadget = new File(newParentDir + File.separator + fileName); Base.copyFile(file.getPackedFile(), newGadget); IGadget gadg = fact.loadGadget(newGadget, System.getProperty("java.io.tmpdir") + File.separator + newGadget.getName()); gadg.setName(newName); ((IPackedFile)gadg).setPackedFile(newGadget); ITemporary tempDir = (ITemporary)gadg; File dir = new File(tempDir.getTempDirectory()); dir.listFiles(); gp.loadGadget(newGadget); gp.saveCurrentGadget();*/ File newFile = fact.copyGadget(gp.getActiveGadget(), newParentDir , newName); //IGadget newGadget = fact.loadGadget(newFile, System.getProperty("java.io.tmpdir") + File.separator + newFile.getName()); gp.loadGadget(newFile); gp.saveCurrentGadget(); } }else{ if (sketch.saveAs()) { message("Done Saving."); // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenusAsync(); } else { message("Save Cancelled."); } } } catch (Exception e) { // show the error as a message in the window error(e); } buttons.clear(); }}); } /** * Handles calling the export() function on sketch, and * queues all the gui status stuff that comes along with it. * * Made synchronized to (hopefully) avoid problems of people * hitting export twice, quickly, and horking things up. */ synchronized public void handleExport() { if(debugging) doStop(); buttons.activate(EditorButtons.EXPORT); console.clear(); //String what = sketch.isLibrary() ? "Applet" : "Library"; //message("Exporting " + what + "..."); message("Uploading to I/O Board..."); final GadgetPanel panel = this.gadgetPanel; this.isExporting = true; this.saveSketches(); SwingUtilities.invokeLater(new Runnable() { public void run() { try { //boolean success = sketch.isLibrary() ? //sketch.exportLibrary() : sketch.exportApplet(); if(panel.getActiveGadget() == null){ boolean success = sketch.exportApplet(new Target( System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores", Preferences.get("boards." + Preferences.get("board") + ".build.core"))); if (success) { message("Done uploading."); } else { // error message will already be visible } }else{ sketch.exportApplet(new Target( System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores", Preferences.get("boards." + panel.getActiveModule().getTarget() + ".build.core"))); } } catch (RunnerException e) { message("Error during upload."); //e.printStackTrace(); error(e); } catch (Exception e) { e.printStackTrace(); } buttons.clear(); }}); } synchronized public void handleExportApp() { message("Exporting application..."); try { if (sketch.exportApplication()) { message("Done exporting."); } else { // error message will already be visible } } catch (Exception e) { message("Error during export."); e.printStackTrace(); } buttons.clear(); } /** * Checks to see if the sketch has been modified, and if so, * asks the user to save the sketch or cancel the export. * This prevents issues where an incomplete version of the sketch * would be exported, and is a fix for * <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=157">Bug 157</A> */ public boolean handleExportCheckModified() { if (!sketch.modified) return true; Object[] options = { "OK", "Cancel" }; int result = JOptionPane.showOptionDialog(this, "Save changes before export?", "Save", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.OK_OPTION) { handleSave(true); } else { // why it's not CANCEL_OPTION is beyond me (at least on the mac) // but f-- it.. let's get this shite done.. //} else if (result == JOptionPane.CANCEL_OPTION) { message("Export canceled, changes must first be saved."); buttons.clear(); return false; } return true; } public void handlePageSetup() { //printerJob = null; if (printerJob == null) { printerJob = PrinterJob.getPrinterJob(); } if (pageFormat == null) { pageFormat = printerJob.defaultPage(); } pageFormat = printerJob.pageDialog(pageFormat); //System.out.println("page format is " + pageFormat); } public void handlePrint() { message("Printing..."); //printerJob = null; if (printerJob == null) { printerJob = PrinterJob.getPrinterJob(); } if (pageFormat != null) { //System.out.println("setting page format " + pageFormat); printerJob.setPrintable(textarea.getPainter(), pageFormat); } else { printerJob.setPrintable(textarea.getPainter()); } // set the name of the job to the code name printerJob.setJobName(sketch.current.name); if (printerJob.printDialog()) { try { printerJob.print(); message("Done printing."); } catch (PrinterException pe) { error("Error while printing."); pe.printStackTrace(); } } else { message("Printing canceled."); } //printerJob = null; // clear this out? } /** * Quit, but first ask user if it's ok. Also store preferences * to disk just in case they want to quit. Final exit() happens * in Editor since it has the callback from EditorStatus. */ public void handleQuitInternal() { // doStop() isn't sufficient with external vm & quit // instead use doClose() which will kill the external vm if(this.gadgetPanel.getActiveGadget() != null){ this.gadgetPanel.saveCurrentGadget(); } doClose(); checkModified(HANDLE_QUIT); } /** * Method for the MRJQuitHandler, needs to be dealt with differently * than the regular handler because OS X has an annoying implementation * <A HREF="http://developer.apple.com/qa/qa2001/qa1187.html">quirk</A> * that requires an exception to be thrown in order to properly cancel * a quit message. */ public void handleQuit() { SwingUtilities.invokeLater(new Runnable() { public void run() { handleQuitInternal(); } }); // Throw IllegalStateException so new thread can execute. // If showing dialog on this thread in 10.2, we would throw // upon JOptionPane.NO_OPTION throw new IllegalStateException("Quit Pending User Confirmation"); } /** * Actually do the quit action. */ protected void handleQuit2() { handleSave2(); storePreferences(); Preferences.save(); sketchbook.clean(); console.handleQuit(); //System.out.println("exiting here"); System.exit(0); } protected void handleReference() { String text = textarea.getSelectedText().trim(); if (text.length() == 0) { message("First select a word to find in the reference."); } else { String referenceFile = PdeKeywords.getReference(text); //System.out.println("reference file is " + referenceFile); if (referenceFile == null) { message("No reference available for \"" + text + "\""); } else { Base.showReference(referenceFile + ".html"); } } } protected void handleBurnBootloader(final String programmer) { if(debugging) doStop(); console.clear(); message("Burning bootloader to I/O Board (this may take a minute)..."); SwingUtilities.invokeLater(new Runnable() { public void run() { try { Uploader uploader = new AvrdudeUploader(); if (uploader.burnBootloader(programmer)) { message("Done burning bootloader."); } else { // error message will already be visible } } catch (RunnerException e) { message("Error while burning bootloader."); //e.printStackTrace(); error(e); } catch (Exception e) { e.printStackTrace(); } buttons.clear(); }}); } public void highlightLine(int lnum) { if (lnum < 0) { textarea.select(0, 0); return; } //System.out.println(lnum); String s = textarea.getText(); int len = s.length(); int st = -1; int ii = 0; int end = -1; int lc = 0; if (lnum == 0) st = 0; for (int i = 0; i < len; i++) { ii++; //if ((s.charAt(i) == '\n') || (s.charAt(i) == '\r')) { boolean newline = false; if (s.charAt(i) == '\r') { if ((i != len-1) && (s.charAt(i+1) == '\n')) { i++; //ii--; } lc++; newline = true; } else if (s.charAt(i) == '\n') { lc++; newline = true; } if (newline) { if (lc == lnum) st = ii; else if (lc == lnum+1) { //end = ii; // to avoid selecting entire, because doing so puts the // cursor on the next line [0090] end = ii - 1; break; } } } if (end == -1) end = len; // sometimes KJC claims that the line it found an error in is // the last line in the file + 1. Just highlight the last line // in this case. [dmose] if (st == -1) st = len; textarea.select(st, end); } // ................................................................... /** * Show an error int the status bar. */ public void error(String what) { status.error(what); } public void error(Exception e) { if (e == null) { System.err.println("Editor.error() was passed a null exception."); return; } // not sure if any RuntimeExceptions will actually arrive // through here, but gonna check for em just in case. String mess = e.getMessage(); if (mess != null) { String rxString = "RuntimeException: "; if (mess.indexOf(rxString) == 0) { mess = mess.substring(rxString.length()); } String javaLang = "java.lang."; if (mess.indexOf(javaLang) == 0) { mess = mess.substring(javaLang.length()); } error(mess); } e.printStackTrace(); } public void error(RunnerException e) { //System.out.println("file and line is " + e.file + " " + e.line); if (e.file >= 0) sketch.setCurrent(e.file); if (e.line >= 0) highlightLine(e.line); // remove the RuntimeException: message since it's not // really all that useful to the user //status.error(e.getMessage()); String mess = e.getMessage(); String rxString = "RuntimeException: "; if (mess.indexOf(rxString) == 0) { mess = mess.substring(rxString.length()); //System.out.println("MESS3: " + mess); } String javaLang = "java.lang."; if (mess.indexOf(javaLang) == 0) { mess = mess.substring(javaLang.length()); } error(mess); buttons.clear(); } public void message(String msg) { status.notice(msg); } // ................................................................... /** * Returns the edit popup menu. */ class TextAreaPopup extends JPopupMenu { //String currentDir = System.getProperty("user.dir"); String referenceFile = null; JMenuItem cutItem, copyItem; JMenuItem referenceItem; public TextAreaPopup() { JMenuItem item; cutItem = new JMenuItem("Cut"); cutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.cut(); sketch.setModified(true); } }); this.add(cutItem); copyItem = new JMenuItem("Copy"); copyItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.copy(); } }); this.add(copyItem); item = new JMenuItem("Paste"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.paste(); sketch.setModified(true); } }); this.add(item); item = new JMenuItem("Select All"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.selectAll(); } }); this.add(item); this.addSeparator(); referenceItem = new JMenuItem("Find in Reference"); referenceItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //Base.showReference(referenceFile + ".html"); handleReference(); //textarea.getSelectedText()); } }); this.add(referenceItem); } // if no text is selected, disable copy and cut menu items public void show(Component component, int x, int y) { if (textarea.isSelectionActive()) { cutItem.setEnabled(true); copyItem.setEnabled(true); String sel = textarea.getSelectedText().trim(); referenceFile = PdeKeywords.getReference(sel); referenceItem.setEnabled(referenceFile != null); } else { cutItem.setEnabled(false); copyItem.setEnabled(false); referenceItem.setEnabled(false); } super.show(component, x, y); } } public void onActiveGadgetChanged(ActiveGadgetObject obj){ this.gadgetPanel.saveCurrentGadget(); if(gadgetPanel.getActiveModule() != null && gadgetPanel.getActiveGadget() != null){ //this.handleSave(true); File sketchFile = obj.getSketch(); File boardFile = obj.getBoards(); this.handleOpen(sketchFile.getPath()); String board = gadgetPanel.getActiveModule().getTarget(); this.curBoard = board; Preferences.set("board", board); Preferences.save(); Preferences.init(); - this.buildToolsMenu(); this.repaint(); }else if(gadgetPanel.getActiveGadget() == null){ this.setVisible(true); } System.out.println("repainting header"); this.header.paint(getGraphics()); } /* * Creates a back up of the current boards.txt file and returns the renamed file * */ private File backUpBoardsFile(){ String boardFile = System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "boards.txt"; System.out.println(boardFile); this.originalBoardsFile = new File(boardFile); this.newBoardsFile = new File(originalBoardsFile.getPath() + ".bak"); originalBoardsFile.renameTo(newBoardsFile); return newBoardsFile; } private void RestoreBoardsFile(){ if(newBoardsFile != null){ File boardsFileToRestore = new File(newBoardsFile.getPath() + ".bak"); boardsFileToRestore.renameTo(boardsFileToRestore); } } private File writeBoardsToStandardLocation(File boardsFile){ File originalBoards = new File(System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "boards.txt"); String path = originalBoards.getPath(); originalBoards.delete(); File copyFile = new File(path); try{ copyFile.createNewFile(); FileReader in = new FileReader(boardsFile); FileWriter out = new FileWriter(copyFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }catch(Exception ex){ ex.printStackTrace(); } Preferences.init(); this.buildToolsMenu(); return copyFile; } private void importBoardsFile(File boardsFile, String target){ String boardExists = Preferences.get("boards." + target + ".build.core"); String originalBoardsFile = System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "boards.txt"; if(boardExists != null && boardExists.length() > 0){ //don't do anything? }else{ String originalBoards = getContents(new File(originalBoardsFile)); String importedBoards = getContents(boardsFile); originalBoards = originalBoards.concat("##############################################################"); originalBoards = originalBoards.concat("\r\n"); originalBoards = originalBoards.concat(importedBoards); try { this.setContents(new File(originalBoardsFile), originalBoards); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public String getContents(File aFile) { //...checks on aFile are elided StringBuffer contents = new StringBuffer(); try { //use buffering, reading one line at a time //FileReader always assumes default encoding is OK! BufferedReader input = new BufferedReader(new FileReader(aFile)); try { String line = null; //not declared within while loop /* * readLine is a bit quirky : * it returns the content of a line MINUS the newline. * it returns null only for the END of the stream. * it returns an empty String if two newlines appear in a row. */ while (( line = input.readLine()) != null){ contents.append(line); contents.append(System.getProperty("line.separator")); } } finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } return contents.toString(); } public void setContents(File aFile, String aContents) throws FileNotFoundException, IOException { if (aFile == null) { throw new IllegalArgumentException("File should not be null."); } if (!aFile.exists()) { throw new FileNotFoundException ("File does not exist: " + aFile); } if (!aFile.isFile()) { throw new IllegalArgumentException("Should not be a directory: " + aFile); } if (!aFile.canWrite()) { throw new IllegalArgumentException("File cannot be written: " + aFile); } //use buffering Writer output = new BufferedWriter(new FileWriter(aFile)); try { // System.out.print( aContents); output.write( aContents ); }finally { output.close(); } } private void loadGadget(IGadget gadget){ for(int i = 0; i < gadget.getModules().length; i++){ this.importModule(gadget.getModules()[i]); } //imageListPanel.setGadgetPanel(this.gadgetPanel); } private void importModule(IModule module){ String target = module.getTarget(); String boardExists = Preferences.get("boards." + target + ".build.core"); System.out.println(System.getProperty("user.dir")); if(boardExists == null || boardExists.length() == 0){ this.importBoardsFile(module.getBoardsFile(), target); String cpyDir = System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores" + File.separator + target; module.copyCoreToDirectory(cpyDir); } } public void setImageListVisable(IModule module){ this.imageListPanel.setModule(module); //this.textarea.setVisible(true); CardLayout cl = ((CardLayout)this.centerPanel.getLayout()); cl.show(centerPanel, FILELIST); } private boolean saveSketches(){ boolean retVal = true; int correctSketch = sketch.currentIndex; for(int i = 0; i < sketch.code.length; i++){ try { sketch.setCurrent(i); sketch.save(); if(!retVal){ retVal = true; } } catch (IOException e) { retVal = false; e.printStackTrace(); } } sketch.setCurrent(correctSketch); return retVal; } }
true
true
public Editor() { super(); _frame = this; this.setTitle(WINDOW_TITLE); // #@$*(@#$ apple.. always gotta think different MRJApplicationUtils.registerAboutHandler(this); MRJApplicationUtils.registerPrefsHandler(this); MRJApplicationUtils.registerQuitHandler(this); MRJApplicationUtils.registerOpenDocumentHandler(this); // run static initialization that grabs all the prefs Preferences.init(); // set the window icon try { icon = Base.getImage("icon.gif", this); _frame.setIconImage(icon); } catch (Exception e) { } // fail silently, no big whup // add listener to handle window close box hit event _frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { handleQuitInternal(); } }); // don't close the window when clicked, the app will take care // of that via the handleQuitInternal() methods // http://dev.processing.org/bugs/show_bug.cgi?id=440 _frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); PdeKeywords keywords = new PdeKeywords(); sketchbook = new Sketchbook(this); JMenuBar menubar = new JMenuBar(); menubar.add(buildFileMenu()); menubar.add(buildEditMenu()); menubar.add(buildSketchMenu()); menubar.add(buildToolsMenu()); // what platform has their help menu way on the right? motif? //menubar.add(Box.createHorizontalGlue()); menubar.add(buildHelpMenu()); _frame.setJMenuBar(menubar); // doesn't matter when this is created, just make it happen at some point //find = new FindReplace(Editor.this); //Container pain = getContentPane(); //pain.setLayout(new BorderLayout()); // for rev 0120, placing things inside a JPanel because //Container contentPain = getContentPane(); this.getContentPane().setLayout(new BorderLayout()); JPanel pain = new JPanel(); pain.setLayout(new BorderLayout()); this.getContentPane().add(pain, BorderLayout.CENTER); Box box = Box.createVerticalBox(); Box upper = Box.createVerticalBox(); JPanel editorSection = new JPanel(new BorderLayout()); buttons = new EditorButtons(this); upper.add(buttons); header = new EditorHeader(this); //header.setBorder(null); upper.add(header); textarea = new JEditTextArea(new PdeTextAreaDefaults()); textarea.setRightClickPopup(new TextAreaPopup()); //textarea.setTokenMarker(new PdeKeywords()); textarea.setHorizontalOffset(6); // assemble console panel, consisting of status area and the console itself consolePanel = new JPanel(); consolePanel.setLayout(new BorderLayout()); status = new EditorStatus(this); consolePanel.add(status, BorderLayout.NORTH); console = new EditorConsole(this); // windows puts an ugly border on this guy console.setBorder(null); consolePanel.add(console, BorderLayout.CENTER); lineStatus = new EditorLineStatus(textarea); consolePanel.add(lineStatus, BorderLayout.SOUTH); leftExpandLabel = new JLabel("<"); leftWing = new JPanel(); leftWing.setBackground(new Color(0x54, 0x91, 0x9e)); leftWing.setOpaque(true); leftWing.setSize(15, 0); leftWing.setPreferredSize(new Dimension(10, 0)); leftWing.setLayout(new BorderLayout()); leftWing.add(leftExpandLabel, BorderLayout.CENTER); leftWing.addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent arg0) { gadgetPanel.setVisible(!gadgetPanel.isVisible()); /* Handle the expand icon */ if (gadgetPanel.isVisible()){ leftExpandLabel.setText(">"); } else { leftExpandLabel.setText("<"); } } public void mouseEntered(MouseEvent arg0) { } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }); JPanel rightWing = new JPanel(); rightWing.setBackground(new Color(0x54, 0x91, 0x9e)); rightWing.setOpaque(true); rightWing.setSize(15, 0); rightWing.setPreferredSize(new Dimension(10, 0)); imageListPanel = new ImageListPanel(this.gadgetPanel, new FlashTransfer()); this.getContentPane().validate(); JPanel testPanel = new JPanel(); JLabel lbl = new JLabel("THIS IS A TEST STRING"); lbl.setVisible(true); lbl.setBackground(Color.BLUE); centerPanel = new JPanel(); Dimension dim = textarea.getSize(); System.out.println("The dimensions...." + dim); centerPanel.setLayout(new CardLayout()); centerPanel.setVisible(true); centerPanel.add(textarea, CODEEDITOR); centerPanel.add(imageListPanel, FILELIST); centerPanel.add(lbl, TEST); CardLayout cl = (CardLayout) centerPanel.getLayout(); cl.show(centerPanel, CODEEDITOR); editorSection.add(leftWing, BorderLayout.WEST); editorSection.add(centerPanel, BorderLayout.CENTER); editorSection.add(rightWing, BorderLayout.EAST); upper.add(editorSection); String libraryDirectory = System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "OpenHardware" + File.separator + "Modules"; gadgetPanel = new GadgetPanel("", this, libraryDirectory); gadgetPanel.addActiveGadgetChangedEventListener(this); leftWing.setVisible(true); //upper.add(gadgetPanel); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upper, consolePanel); //textarea, consolePanel); splitPane.setOneTouchExpandable(true); // repaint child panes while resizing splitPane.setContinuousLayout(true); // if window increases in size, give all of increase to // the textarea in the uppper pane splitPane.setResizeWeight(1D); // to fix ugliness.. normally macosx java 1.3 puts an // ugly white border around this object, so turn it off. splitPane.setBorder(null); // the default size on windows is too small and kinda ugly int dividerSize = Preferences.getInteger("editor.divider.size"); if (dividerSize != 0) { splitPane.setDividerSize(dividerSize); } splitPane.setMinimumSize(new Dimension(this.getWidth(), 300)); box.add(splitPane); // hopefully these are no longer needed w/ swing // (har har har.. that was wishful thinking) listener = new EditorListener(this, textarea); pain.add(box); pain.setTransferHandler(new TransferHandler() { public boolean canImport(JComponent dest, DataFlavor[] flavors) { // claim that we can import everything return true; } public boolean importData(JComponent src, Transferable transferable) { DataFlavor[] flavors = transferable.getTransferDataFlavors(); /* DropTarget dt = new DropTarget(this, new DropTargetListener() { public void dragEnter(DropTargetDragEvent event) { // debug messages for diagnostics //System.out.println("dragEnter " + event); event.acceptDrag(DnDConstants.ACTION_COPY); } public void dragExit(DropTargetEvent event) { //System.out.println("dragExit " + event); } public void dragOver(DropTargetDragEvent event) { //System.out.println("dragOver " + event); event.acceptDrag(DnDConstants.ACTION_COPY); } public void dropActionChanged(DropTargetDragEvent event) { //System.out.println("dropActionChanged " + event); } public void drop(DropTargetDropEvent event) { //System.out.println("drop " + event); event.acceptDrop(DnDConstants.ACTION_COPY); Transferable transferable = event.getTransferable(); DataFlavor flavors[] = transferable.getTransferDataFlavors(); */ int successful = 0; for (int i = 0; i < flavors.length; i++) { try { //System.out.println(flavors[i]); //System.out.println(transferable.getTransferData(flavors[i])); Object stuff = transferable.getTransferData(flavors[i]); if (!(stuff instanceof java.util.List)) continue; java.util.List list = (java.util.List) stuff; for (int j = 0; j < list.size(); j++) { Object item = list.get(j); if (item instanceof File) { File file = (File) item; // see if this is a .pde file to be opened String filename = file.getName(); if (filename.endsWith(".pde")) { String name = filename.substring(0, filename.length() - 4); File parent = file.getParentFile(); if (name.equals(parent.getName())) { handleOpenFile(file); return true; } } if (sketch.addFile(file)) { successful++; } } } } catch (Exception e) { e.printStackTrace(); return false; } } if (successful == 0) { error("No files were added to the sketch."); } else if (successful == 1) { message("One file added to the sketch."); } else { message(successful + " files added to the sketch."); } return true; } }); } /** * Hack for #@#)$(* Mac OS X 10.2. * <p/> * This appears to only be required on OS X 10.2, and is not * even being called on later versions of OS X or Windows. */ public Dimension getMinimumSize() { //System.out.println("getting minimum size"); return new Dimension(500, 550); } // ................................................................... /** * Builds any unbuilt buildable libraries * Adds syntax coloring from those libraries (if exists) * Rebuilds sketchbook menu with library examples (if they exist) */ public void prepareLibraries() { // build any unbuilt libraries try { LibraryManager libraryManager = new LibraryManager(); libraryManager.buildAllUnbuilt(); // update syntax coloring table libraryManager.addSyntaxColoring(new PdeKeywords()); } catch (RunnerException re) { message("Error compiling library ..."); error(re); } catch (Exception ex) { ex.printStackTrace(); } // update sketchbook menu, this adds examples of any built libs sketchbook.rebuildMenus(); } // ................................................................... /** * Post-constructor setup for the editor area. Loads the last * sketch that was used (if any), and restores other Editor settings. * The complement to "storePreferences", this is called when the * application is first launched. */ public void restorePreferences() { // figure out window placement Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); boolean windowPositionValid = true; if (Preferences.get("last.screen.height") != null) { // if screen size has changed, the window coordinates no longer // make sense, so don't use them unless they're identical int screenW = Preferences.getInteger("last.screen.width"); int screenH = Preferences.getInteger("last.screen.height"); if ((screen.width != screenW) || (screen.height != screenH)) { windowPositionValid = false; } int windowX = Preferences.getInteger("last.window.x"); int windowY = Preferences.getInteger("last.window.y"); if ((windowX < 0) || (windowY < 0) || (windowX > screenW) || (windowY > screenH)) { windowPositionValid = false; } } else { windowPositionValid = false; } if (!windowPositionValid) { //System.out.println("using default size"); int windowH = Preferences.getInteger("default.window.height"); int windowW = Preferences.getInteger("default.window.width"); setBounds((screen.width - windowW) / 2, (screen.height - windowH) / 2, windowW, windowH); // this will be invalid as well, so grab the new value Preferences.setInteger("last.divider.location", splitPane.getDividerLocation()); } else { setBounds(Preferences.getInteger("last.window.x"), Preferences.getInteger("last.window.y"), Preferences.getInteger("last.window.width"), Preferences.getInteger("last.window.height")); } // last sketch that was in use, or used to launch the app if (Base.openedAtStartup != null) { handleOpen2(Base.openedAtStartup); } else { //String sketchName = Preferences.get("last.sketch.name"); String sketchPath = null/*Preferences.get("last.sketch.path")*/; //Sketch sketchTemp = new Sketch(sketchPath); if ((sketchPath != null) && (new File(sketchPath)).exists()) { // don't check modified because nothing is open yet handleOpen2(sketchPath); } else { handleNew2(true); this.header.rebuild(); } } // location for the console/editor area divider int location = Preferences.getInteger("last.divider.location"); splitPane.setDividerLocation(location); // read the preferences that are settable in the preferences window applyPreferences(); } /** * Read and apply new values from the preferences, either because * the app is just starting up, or the user just finished messing * with things in the Preferences window. */ public void applyPreferences() { // apply the setting for 'use external editor' boolean external = Preferences.getBoolean("editor.external"); textarea.setEditable(!external); saveMenuItem.setEnabled(!external); saveAsMenuItem.setEnabled(!external); //beautifyMenuItem.setEnabled(!external); TextAreaPainter painter = textarea.getPainter(); if (external) { // disable line highlight and turn off the caret when disabling Color color = Preferences.getColor("editor.external.bgcolor"); painter.setBackground(color); painter.setLineHighlightEnabled(false); textarea.setCaretVisible(false); } else { Color color = Preferences.getColor("editor.bgcolor"); painter.setBackground(color); boolean highlight = Preferences.getBoolean("editor.linehighlight"); painter.setLineHighlightEnabled(highlight); textarea.setCaretVisible(true); } // apply changes to the font size for the editor //TextAreaPainter painter = textarea.getPainter(); painter.setFont(Preferences.getFont("editor.font")); //Font font = painter.getFont(); //textarea.getPainter().setFont(new Font("Courier", Font.PLAIN, 36)); // in case tab expansion stuff has changed listener.applyPreferences(); // in case moved to a new location // For 0125, changing to async version (to be implemented later) //sketchbook.rebuildMenus(); sketchbook.rebuildMenusAsync(); } /** * Store preferences about the editor's current state. * Called when the application is quitting. */ public void storePreferences() { //System.out.println("storing preferences"); // window location information Rectangle bounds = getBounds(); Preferences.setInteger("last.window.x", bounds.x); Preferences.setInteger("last.window.y", bounds.y); Preferences.setInteger("last.window.width", bounds.width); Preferences.setInteger("last.window.height", bounds.height); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Preferences.setInteger("last.screen.width", screen.width); Preferences.setInteger("last.screen.height", screen.height); // last sketch that was in use //Preferences.set("last.sketch.name", sketchName); //Preferences.set("last.sketch.name", sketch.name); Preferences.set("last.sketch.path", sketch.getMainFilePath()); // location for the console/editor area divider int location = splitPane.getDividerLocation(); Preferences.setInteger("last.divider.location", location); } // ................................................................... protected JMenu buildFileMenu() { JMenuItem item; JMenu menu = new JMenu("File"); item = newJMenuItem("New", 'N'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleNew(false); } }); menu.add(item); menu.add(sketchbook.getOpenMenu()); saveMenuItem = newJMenuItem("Save", 'S'); saveMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSave(false); } }); menu.add(saveMenuItem); saveAsMenuItem = newJMenuItem("Save As...", 'S', true); saveAsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSaveAs(); } }); menu.add(saveAsMenuItem); item = newJMenuItem("Upload to I/O Board", 'U'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleExport(); } }); menu.add(item); /*exportAppItem = newJMenuItem("Export Application", 'E', true); exportAppItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //buttons.activate(EditorButtons.EXPORT); //SwingUtilities.invokeLater(new Runnable() { //public void run() { handleExportApplication(); //}}); } }); menu.add(exportAppItem); */ menu.addSeparator(); item = newJMenuItem("Page Setup", 'P', true); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePageSetup(); } }); menu.add(item); item = newJMenuItem("Print", 'P'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePrint(); } }); menu.add(item); // macosx already has its own preferences and quit menu if (!Base.isMacOS()) { menu.addSeparator(); item = newJMenuItem("Preferences", ','); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePrefs(); } }); menu.add(item); menu.addSeparator(); item = newJMenuItem("Quit", 'Q'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleQuitInternal(); } }); menu.add(item); } return menu; } protected JMenu buildSketchMenu() { JMenuItem item; JMenu menu = new JMenu("Sketch"); item = newJMenuItem("Verify/Compile", 'R'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { handleRun(false); } catch (IOException ex) { ex.printStackTrace(); } } }); menu.add(item); /*item = newJMenuItem("Present", 'R', true); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleRun(true); } }); menu.add(item); */ item = new JMenuItem("Stop"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleStop(); } }); menu.add(item); menu.addSeparator(); menu.add(sketchbook.getImportMenu()); //if (Base.isWindows() || Base.isMacOS()) { // no way to do an 'open in file browser' on other platforms // since there isn't any sort of standard item = newJMenuItem("Show Sketch Folder", 'K', false); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //Base.openFolder(sketchDir); Base.openFolder(sketch.folder); } }); menu.add(item); if (!Base.openFolderAvailable()) { item.setEnabled(false); } //menu.addSeparator(); item = new JMenuItem("Add File..."); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sketch.addFile(); } }); menu.add(item); // TODO re-enable history //history.attachMenu(menu); return menu; } protected JMenu buildToolsMenu() { JMenuItem item; JMenuItem rbMenuItem; JMenuItem cbMenuItem; serialMenuListener = new SerialMenuListener(); JMenu menu = new JMenu("Tools"); item = newJMenuItem("Auto Format", 'T', false); item.addActionListener(new ActionListener() { synchronized public void actionPerformed(ActionEvent e) { new AutoFormat(Editor.this).show(); /* Jalopy jalopy = new Jalopy(); jalopy.setInput(getText(), sketch.current.file.getAbsolutePath()); StringBuffer buffer = new StringBuffer(); jalopy.setOutput(buffer); jalopy.setInspect(false); jalopy.format(); setText(buffer.toString(), 0, 0); if (jalopy.getState() == Jalopy.State.OK) System.out.println("successfully formatted"); else if (jalopy.getState() == Jalopy.State.WARN) System.out.println(" formatted with warnings"); else if (jalopy.getState() == Jalopy.State.ERROR) System.out.println(" could not be formatted"); */ } }); menu.add(item); item = new JMenuItem("Copy for Forum"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { new DiscourseFormat(Editor.this).show(); } }); } }); menu.add(item); item = new JMenuItem("Archive Sketch"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new Archiver(Editor.this).show(); //Archiver archiver = new Archiver(); //archiver.setup(Editor.this); //archiver.show(); } }); menu.add(item); /* item = new JMenuItem("Export Folder..."); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { new ExportFolder(Editor.this).show(); } }); menu.add(item); */ menu.addSeparator(); JMenu boardsMenu = new JMenu("Board"); ButtonGroup boardGroup = new ButtonGroup(); for (Iterator i = Preferences.getSubKeys("boards"); i.hasNext(); ) { String board = (String) i.next(); Action action = new BoardMenuAction(board); item = new JRadioButtonMenuItem(action); String selectedBoard = Preferences.get("board"); if (board.equals(Preferences.get("board"))) item.setSelected(true); boardGroup.add(item); boardsMenu.add(item); } menu.add(boardsMenu); serialMenu = new JMenu("Serial Port"); populateSerialMenu(); menu.add(serialMenu); menu.addSeparator(); JMenu bootloaderMenu = new JMenu("Burn Bootloader"); for (Iterator i = Preferences.getSubKeys("programmers"); i.hasNext(); ) { String programmer = (String) i.next(); Action action = new BootloaderMenuAction(programmer); item = new JMenuItem(action); bootloaderMenu.add(item); } menu.add(bootloaderMenu); menu.addMenuListener(new MenuListener() { public void menuCanceled(MenuEvent e) {} public void menuDeselected(MenuEvent e) {} public void menuSelected(MenuEvent e) { //System.out.println("Tools menu selected."); populateSerialMenu(); } }); return menu; } class SerialMenuListener implements ActionListener { //public SerialMenuListener() { } public void actionPerformed(ActionEvent e) { if(serialMenu == null) { System.out.println("serialMenu is null"); return; } int count = serialMenu.getItemCount(); for (int i = 0; i < count; i++) { ((JCheckBoxMenuItem)serialMenu.getItem(i)).setState(false); } JCheckBoxMenuItem item = (JCheckBoxMenuItem)e.getSource(); item.setState(true); String name = item.getText(); //System.out.println(item.getLabel()); Preferences.set("serial.port", name); //System.out.println("set to " + get("serial.port")); } /* public void actionPerformed(ActionEvent e) { System.out.println(e.getSource()); String name = e.getActionCommand(); PdeBase.properties.put("serial.port", name); System.out.println("set to " + get("serial.port")); //editor.skOpen(path + File.separator + name, name); // need to push "serial.port" into PdeBase.properties } */ } class BoardMenuAction extends AbstractAction { private String board; public BoardMenuAction(String board) { super(Preferences.get("boards." + board + ".name")); this.board = board; } public void actionPerformed(ActionEvent actionevent) { System.out.println("Switching to " + board); Preferences.set("board", board); try { //LibraryManager libraryManager = new LibraryManager(); //libraryManager.rebuildAllBuilt(); } catch (Exception e) { e.printStackTrace(); //} catch (RunnerException e) { // message("Error rebuilding libraries..."); // error(e); } } } class BootloaderMenuAction extends AbstractAction { private String programmer; public BootloaderMenuAction(String programmer) { super("w/ " + Preferences.get("programmers." + programmer + ".name")); this.programmer = programmer; } public void actionPerformed(ActionEvent actionevent) { handleBurnBootloader(programmer); } } protected void populateSerialMenu() { // getting list of ports JMenuItem rbMenuItem; //System.out.println("Clearing serial port menu."); serialMenu.removeAll(); boolean empty = true; try { for (Enumeration enumeration = CommPortIdentifier.getPortIdentifiers(); enumeration.hasMoreElements();) { CommPortIdentifier commportidentifier = (CommPortIdentifier)enumeration.nextElement(); //System.out.println("Found communication port: " + commportidentifier); if (commportidentifier.getPortType() == CommPortIdentifier.PORT_SERIAL) { //System.out.println("Adding port to serial port menu: " + commportidentifier); String curr_port = commportidentifier.getName(); rbMenuItem = new JCheckBoxMenuItem(curr_port, curr_port.equals(Preferences.get("serial.port"))); rbMenuItem.addActionListener(serialMenuListener); //serialGroup.add(rbMenuItem); serialMenu.add(rbMenuItem); empty = false; } } if (!empty) { //System.out.println("enabling the serialMenu"); serialMenu.setEnabled(true); } } catch (Exception exception) { System.out.println("error retrieving port list"); exception.printStackTrace(); } if (serialMenu.getItemCount() == 0) { serialMenu.setEnabled(false); } //serialMenu.addSeparator(); //serialMenu.add(item); } protected JMenu buildHelpMenu() { JMenu menu = new JMenu("Help"); JMenuItem item; if (!Base.isLinux()) { item = new JMenuItem("Getting Started"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (Base.isWindows()) Base.openURL(System.getProperty("user.dir") + File.separator + "reference" + File.separator + "Guide_Windows.html"); else Base.openURL(System.getProperty("user.dir") + File.separator + "reference" + File.separator + "Guide_MacOSX.html"); } }); menu.add(item); } item = new JMenuItem("Environment"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showEnvironment(); } }); menu.add(item); item = new JMenuItem("Troubleshooting"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showTroubleshooting(); } }); menu.add(item); item = new JMenuItem("Reference"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference(); } }); menu.add(item); item = newJMenuItem("Find in Reference", 'F', true); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (textarea.isSelectionActive()) { handleReference(); } } }); menu.add(item); item = new JMenuItem("Frequently Asked Questions"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showFAQ(); } }); menu.add(item); item = newJMenuItem("Visit www.arduino.cc", '5'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL("http://www.arduino.cc/"); } }); menu.add(item); // macosx already has its own about menu if (!Base.isMacOS()) { menu.addSeparator(); item = new JMenuItem("About Arduino"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleAbout(); } }); menu.add(item); } return menu; } public JMenu buildEditMenu() { JMenu menu = new JMenu("Edit"); JMenuItem item; undoItem = newJMenuItem("Undo", 'Z'); undoItem.addActionListener(undoAction = new UndoAction()); menu.add(undoItem); redoItem = newJMenuItem("Redo", 'Y'); redoItem.addActionListener(redoAction = new RedoAction()); menu.add(redoItem); menu.addSeparator(); // TODO "cut" and "copy" should really only be enabled // if some text is currently selected item = newJMenuItem("Cut", 'X'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.cut(); sketch.setModified(true); } }); menu.add(item); item = newJMenuItem("Copy", 'C'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.copy(); } }); menu.add(item); item = newJMenuItem("Paste", 'V'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.paste(); sketch.setModified(true); } }); menu.add(item); item = newJMenuItem("Select All", 'A'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.selectAll(); } }); menu.add(item); menu.addSeparator(); item = newJMenuItem("Find...", 'F'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find == null) { find = new FindReplace(Editor.this); } //new FindReplace(Editor.this).show(); find.show(); //find.setVisible(true); } }); menu.add(item); // TODO find next should only be enabled after a // search has actually taken place item = newJMenuItem("Find Next", 'G'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find != null) { //find.find(true); //FindReplace find = new FindReplace(Editor.this); //.show(); find.find(true); } } }); menu.add(item); return menu; } /** * Convenience method, see below. */ static public JMenuItem newJMenuItem(String title, int what) { return newJMenuItem(title, what, false); } /** * A software engineer, somewhere, needs to have his abstraction * taken away. In some countries they jail or beat people for writing * the sort of API that would require a five line helper function * just to set the command key for a menu item. */ static public JMenuItem newJMenuItem(String title, int what, boolean shift) { JMenuItem menuItem = new JMenuItem(title); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); if (shift) modifiers |= ActionEvent.SHIFT_MASK; menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); return menuItem; } // ................................................................... class UndoAction extends AbstractAction { public UndoAction() { super("Undo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undo.undo(); } catch (CannotUndoException ex) { //System.out.println("Unable to undo: " + ex); //ex.printStackTrace(); } updateUndoState(); redoAction.updateRedoState(); } protected void updateUndoState() { if (undo.canUndo()) { this.setEnabled(true); undoItem.setEnabled(true); undoItem.setText(undo.getUndoPresentationName()); putValue(Action.NAME, undo.getUndoPresentationName()); if (sketch != null) { sketch.setModified(true); // 0107 } } else { this.setEnabled(false); undoItem.setEnabled(false); undoItem.setText("Undo"); putValue(Action.NAME, "Undo"); if (sketch != null) { sketch.setModified(false); // 0107 } } } } class RedoAction extends AbstractAction { public RedoAction() { super("Redo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undo.redo(); } catch (CannotRedoException ex) { //System.out.println("Unable to redo: " + ex); //ex.printStackTrace(); } updateRedoState(); undoAction.updateUndoState(); } protected void updateRedoState() { if (undo.canRedo()) { redoItem.setEnabled(true); redoItem.setText(undo.getRedoPresentationName()); putValue(Action.NAME, undo.getRedoPresentationName()); } else { this.setEnabled(false); redoItem.setEnabled(false); redoItem.setText("Redo"); putValue(Action.NAME, "Redo"); } } } // ................................................................... // interfaces for MRJ Handlers, but naming is fine // so used internally for everything else public void handleAbout() { final Image image = Base.getImage("about.jpg", this); int w = image.getWidth(this); int h = image.getHeight(this); final Window window = new Window(_frame) { public void paint(Graphics g) { g.drawImage(image, 0, 0, null); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); g.setFont(new Font("SansSerif", Font.PLAIN, 11)); g.setColor(Color.white); g.drawString(Base.DIST_NAME + " v" + Base.VERSION_NAME, 50, 30); } }; window.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { window.dispose(); } }); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); window.setBounds((screen.width-w)/2, (screen.height-h)/2, w, h); window.show(); } /** * Show the preferences window. */ public void handlePrefs() { Preferences preferences = new Preferences(); preferences.showFrame(this); // since this can't actually block, it'll hide // the editor window while the prefs are open //preferences.showFrame(this); // and then call applyPreferences if 'ok' is hit // and then unhide // may need to rebuild sketch and other menus //applyPreferences(); // next have editor do its thing //editor.appyPreferences(); } // ................................................................... /** * Get the contents of the current buffer. Used by the Sketch class. */ public String getText() { return textarea.getText(); } /** * Called to update the text but not switch to a different * set of code (which would affect the undo manager). */ public void setText(String what, int selectionStart, int selectionEnd) { beginCompoundEdit(); textarea.setText(what); endCompoundEdit(); // make sure that a tool isn't asking for a bad location selectionStart = Math.max(0, Math.min(selectionStart, textarea.getDocumentLength())); selectionEnd = Math.max(0, Math.min(selectionStart, textarea.getDocumentLength())); textarea.select(selectionStart, selectionEnd); textarea.requestFocus(); // get the caret blinking } /** * Switch between tabs, this swaps out the Document object * that's currently being manipulated. */ public void setCode(SketchCode code) { if (code.document == null) { // this document not yet inited code.document = new SyntaxDocument(); // turn on syntax highlighting code.document.setTokenMarker(new PdeKeywords()); // insert the program text into the document object try { code.document.insertString(0, code.program, null); } catch (BadLocationException bl) { bl.printStackTrace(); } // set up this guy's own undo manager code.undo = new UndoManager(); // connect the undo listener to the editor code.document.addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent e) { if (compoundEdit != null) { compoundEdit.addEdit(e.getEdit()); } else if (undo != null) { undo.addEdit(e.getEdit()); undoAction.updateUndoState(); redoAction.updateRedoState(); } } }); } //switch to a code card try{ CardLayout cl = (CardLayout)this.getLayout(); cl.show(textarea, CODEEDITOR); }catch(Exception ex){ } //set the card layout to give focus to the textarea CardLayout layout = (CardLayout)this.centerPanel.getLayout(); layout.show(this.centerPanel, CODEEDITOR); // update the document object that's in use textarea.setDocument(code.document, code.selectionStart, code.selectionStop, code.scrollPosition); textarea.requestFocus(); // get the caret blinking this.undo = code.undo; undoAction.updateUndoState(); redoAction.updateRedoState(); } public void beginCompoundEdit() { compoundEdit = new CompoundEdit(); } public void endCompoundEdit() { compoundEdit.end(); undo.addEdit(compoundEdit); undoAction.updateUndoState(); redoAction.updateRedoState(); compoundEdit = null; } // ................................................................... public void handleRun(final boolean present) throws IOException { System.out.println("handling the run"); doClose(); running = true; this.isExporting = false; buttons.activate(EditorButtons.RUN); message("Compiling..."); // do this for the terminal window / dos prompt / etc for (int i = 0; i < 10; i++) System.out.println(); // clear the console on each run, unless the user doesn't want to //if (Base.getBoolean("console.auto_clear", true)) { //if (Preferences.getBoolean("console.auto_clear", true)) { if (Preferences.getBoolean("console.auto_clear")) { console.clear(); } presenting = present; if (presenting && Base.isMacOS()) { // check to see if osx 10.2, if so, show a warning String osver = System.getProperty("os.version").substring(0, 4); if (osver.equals("10.2")) { Base.showWarning("Time for an OS Upgrade", "The \"Present\" feature may not be available on\n" + "Mac OS X 10.2, because of what appears to be\n" + "a bug in the Java 1.4 implementation on 10.2.\n" + "In case it works on your machine, present mode\n" + "will start, but if you get a flickering white\n" + "window, using Command-Q to quit the sketch", null); } } this.saveSketches(); if(gadgetPanel.getActiveGadget() != null){ if(gadgetPanel.getActiveModule().getRules() != null){ IMessage message = gadgetPanel.getActiveModule().getRules().getMessages()[0]; if(message != null && this.isExporting){ IOkListener ourListener = new IOkListener(){ private String msg; public void OkButton() { compile(); } public String getMessage() { return msg; } public void setMessage(String message) { msg = message; } }; status.CreateOkDialog(ourListener, message.getMessage()); }else{ this.compile(); //no message just compile } }else{ this.compile(); } }else{ this.compile(); } // this doesn't seem to help much or at all /* final SwingWorker worker = new SwingWorker() { public Object construct() { try { if (!sketch.handleRun()) return null; runtime = new Runner(sketch, Editor.this); runtime.start(presenting ? presentLocation : appletLocation); watcher = new RunButtonWatcher(); message("Done compiling."); } catch (RunnerException e) { message("Error compiling..."); error(e); } catch (Exception e) { e.printStackTrace(); } return null; // needn't return anything } }; worker.start(); */ //sketch.cleanup(); // where does this go? buttons.clear(); } private void compile(){ final Sketch sketch = this.sketch; SwingUtilities.invokeLater(new Runnable() { public void run() { try { if(gadgetPanel != null){ if(gadgetPanel.getActiveModule() != null){ IGadget book = gadgetPanel.getActiveGadget(); IModule[] gadgets = book.getModules(); IModule gadget = gadgetPanel.getActiveModule(); File sketchFile = gadget.getSketchFile(); Sketch currentSketch = new Sketch(new Editor(), sketchFile.getPath()); String target = gadget.getTarget(); System.out.println("Running file with target : " + target); String boardName = Preferences.get("board"); System.out.println(boardName); if(!currentSketch.handleRun(new Target(System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores", Preferences.get("boards." + target + ".build.core")))){ System.out.println("Error compiling file"); } }else{ //There is no active gadget; we should do a classic run String boardName = Preferences.get("board"); if(!sketch.handleRun(new Target(System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores", Preferences.get("boards." + boardName + ".build.core")))){ System.out.println("Error compiling file"); } } }else{ System.out.println("error getting the gadget panel"); } /* if (!sketch.handleRun(new Target( System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores", Preferences.get("boards." + Preferences.get("board") + ".build.core")))) return; */ //runtime = new Runner(sketch, Editor.this); //runtime.start(appletLocation); watcher = new RunButtonWatcher(); message("Done compiling."); if(watcher != null) watcher.stop(); } catch (RunnerException e) { message("Error compiling..."); error(e); } catch (Exception e) { e.printStackTrace(); } }}); } class RunButtonWatcher implements Runnable { Thread thread; public RunButtonWatcher() { thread = new Thread(this, "run button watcher"); thread.setPriority(Thread.MIN_PRIORITY); thread.start(); } public void run() { while (Thread.currentThread() == thread) { /*if (runtime == null) { stop(); } else { if (runtime.applet != null) { if (runtime.applet.finished) { stop(); } //buttons.running(!runtime.applet.finished); } else if (runtime.process != null) { //buttons.running(true); // ?? } else { stop(); } }*/ try { Thread.sleep(250); } catch (InterruptedException e) { } //System.out.println("still inside runner thread"); } } public void stop() { buttons.running(false); thread = null; } } public void handleSerial() { if (!debugging) { try { ImageListPanel.killActiveTransfer(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } serialPort = new Serial(true); this.gadgetPanel.setSerial(serialPort); console.clear(); buttons.activate(EditorButtons.SERIAL); debugging = true; status.serial(); } catch(SerialException e) { error(e); } } else { doStop(); } } public void handleStop() { // called by menu or buttons if (presenting) { doClose(); } else { doStop(); } buttons.clear(); } /** * Stop the applet but don't kill its window. */ public void doStop() { //if (runtime != null) runtime.stop(); if (debugging) { status.unserial(); serialPort.dispose(); debugging = false; } if (watcher != null) watcher.stop(); message(EMPTY); // the buttons are sometimes still null during the constructor // is this still true? are people still hitting this error? /*if (buttons != null)*/ buttons.clear(); running = false; } /** * Stop the applet and kill its window. When running in presentation * mode, this will always be called instead of doStop(). */ public void doClose() { //if (presenting) { //presentationWindow.hide(); //} else { //try { // the window will also be null the process was running // externally. so don't even try setting if window is null // since Runner will set the appletLocation when an // external process is in use. // if (runtime.window != null) { // appletLocation = runtime.window.getLocation(); // } //} catch (NullPointerException e) { } //} //if (running) doStop(); doStop(); // need to stop if runtime error //try { /*if (runtime != null) { runtime.close(); // kills the window runtime = null; // will this help? }*/ //} catch (Exception e) { } //buttons.clear(); // done by doStop sketch.cleanup(); // [toxi 030903] // focus the PDE again after quitting presentation mode _frame.toFront(); if(this.gadgetPanel.isActive()){ this.gadgetPanel.saveCurrentGadget(); Preferences.set("gadget.active", "true"); try{ Preferences.set("last.active.gadget", ((IPackedFile)this.gadgetPanel.getActiveGadget()).getPackedFile().getPath()); }catch(Exception ex){ //there is no gadget } } } /** * Check to see if there have been changes. If so, prompt user * whether or not to save first. If the user cancels, just ignore. * Otherwise, one of the other methods will handle calling * checkModified2() which will get on with business. */ protected void checkModified(int checkModifiedMode) { this.checkModifiedMode = checkModifiedMode; if (!sketch.modified) { checkModified2(); return; } String prompt = "Save changes to " + sketch.name + "? "; if (checkModifiedMode != HANDLE_QUIT) { // if the user is not quitting, then use simpler nicer // dialog that's actually inside the p5 window. status.prompt(prompt); } else { if (!Base.isMacOS() || PApplet.javaVersion < 1.5f) { int result = JOptionPane.showConfirmDialog(this, prompt, "Quit", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { handleSave(true); checkModified2(); } else if (result == JOptionPane.NO_OPTION) { checkModified2(); } // cancel is ignored altogether } else { // This code is disabled unless Java 1.5 is being used on Mac OS X // because of a Java bug that prevents the initial value of the // dialog from being set properly (at least on my MacBook Pro). // The bug causes the "Don't Save" option to be the highlighted, // blinking, default. This sucks. But I'll tell you what doesn't // suck--workarounds for the Mac and Apple's snobby attitude about it! // adapted from the quaqua guide // http://www.randelshofer.ch/quaqua/guide/joptionpane.html JOptionPane pane = new JOptionPane("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Do you want to save changes to this sketch<BR>" + " before closing?</b>" + "<p>If you don't save, your changes will be lost.", JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { "Save", "Cancel", "Don't Save" }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); // on macosx, setting the destructive property places this option // away from the others at the lefthand side pane.putClientProperty("Quaqua.OptionPane.destructiveOption", new Integer(2)); JDialog dialog = pane.createDialog(this, null); dialog.show(); Object result = pane.getValue(); if (result == options[0]) { // save (and quit) handleSave(true); checkModified2(); } else if (result == options[2]) { // don't save (still quit) checkModified2(); } } } } /** * Called by EditorStatus to complete the job and re-dispatch * to handleNew, handleOpen, handleQuit. */ public void checkModified2() { switch (checkModifiedMode) { case HANDLE_NEW: handleNew2(false); break; case HANDLE_OPEN: handleOpen2(handleOpenPath); break; case HANDLE_QUIT: handleQuit2(); break; } checkModifiedMode = 0; } /** * New was called (by buttons or by menu), first check modified * and if things work out ok, handleNew2() will be called. * <p/> * If shift is pressed when clicking the toolbar button, then * force the opposite behavior from sketchbook.prompt's setting */ public void handleNew(final boolean shift) { buttons.activate(EditorButtons.NEW); SwingUtilities.invokeLater(new Runnable() { public void run() { doStop(); handleNewShift = shift; handleNewLibrary = false; checkModified(HANDLE_NEW); }}); this.header.paintComponents(this.getGraphics()); } /** * Extra public method so that Sketch can call this when a sketch * is selected to be deleted, and it won't call checkModified() * to prompt for save as. */ public void handleNewUnchecked() { doStop(); handleNewShift = false; handleNewLibrary = false; handleNew2(true); } /** * User selected "New Library", this will act just like handleNew * but internally set a flag that the new guy is a library, * meaning that a "library" subfolder will be added. */ public void handleNewLibrary() { doStop(); handleNewShift = false; handleNewLibrary = true; checkModified(HANDLE_NEW); } /** * Does all the plumbing to create a new project * then calls handleOpen to load it up. * * @param noPrompt true to disable prompting for the sketch * name, used when the app is starting (auto-create a sketch) */ protected void handleNew2(boolean noPrompt) { try { String pdePath = sketchbook.handleNew(noPrompt, handleNewShift, handleNewLibrary); if (pdePath != null) handleOpen2(pdePath); this.header.rebuild(); } catch (IOException e) { // not sure why this would happen, but since there's no way to // recover (outside of creating another new setkch, which might // just cause more trouble), then they've gotta quit. Base.showError("Problem creating a new sketch", "An error occurred while creating\n" + "a new sketch. Arduino must now quit.", e); } buttons.clear(); } /** * This is the implementation of the MRJ open document event, * and the Windows XP open document will be routed through this too. */ public void handleOpenFile(File file) { //System.out.println("handling open file: " + file); handleOpen(file.getAbsolutePath()); } /** * Open a sketch given the full path to the .pde file. * Pass in 'null' to prompt the user for the name of the sketch. */ public void handleOpen(final String ipath) { // haven't run across a case where i can verify that this works // because open is usually very fast. buttons.activate(EditorButtons.OPEN); SwingUtilities.invokeLater(new Runnable() { public void run() { String path = ipath; if (path == null) { // "open..." selected from the menu path = sketchbook.handleOpen(); if (path == null) return; } doClose(); handleOpenPath = path; checkModified(HANDLE_OPEN); }}); } /** * Open a sketch from a particular path, but don't check to save changes. * Used by Sketch.saveAs() to re-open a sketch after the "Save As" */ public void handleOpenUnchecked(String path, int codeIndex, int selStart, int selStop, int scrollPos) { doClose(); handleOpen2(path); sketch.setCurrent(codeIndex); textarea.select(selStart, selStop); //textarea.updateScrollBars(); textarea.setScrollPosition(scrollPos); } /** * Second stage of open, occurs after having checked to * see if the modifications (if any) to the previous sketch * need to be saved. */ protected void handleOpen2(String path) { if (sketch != null) { // if leaving an empty sketch (i.e. the default) do an // auto-clean right away try { // don't clean if we're re-opening the same file String oldPath = sketch.code[0].file.getPath(); String newPath = new File(path).getPath(); if (!oldPath.equals(newPath)) { if (Base.calcFolderSize(sketch.folder) == 0) { Base.removeDir(sketch.folder); //sketchbook.rebuildMenus(); sketchbook.rebuildMenusAsync(); } } } catch (Exception e) { } // oh well } try { // check to make sure that this .pde file is // in a folder of the same name File file = new File(path); File parentFile = new File(file.getParent()); String parentName = parentFile.getName(); String pdeName = parentName + ".pde"; File altFile = new File(file.getParent(), pdeName); boolean isGadgetFile = false; //System.out.println("path = " + file.getParent()); //System.out.println("name = " + file.getName()); //System.out.println("pname = " + parentName); if (pdeName.equals(file.getName())) { // no beef with this guy } else if (altFile.exists()) { // user selected a .java from the same sketch, // but open the .pde instead path = altFile.getAbsolutePath(); //System.out.println("found alt file in same folder"); } else if (!path.endsWith(".pde")) { Base.showWarning("Bad file selected", "Arduino can only open its own sketches\n" + "and other files ending in .pde", null); return; } else if (path.endsWith(".gadget")){ this.gadgetPanel.loadGadget(new File(path)); path = this.gadgetPanel.getActiveModule().getSketchFile().getPath(); this.loadGadget(this.gadgetPanel.getActiveGadget()); isGadgetFile = true; this.lastActiveGadgetPath = path; }else { try{ this.gadgetPanel.loadGadget(new File(path)); IModule module = this.gadgetPanel.getActiveModule(); File sketchFile = module.getSketchFile(); path = sketchFile.getPath(); this.loadGadget(this.gadgetPanel.getActiveGadget()); isGadgetFile = true; this.lastActiveGadgetPath = path; }catch(Exception ex){ ex.printStackTrace(); isGadgetFile = false; String properParent = file.getName().substring(0, file.getName().length() - 4); Object[] options = { "OK", "Cancel" }; String prompt = "The file \"" + file.getName() + "\" needs to be inside\n" + "a sketch folder named \"" + properParent + "\".\n" + "Create this folder, move the file, and continue?"; int result = JOptionPane.showOptionDialog(this, prompt, "Moving", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.YES_OPTION) { // create properly named folder File properFolder = new File(file.getParent(), properParent); if (properFolder.exists()) { Base.showWarning("Error", "A folder named \"" + properParent + "\" " + "already exists. Can't open sketch.", null); return; } if (!properFolder.mkdirs()) { throw new IOException("Couldn't create sketch folder"); } // copy the sketch inside File properPdeFile = new File(properFolder, file.getName()); File origPdeFile = new File(path); Base.copyFile(origPdeFile, properPdeFile); // remove the original file, so user doesn't get confused origPdeFile.delete(); // update with the new path path = properPdeFile.getAbsolutePath(); } else if (result == JOptionPane.NO_OPTION) { return; } } } //do one last check if(this.gadgetPanel.getActiveGadget() != null){ for(int i = 0; i < gadgetPanel.getActiveGadget().getModules().length; i++){ if(gadgetPanel.getActiveGadget().getModules()[i].getSketchFile().getPath().equalsIgnoreCase(path)){ isGadgetFile = true; break; } } } this.gadgetPanel.setVisible(isGadgetFile); if(isGadgetFile){ gadgetPanel.show(); /* The Boards menu doesn't * make sense with a gadget .pde file, so disable it */ _frame.getJMenuBar().getMenu(3).getItem(4).setEnabled(false); leftExpandLabel.setText(">"); }else{ this.gadgetPanel.Unload(); //remove the gadget list and unload active module /* Use the Boards menu with a std .pde file */ _frame.getJMenuBar().getMenu(3).getItem(4).setEnabled(true); gadgetPanel.hide(); } sketch = new Sketch(this, path); if(isGadgetFile){ System.out.println(path); } // TODO re-enable this once export application works //exportAppItem.setEnabled(false); //exportAppItem.setEnabled(false && !sketch.isLibrary()); //buttons.disableRun(sketch.isLibrary()); header.rebuild(); if (Preferences.getBoolean("console.auto_clear")) { console.clear(); } } catch (Exception e) { error(e); } } // there is no handleSave1 since there's never a need to prompt /** * Actually handle the save command. If 'force' is set to false, * this will happen in another thread so that the message area * will update and the save button will stay highlighted while the * save is happening. If 'force' is true, then it will happen * immediately. This is used during a quit, because invokeLater() * won't run properly while a quit is happening. This fixes * <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=276">Bug 276</A>. */ public void handleSave(boolean force) { doStop(); buttons.activate(EditorButtons.SAVE); if (force) { handleSave2(); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { handleSave2(); } }); } } public void handleSave2() { message("Saving..."); try { sketch.save(); if (saveSketches()) { message("Done Saving."); } else { message(EMPTY); } if(this.gadgetPanel.getActiveGadget()!= null){ this.gadgetPanel.saveCurrentGadget(); System.out.println("saved gadget"); } // rebuild sketch menu in case a save-as was forced // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenus(); //sketchbook.rebuildMenusAsync(); } catch (Exception e) { // show the error as a message in the window error(e); // zero out the current action, // so that checkModified2 will just do nothing checkModifiedMode = 0; // this is used when another operation calls a save } buttons.clear(); } public void handleSaveAs() { doStop(); buttons.activate(EditorButtons.SAVE); final GadgetPanel gp = this.gadgetPanel; final Editor edit = this; SwingUtilities.invokeLater(new Runnable() { public void run() { message("Saving..."); try { sketch.save(); } catch (IOException e1) { e1.printStackTrace(); } try { if(gp.getActiveGadget() != null){ FileDialog fd = new FileDialog(edit._frame, "Save gadget file as...", FileDialog.SAVE); File packedDirectory = ((IPackedFile)gp.getActiveGadget()).getPackedFile().getParentFile(); fd.setDirectory(packedDirectory.getPath()); fd.setFile(gp.getActiveGadget().getName()); fd.show(); String newParentDir = fd.getDirectory(); String newName = fd.getFile(); if (newName != null){ String fileName; if(newName.endsWith(".pde")){ fileName = newName; newName = newName.substring(0, newName.length() - 4); }else{ fileName = newName + ".pde"; } //save the gadget file GadgetFactory fact = new GadgetFactory(); /* IPackedFile file = ((IPackedFile)gp.getActiveGadget()); File newGadget = new File(newParentDir + File.separator + fileName); Base.copyFile(file.getPackedFile(), newGadget); IGadget gadg = fact.loadGadget(newGadget, System.getProperty("java.io.tmpdir") + File.separator + newGadget.getName()); gadg.setName(newName); ((IPackedFile)gadg).setPackedFile(newGadget); ITemporary tempDir = (ITemporary)gadg; File dir = new File(tempDir.getTempDirectory()); dir.listFiles(); gp.loadGadget(newGadget); gp.saveCurrentGadget();*/ File newFile = fact.copyGadget(gp.getActiveGadget(), newParentDir , newName); //IGadget newGadget = fact.loadGadget(newFile, System.getProperty("java.io.tmpdir") + File.separator + newFile.getName()); gp.loadGadget(newFile); gp.saveCurrentGadget(); } }else{ if (sketch.saveAs()) { message("Done Saving."); // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenusAsync(); } else { message("Save Cancelled."); } } } catch (Exception e) { // show the error as a message in the window error(e); } buttons.clear(); }}); } /** * Handles calling the export() function on sketch, and * queues all the gui status stuff that comes along with it. * * Made synchronized to (hopefully) avoid problems of people * hitting export twice, quickly, and horking things up. */ synchronized public void handleExport() { if(debugging) doStop(); buttons.activate(EditorButtons.EXPORT); console.clear(); //String what = sketch.isLibrary() ? "Applet" : "Library"; //message("Exporting " + what + "..."); message("Uploading to I/O Board..."); final GadgetPanel panel = this.gadgetPanel; this.isExporting = true; this.saveSketches(); SwingUtilities.invokeLater(new Runnable() { public void run() { try { //boolean success = sketch.isLibrary() ? //sketch.exportLibrary() : sketch.exportApplet(); if(panel.getActiveGadget() == null){ boolean success = sketch.exportApplet(new Target( System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores", Preferences.get("boards." + Preferences.get("board") + ".build.core"))); if (success) { message("Done uploading."); } else { // error message will already be visible } }else{ sketch.exportApplet(new Target( System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores", Preferences.get("boards." + panel.getActiveModule().getTarget() + ".build.core"))); } } catch (RunnerException e) { message("Error during upload."); //e.printStackTrace(); error(e); } catch (Exception e) { e.printStackTrace(); } buttons.clear(); }}); } synchronized public void handleExportApp() { message("Exporting application..."); try { if (sketch.exportApplication()) { message("Done exporting."); } else { // error message will already be visible } } catch (Exception e) { message("Error during export."); e.printStackTrace(); } buttons.clear(); } /** * Checks to see if the sketch has been modified, and if so, * asks the user to save the sketch or cancel the export. * This prevents issues where an incomplete version of the sketch * would be exported, and is a fix for * <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=157">Bug 157</A> */ public boolean handleExportCheckModified() { if (!sketch.modified) return true; Object[] options = { "OK", "Cancel" }; int result = JOptionPane.showOptionDialog(this, "Save changes before export?", "Save", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.OK_OPTION) { handleSave(true); } else { // why it's not CANCEL_OPTION is beyond me (at least on the mac) // but f-- it.. let's get this shite done.. //} else if (result == JOptionPane.CANCEL_OPTION) { message("Export canceled, changes must first be saved."); buttons.clear(); return false; } return true; } public void handlePageSetup() { //printerJob = null; if (printerJob == null) { printerJob = PrinterJob.getPrinterJob(); } if (pageFormat == null) { pageFormat = printerJob.defaultPage(); } pageFormat = printerJob.pageDialog(pageFormat); //System.out.println("page format is " + pageFormat); } public void handlePrint() { message("Printing..."); //printerJob = null; if (printerJob == null) { printerJob = PrinterJob.getPrinterJob(); } if (pageFormat != null) { //System.out.println("setting page format " + pageFormat); printerJob.setPrintable(textarea.getPainter(), pageFormat); } else { printerJob.setPrintable(textarea.getPainter()); } // set the name of the job to the code name printerJob.setJobName(sketch.current.name); if (printerJob.printDialog()) { try { printerJob.print(); message("Done printing."); } catch (PrinterException pe) { error("Error while printing."); pe.printStackTrace(); } } else { message("Printing canceled."); } //printerJob = null; // clear this out? } /** * Quit, but first ask user if it's ok. Also store preferences * to disk just in case they want to quit. Final exit() happens * in Editor since it has the callback from EditorStatus. */ public void handleQuitInternal() { // doStop() isn't sufficient with external vm & quit // instead use doClose() which will kill the external vm if(this.gadgetPanel.getActiveGadget() != null){ this.gadgetPanel.saveCurrentGadget(); } doClose(); checkModified(HANDLE_QUIT); } /** * Method for the MRJQuitHandler, needs to be dealt with differently * than the regular handler because OS X has an annoying implementation * <A HREF="http://developer.apple.com/qa/qa2001/qa1187.html">quirk</A> * that requires an exception to be thrown in order to properly cancel * a quit message. */ public void handleQuit() { SwingUtilities.invokeLater(new Runnable() { public void run() { handleQuitInternal(); } }); // Throw IllegalStateException so new thread can execute. // If showing dialog on this thread in 10.2, we would throw // upon JOptionPane.NO_OPTION throw new IllegalStateException("Quit Pending User Confirmation"); } /** * Actually do the quit action. */ protected void handleQuit2() { handleSave2(); storePreferences(); Preferences.save(); sketchbook.clean(); console.handleQuit(); //System.out.println("exiting here"); System.exit(0); } protected void handleReference() { String text = textarea.getSelectedText().trim(); if (text.length() == 0) { message("First select a word to find in the reference."); } else { String referenceFile = PdeKeywords.getReference(text); //System.out.println("reference file is " + referenceFile); if (referenceFile == null) { message("No reference available for \"" + text + "\""); } else { Base.showReference(referenceFile + ".html"); } } } protected void handleBurnBootloader(final String programmer) { if(debugging) doStop(); console.clear(); message("Burning bootloader to I/O Board (this may take a minute)..."); SwingUtilities.invokeLater(new Runnable() { public void run() { try { Uploader uploader = new AvrdudeUploader(); if (uploader.burnBootloader(programmer)) { message("Done burning bootloader."); } else { // error message will already be visible } } catch (RunnerException e) { message("Error while burning bootloader."); //e.printStackTrace(); error(e); } catch (Exception e) { e.printStackTrace(); } buttons.clear(); }}); } public void highlightLine(int lnum) { if (lnum < 0) { textarea.select(0, 0); return; } //System.out.println(lnum); String s = textarea.getText(); int len = s.length(); int st = -1; int ii = 0; int end = -1; int lc = 0; if (lnum == 0) st = 0; for (int i = 0; i < len; i++) { ii++; //if ((s.charAt(i) == '\n') || (s.charAt(i) == '\r')) { boolean newline = false; if (s.charAt(i) == '\r') { if ((i != len-1) && (s.charAt(i+1) == '\n')) { i++; //ii--; } lc++; newline = true; } else if (s.charAt(i) == '\n') { lc++; newline = true; } if (newline) { if (lc == lnum) st = ii; else if (lc == lnum+1) { //end = ii; // to avoid selecting entire, because doing so puts the // cursor on the next line [0090] end = ii - 1; break; } } } if (end == -1) end = len; // sometimes KJC claims that the line it found an error in is // the last line in the file + 1. Just highlight the last line // in this case. [dmose] if (st == -1) st = len; textarea.select(st, end); } // ................................................................... /** * Show an error int the status bar. */ public void error(String what) { status.error(what); } public void error(Exception e) { if (e == null) { System.err.println("Editor.error() was passed a null exception."); return; } // not sure if any RuntimeExceptions will actually arrive // through here, but gonna check for em just in case. String mess = e.getMessage(); if (mess != null) { String rxString = "RuntimeException: "; if (mess.indexOf(rxString) == 0) { mess = mess.substring(rxString.length()); } String javaLang = "java.lang."; if (mess.indexOf(javaLang) == 0) { mess = mess.substring(javaLang.length()); } error(mess); } e.printStackTrace(); } public void error(RunnerException e) { //System.out.println("file and line is " + e.file + " " + e.line); if (e.file >= 0) sketch.setCurrent(e.file); if (e.line >= 0) highlightLine(e.line); // remove the RuntimeException: message since it's not // really all that useful to the user //status.error(e.getMessage()); String mess = e.getMessage(); String rxString = "RuntimeException: "; if (mess.indexOf(rxString) == 0) { mess = mess.substring(rxString.length()); //System.out.println("MESS3: " + mess); } String javaLang = "java.lang."; if (mess.indexOf(javaLang) == 0) { mess = mess.substring(javaLang.length()); } error(mess); buttons.clear(); } public void message(String msg) { status.notice(msg); } // ................................................................... /** * Returns the edit popup menu. */ class TextAreaPopup extends JPopupMenu { //String currentDir = System.getProperty("user.dir"); String referenceFile = null; JMenuItem cutItem, copyItem; JMenuItem referenceItem; public TextAreaPopup() { JMenuItem item; cutItem = new JMenuItem("Cut"); cutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.cut(); sketch.setModified(true); } }); this.add(cutItem); copyItem = new JMenuItem("Copy"); copyItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.copy(); } }); this.add(copyItem); item = new JMenuItem("Paste"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.paste(); sketch.setModified(true); } }); this.add(item); item = new JMenuItem("Select All"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.selectAll(); } }); this.add(item); this.addSeparator(); referenceItem = new JMenuItem("Find in Reference"); referenceItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //Base.showReference(referenceFile + ".html"); handleReference(); //textarea.getSelectedText()); } }); this.add(referenceItem); } // if no text is selected, disable copy and cut menu items public void show(Component component, int x, int y) { if (textarea.isSelectionActive()) { cutItem.setEnabled(true); copyItem.setEnabled(true); String sel = textarea.getSelectedText().trim(); referenceFile = PdeKeywords.getReference(sel); referenceItem.setEnabled(referenceFile != null); } else { cutItem.setEnabled(false); copyItem.setEnabled(false); referenceItem.setEnabled(false); } super.show(component, x, y); } } public void onActiveGadgetChanged(ActiveGadgetObject obj){ this.gadgetPanel.saveCurrentGadget(); if(gadgetPanel.getActiveModule() != null && gadgetPanel.getActiveGadget() != null){ //this.handleSave(true); File sketchFile = obj.getSketch(); File boardFile = obj.getBoards(); this.handleOpen(sketchFile.getPath()); String board = gadgetPanel.getActiveModule().getTarget(); this.curBoard = board; Preferences.set("board", board); Preferences.save(); Preferences.init(); this.buildToolsMenu(); this.repaint(); }else if(gadgetPanel.getActiveGadget() == null){ this.setVisible(true); } System.out.println("repainting header"); this.header.paint(getGraphics()); } /* * Creates a back up of the current boards.txt file and returns the renamed file * */ private File backUpBoardsFile(){ String boardFile = System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "boards.txt"; System.out.println(boardFile); this.originalBoardsFile = new File(boardFile); this.newBoardsFile = new File(originalBoardsFile.getPath() + ".bak"); originalBoardsFile.renameTo(newBoardsFile); return newBoardsFile; } private void RestoreBoardsFile(){ if(newBoardsFile != null){ File boardsFileToRestore = new File(newBoardsFile.getPath() + ".bak"); boardsFileToRestore.renameTo(boardsFileToRestore); } } private File writeBoardsToStandardLocation(File boardsFile){ File originalBoards = new File(System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "boards.txt"); String path = originalBoards.getPath(); originalBoards.delete(); File copyFile = new File(path); try{ copyFile.createNewFile(); FileReader in = new FileReader(boardsFile); FileWriter out = new FileWriter(copyFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }catch(Exception ex){ ex.printStackTrace(); } Preferences.init(); this.buildToolsMenu(); return copyFile; } private void importBoardsFile(File boardsFile, String target){ String boardExists = Preferences.get("boards." + target + ".build.core"); String originalBoardsFile = System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "boards.txt"; if(boardExists != null && boardExists.length() > 0){ //don't do anything? }else{ String originalBoards = getContents(new File(originalBoardsFile)); String importedBoards = getContents(boardsFile); originalBoards = originalBoards.concat("##############################################################"); originalBoards = originalBoards.concat("\r\n"); originalBoards = originalBoards.concat(importedBoards); try { this.setContents(new File(originalBoardsFile), originalBoards); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public String getContents(File aFile) { //...checks on aFile are elided StringBuffer contents = new StringBuffer(); try { //use buffering, reading one line at a time //FileReader always assumes default encoding is OK! BufferedReader input = new BufferedReader(new FileReader(aFile)); try { String line = null; //not declared within while loop /* * readLine is a bit quirky : * it returns the content of a line MINUS the newline. * it returns null only for the END of the stream. * it returns an empty String if two newlines appear in a row. */ while (( line = input.readLine()) != null){ contents.append(line); contents.append(System.getProperty("line.separator")); } } finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } return contents.toString(); } public void setContents(File aFile, String aContents) throws FileNotFoundException, IOException { if (aFile == null) { throw new IllegalArgumentException("File should not be null."); } if (!aFile.exists()) { throw new FileNotFoundException ("File does not exist: " + aFile); } if (!aFile.isFile()) { throw new IllegalArgumentException("Should not be a directory: " + aFile); } if (!aFile.canWrite()) { throw new IllegalArgumentException("File cannot be written: " + aFile); } //use buffering Writer output = new BufferedWriter(new FileWriter(aFile)); try { // System.out.print( aContents); output.write( aContents ); }finally { output.close(); } } private void loadGadget(IGadget gadget){ for(int i = 0; i < gadget.getModules().length; i++){ this.importModule(gadget.getModules()[i]); } //imageListPanel.setGadgetPanel(this.gadgetPanel); } private void importModule(IModule module){ String target = module.getTarget(); String boardExists = Preferences.get("boards." + target + ".build.core"); System.out.println(System.getProperty("user.dir")); if(boardExists == null || boardExists.length() == 0){ this.importBoardsFile(module.getBoardsFile(), target); String cpyDir = System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores" + File.separator + target; module.copyCoreToDirectory(cpyDir); } } public void setImageListVisable(IModule module){ this.imageListPanel.setModule(module); //this.textarea.setVisible(true); CardLayout cl = ((CardLayout)this.centerPanel.getLayout()); cl.show(centerPanel, FILELIST); } private boolean saveSketches(){ boolean retVal = true; int correctSketch = sketch.currentIndex; for(int i = 0; i < sketch.code.length; i++){ try { sketch.setCurrent(i); sketch.save(); if(!retVal){ retVal = true; } } catch (IOException e) { retVal = false; e.printStackTrace(); } } sketch.setCurrent(correctSketch); return retVal; } }
public Editor() { super(); _frame = this; this.setTitle(WINDOW_TITLE); // #@$*(@#$ apple.. always gotta think different MRJApplicationUtils.registerAboutHandler(this); MRJApplicationUtils.registerPrefsHandler(this); MRJApplicationUtils.registerQuitHandler(this); MRJApplicationUtils.registerOpenDocumentHandler(this); // run static initialization that grabs all the prefs Preferences.init(); // set the window icon try { icon = Base.getImage("icon.gif", this); _frame.setIconImage(icon); } catch (Exception e) { } // fail silently, no big whup // add listener to handle window close box hit event _frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { handleQuitInternal(); } }); // don't close the window when clicked, the app will take care // of that via the handleQuitInternal() methods // http://dev.processing.org/bugs/show_bug.cgi?id=440 _frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); PdeKeywords keywords = new PdeKeywords(); sketchbook = new Sketchbook(this); JMenuBar menubar = new JMenuBar(); menubar.add(buildFileMenu()); menubar.add(buildEditMenu()); menubar.add(buildSketchMenu()); menubar.add(buildToolsMenu()); // what platform has their help menu way on the right? motif? //menubar.add(Box.createHorizontalGlue()); menubar.add(buildHelpMenu()); _frame.setJMenuBar(menubar); // doesn't matter when this is created, just make it happen at some point //find = new FindReplace(Editor.this); //Container pain = getContentPane(); //pain.setLayout(new BorderLayout()); // for rev 0120, placing things inside a JPanel because //Container contentPain = getContentPane(); this.getContentPane().setLayout(new BorderLayout()); JPanel pain = new JPanel(); pain.setLayout(new BorderLayout()); this.getContentPane().add(pain, BorderLayout.CENTER); Box box = Box.createVerticalBox(); Box upper = Box.createVerticalBox(); JPanel editorSection = new JPanel(new BorderLayout()); buttons = new EditorButtons(this); upper.add(buttons); header = new EditorHeader(this); //header.setBorder(null); upper.add(header); textarea = new JEditTextArea(new PdeTextAreaDefaults()); textarea.setRightClickPopup(new TextAreaPopup()); //textarea.setTokenMarker(new PdeKeywords()); textarea.setHorizontalOffset(6); // assemble console panel, consisting of status area and the console itself consolePanel = new JPanel(); consolePanel.setLayout(new BorderLayout()); status = new EditorStatus(this); consolePanel.add(status, BorderLayout.NORTH); console = new EditorConsole(this); // windows puts an ugly border on this guy console.setBorder(null); consolePanel.add(console, BorderLayout.CENTER); lineStatus = new EditorLineStatus(textarea); consolePanel.add(lineStatus, BorderLayout.SOUTH); leftExpandLabel = new JLabel("<"); leftWing = new JPanel(); leftWing.setBackground(new Color(0x54, 0x91, 0x9e)); leftWing.setOpaque(true); leftWing.setSize(15, 0); leftWing.setPreferredSize(new Dimension(10, 0)); leftWing.setLayout(new BorderLayout()); leftWing.add(leftExpandLabel, BorderLayout.CENTER); leftWing.addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent arg0) { gadgetPanel.setVisible(!gadgetPanel.isVisible()); /* Handle the expand icon */ if (gadgetPanel.isVisible()){ leftExpandLabel.setText(">"); } else { leftExpandLabel.setText("<"); } } public void mouseEntered(MouseEvent arg0) { } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }); JPanel rightWing = new JPanel(); rightWing.setBackground(new Color(0x54, 0x91, 0x9e)); rightWing.setOpaque(true); rightWing.setSize(15, 0); rightWing.setPreferredSize(new Dimension(10, 0)); imageListPanel = new ImageListPanel(this.gadgetPanel, new FlashTransfer()); this.getContentPane().validate(); JPanel testPanel = new JPanel(); JLabel lbl = new JLabel("THIS IS A TEST STRING"); lbl.setVisible(true); lbl.setBackground(Color.BLUE); centerPanel = new JPanel(); Dimension dim = textarea.getSize(); System.out.println("The dimensions...." + dim); centerPanel.setLayout(new CardLayout()); centerPanel.setVisible(true); centerPanel.add(textarea, CODEEDITOR); centerPanel.add(imageListPanel, FILELIST); centerPanel.add(lbl, TEST); CardLayout cl = (CardLayout) centerPanel.getLayout(); cl.show(centerPanel, CODEEDITOR); editorSection.add(leftWing, BorderLayout.WEST); editorSection.add(centerPanel, BorderLayout.CENTER); editorSection.add(rightWing, BorderLayout.EAST); upper.add(editorSection); String libraryDirectory = System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "OpenHardware" + File.separator + "Modules"; gadgetPanel = new GadgetPanel("", this, libraryDirectory); gadgetPanel.addActiveGadgetChangedEventListener(this); leftWing.setVisible(true); //upper.add(gadgetPanel); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upper, consolePanel); //textarea, consolePanel); splitPane.setOneTouchExpandable(true); // repaint child panes while resizing splitPane.setContinuousLayout(true); // if window increases in size, give all of increase to // the textarea in the uppper pane splitPane.setResizeWeight(1D); // to fix ugliness.. normally macosx java 1.3 puts an // ugly white border around this object, so turn it off. splitPane.setBorder(null); // the default size on windows is too small and kinda ugly int dividerSize = Preferences.getInteger("editor.divider.size"); if (dividerSize != 0) { splitPane.setDividerSize(dividerSize); } splitPane.setMinimumSize(new Dimension(this.getWidth(), 300)); box.add(splitPane); // hopefully these are no longer needed w/ swing // (har har har.. that was wishful thinking) listener = new EditorListener(this, textarea); pain.add(box); pain.setTransferHandler(new TransferHandler() { public boolean canImport(JComponent dest, DataFlavor[] flavors) { // claim that we can import everything return true; } public boolean importData(JComponent src, Transferable transferable) { DataFlavor[] flavors = transferable.getTransferDataFlavors(); /* DropTarget dt = new DropTarget(this, new DropTargetListener() { public void dragEnter(DropTargetDragEvent event) { // debug messages for diagnostics //System.out.println("dragEnter " + event); event.acceptDrag(DnDConstants.ACTION_COPY); } public void dragExit(DropTargetEvent event) { //System.out.println("dragExit " + event); } public void dragOver(DropTargetDragEvent event) { //System.out.println("dragOver " + event); event.acceptDrag(DnDConstants.ACTION_COPY); } public void dropActionChanged(DropTargetDragEvent event) { //System.out.println("dropActionChanged " + event); } public void drop(DropTargetDropEvent event) { //System.out.println("drop " + event); event.acceptDrop(DnDConstants.ACTION_COPY); Transferable transferable = event.getTransferable(); DataFlavor flavors[] = transferable.getTransferDataFlavors(); */ int successful = 0; for (int i = 0; i < flavors.length; i++) { try { //System.out.println(flavors[i]); //System.out.println(transferable.getTransferData(flavors[i])); Object stuff = transferable.getTransferData(flavors[i]); if (!(stuff instanceof java.util.List)) continue; java.util.List list = (java.util.List) stuff; for (int j = 0; j < list.size(); j++) { Object item = list.get(j); if (item instanceof File) { File file = (File) item; // see if this is a .pde file to be opened String filename = file.getName(); if (filename.endsWith(".pde")) { String name = filename.substring(0, filename.length() - 4); File parent = file.getParentFile(); if (name.equals(parent.getName())) { handleOpenFile(file); return true; } } if (sketch.addFile(file)) { successful++; } } } } catch (Exception e) { e.printStackTrace(); return false; } } if (successful == 0) { error("No files were added to the sketch."); } else if (successful == 1) { message("One file added to the sketch."); } else { message(successful + " files added to the sketch."); } return true; } }); } /** * Hack for #@#)$(* Mac OS X 10.2. * <p/> * This appears to only be required on OS X 10.2, and is not * even being called on later versions of OS X or Windows. */ public Dimension getMinimumSize() { //System.out.println("getting minimum size"); return new Dimension(500, 550); } // ................................................................... /** * Builds any unbuilt buildable libraries * Adds syntax coloring from those libraries (if exists) * Rebuilds sketchbook menu with library examples (if they exist) */ public void prepareLibraries() { // build any unbuilt libraries try { LibraryManager libraryManager = new LibraryManager(); libraryManager.buildAllUnbuilt(); // update syntax coloring table libraryManager.addSyntaxColoring(new PdeKeywords()); } catch (RunnerException re) { message("Error compiling library ..."); error(re); } catch (Exception ex) { ex.printStackTrace(); } // update sketchbook menu, this adds examples of any built libs sketchbook.rebuildMenus(); } // ................................................................... /** * Post-constructor setup for the editor area. Loads the last * sketch that was used (if any), and restores other Editor settings. * The complement to "storePreferences", this is called when the * application is first launched. */ public void restorePreferences() { // figure out window placement Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); boolean windowPositionValid = true; if (Preferences.get("last.screen.height") != null) { // if screen size has changed, the window coordinates no longer // make sense, so don't use them unless they're identical int screenW = Preferences.getInteger("last.screen.width"); int screenH = Preferences.getInteger("last.screen.height"); if ((screen.width != screenW) || (screen.height != screenH)) { windowPositionValid = false; } int windowX = Preferences.getInteger("last.window.x"); int windowY = Preferences.getInteger("last.window.y"); if ((windowX < 0) || (windowY < 0) || (windowX > screenW) || (windowY > screenH)) { windowPositionValid = false; } } else { windowPositionValid = false; } if (!windowPositionValid) { //System.out.println("using default size"); int windowH = Preferences.getInteger("default.window.height"); int windowW = Preferences.getInteger("default.window.width"); setBounds((screen.width - windowW) / 2, (screen.height - windowH) / 2, windowW, windowH); // this will be invalid as well, so grab the new value Preferences.setInteger("last.divider.location", splitPane.getDividerLocation()); } else { setBounds(Preferences.getInteger("last.window.x"), Preferences.getInteger("last.window.y"), Preferences.getInteger("last.window.width"), Preferences.getInteger("last.window.height")); } // last sketch that was in use, or used to launch the app if (Base.openedAtStartup != null) { handleOpen2(Base.openedAtStartup); } else { //String sketchName = Preferences.get("last.sketch.name"); String sketchPath = null/*Preferences.get("last.sketch.path")*/; //Sketch sketchTemp = new Sketch(sketchPath); if ((sketchPath != null) && (new File(sketchPath)).exists()) { // don't check modified because nothing is open yet handleOpen2(sketchPath); } else { handleNew2(true); this.header.rebuild(); } } // location for the console/editor area divider int location = Preferences.getInteger("last.divider.location"); splitPane.setDividerLocation(location); // read the preferences that are settable in the preferences window applyPreferences(); } /** * Read and apply new values from the preferences, either because * the app is just starting up, or the user just finished messing * with things in the Preferences window. */ public void applyPreferences() { // apply the setting for 'use external editor' boolean external = Preferences.getBoolean("editor.external"); textarea.setEditable(!external); saveMenuItem.setEnabled(!external); saveAsMenuItem.setEnabled(!external); //beautifyMenuItem.setEnabled(!external); TextAreaPainter painter = textarea.getPainter(); if (external) { // disable line highlight and turn off the caret when disabling Color color = Preferences.getColor("editor.external.bgcolor"); painter.setBackground(color); painter.setLineHighlightEnabled(false); textarea.setCaretVisible(false); } else { Color color = Preferences.getColor("editor.bgcolor"); painter.setBackground(color); boolean highlight = Preferences.getBoolean("editor.linehighlight"); painter.setLineHighlightEnabled(highlight); textarea.setCaretVisible(true); } // apply changes to the font size for the editor //TextAreaPainter painter = textarea.getPainter(); painter.setFont(Preferences.getFont("editor.font")); //Font font = painter.getFont(); //textarea.getPainter().setFont(new Font("Courier", Font.PLAIN, 36)); // in case tab expansion stuff has changed listener.applyPreferences(); // in case moved to a new location // For 0125, changing to async version (to be implemented later) //sketchbook.rebuildMenus(); sketchbook.rebuildMenusAsync(); } /** * Store preferences about the editor's current state. * Called when the application is quitting. */ public void storePreferences() { //System.out.println("storing preferences"); // window location information Rectangle bounds = getBounds(); Preferences.setInteger("last.window.x", bounds.x); Preferences.setInteger("last.window.y", bounds.y); Preferences.setInteger("last.window.width", bounds.width); Preferences.setInteger("last.window.height", bounds.height); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Preferences.setInteger("last.screen.width", screen.width); Preferences.setInteger("last.screen.height", screen.height); // last sketch that was in use //Preferences.set("last.sketch.name", sketchName); //Preferences.set("last.sketch.name", sketch.name); Preferences.set("last.sketch.path", sketch.getMainFilePath()); // location for the console/editor area divider int location = splitPane.getDividerLocation(); Preferences.setInteger("last.divider.location", location); } // ................................................................... protected JMenu buildFileMenu() { JMenuItem item; JMenu menu = new JMenu("File"); item = newJMenuItem("New", 'N'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleNew(false); } }); menu.add(item); menu.add(sketchbook.getOpenMenu()); saveMenuItem = newJMenuItem("Save", 'S'); saveMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSave(false); } }); menu.add(saveMenuItem); saveAsMenuItem = newJMenuItem("Save As...", 'S', true); saveAsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSaveAs(); } }); menu.add(saveAsMenuItem); item = newJMenuItem("Upload to I/O Board", 'U'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleExport(); } }); menu.add(item); /*exportAppItem = newJMenuItem("Export Application", 'E', true); exportAppItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //buttons.activate(EditorButtons.EXPORT); //SwingUtilities.invokeLater(new Runnable() { //public void run() { handleExportApplication(); //}}); } }); menu.add(exportAppItem); */ menu.addSeparator(); item = newJMenuItem("Page Setup", 'P', true); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePageSetup(); } }); menu.add(item); item = newJMenuItem("Print", 'P'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePrint(); } }); menu.add(item); // macosx already has its own preferences and quit menu if (!Base.isMacOS()) { menu.addSeparator(); item = newJMenuItem("Preferences", ','); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePrefs(); } }); menu.add(item); menu.addSeparator(); item = newJMenuItem("Quit", 'Q'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleQuitInternal(); } }); menu.add(item); } return menu; } protected JMenu buildSketchMenu() { JMenuItem item; JMenu menu = new JMenu("Sketch"); item = newJMenuItem("Verify/Compile", 'R'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { handleRun(false); } catch (IOException ex) { ex.printStackTrace(); } } }); menu.add(item); /*item = newJMenuItem("Present", 'R', true); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleRun(true); } }); menu.add(item); */ item = new JMenuItem("Stop"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleStop(); } }); menu.add(item); menu.addSeparator(); menu.add(sketchbook.getImportMenu()); //if (Base.isWindows() || Base.isMacOS()) { // no way to do an 'open in file browser' on other platforms // since there isn't any sort of standard item = newJMenuItem("Show Sketch Folder", 'K', false); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //Base.openFolder(sketchDir); Base.openFolder(sketch.folder); } }); menu.add(item); if (!Base.openFolderAvailable()) { item.setEnabled(false); } //menu.addSeparator(); item = new JMenuItem("Add File..."); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sketch.addFile(); } }); menu.add(item); // TODO re-enable history //history.attachMenu(menu); return menu; } protected JMenu buildToolsMenu() { JMenuItem item; JMenuItem rbMenuItem; JMenuItem cbMenuItem; serialMenuListener = new SerialMenuListener(); JMenu menu = new JMenu("Tools"); item = newJMenuItem("Auto Format", 'T', false); item.addActionListener(new ActionListener() { synchronized public void actionPerformed(ActionEvent e) { new AutoFormat(Editor.this).show(); /* Jalopy jalopy = new Jalopy(); jalopy.setInput(getText(), sketch.current.file.getAbsolutePath()); StringBuffer buffer = new StringBuffer(); jalopy.setOutput(buffer); jalopy.setInspect(false); jalopy.format(); setText(buffer.toString(), 0, 0); if (jalopy.getState() == Jalopy.State.OK) System.out.println("successfully formatted"); else if (jalopy.getState() == Jalopy.State.WARN) System.out.println(" formatted with warnings"); else if (jalopy.getState() == Jalopy.State.ERROR) System.out.println(" could not be formatted"); */ } }); menu.add(item); item = new JMenuItem("Copy for Forum"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { new DiscourseFormat(Editor.this).show(); } }); } }); menu.add(item); item = new JMenuItem("Archive Sketch"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new Archiver(Editor.this).show(); //Archiver archiver = new Archiver(); //archiver.setup(Editor.this); //archiver.show(); } }); menu.add(item); /* item = new JMenuItem("Export Folder..."); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { new ExportFolder(Editor.this).show(); } }); menu.add(item); */ menu.addSeparator(); JMenu boardsMenu = new JMenu("Board"); ButtonGroup boardGroup = new ButtonGroup(); for (Iterator i = Preferences.getSubKeys("boards"); i.hasNext(); ) { String board = (String) i.next(); Action action = new BoardMenuAction(board); item = new JRadioButtonMenuItem(action); String selectedBoard = Preferences.get("board"); if (board.equals(Preferences.get("board"))) item.setSelected(true); boardGroup.add(item); boardsMenu.add(item); } menu.add(boardsMenu); serialMenu = new JMenu("Serial Port"); populateSerialMenu(); menu.add(serialMenu); menu.addSeparator(); JMenu bootloaderMenu = new JMenu("Burn Bootloader"); for (Iterator i = Preferences.getSubKeys("programmers"); i.hasNext(); ) { String programmer = (String) i.next(); Action action = new BootloaderMenuAction(programmer); item = new JMenuItem(action); bootloaderMenu.add(item); } menu.add(bootloaderMenu); menu.addMenuListener(new MenuListener() { public void menuCanceled(MenuEvent e) {} public void menuDeselected(MenuEvent e) {} public void menuSelected(MenuEvent e) { //System.out.println("Tools menu selected."); populateSerialMenu(); } }); return menu; } class SerialMenuListener implements ActionListener { //public SerialMenuListener() { } public void actionPerformed(ActionEvent e) { if(serialMenu == null) { System.out.println("serialMenu is null"); return; } int count = serialMenu.getItemCount(); for (int i = 0; i < count; i++) { ((JCheckBoxMenuItem)serialMenu.getItem(i)).setState(false); } JCheckBoxMenuItem item = (JCheckBoxMenuItem)e.getSource(); item.setState(true); String name = item.getText(); //System.out.println(item.getLabel()); Preferences.set("serial.port", name); //System.out.println("set to " + get("serial.port")); } /* public void actionPerformed(ActionEvent e) { System.out.println(e.getSource()); String name = e.getActionCommand(); PdeBase.properties.put("serial.port", name); System.out.println("set to " + get("serial.port")); //editor.skOpen(path + File.separator + name, name); // need to push "serial.port" into PdeBase.properties } */ } class BoardMenuAction extends AbstractAction { private String board; public BoardMenuAction(String board) { super(Preferences.get("boards." + board + ".name")); this.board = board; } public void actionPerformed(ActionEvent actionevent) { System.out.println("Switching to " + board); Preferences.set("board", board); try { //LibraryManager libraryManager = new LibraryManager(); //libraryManager.rebuildAllBuilt(); } catch (Exception e) { e.printStackTrace(); //} catch (RunnerException e) { // message("Error rebuilding libraries..."); // error(e); } } } class BootloaderMenuAction extends AbstractAction { private String programmer; public BootloaderMenuAction(String programmer) { super("w/ " + Preferences.get("programmers." + programmer + ".name")); this.programmer = programmer; } public void actionPerformed(ActionEvent actionevent) { handleBurnBootloader(programmer); } } protected void populateSerialMenu() { // getting list of ports JMenuItem rbMenuItem; //System.out.println("Clearing serial port menu."); serialMenu.removeAll(); boolean empty = true; try { for (Enumeration enumeration = CommPortIdentifier.getPortIdentifiers(); enumeration.hasMoreElements();) { CommPortIdentifier commportidentifier = (CommPortIdentifier)enumeration.nextElement(); //System.out.println("Found communication port: " + commportidentifier); if (commportidentifier.getPortType() == CommPortIdentifier.PORT_SERIAL) { //System.out.println("Adding port to serial port menu: " + commportidentifier); String curr_port = commportidentifier.getName(); rbMenuItem = new JCheckBoxMenuItem(curr_port, curr_port.equals(Preferences.get("serial.port"))); rbMenuItem.addActionListener(serialMenuListener); //serialGroup.add(rbMenuItem); serialMenu.add(rbMenuItem); empty = false; } } if (!empty) { //System.out.println("enabling the serialMenu"); serialMenu.setEnabled(true); } } catch (Exception exception) { System.out.println("error retrieving port list"); exception.printStackTrace(); } if (serialMenu.getItemCount() == 0) { serialMenu.setEnabled(false); } //serialMenu.addSeparator(); //serialMenu.add(item); } protected JMenu buildHelpMenu() { JMenu menu = new JMenu("Help"); JMenuItem item; if (!Base.isLinux()) { item = new JMenuItem("Getting Started"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (Base.isWindows()) Base.openURL(System.getProperty("user.dir") + File.separator + "reference" + File.separator + "Guide_Windows.html"); else Base.openURL(System.getProperty("user.dir") + File.separator + "reference" + File.separator + "Guide_MacOSX.html"); } }); menu.add(item); } item = new JMenuItem("Environment"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showEnvironment(); } }); menu.add(item); item = new JMenuItem("Troubleshooting"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showTroubleshooting(); } }); menu.add(item); item = new JMenuItem("Reference"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference(); } }); menu.add(item); item = newJMenuItem("Find in Reference", 'F', true); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (textarea.isSelectionActive()) { handleReference(); } } }); menu.add(item); item = new JMenuItem("Frequently Asked Questions"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showFAQ(); } }); menu.add(item); item = newJMenuItem("Visit www.arduino.cc", '5'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL("http://www.arduino.cc/"); } }); menu.add(item); // macosx already has its own about menu if (!Base.isMacOS()) { menu.addSeparator(); item = new JMenuItem("About Arduino"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleAbout(); } }); menu.add(item); } return menu; } public JMenu buildEditMenu() { JMenu menu = new JMenu("Edit"); JMenuItem item; undoItem = newJMenuItem("Undo", 'Z'); undoItem.addActionListener(undoAction = new UndoAction()); menu.add(undoItem); redoItem = newJMenuItem("Redo", 'Y'); redoItem.addActionListener(redoAction = new RedoAction()); menu.add(redoItem); menu.addSeparator(); // TODO "cut" and "copy" should really only be enabled // if some text is currently selected item = newJMenuItem("Cut", 'X'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.cut(); sketch.setModified(true); } }); menu.add(item); item = newJMenuItem("Copy", 'C'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.copy(); } }); menu.add(item); item = newJMenuItem("Paste", 'V'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.paste(); sketch.setModified(true); } }); menu.add(item); item = newJMenuItem("Select All", 'A'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.selectAll(); } }); menu.add(item); menu.addSeparator(); item = newJMenuItem("Find...", 'F'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find == null) { find = new FindReplace(Editor.this); } //new FindReplace(Editor.this).show(); find.show(); //find.setVisible(true); } }); menu.add(item); // TODO find next should only be enabled after a // search has actually taken place item = newJMenuItem("Find Next", 'G'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find != null) { //find.find(true); //FindReplace find = new FindReplace(Editor.this); //.show(); find.find(true); } } }); menu.add(item); return menu; } /** * Convenience method, see below. */ static public JMenuItem newJMenuItem(String title, int what) { return newJMenuItem(title, what, false); } /** * A software engineer, somewhere, needs to have his abstraction * taken away. In some countries they jail or beat people for writing * the sort of API that would require a five line helper function * just to set the command key for a menu item. */ static public JMenuItem newJMenuItem(String title, int what, boolean shift) { JMenuItem menuItem = new JMenuItem(title); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); if (shift) modifiers |= ActionEvent.SHIFT_MASK; menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); return menuItem; } // ................................................................... class UndoAction extends AbstractAction { public UndoAction() { super("Undo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undo.undo(); } catch (CannotUndoException ex) { //System.out.println("Unable to undo: " + ex); //ex.printStackTrace(); } updateUndoState(); redoAction.updateRedoState(); } protected void updateUndoState() { if (undo.canUndo()) { this.setEnabled(true); undoItem.setEnabled(true); undoItem.setText(undo.getUndoPresentationName()); putValue(Action.NAME, undo.getUndoPresentationName()); if (sketch != null) { sketch.setModified(true); // 0107 } } else { this.setEnabled(false); undoItem.setEnabled(false); undoItem.setText("Undo"); putValue(Action.NAME, "Undo"); if (sketch != null) { sketch.setModified(false); // 0107 } } } } class RedoAction extends AbstractAction { public RedoAction() { super("Redo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undo.redo(); } catch (CannotRedoException ex) { //System.out.println("Unable to redo: " + ex); //ex.printStackTrace(); } updateRedoState(); undoAction.updateUndoState(); } protected void updateRedoState() { if (undo.canRedo()) { redoItem.setEnabled(true); redoItem.setText(undo.getRedoPresentationName()); putValue(Action.NAME, undo.getRedoPresentationName()); } else { this.setEnabled(false); redoItem.setEnabled(false); redoItem.setText("Redo"); putValue(Action.NAME, "Redo"); } } } // ................................................................... // interfaces for MRJ Handlers, but naming is fine // so used internally for everything else public void handleAbout() { final Image image = Base.getImage("about.jpg", this); int w = image.getWidth(this); int h = image.getHeight(this); final Window window = new Window(_frame) { public void paint(Graphics g) { g.drawImage(image, 0, 0, null); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); g.setFont(new Font("SansSerif", Font.PLAIN, 11)); g.setColor(Color.white); g.drawString(Base.DIST_NAME + " v" + Base.VERSION_NAME, 50, 30); } }; window.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { window.dispose(); } }); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); window.setBounds((screen.width-w)/2, (screen.height-h)/2, w, h); window.show(); } /** * Show the preferences window. */ public void handlePrefs() { Preferences preferences = new Preferences(); preferences.showFrame(this); // since this can't actually block, it'll hide // the editor window while the prefs are open //preferences.showFrame(this); // and then call applyPreferences if 'ok' is hit // and then unhide // may need to rebuild sketch and other menus //applyPreferences(); // next have editor do its thing //editor.appyPreferences(); } // ................................................................... /** * Get the contents of the current buffer. Used by the Sketch class. */ public String getText() { return textarea.getText(); } /** * Called to update the text but not switch to a different * set of code (which would affect the undo manager). */ public void setText(String what, int selectionStart, int selectionEnd) { beginCompoundEdit(); textarea.setText(what); endCompoundEdit(); // make sure that a tool isn't asking for a bad location selectionStart = Math.max(0, Math.min(selectionStart, textarea.getDocumentLength())); selectionEnd = Math.max(0, Math.min(selectionStart, textarea.getDocumentLength())); textarea.select(selectionStart, selectionEnd); textarea.requestFocus(); // get the caret blinking } /** * Switch between tabs, this swaps out the Document object * that's currently being manipulated. */ public void setCode(SketchCode code) { if (code.document == null) { // this document not yet inited code.document = new SyntaxDocument(); // turn on syntax highlighting code.document.setTokenMarker(new PdeKeywords()); // insert the program text into the document object try { code.document.insertString(0, code.program, null); } catch (BadLocationException bl) { bl.printStackTrace(); } // set up this guy's own undo manager code.undo = new UndoManager(); // connect the undo listener to the editor code.document.addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent e) { if (compoundEdit != null) { compoundEdit.addEdit(e.getEdit()); } else if (undo != null) { undo.addEdit(e.getEdit()); undoAction.updateUndoState(); redoAction.updateRedoState(); } } }); } //switch to a code card try{ CardLayout cl = (CardLayout)this.getLayout(); cl.show(textarea, CODEEDITOR); }catch(Exception ex){ } //set the card layout to give focus to the textarea CardLayout layout = (CardLayout)this.centerPanel.getLayout(); layout.show(this.centerPanel, CODEEDITOR); // update the document object that's in use textarea.setDocument(code.document, code.selectionStart, code.selectionStop, code.scrollPosition); textarea.requestFocus(); // get the caret blinking this.undo = code.undo; undoAction.updateUndoState(); redoAction.updateRedoState(); } public void beginCompoundEdit() { compoundEdit = new CompoundEdit(); } public void endCompoundEdit() { compoundEdit.end(); undo.addEdit(compoundEdit); undoAction.updateUndoState(); redoAction.updateRedoState(); compoundEdit = null; } // ................................................................... public void handleRun(final boolean present) throws IOException { System.out.println("handling the run"); doClose(); running = true; this.isExporting = false; buttons.activate(EditorButtons.RUN); message("Compiling..."); // do this for the terminal window / dos prompt / etc for (int i = 0; i < 10; i++) System.out.println(); // clear the console on each run, unless the user doesn't want to //if (Base.getBoolean("console.auto_clear", true)) { //if (Preferences.getBoolean("console.auto_clear", true)) { if (Preferences.getBoolean("console.auto_clear")) { console.clear(); } presenting = present; if (presenting && Base.isMacOS()) { // check to see if osx 10.2, if so, show a warning String osver = System.getProperty("os.version").substring(0, 4); if (osver.equals("10.2")) { Base.showWarning("Time for an OS Upgrade", "The \"Present\" feature may not be available on\n" + "Mac OS X 10.2, because of what appears to be\n" + "a bug in the Java 1.4 implementation on 10.2.\n" + "In case it works on your machine, present mode\n" + "will start, but if you get a flickering white\n" + "window, using Command-Q to quit the sketch", null); } } this.saveSketches(); if(gadgetPanel.getActiveGadget() != null){ if(gadgetPanel.getActiveModule().getRules() != null){ IMessage message = gadgetPanel.getActiveModule().getRules().getMessages()[0]; if(message != null && this.isExporting){ IOkListener ourListener = new IOkListener(){ private String msg; public void OkButton() { compile(); } public String getMessage() { return msg; } public void setMessage(String message) { msg = message; } }; status.CreateOkDialog(ourListener, message.getMessage()); }else{ this.compile(); //no message just compile } }else{ this.compile(); } }else{ this.compile(); } // this doesn't seem to help much or at all /* final SwingWorker worker = new SwingWorker() { public Object construct() { try { if (!sketch.handleRun()) return null; runtime = new Runner(sketch, Editor.this); runtime.start(presenting ? presentLocation : appletLocation); watcher = new RunButtonWatcher(); message("Done compiling."); } catch (RunnerException e) { message("Error compiling..."); error(e); } catch (Exception e) { e.printStackTrace(); } return null; // needn't return anything } }; worker.start(); */ //sketch.cleanup(); // where does this go? buttons.clear(); } private void compile(){ final Sketch sketch = this.sketch; SwingUtilities.invokeLater(new Runnable() { public void run() { try { if(gadgetPanel != null){ if(gadgetPanel.getActiveModule() != null){ IGadget book = gadgetPanel.getActiveGadget(); IModule[] gadgets = book.getModules(); IModule gadget = gadgetPanel.getActiveModule(); File sketchFile = gadget.getSketchFile(); Sketch currentSketch = new Sketch(new Editor(), sketchFile.getPath()); String target = gadget.getTarget(); System.out.println("Running file with target : " + target); String boardName = Preferences.get("board"); System.out.println(boardName); if(!currentSketch.handleRun(new Target(System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores", Preferences.get("boards." + target + ".build.core")))){ System.out.println("Error compiling file"); } }else{ //There is no active gadget; we should do a classic run String boardName = Preferences.get("board"); if(!sketch.handleRun(new Target(System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores", Preferences.get("boards." + boardName + ".build.core")))){ System.out.println("Error compiling file"); } } }else{ System.out.println("error getting the gadget panel"); } /* if (!sketch.handleRun(new Target( System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores", Preferences.get("boards." + Preferences.get("board") + ".build.core")))) return; */ //runtime = new Runner(sketch, Editor.this); //runtime.start(appletLocation); watcher = new RunButtonWatcher(); message("Done compiling."); if(watcher != null) watcher.stop(); } catch (RunnerException e) { message("Error compiling..."); error(e); } catch (Exception e) { e.printStackTrace(); } }}); } class RunButtonWatcher implements Runnable { Thread thread; public RunButtonWatcher() { thread = new Thread(this, "run button watcher"); thread.setPriority(Thread.MIN_PRIORITY); thread.start(); } public void run() { while (Thread.currentThread() == thread) { /*if (runtime == null) { stop(); } else { if (runtime.applet != null) { if (runtime.applet.finished) { stop(); } //buttons.running(!runtime.applet.finished); } else if (runtime.process != null) { //buttons.running(true); // ?? } else { stop(); } }*/ try { Thread.sleep(250); } catch (InterruptedException e) { } //System.out.println("still inside runner thread"); } } public void stop() { buttons.running(false); thread = null; } } public void handleSerial() { if (!debugging) { try { ImageListPanel.killActiveTransfer(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } serialPort = new Serial(true); this.gadgetPanel.setSerial(serialPort); console.clear(); buttons.activate(EditorButtons.SERIAL); debugging = true; status.serial(); } catch(SerialException e) { error(e); } } else { doStop(); } } public void handleStop() { // called by menu or buttons if (presenting) { doClose(); } else { doStop(); } buttons.clear(); } /** * Stop the applet but don't kill its window. */ public void doStop() { //if (runtime != null) runtime.stop(); if (debugging) { status.unserial(); serialPort.dispose(); debugging = false; } if (watcher != null) watcher.stop(); message(EMPTY); // the buttons are sometimes still null during the constructor // is this still true? are people still hitting this error? /*if (buttons != null)*/ buttons.clear(); running = false; } /** * Stop the applet and kill its window. When running in presentation * mode, this will always be called instead of doStop(). */ public void doClose() { //if (presenting) { //presentationWindow.hide(); //} else { //try { // the window will also be null the process was running // externally. so don't even try setting if window is null // since Runner will set the appletLocation when an // external process is in use. // if (runtime.window != null) { // appletLocation = runtime.window.getLocation(); // } //} catch (NullPointerException e) { } //} //if (running) doStop(); doStop(); // need to stop if runtime error //try { /*if (runtime != null) { runtime.close(); // kills the window runtime = null; // will this help? }*/ //} catch (Exception e) { } //buttons.clear(); // done by doStop sketch.cleanup(); // [toxi 030903] // focus the PDE again after quitting presentation mode _frame.toFront(); if(this.gadgetPanel.isActive()){ this.gadgetPanel.saveCurrentGadget(); Preferences.set("gadget.active", "true"); try{ Preferences.set("last.active.gadget", ((IPackedFile)this.gadgetPanel.getActiveGadget()).getPackedFile().getPath()); }catch(Exception ex){ //there is no gadget } } } /** * Check to see if there have been changes. If so, prompt user * whether or not to save first. If the user cancels, just ignore. * Otherwise, one of the other methods will handle calling * checkModified2() which will get on with business. */ protected void checkModified(int checkModifiedMode) { this.checkModifiedMode = checkModifiedMode; if (!sketch.modified) { checkModified2(); return; } String prompt = "Save changes to " + sketch.name + "? "; if (checkModifiedMode != HANDLE_QUIT) { // if the user is not quitting, then use simpler nicer // dialog that's actually inside the p5 window. status.prompt(prompt); } else { if (!Base.isMacOS() || PApplet.javaVersion < 1.5f) { int result = JOptionPane.showConfirmDialog(this, prompt, "Quit", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { handleSave(true); checkModified2(); } else if (result == JOptionPane.NO_OPTION) { checkModified2(); } // cancel is ignored altogether } else { // This code is disabled unless Java 1.5 is being used on Mac OS X // because of a Java bug that prevents the initial value of the // dialog from being set properly (at least on my MacBook Pro). // The bug causes the "Don't Save" option to be the highlighted, // blinking, default. This sucks. But I'll tell you what doesn't // suck--workarounds for the Mac and Apple's snobby attitude about it! // adapted from the quaqua guide // http://www.randelshofer.ch/quaqua/guide/joptionpane.html JOptionPane pane = new JOptionPane("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Do you want to save changes to this sketch<BR>" + " before closing?</b>" + "<p>If you don't save, your changes will be lost.", JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { "Save", "Cancel", "Don't Save" }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); // on macosx, setting the destructive property places this option // away from the others at the lefthand side pane.putClientProperty("Quaqua.OptionPane.destructiveOption", new Integer(2)); JDialog dialog = pane.createDialog(this, null); dialog.show(); Object result = pane.getValue(); if (result == options[0]) { // save (and quit) handleSave(true); checkModified2(); } else if (result == options[2]) { // don't save (still quit) checkModified2(); } } } } /** * Called by EditorStatus to complete the job and re-dispatch * to handleNew, handleOpen, handleQuit. */ public void checkModified2() { switch (checkModifiedMode) { case HANDLE_NEW: handleNew2(false); break; case HANDLE_OPEN: handleOpen2(handleOpenPath); break; case HANDLE_QUIT: handleQuit2(); break; } checkModifiedMode = 0; } /** * New was called (by buttons or by menu), first check modified * and if things work out ok, handleNew2() will be called. * <p/> * If shift is pressed when clicking the toolbar button, then * force the opposite behavior from sketchbook.prompt's setting */ public void handleNew(final boolean shift) { buttons.activate(EditorButtons.NEW); SwingUtilities.invokeLater(new Runnable() { public void run() { doStop(); handleNewShift = shift; handleNewLibrary = false; checkModified(HANDLE_NEW); }}); this.header.paintComponents(this.getGraphics()); } /** * Extra public method so that Sketch can call this when a sketch * is selected to be deleted, and it won't call checkModified() * to prompt for save as. */ public void handleNewUnchecked() { doStop(); handleNewShift = false; handleNewLibrary = false; handleNew2(true); } /** * User selected "New Library", this will act just like handleNew * but internally set a flag that the new guy is a library, * meaning that a "library" subfolder will be added. */ public void handleNewLibrary() { doStop(); handleNewShift = false; handleNewLibrary = true; checkModified(HANDLE_NEW); } /** * Does all the plumbing to create a new project * then calls handleOpen to load it up. * * @param noPrompt true to disable prompting for the sketch * name, used when the app is starting (auto-create a sketch) */ protected void handleNew2(boolean noPrompt) { try { String pdePath = sketchbook.handleNew(noPrompt, handleNewShift, handleNewLibrary); if (pdePath != null) handleOpen2(pdePath); this.header.rebuild(); } catch (IOException e) { // not sure why this would happen, but since there's no way to // recover (outside of creating another new setkch, which might // just cause more trouble), then they've gotta quit. Base.showError("Problem creating a new sketch", "An error occurred while creating\n" + "a new sketch. Arduino must now quit.", e); } buttons.clear(); } /** * This is the implementation of the MRJ open document event, * and the Windows XP open document will be routed through this too. */ public void handleOpenFile(File file) { //System.out.println("handling open file: " + file); handleOpen(file.getAbsolutePath()); } /** * Open a sketch given the full path to the .pde file. * Pass in 'null' to prompt the user for the name of the sketch. */ public void handleOpen(final String ipath) { // haven't run across a case where i can verify that this works // because open is usually very fast. buttons.activate(EditorButtons.OPEN); SwingUtilities.invokeLater(new Runnable() { public void run() { String path = ipath; if (path == null) { // "open..." selected from the menu path = sketchbook.handleOpen(); if (path == null) return; } doClose(); handleOpenPath = path; checkModified(HANDLE_OPEN); }}); } /** * Open a sketch from a particular path, but don't check to save changes. * Used by Sketch.saveAs() to re-open a sketch after the "Save As" */ public void handleOpenUnchecked(String path, int codeIndex, int selStart, int selStop, int scrollPos) { doClose(); handleOpen2(path); sketch.setCurrent(codeIndex); textarea.select(selStart, selStop); //textarea.updateScrollBars(); textarea.setScrollPosition(scrollPos); } /** * Second stage of open, occurs after having checked to * see if the modifications (if any) to the previous sketch * need to be saved. */ protected void handleOpen2(String path) { if (sketch != null) { // if leaving an empty sketch (i.e. the default) do an // auto-clean right away try { // don't clean if we're re-opening the same file String oldPath = sketch.code[0].file.getPath(); String newPath = new File(path).getPath(); if (!oldPath.equals(newPath)) { if (Base.calcFolderSize(sketch.folder) == 0) { Base.removeDir(sketch.folder); //sketchbook.rebuildMenus(); sketchbook.rebuildMenusAsync(); } } } catch (Exception e) { } // oh well } try { // check to make sure that this .pde file is // in a folder of the same name File file = new File(path); File parentFile = new File(file.getParent()); String parentName = parentFile.getName(); String pdeName = parentName + ".pde"; File altFile = new File(file.getParent(), pdeName); boolean isGadgetFile = false; //System.out.println("path = " + file.getParent()); //System.out.println("name = " + file.getName()); //System.out.println("pname = " + parentName); if (pdeName.equals(file.getName())) { // no beef with this guy } else if (altFile.exists()) { // user selected a .java from the same sketch, // but open the .pde instead path = altFile.getAbsolutePath(); //System.out.println("found alt file in same folder"); } else if (!path.endsWith(".pde")) { Base.showWarning("Bad file selected", "Arduino can only open its own sketches\n" + "and other files ending in .pde", null); return; } else if (path.endsWith(".gadget")){ this.gadgetPanel.loadGadget(new File(path)); path = this.gadgetPanel.getActiveModule().getSketchFile().getPath(); this.loadGadget(this.gadgetPanel.getActiveGadget()); isGadgetFile = true; this.lastActiveGadgetPath = path; }else { try{ this.gadgetPanel.loadGadget(new File(path)); IModule module = this.gadgetPanel.getActiveModule(); File sketchFile = module.getSketchFile(); path = sketchFile.getPath(); this.loadGadget(this.gadgetPanel.getActiveGadget()); isGadgetFile = true; this.lastActiveGadgetPath = path; }catch(Exception ex){ ex.printStackTrace(); isGadgetFile = false; String properParent = file.getName().substring(0, file.getName().length() - 4); Object[] options = { "OK", "Cancel" }; String prompt = "The file \"" + file.getName() + "\" needs to be inside\n" + "a sketch folder named \"" + properParent + "\".\n" + "Create this folder, move the file, and continue?"; int result = JOptionPane.showOptionDialog(this, prompt, "Moving", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.YES_OPTION) { // create properly named folder File properFolder = new File(file.getParent(), properParent); if (properFolder.exists()) { Base.showWarning("Error", "A folder named \"" + properParent + "\" " + "already exists. Can't open sketch.", null); return; } if (!properFolder.mkdirs()) { throw new IOException("Couldn't create sketch folder"); } // copy the sketch inside File properPdeFile = new File(properFolder, file.getName()); File origPdeFile = new File(path); Base.copyFile(origPdeFile, properPdeFile); // remove the original file, so user doesn't get confused origPdeFile.delete(); // update with the new path path = properPdeFile.getAbsolutePath(); } else if (result == JOptionPane.NO_OPTION) { return; } } } //do one last check if(this.gadgetPanel.getActiveGadget() != null){ for(int i = 0; i < gadgetPanel.getActiveGadget().getModules().length; i++){ if(gadgetPanel.getActiveGadget().getModules()[i].getSketchFile().getPath().equalsIgnoreCase(path)){ isGadgetFile = true; break; } } } this.gadgetPanel.setVisible(isGadgetFile); if(isGadgetFile){ gadgetPanel.show(); /* The Boards menu doesn't * make sense with a gadget .pde file, so disable it */ _frame.getJMenuBar().getMenu(3).getItem(4).setEnabled(false); leftExpandLabel.setText(">"); }else{ this.gadgetPanel.Unload(); //remove the gadget list and unload active module /* Use the Boards menu with a std .pde file */ _frame.getJMenuBar().getMenu(3).getItem(4).setEnabled(true); gadgetPanel.hide(); } sketch = new Sketch(this, path); if(isGadgetFile){ System.out.println(path); } // TODO re-enable this once export application works //exportAppItem.setEnabled(false); //exportAppItem.setEnabled(false && !sketch.isLibrary()); //buttons.disableRun(sketch.isLibrary()); header.rebuild(); if (Preferences.getBoolean("console.auto_clear")) { console.clear(); } } catch (Exception e) { error(e); } } // there is no handleSave1 since there's never a need to prompt /** * Actually handle the save command. If 'force' is set to false, * this will happen in another thread so that the message area * will update and the save button will stay highlighted while the * save is happening. If 'force' is true, then it will happen * immediately. This is used during a quit, because invokeLater() * won't run properly while a quit is happening. This fixes * <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=276">Bug 276</A>. */ public void handleSave(boolean force) { doStop(); buttons.activate(EditorButtons.SAVE); if (force) { handleSave2(); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { handleSave2(); } }); } } public void handleSave2() { message("Saving..."); try { sketch.save(); if (saveSketches()) { message("Done Saving."); } else { message(EMPTY); } if(this.gadgetPanel.getActiveGadget()!= null){ this.gadgetPanel.saveCurrentGadget(); System.out.println("saved gadget"); } // rebuild sketch menu in case a save-as was forced // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenus(); //sketchbook.rebuildMenusAsync(); } catch (Exception e) { // show the error as a message in the window error(e); // zero out the current action, // so that checkModified2 will just do nothing checkModifiedMode = 0; // this is used when another operation calls a save } buttons.clear(); } public void handleSaveAs() { doStop(); buttons.activate(EditorButtons.SAVE); final GadgetPanel gp = this.gadgetPanel; final Editor edit = this; SwingUtilities.invokeLater(new Runnable() { public void run() { message("Saving..."); try { sketch.save(); } catch (IOException e1) { e1.printStackTrace(); } try { if(gp.getActiveGadget() != null){ FileDialog fd = new FileDialog(edit._frame, "Save gadget file as...", FileDialog.SAVE); File packedDirectory = ((IPackedFile)gp.getActiveGadget()).getPackedFile().getParentFile(); fd.setDirectory(packedDirectory.getPath()); fd.setFile(gp.getActiveGadget().getName()); fd.show(); String newParentDir = fd.getDirectory(); String newName = fd.getFile(); if (newName != null){ String fileName; if(newName.endsWith(".pde")){ fileName = newName; newName = newName.substring(0, newName.length() - 4); }else{ fileName = newName + ".pde"; } //save the gadget file GadgetFactory fact = new GadgetFactory(); /* IPackedFile file = ((IPackedFile)gp.getActiveGadget()); File newGadget = new File(newParentDir + File.separator + fileName); Base.copyFile(file.getPackedFile(), newGadget); IGadget gadg = fact.loadGadget(newGadget, System.getProperty("java.io.tmpdir") + File.separator + newGadget.getName()); gadg.setName(newName); ((IPackedFile)gadg).setPackedFile(newGadget); ITemporary tempDir = (ITemporary)gadg; File dir = new File(tempDir.getTempDirectory()); dir.listFiles(); gp.loadGadget(newGadget); gp.saveCurrentGadget();*/ File newFile = fact.copyGadget(gp.getActiveGadget(), newParentDir , newName); //IGadget newGadget = fact.loadGadget(newFile, System.getProperty("java.io.tmpdir") + File.separator + newFile.getName()); gp.loadGadget(newFile); gp.saveCurrentGadget(); } }else{ if (sketch.saveAs()) { message("Done Saving."); // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenusAsync(); } else { message("Save Cancelled."); } } } catch (Exception e) { // show the error as a message in the window error(e); } buttons.clear(); }}); } /** * Handles calling the export() function on sketch, and * queues all the gui status stuff that comes along with it. * * Made synchronized to (hopefully) avoid problems of people * hitting export twice, quickly, and horking things up. */ synchronized public void handleExport() { if(debugging) doStop(); buttons.activate(EditorButtons.EXPORT); console.clear(); //String what = sketch.isLibrary() ? "Applet" : "Library"; //message("Exporting " + what + "..."); message("Uploading to I/O Board..."); final GadgetPanel panel = this.gadgetPanel; this.isExporting = true; this.saveSketches(); SwingUtilities.invokeLater(new Runnable() { public void run() { try { //boolean success = sketch.isLibrary() ? //sketch.exportLibrary() : sketch.exportApplet(); if(panel.getActiveGadget() == null){ boolean success = sketch.exportApplet(new Target( System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores", Preferences.get("boards." + Preferences.get("board") + ".build.core"))); if (success) { message("Done uploading."); } else { // error message will already be visible } }else{ sketch.exportApplet(new Target( System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores", Preferences.get("boards." + panel.getActiveModule().getTarget() + ".build.core"))); } } catch (RunnerException e) { message("Error during upload."); //e.printStackTrace(); error(e); } catch (Exception e) { e.printStackTrace(); } buttons.clear(); }}); } synchronized public void handleExportApp() { message("Exporting application..."); try { if (sketch.exportApplication()) { message("Done exporting."); } else { // error message will already be visible } } catch (Exception e) { message("Error during export."); e.printStackTrace(); } buttons.clear(); } /** * Checks to see if the sketch has been modified, and if so, * asks the user to save the sketch or cancel the export. * This prevents issues where an incomplete version of the sketch * would be exported, and is a fix for * <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=157">Bug 157</A> */ public boolean handleExportCheckModified() { if (!sketch.modified) return true; Object[] options = { "OK", "Cancel" }; int result = JOptionPane.showOptionDialog(this, "Save changes before export?", "Save", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.OK_OPTION) { handleSave(true); } else { // why it's not CANCEL_OPTION is beyond me (at least on the mac) // but f-- it.. let's get this shite done.. //} else if (result == JOptionPane.CANCEL_OPTION) { message("Export canceled, changes must first be saved."); buttons.clear(); return false; } return true; } public void handlePageSetup() { //printerJob = null; if (printerJob == null) { printerJob = PrinterJob.getPrinterJob(); } if (pageFormat == null) { pageFormat = printerJob.defaultPage(); } pageFormat = printerJob.pageDialog(pageFormat); //System.out.println("page format is " + pageFormat); } public void handlePrint() { message("Printing..."); //printerJob = null; if (printerJob == null) { printerJob = PrinterJob.getPrinterJob(); } if (pageFormat != null) { //System.out.println("setting page format " + pageFormat); printerJob.setPrintable(textarea.getPainter(), pageFormat); } else { printerJob.setPrintable(textarea.getPainter()); } // set the name of the job to the code name printerJob.setJobName(sketch.current.name); if (printerJob.printDialog()) { try { printerJob.print(); message("Done printing."); } catch (PrinterException pe) { error("Error while printing."); pe.printStackTrace(); } } else { message("Printing canceled."); } //printerJob = null; // clear this out? } /** * Quit, but first ask user if it's ok. Also store preferences * to disk just in case they want to quit. Final exit() happens * in Editor since it has the callback from EditorStatus. */ public void handleQuitInternal() { // doStop() isn't sufficient with external vm & quit // instead use doClose() which will kill the external vm if(this.gadgetPanel.getActiveGadget() != null){ this.gadgetPanel.saveCurrentGadget(); } doClose(); checkModified(HANDLE_QUIT); } /** * Method for the MRJQuitHandler, needs to be dealt with differently * than the regular handler because OS X has an annoying implementation * <A HREF="http://developer.apple.com/qa/qa2001/qa1187.html">quirk</A> * that requires an exception to be thrown in order to properly cancel * a quit message. */ public void handleQuit() { SwingUtilities.invokeLater(new Runnable() { public void run() { handleQuitInternal(); } }); // Throw IllegalStateException so new thread can execute. // If showing dialog on this thread in 10.2, we would throw // upon JOptionPane.NO_OPTION throw new IllegalStateException("Quit Pending User Confirmation"); } /** * Actually do the quit action. */ protected void handleQuit2() { handleSave2(); storePreferences(); Preferences.save(); sketchbook.clean(); console.handleQuit(); //System.out.println("exiting here"); System.exit(0); } protected void handleReference() { String text = textarea.getSelectedText().trim(); if (text.length() == 0) { message("First select a word to find in the reference."); } else { String referenceFile = PdeKeywords.getReference(text); //System.out.println("reference file is " + referenceFile); if (referenceFile == null) { message("No reference available for \"" + text + "\""); } else { Base.showReference(referenceFile + ".html"); } } } protected void handleBurnBootloader(final String programmer) { if(debugging) doStop(); console.clear(); message("Burning bootloader to I/O Board (this may take a minute)..."); SwingUtilities.invokeLater(new Runnable() { public void run() { try { Uploader uploader = new AvrdudeUploader(); if (uploader.burnBootloader(programmer)) { message("Done burning bootloader."); } else { // error message will already be visible } } catch (RunnerException e) { message("Error while burning bootloader."); //e.printStackTrace(); error(e); } catch (Exception e) { e.printStackTrace(); } buttons.clear(); }}); } public void highlightLine(int lnum) { if (lnum < 0) { textarea.select(0, 0); return; } //System.out.println(lnum); String s = textarea.getText(); int len = s.length(); int st = -1; int ii = 0; int end = -1; int lc = 0; if (lnum == 0) st = 0; for (int i = 0; i < len; i++) { ii++; //if ((s.charAt(i) == '\n') || (s.charAt(i) == '\r')) { boolean newline = false; if (s.charAt(i) == '\r') { if ((i != len-1) && (s.charAt(i+1) == '\n')) { i++; //ii--; } lc++; newline = true; } else if (s.charAt(i) == '\n') { lc++; newline = true; } if (newline) { if (lc == lnum) st = ii; else if (lc == lnum+1) { //end = ii; // to avoid selecting entire, because doing so puts the // cursor on the next line [0090] end = ii - 1; break; } } } if (end == -1) end = len; // sometimes KJC claims that the line it found an error in is // the last line in the file + 1. Just highlight the last line // in this case. [dmose] if (st == -1) st = len; textarea.select(st, end); } // ................................................................... /** * Show an error int the status bar. */ public void error(String what) { status.error(what); } public void error(Exception e) { if (e == null) { System.err.println("Editor.error() was passed a null exception."); return; } // not sure if any RuntimeExceptions will actually arrive // through here, but gonna check for em just in case. String mess = e.getMessage(); if (mess != null) { String rxString = "RuntimeException: "; if (mess.indexOf(rxString) == 0) { mess = mess.substring(rxString.length()); } String javaLang = "java.lang."; if (mess.indexOf(javaLang) == 0) { mess = mess.substring(javaLang.length()); } error(mess); } e.printStackTrace(); } public void error(RunnerException e) { //System.out.println("file and line is " + e.file + " " + e.line); if (e.file >= 0) sketch.setCurrent(e.file); if (e.line >= 0) highlightLine(e.line); // remove the RuntimeException: message since it's not // really all that useful to the user //status.error(e.getMessage()); String mess = e.getMessage(); String rxString = "RuntimeException: "; if (mess.indexOf(rxString) == 0) { mess = mess.substring(rxString.length()); //System.out.println("MESS3: " + mess); } String javaLang = "java.lang."; if (mess.indexOf(javaLang) == 0) { mess = mess.substring(javaLang.length()); } error(mess); buttons.clear(); } public void message(String msg) { status.notice(msg); } // ................................................................... /** * Returns the edit popup menu. */ class TextAreaPopup extends JPopupMenu { //String currentDir = System.getProperty("user.dir"); String referenceFile = null; JMenuItem cutItem, copyItem; JMenuItem referenceItem; public TextAreaPopup() { JMenuItem item; cutItem = new JMenuItem("Cut"); cutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.cut(); sketch.setModified(true); } }); this.add(cutItem); copyItem = new JMenuItem("Copy"); copyItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.copy(); } }); this.add(copyItem); item = new JMenuItem("Paste"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.paste(); sketch.setModified(true); } }); this.add(item); item = new JMenuItem("Select All"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.selectAll(); } }); this.add(item); this.addSeparator(); referenceItem = new JMenuItem("Find in Reference"); referenceItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //Base.showReference(referenceFile + ".html"); handleReference(); //textarea.getSelectedText()); } }); this.add(referenceItem); } // if no text is selected, disable copy and cut menu items public void show(Component component, int x, int y) { if (textarea.isSelectionActive()) { cutItem.setEnabled(true); copyItem.setEnabled(true); String sel = textarea.getSelectedText().trim(); referenceFile = PdeKeywords.getReference(sel); referenceItem.setEnabled(referenceFile != null); } else { cutItem.setEnabled(false); copyItem.setEnabled(false); referenceItem.setEnabled(false); } super.show(component, x, y); } } public void onActiveGadgetChanged(ActiveGadgetObject obj){ this.gadgetPanel.saveCurrentGadget(); if(gadgetPanel.getActiveModule() != null && gadgetPanel.getActiveGadget() != null){ //this.handleSave(true); File sketchFile = obj.getSketch(); File boardFile = obj.getBoards(); this.handleOpen(sketchFile.getPath()); String board = gadgetPanel.getActiveModule().getTarget(); this.curBoard = board; Preferences.set("board", board); Preferences.save(); Preferences.init(); this.repaint(); }else if(gadgetPanel.getActiveGadget() == null){ this.setVisible(true); } System.out.println("repainting header"); this.header.paint(getGraphics()); } /* * Creates a back up of the current boards.txt file and returns the renamed file * */ private File backUpBoardsFile(){ String boardFile = System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "boards.txt"; System.out.println(boardFile); this.originalBoardsFile = new File(boardFile); this.newBoardsFile = new File(originalBoardsFile.getPath() + ".bak"); originalBoardsFile.renameTo(newBoardsFile); return newBoardsFile; } private void RestoreBoardsFile(){ if(newBoardsFile != null){ File boardsFileToRestore = new File(newBoardsFile.getPath() + ".bak"); boardsFileToRestore.renameTo(boardsFileToRestore); } } private File writeBoardsToStandardLocation(File boardsFile){ File originalBoards = new File(System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "boards.txt"); String path = originalBoards.getPath(); originalBoards.delete(); File copyFile = new File(path); try{ copyFile.createNewFile(); FileReader in = new FileReader(boardsFile); FileWriter out = new FileWriter(copyFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }catch(Exception ex){ ex.printStackTrace(); } Preferences.init(); this.buildToolsMenu(); return copyFile; } private void importBoardsFile(File boardsFile, String target){ String boardExists = Preferences.get("boards." + target + ".build.core"); String originalBoardsFile = System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "boards.txt"; if(boardExists != null && boardExists.length() > 0){ //don't do anything? }else{ String originalBoards = getContents(new File(originalBoardsFile)); String importedBoards = getContents(boardsFile); originalBoards = originalBoards.concat("##############################################################"); originalBoards = originalBoards.concat("\r\n"); originalBoards = originalBoards.concat(importedBoards); try { this.setContents(new File(originalBoardsFile), originalBoards); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public String getContents(File aFile) { //...checks on aFile are elided StringBuffer contents = new StringBuffer(); try { //use buffering, reading one line at a time //FileReader always assumes default encoding is OK! BufferedReader input = new BufferedReader(new FileReader(aFile)); try { String line = null; //not declared within while loop /* * readLine is a bit quirky : * it returns the content of a line MINUS the newline. * it returns null only for the END of the stream. * it returns an empty String if two newlines appear in a row. */ while (( line = input.readLine()) != null){ contents.append(line); contents.append(System.getProperty("line.separator")); } } finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } return contents.toString(); } public void setContents(File aFile, String aContents) throws FileNotFoundException, IOException { if (aFile == null) { throw new IllegalArgumentException("File should not be null."); } if (!aFile.exists()) { throw new FileNotFoundException ("File does not exist: " + aFile); } if (!aFile.isFile()) { throw new IllegalArgumentException("Should not be a directory: " + aFile); } if (!aFile.canWrite()) { throw new IllegalArgumentException("File cannot be written: " + aFile); } //use buffering Writer output = new BufferedWriter(new FileWriter(aFile)); try { // System.out.print( aContents); output.write( aContents ); }finally { output.close(); } } private void loadGadget(IGadget gadget){ for(int i = 0; i < gadget.getModules().length; i++){ this.importModule(gadget.getModules()[i]); } //imageListPanel.setGadgetPanel(this.gadgetPanel); } private void importModule(IModule module){ String target = module.getTarget(); String boardExists = Preferences.get("boards." + target + ".build.core"); System.out.println(System.getProperty("user.dir")); if(boardExists == null || boardExists.length() == 0){ this.importBoardsFile(module.getBoardsFile(), target); String cpyDir = System.getProperty("user.dir") + File.separator + "hardware" + File.separator + "cores" + File.separator + target; module.copyCoreToDirectory(cpyDir); } } public void setImageListVisable(IModule module){ this.imageListPanel.setModule(module); //this.textarea.setVisible(true); CardLayout cl = ((CardLayout)this.centerPanel.getLayout()); cl.show(centerPanel, FILELIST); } private boolean saveSketches(){ boolean retVal = true; int correctSketch = sketch.currentIndex; for(int i = 0; i < sketch.code.length; i++){ try { sketch.setCurrent(i); sketch.save(); if(!retVal){ retVal = true; } } catch (IOException e) { retVal = false; e.printStackTrace(); } } sketch.setCurrent(correctSketch); return retVal; } }
diff --git a/nuxeo-theme-webengine/src/main/java/org/nuxeo/theme/webengine/fm/extensions/NXThemesHeadDirective.java b/nuxeo-theme-webengine/src/main/java/org/nuxeo/theme/webengine/fm/extensions/NXThemesHeadDirective.java index 92e45e7..abdc75d 100644 --- a/nuxeo-theme-webengine/src/main/java/org/nuxeo/theme/webengine/fm/extensions/NXThemesHeadDirective.java +++ b/nuxeo-theme-webengine/src/main/java/org/nuxeo/theme/webengine/fm/extensions/NXThemesHeadDirective.java @@ -1,77 +1,77 @@ /* * (C) Copyright 2006-2008 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: * Jean-Marc Orliaguet, Chalmers * * $Id$ */ package org.nuxeo.theme.webengine.fm.extensions; import java.io.IOException; import java.io.Writer; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.nuxeo.ecm.webengine.WebEngine; import org.nuxeo.ecm.webengine.model.WebContext; import org.nuxeo.theme.html.ui.Head; import org.nuxeo.theme.themes.ThemeManager; import freemarker.core.Environment; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; /** * @author <a href="mailto:[email protected]">Jean-Marc Orliaguet</a> * */ public class NXThemesHeadDirective implements TemplateDirectiveModel { @SuppressWarnings("unchecked") public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { if (!params.isEmpty()) { throw new TemplateModelException( "This directive doesn't allow parameters."); } if (loopVars.length != 0) { throw new TemplateModelException( "This directive doesn't allow loop variables."); } if (body != null) { throw new TemplateModelException("Didn't expect a body"); } Writer writer = env.getOut(); WebContext context = WebEngine.getActiveContext(); HttpServletRequest request = context.getRequest(); final URL themeUrl = (URL) request.getAttribute("org.nuxeo.theme.url"); Map<String, String> attributes = new HashMap<String, String>(); attributes.put("themeName", ThemeManager.getThemeNameByUrl(themeUrl)); attributes.put("path", context.getModulePath()); - attributes.put("baseUrl", context.getModulePath()); + attributes.put("baseUrl", context.getHead().getURL()); writer.write(Head.render(attributes)); } }
true
true
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { if (!params.isEmpty()) { throw new TemplateModelException( "This directive doesn't allow parameters."); } if (loopVars.length != 0) { throw new TemplateModelException( "This directive doesn't allow loop variables."); } if (body != null) { throw new TemplateModelException("Didn't expect a body"); } Writer writer = env.getOut(); WebContext context = WebEngine.getActiveContext(); HttpServletRequest request = context.getRequest(); final URL themeUrl = (URL) request.getAttribute("org.nuxeo.theme.url"); Map<String, String> attributes = new HashMap<String, String>(); attributes.put("themeName", ThemeManager.getThemeNameByUrl(themeUrl)); attributes.put("path", context.getModulePath()); attributes.put("baseUrl", context.getModulePath()); writer.write(Head.render(attributes)); }
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { if (!params.isEmpty()) { throw new TemplateModelException( "This directive doesn't allow parameters."); } if (loopVars.length != 0) { throw new TemplateModelException( "This directive doesn't allow loop variables."); } if (body != null) { throw new TemplateModelException("Didn't expect a body"); } Writer writer = env.getOut(); WebContext context = WebEngine.getActiveContext(); HttpServletRequest request = context.getRequest(); final URL themeUrl = (URL) request.getAttribute("org.nuxeo.theme.url"); Map<String, String> attributes = new HashMap<String, String>(); attributes.put("themeName", ThemeManager.getThemeNameByUrl(themeUrl)); attributes.put("path", context.getModulePath()); attributes.put("baseUrl", context.getHead().getURL()); writer.write(Head.render(attributes)); }
diff --git a/tool/src/java/org/sakaiproject/assignment2/tool/producers/renderers/AsnnSubmissionVersionRenderer.java b/tool/src/java/org/sakaiproject/assignment2/tool/producers/renderers/AsnnSubmissionVersionRenderer.java index 3fc83235..15a4d5f3 100644 --- a/tool/src/java/org/sakaiproject/assignment2/tool/producers/renderers/AsnnSubmissionVersionRenderer.java +++ b/tool/src/java/org/sakaiproject/assignment2/tool/producers/renderers/AsnnSubmissionVersionRenderer.java @@ -1,129 +1,137 @@ package org.sakaiproject.assignment2.tool.producers.renderers; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.assignment2.model.Assignment2; import org.sakaiproject.assignment2.model.AssignmentSubmission; import org.sakaiproject.assignment2.model.AssignmentSubmissionVersion; import org.sakaiproject.assignment2.model.constants.AssignmentConstants; import uk.org.ponder.rsf.components.UIContainer; import uk.org.ponder.rsf.components.UIJointContainer; import uk.org.ponder.rsf.components.UIMessage; import uk.org.ponder.rsf.components.UIVerbatim; import uk.org.ponder.rsf.producers.BasicProducer; import uk.org.ponder.rsf.viewstate.ViewParameters; /** * Renders a single submission version from a Student. You'll see this on the * Student View Assn Details page, or as part of an aggregated drop down when * there are multiple submissions. It includes the title, student name, * submission date, and then the text/attachments of the submission. * * If there is feedback from the Instructor for this version that will be * rendered as well. * * * @author sgithens * */ public class AsnnSubmissionVersionRenderer implements BasicProducer { private static Log log = LogFactory.getLog(AsnnSubmissionVersionRenderer.class); // Dependency private ViewParameters viewParameters; public void setViewParameters(ViewParameters viewParameters) { this.viewParameters = viewParameters; } // Dependency private AttachmentListRenderer attachmentListRenderer; public void setAttachmentListRenderer (AttachmentListRenderer attachmentListRenderer) { this.attachmentListRenderer = attachmentListRenderer; } /** * Renders the Submission Version in the parent container in element with * the client id. Returns the new UIContainer that holds this rendered * version. * * @param parent * @param clientID * @param asnnSubVersion * @param multipleVersionDisplay true if this version is being displayed in a multi-version scenario. * this will prevent unnecessary repeated headers * @param singleVersionDisplay - true if being used in the context of a single * version. the heading information is different for multi-version display (ie the history) * @return */ public UIContainer fillComponents(UIContainer parent, String clientID, AssignmentSubmissionVersion asnnSubVersion, boolean multipleVersionDisplay) { UIJointContainer joint = new UIJointContainer(parent, clientID, "asnn2-submission-version-widget:"); AssignmentSubmission assignmentSubmssion = asnnSubVersion.getAssignmentSubmission(); Assignment2 assignment = assignmentSubmssion.getAssignment(); int submissionType = assignment.getSubmissionType(); /* * Render the headers */ if (!multipleVersionDisplay) { UIMessage.make(joint, "submission-header", "assignment2.student-submission.submission.header"); } //TODO FIXME time and date of submission here /* * Render the Students Submission Materials * These are not displayed if the version number is 0 - this indicates * feedback without a submission */ if (asnnSubVersion.getSubmittedVersionNumber() != 0) { if (submissionType == AssignmentConstants.SUBMIT_ATTACH_ONLY || submissionType == AssignmentConstants.SUBMIT_INLINE_AND_ATTACH) { // TODO FIXME if the student didn't actually submit any attachments // what should we say UIMessage.make(joint, "submission-attachments-header", "assignment2.student-submit.submitted_attachments"); if (asnnSubVersion.getSubmissionAttachSet() != null && !asnnSubVersion.getSubmissionAttachSet().isEmpty()){ attachmentListRenderer.makeAttachmentFromSubmissionAttachmentSet(joint, "submission-attachment-list:", viewParameters.viewID, asnnSubVersion.getSubmissionAttachSet()); } else { UIMessage.make(joint, "no_submitted_attachments", "assignment2.student-submit.no_attachments_submitted"); } } - if (submissionType == AssignmentConstants.SUBMIT_INLINE_AND_ATTACH || submissionType == AssignmentConstants.SUBMIT_INLINE_ONLY) { - UIMessage.make(joint, "submission-text-header", "assignment2.student-submit.submission_text"); - UIVerbatim.make(joint, "submission-text", asnnSubVersion.getSubmittedText()); + if (submissionType == AssignmentConstants.SUBMIT_INLINE_AND_ATTACH || + submissionType == AssignmentConstants.SUBMIT_INLINE_ONLY) { + // if feedback is released, we display the submitted text with + // instructor annotations + if (asnnSubVersion.isFeedbackReleased()) { + UIMessage.make(joint, "submission-text-header", "assignment2.student-submit.submission_text.annotated"); + UIVerbatim.make(joint, "submission-text", asnnSubVersion.getAnnotatedText()); + } else { + UIMessage.make(joint, "submission-text-header", "assignment2.student-submit.submission_text"); + UIVerbatim.make(joint, "submission-text", asnnSubVersion.getSubmittedText()); + } } } /* * Render the Instructor's Feedback Materials */ if (asnnSubVersion.isFeedbackReleased()) { UIMessage.make(joint, "feedback-header", "assignment2.student-submission.feedback.header"); String feedbackText = asnnSubVersion.getFeedbackNotes(); if (feedbackText != null && feedbackText.trim().length() > 0) { UIVerbatim.make(joint, "feedback-text", asnnSubVersion.getFeedbackNotes()); } else { UIMessage.make(joint, "feedback-text", "assignment2.student-submission.feedback.none"); } if (asnnSubVersion.getFeedbackAttachSet() != null && asnnSubVersion.getFeedbackAttachSet().size() > 0) { UIMessage.make(joint, "feedback-attachments-header", "assignment2.student-submission.feedback.materials.header"); attachmentListRenderer.makeAttachmentFromFeedbackAttachmentSet(joint, "feedback-attachment-list:", viewParameters.viewID, asnnSubVersion.getFeedbackAttachSet()); } } return joint; } public void fillComponents(UIContainer parent, String clientID) { } }
true
true
public UIContainer fillComponents(UIContainer parent, String clientID, AssignmentSubmissionVersion asnnSubVersion, boolean multipleVersionDisplay) { UIJointContainer joint = new UIJointContainer(parent, clientID, "asnn2-submission-version-widget:"); AssignmentSubmission assignmentSubmssion = asnnSubVersion.getAssignmentSubmission(); Assignment2 assignment = assignmentSubmssion.getAssignment(); int submissionType = assignment.getSubmissionType(); /* * Render the headers */ if (!multipleVersionDisplay) { UIMessage.make(joint, "submission-header", "assignment2.student-submission.submission.header"); } //TODO FIXME time and date of submission here /* * Render the Students Submission Materials * These are not displayed if the version number is 0 - this indicates * feedback without a submission */ if (asnnSubVersion.getSubmittedVersionNumber() != 0) { if (submissionType == AssignmentConstants.SUBMIT_ATTACH_ONLY || submissionType == AssignmentConstants.SUBMIT_INLINE_AND_ATTACH) { // TODO FIXME if the student didn't actually submit any attachments // what should we say UIMessage.make(joint, "submission-attachments-header", "assignment2.student-submit.submitted_attachments"); if (asnnSubVersion.getSubmissionAttachSet() != null && !asnnSubVersion.getSubmissionAttachSet().isEmpty()){ attachmentListRenderer.makeAttachmentFromSubmissionAttachmentSet(joint, "submission-attachment-list:", viewParameters.viewID, asnnSubVersion.getSubmissionAttachSet()); } else { UIMessage.make(joint, "no_submitted_attachments", "assignment2.student-submit.no_attachments_submitted"); } } if (submissionType == AssignmentConstants.SUBMIT_INLINE_AND_ATTACH || submissionType == AssignmentConstants.SUBMIT_INLINE_ONLY) { UIMessage.make(joint, "submission-text-header", "assignment2.student-submit.submission_text"); UIVerbatim.make(joint, "submission-text", asnnSubVersion.getSubmittedText()); } } /* * Render the Instructor's Feedback Materials */ if (asnnSubVersion.isFeedbackReleased()) { UIMessage.make(joint, "feedback-header", "assignment2.student-submission.feedback.header"); String feedbackText = asnnSubVersion.getFeedbackNotes(); if (feedbackText != null && feedbackText.trim().length() > 0) { UIVerbatim.make(joint, "feedback-text", asnnSubVersion.getFeedbackNotes()); } else { UIMessage.make(joint, "feedback-text", "assignment2.student-submission.feedback.none"); } if (asnnSubVersion.getFeedbackAttachSet() != null && asnnSubVersion.getFeedbackAttachSet().size() > 0) { UIMessage.make(joint, "feedback-attachments-header", "assignment2.student-submission.feedback.materials.header"); attachmentListRenderer.makeAttachmentFromFeedbackAttachmentSet(joint, "feedback-attachment-list:", viewParameters.viewID, asnnSubVersion.getFeedbackAttachSet()); } } return joint; }
public UIContainer fillComponents(UIContainer parent, String clientID, AssignmentSubmissionVersion asnnSubVersion, boolean multipleVersionDisplay) { UIJointContainer joint = new UIJointContainer(parent, clientID, "asnn2-submission-version-widget:"); AssignmentSubmission assignmentSubmssion = asnnSubVersion.getAssignmentSubmission(); Assignment2 assignment = assignmentSubmssion.getAssignment(); int submissionType = assignment.getSubmissionType(); /* * Render the headers */ if (!multipleVersionDisplay) { UIMessage.make(joint, "submission-header", "assignment2.student-submission.submission.header"); } //TODO FIXME time and date of submission here /* * Render the Students Submission Materials * These are not displayed if the version number is 0 - this indicates * feedback without a submission */ if (asnnSubVersion.getSubmittedVersionNumber() != 0) { if (submissionType == AssignmentConstants.SUBMIT_ATTACH_ONLY || submissionType == AssignmentConstants.SUBMIT_INLINE_AND_ATTACH) { // TODO FIXME if the student didn't actually submit any attachments // what should we say UIMessage.make(joint, "submission-attachments-header", "assignment2.student-submit.submitted_attachments"); if (asnnSubVersion.getSubmissionAttachSet() != null && !asnnSubVersion.getSubmissionAttachSet().isEmpty()){ attachmentListRenderer.makeAttachmentFromSubmissionAttachmentSet(joint, "submission-attachment-list:", viewParameters.viewID, asnnSubVersion.getSubmissionAttachSet()); } else { UIMessage.make(joint, "no_submitted_attachments", "assignment2.student-submit.no_attachments_submitted"); } } if (submissionType == AssignmentConstants.SUBMIT_INLINE_AND_ATTACH || submissionType == AssignmentConstants.SUBMIT_INLINE_ONLY) { // if feedback is released, we display the submitted text with // instructor annotations if (asnnSubVersion.isFeedbackReleased()) { UIMessage.make(joint, "submission-text-header", "assignment2.student-submit.submission_text.annotated"); UIVerbatim.make(joint, "submission-text", asnnSubVersion.getAnnotatedText()); } else { UIMessage.make(joint, "submission-text-header", "assignment2.student-submit.submission_text"); UIVerbatim.make(joint, "submission-text", asnnSubVersion.getSubmittedText()); } } } /* * Render the Instructor's Feedback Materials */ if (asnnSubVersion.isFeedbackReleased()) { UIMessage.make(joint, "feedback-header", "assignment2.student-submission.feedback.header"); String feedbackText = asnnSubVersion.getFeedbackNotes(); if (feedbackText != null && feedbackText.trim().length() > 0) { UIVerbatim.make(joint, "feedback-text", asnnSubVersion.getFeedbackNotes()); } else { UIMessage.make(joint, "feedback-text", "assignment2.student-submission.feedback.none"); } if (asnnSubVersion.getFeedbackAttachSet() != null && asnnSubVersion.getFeedbackAttachSet().size() > 0) { UIMessage.make(joint, "feedback-attachments-header", "assignment2.student-submission.feedback.materials.header"); attachmentListRenderer.makeAttachmentFromFeedbackAttachmentSet(joint, "feedback-attachment-list:", viewParameters.viewID, asnnSubVersion.getFeedbackAttachSet()); } } return joint; }
diff --git a/src/com/orangeleap/tangerine/web/common/TangerineCustomDateEditor.java b/src/com/orangeleap/tangerine/web/common/TangerineCustomDateEditor.java index 8f7acee8..f7b5f106 100644 --- a/src/com/orangeleap/tangerine/web/common/TangerineCustomDateEditor.java +++ b/src/com/orangeleap/tangerine/web/common/TangerineCustomDateEditor.java @@ -1,65 +1,65 @@ package com.orangeleap.tangerine.web.common; import org.springframework.beans.propertyeditors.CustomDateEditor; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; import java.util.Date; import java.util.Calendar; /** * Extend the normal CustomDateEditor to know how to deal with * seasonal dates, which are just specified as Month-Day, without * a year. Will correctly parse a standard date format (MM/dd/yyyy) * along with dates that are just MMMMM-d format. Will add the current * year as the year component, unless that date would fall earlier * than current date, which means Date is for next year. * @version 1.0 */ public class TangerineCustomDateEditor extends CustomDateEditor { private DateFormat alternateDateFormat = new SimpleDateFormat("MMMMM-d"); public TangerineCustomDateEditor(DateFormat dateFormat, boolean allowEmpty) { super(dateFormat, allowEmpty); } public TangerineCustomDateEditor(DateFormat dateFormat, boolean allowEmpty, int exactDateLength) { super(dateFormat, allowEmpty, exactDateLength); } @Override public void setAsText(String text) throws IllegalArgumentException { try { super.setAsText(text); } catch(IllegalArgumentException ex) { try { // need to add a year component if Date d = this.alternateDateFormat.parse(text); Calendar now = Calendar.getInstance(); int year = now.get(Calendar.YEAR); Calendar c = Calendar.getInstance(); c.setTime(d); c.set(Calendar.YEAR, year); // if the date is before current date, assume it is next year - if(c.before(now)) { + if(c.get(Calendar.DAY_OF_YEAR) < now.get(Calendar.DAY_OF_YEAR)) { c.set(Calendar.YEAR, year+1); } setValue(c.getTime()); } catch (ParseException parseEx) { IllegalArgumentException iae = new IllegalArgumentException("Could not parse date: " + parseEx.getMessage()); iae.initCause(parseEx); throw iae; } } } }
true
true
public void setAsText(String text) throws IllegalArgumentException { try { super.setAsText(text); } catch(IllegalArgumentException ex) { try { // need to add a year component if Date d = this.alternateDateFormat.parse(text); Calendar now = Calendar.getInstance(); int year = now.get(Calendar.YEAR); Calendar c = Calendar.getInstance(); c.setTime(d); c.set(Calendar.YEAR, year); // if the date is before current date, assume it is next year if(c.before(now)) { c.set(Calendar.YEAR, year+1); } setValue(c.getTime()); } catch (ParseException parseEx) { IllegalArgumentException iae = new IllegalArgumentException("Could not parse date: " + parseEx.getMessage()); iae.initCause(parseEx); throw iae; } } }
public void setAsText(String text) throws IllegalArgumentException { try { super.setAsText(text); } catch(IllegalArgumentException ex) { try { // need to add a year component if Date d = this.alternateDateFormat.parse(text); Calendar now = Calendar.getInstance(); int year = now.get(Calendar.YEAR); Calendar c = Calendar.getInstance(); c.setTime(d); c.set(Calendar.YEAR, year); // if the date is before current date, assume it is next year if(c.get(Calendar.DAY_OF_YEAR) < now.get(Calendar.DAY_OF_YEAR)) { c.set(Calendar.YEAR, year+1); } setValue(c.getTime()); } catch (ParseException parseEx) { IllegalArgumentException iae = new IllegalArgumentException("Could not parse date: " + parseEx.getMessage()); iae.initCause(parseEx); throw iae; } } }
diff --git a/OS/src/edu/uw/cs/cse461/sp12/OS/RPCService.java b/OS/src/edu/uw/cs/cse461/sp12/OS/RPCService.java index 7c14a51..b1278d8 100644 --- a/OS/src/edu/uw/cs/cse461/sp12/OS/RPCService.java +++ b/OS/src/edu/uw/cs/cse461/sp12/OS/RPCService.java @@ -1,245 +1,251 @@ package edu.uw.cs.cse461.sp12.OS; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import edu.uw.cs.cse461.sp12.OS.RPCCallable.RPCCallableMethod; import edu.uw.cs.cse461.sp12.util.TCPMessageHandler; /** * Implements the side of RPC that receives remote invocation requests. * * @author zahorjan * */ public class RPCService extends RPCCallable { // used with the android idiom Log.x, as in Log.v(TAG, "some debug log message") public static final String TAG="RPCService"; private ServerSocket mServerSocket; private Thread connectionListener; private Map<String, RPCCallableMethod> callbacks; /** * This method must be implemented by RPCCallable's. * "rpc" is the well-known name of this service. */ @Override public String servicename() { return "rpc"; } /** * Constructor. Creates the Java ServerSocket and binds it to a port. * If the config file specifies an rpc.serverport value, it should be bound to that port. * Otherwise, you should specify port 0, meaning the operating system should choose a currently unused port. * (The config file settings are available via the OS object.) * <p> * Once the port is created, a thread needs to be created to listen for connections on it. * * @throws Exception */ RPCService() throws Exception { // Set some socket options. // setReuseAddress lets you reuse a server port immediately after terminating // an application that has used it. (Normally that port is unavailable for a while, for reasons we'll see // later in the course. // setSoTimeout causes a thread waiting for connections to timeout, instead of waiting forever, if no connection // is made before the timeout interval expires. (You don't have to use 1/2 sec. for this value - choose your own.) String port = OS.config().getProperty("rpc.serverport"); if(port != null && port.length() > 0) mServerSocket = new ServerSocket(Integer.parseInt(port)); else{ mServerSocket = new ServerSocket(0); } mServerSocket.setReuseAddress(true); // allow port number to be reused immediately after close of this socket mServerSocket.setSoTimeout(500); // well, we have to wake up every once and a while to check for program termination callbacks = new HashMap<String, RPCCallableMethod>(); ServerConnection newConnection = new ServerConnection(mServerSocket, callbacks); connectionListener = new Thread(newConnection); connectionListener.start(); //TODO: implement } /** * System is shutting down imminently. Do any cleanup required. */ public void shutdown() { try { mServerSocket.close(); } catch (IOException e) {} } public Map<String, RPCCallableMethod> getHandlers() { return Collections.unmodifiableMap(callbacks); } /** * Services and applications with RPC callable methods register them with the RPC service using this routine. * Those methods are then invoked as callbacks when an remote RPC request for them arrives. * @param serviceName The name of the service. * @param methodName The external, well-known name of the service's method to call * @param method The descriptor allowing invocation of the Java method implementing the call * @throws Exception */ public synchronized void registerHandler(String serviceName, String methodName, RPCCallableMethod method) throws Exception { //TODO: implement callbacks.put(serviceName + methodName, method); } /** * Returns the local IP address. * @return * @throws UnknownHostException */ public String localIP() throws UnknownHostException { return InetAddress.getLocalHost().getHostAddress(); } /** * Returns the port to which the RPC ServerSocket is bound. * @return */ public int localPort() { return mServerSocket.getLocalPort(); } /** * Manages a single user's connection to the server / back end logic */ private class ServerConnection implements Runnable { private ServerSocket connection; public ServerConnection(ServerSocket connection, Map<String, RPCCallableMethod> callbacks) { this.connection = connection; } @Override public void run() { // TODO Auto-generated method stub while(!connection.isClosed()) { try { Socket newUser = connection.accept(); UserConnection thread = new UserConnection(newUser, callbacks); thread.run(); } catch (IOException e) {} } } } private class UserConnection implements Runnable { private Socket user; private TCPMessageHandler handler; private boolean listening; private boolean handshook; private int id; public UserConnection(Socket user, Map<String, RPCCallableMethod> callbacks) throws IOException { System.out.println("connection made"); handler = new TCPMessageHandler(user); listening = true; handshook = false; id = 1; this.user = user; } @Override public void run() { // TODO Auto-generated method stub while(!user.isClosed()) { try { parseMessage(handler.readMessageAsJSONObject()); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); break; } } } public void parseMessage(JSONObject json) throws Exception{ if(!handshook){ try { if(json.getString("action").equals("connect")){ JSONObject reply = new JSONObject(); reply.put("id", id); reply.put("host", ""); reply.put("callid", json.getInt("id")); reply.put("type", "OK"); handler.sendMessage(reply); id++; handshook = true; } } catch (JSONException e) { //didn't contain the key "action" JSONObject error = new JSONObject(); error.put("id", id); error.put("host", ""); error.put("callid", json.getInt("id")); error.put("type", "ERROR"); error.put("message", "handshake message malformed"); handler.sendMessage(error); id++; } }else { try { if(json.getString("type").equals("invoke")) { String key = ""; key += json.getString("app") + json.getString("method"); - handler.sendMessage(callbacks.get(key).handleCall(json)); + JSONObject reply = new JSONObject(); + reply.put("value", callbacks.get(key).handleCall(json.getJSONObject("args"))); + reply.put("id", id); + reply.put("host", ""); + reply.put("callid", json.get("id")); + reply.put("type", "OK"); + handler.sendMessage(reply); id++; } } catch (JSONException e) { JSONObject error = new JSONObject(); error.put("id", id); error.put("host", ""); error.put("callid", json.getInt("id")); error.put("type", "ERROR"); error.put("message", "message malformed"); JSONObject copy = new JSONObject(); JSONArray names = json.names(); for ( int i=0; i<names.length(); i++ ) { String key = (String)names.getString(i); copy.put(key, json.getString(key)); } error.put("callargs", copy); handler.sendMessage(error); id++; } catch (NullPointerException e) { JSONObject error = new JSONObject(); error.put("id", id); error.put("host", ""); error.put("callid", json.getInt("id")); error.put("type", "ERROR"); error.put("message", "method not found"); JSONObject copy = new JSONObject(); JSONArray names = json.names(); for ( int i=0; i<names.length(); i++ ) { String key = (String)names.getString(i); copy.put(key, json.getString(key)); } error.put("callargs", copy); handler.sendMessage(error); id++; } } } } }
true
true
public void parseMessage(JSONObject json) throws Exception{ if(!handshook){ try { if(json.getString("action").equals("connect")){ JSONObject reply = new JSONObject(); reply.put("id", id); reply.put("host", ""); reply.put("callid", json.getInt("id")); reply.put("type", "OK"); handler.sendMessage(reply); id++; handshook = true; } } catch (JSONException e) { //didn't contain the key "action" JSONObject error = new JSONObject(); error.put("id", id); error.put("host", ""); error.put("callid", json.getInt("id")); error.put("type", "ERROR"); error.put("message", "handshake message malformed"); handler.sendMessage(error); id++; } }else { try { if(json.getString("type").equals("invoke")) { String key = ""; key += json.getString("app") + json.getString("method"); handler.sendMessage(callbacks.get(key).handleCall(json)); id++; } } catch (JSONException e) { JSONObject error = new JSONObject(); error.put("id", id); error.put("host", ""); error.put("callid", json.getInt("id")); error.put("type", "ERROR"); error.put("message", "message malformed"); JSONObject copy = new JSONObject(); JSONArray names = json.names(); for ( int i=0; i<names.length(); i++ ) { String key = (String)names.getString(i); copy.put(key, json.getString(key)); } error.put("callargs", copy); handler.sendMessage(error); id++; } catch (NullPointerException e) { JSONObject error = new JSONObject(); error.put("id", id); error.put("host", ""); error.put("callid", json.getInt("id")); error.put("type", "ERROR"); error.put("message", "method not found"); JSONObject copy = new JSONObject(); JSONArray names = json.names(); for ( int i=0; i<names.length(); i++ ) { String key = (String)names.getString(i); copy.put(key, json.getString(key)); } error.put("callargs", copy); handler.sendMessage(error); id++; } } }
public void parseMessage(JSONObject json) throws Exception{ if(!handshook){ try { if(json.getString("action").equals("connect")){ JSONObject reply = new JSONObject(); reply.put("id", id); reply.put("host", ""); reply.put("callid", json.getInt("id")); reply.put("type", "OK"); handler.sendMessage(reply); id++; handshook = true; } } catch (JSONException e) { //didn't contain the key "action" JSONObject error = new JSONObject(); error.put("id", id); error.put("host", ""); error.put("callid", json.getInt("id")); error.put("type", "ERROR"); error.put("message", "handshake message malformed"); handler.sendMessage(error); id++; } }else { try { if(json.getString("type").equals("invoke")) { String key = ""; key += json.getString("app") + json.getString("method"); JSONObject reply = new JSONObject(); reply.put("value", callbacks.get(key).handleCall(json.getJSONObject("args"))); reply.put("id", id); reply.put("host", ""); reply.put("callid", json.get("id")); reply.put("type", "OK"); handler.sendMessage(reply); id++; } } catch (JSONException e) { JSONObject error = new JSONObject(); error.put("id", id); error.put("host", ""); error.put("callid", json.getInt("id")); error.put("type", "ERROR"); error.put("message", "message malformed"); JSONObject copy = new JSONObject(); JSONArray names = json.names(); for ( int i=0; i<names.length(); i++ ) { String key = (String)names.getString(i); copy.put(key, json.getString(key)); } error.put("callargs", copy); handler.sendMessage(error); id++; } catch (NullPointerException e) { JSONObject error = new JSONObject(); error.put("id", id); error.put("host", ""); error.put("callid", json.getInt("id")); error.put("type", "ERROR"); error.put("message", "method not found"); JSONObject copy = new JSONObject(); JSONArray names = json.names(); for ( int i=0; i<names.length(); i++ ) { String key = (String)names.getString(i); copy.put(key, json.getString(key)); } error.put("callargs", copy); handler.sendMessage(error); id++; } } }
diff --git a/trunk/src/webcamstudio/layout/Layout.java b/trunk/src/webcamstudio/layout/Layout.java index f510e51..0484e00 100644 --- a/trunk/src/webcamstudio/layout/Layout.java +++ b/trunk/src/webcamstudio/layout/Layout.java @@ -1,319 +1,319 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package webcamstudio.layout; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.util.Collection; import java.util.logging.Level; import java.util.logging.Logger; import java.util.prefs.BackingStoreException; import webcamstudio.components.PulseAudioManager; import webcamstudio.layout.transitions.Transition; import webcamstudio.sources.*; import webcamstudio.studio.Studio; /** * * @author pballeux */ public class Layout { private java.util.TreeMap<Integer, LayoutItem> items = new java.util.TreeMap<Integer, LayoutItem>(); private String name = ""; private String layoutUUID = java.util.UUID.randomUUID().toString(); private String hotKey = ""; private boolean isActive = false; private boolean isEntering = false; private boolean isExiting = false; private static Layout activeLayout = null; public static Layout previousActiveLayout = null; private String inputSource = ""; private String inputSourceApp = ""; private int duration = 0; private String nextLayoutName = ""; public long timeStamp = 0; protected BufferedImage preview = null; public void setDuration(int sec, String nextLayout) { duration = sec; nextLayoutName = nextLayout; } public int getDuration() { return duration; } public String getNextLayout() { return nextLayoutName; } public void setAudioSource(String source) { inputSource = source; } public void setAudioApp(String app) { inputSourceApp = app; } public String getAudioSource() { return inputSource; } public String getAudioApp() { return inputSourceApp; } public static Layout getActiveLayout() { return activeLayout; } public Layout(String name) { this.name = name; } public boolean isActive() { return isActive; } public Layout() { } public String getHotKey() { return hotKey; } public void setHotKey(String key) { hotKey = key; } public void moveUpItem(LayoutItem item) { if (items.higherKey(item.getLayer()) != null) { int highKey = items.higherKey(item.getLayer()); LayoutItem hiItem = items.get(highKey); hiItem.setLayer(item.getLayer()); item.setLayer(highKey); items.remove(item.getLayer()); items.remove(hiItem.getLayer()); items.put(item.getLayer(), item); items.put(hiItem.getLayer(), hiItem); } } public void moveDownItem(LayoutItem item) { if (items.lowerKey(item.getLayer()) != null) { int loKey = items.lowerKey(item.getLayer()); LayoutItem loItem = items.get(loKey); loItem.setLayer(item.getLayer()); item.setLayer(loKey); items.remove(item.getLayer()); items.remove(loItem.getLayer()); items.put(item.getLayer(), item); items.put(loItem.getLayer(), loItem); } } public void setName(String name) { this.name = name; } public void enterLayout() { isEntering = true; if (previousActiveLayout != null) { previousActiveLayout.exitLayout(); } activeLayout = this; previousActiveLayout = activeLayout; if (inputSourceApp.length() > 0) { PulseAudioManager p = new PulseAudioManager(); p.setSoundInput(inputSourceApp, inputSource); } for (LayoutItem item : items.values()) { item.getSource().setLayer(item.getLayer()); } if (items.size() > 0) { java.util.concurrent.ExecutorService tp = java.util.concurrent.Executors.newFixedThreadPool(items.size()); for (LayoutItem item : items.values()) { item.setTransitionToDo(item.getTransitionIn()); item.setActive(true); tp.submit(item); } tp.shutdown(); try { while (!tp.isTerminated()) { Thread.sleep(100); } } catch (InterruptedException ex) { Logger.getLogger(Layout.class.getName()).log(Level.SEVERE, null, ex); } tp = null; } isEntering = false; isActive = true; } private void exitLayout() { isExiting = true; isActive = false; if (items.size() > 0) { java.util.concurrent.ExecutorService tp = java.util.concurrent.Executors.newFixedThreadPool(items.size()); for (LayoutItem item : items.values()) { item.setTransitionToDo(item.getTransitionOut()); item.setActive(false); tp.submit(item); } tp.shutdown(); try { while (!tp.isTerminated()) { Thread.sleep(100); } } catch (InterruptedException ex) { Logger.getLogger(Layout.class.getName()).log(Level.SEVERE, null, ex); } tp = null; } isExiting = false; } public Collection<LayoutItem> getItems() { return items.values(); } public Image getPreview(int w, int h) { if (preview == null || preview.getWidth() != w || preview.getHeight() != h) { preview = new java.awt.image.BufferedImage(w, h, java.awt.image.BufferedImage.TYPE_INT_ARGB); } Graphics2D buffer = preview.createGraphics(); buffer.setBackground(Color.GRAY); buffer.clearRect(0, 0, w, h); buffer.setStroke(new java.awt.BasicStroke(10f)); buffer.setColor(Color.BLACK); buffer.drawRect(0, 0, w, h); for (LayoutItem item : items.values()) { buffer.setColor(Color.WHITE); if (item.getSource() instanceof VideoSourceV4L || item.getSource() instanceof VideoSourceDV) { buffer.setColor(Color.RED); } else if (item.getSource() instanceof VideoSourceText) { buffer.setColor(Color.DARK_GRAY); } else if (item.getSource() instanceof VideoSourceWidget || item.getSource() instanceof VideoSourceAnimation) { buffer.setColor(Color.GREEN); } else if (item.getSource() instanceof VideoSourceMovie) { buffer.setColor(Color.BLUE); } else if (item.getSource() instanceof VideoSourceImage) { buffer.setColor(Color.YELLOW); } else if (item.getSource() instanceof VideoSourceDesktop) { buffer.setColor(Color.ORANGE); } if (item.getSource().getImage() != null) { buffer.drawImage(item.getSource().getImage(), item.getX(), item.getY(), item.getWidth() + item.getX(), item.getHeight() + item.getY(), 0, 0, item.getSource().getImage().getWidth(), item.getSource().getImage().getHeight(), null); } buffer.drawRect(item.getX(), item.getY(), item.getWidth(), item.getHeight()); } buffer.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, 0.5F)); buffer.setColor(Color.DARK_GRAY); - buffer.fillRect(0, 0, w, 34); + buffer.fillRect(0, 0, w, 17); if (isEntering) { buffer.setColor(Color.YELLOW); } else if (isExiting) { buffer.setColor(Color.RED); } else if (isActive) { buffer.setColor(Color.GREEN); } buffer.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, 1F)); - buffer.setFont(new Font("Monospaced", Font.BOLD, 30)); - buffer.drawString(name, 5,30); + buffer.setFont(new Font("Monospaced", Font.BOLD, 15)); + buffer.drawString(name, 5,15); buffer.dispose(); return preview; } public void removeSource(VideoSource source) { LayoutItem foundItem = null; for (LayoutItem item : items.values()) { if (item.getSource().getUUID().equals(source.getUUID())) { foundItem = item; } } if (foundItem != null) { items.remove(foundItem.getLayer()); } } public void updateSourceTransition(VideoSource source, Transition transIn, Transition transOut) { for (LayoutItem item : items.values()) { if (item.getSource().getUUID().equals(source.getUUID())) { item.setTransitionIn(transIn); item.setTransitionOut(transOut); } } } public void addSource(VideoSource source) { int index = 0; if (items.size() != 0) { index = items.lastKey() + 1; } VideoSource tempSource = source; if (VideoSource.loadedSources.containsKey(source.getLocation())) { tempSource = VideoSource.loadedSources.get(source.getLocation()); System.out.println("Same source" + source.getLocation()); } else { VideoSource.loadedSources.put(source.getLocation(), source); System.out.println("Not same source" + source.getLocation()); } LayoutItem item = new LayoutItem(tempSource, index); items.put(item.getLayer(), item); if (isActive) { item.getSource().setLayer(item.getLayer()); item.setActive(true); item.setTransitionToDo(item.getTransitionIn()); item.run(); } } public void applyStudioConfig(java.util.prefs.Preferences prefs, int order) { java.util.prefs.Preferences layout = prefs.node(Studio.getKeyIndex(order)); layout.put("name", name); layout.put("uuid", layoutUUID); layout.put("hotkey", hotKey); layout.put("inputsource", inputSource); layout.put("inputsourceapp", inputSourceApp); layout.putInt("duration", duration); layout.put("nextlayout", nextLayoutName); for (LayoutItem item : items.values()) { item.applyStudioConfig(layout.node("Items").node("" + item.getLayer())); } } public void loadFromStudioConfig(java.util.prefs.Preferences prefs) throws BackingStoreException { java.util.prefs.Preferences layout = prefs; name = layout.get("name", name); layoutUUID = layout.get("uuid", layoutUUID); hotKey = layout.get("hotkey", hotKey); inputSource = layout.get("inputsource", inputSource); inputSourceApp = layout.get("inputsourceapp", inputSourceApp); duration = layout.getInt("duration", duration); nextLayoutName = layout.get("nextlayout", nextLayoutName); String[] itemIndexes = layout.node("Items").childrenNames(); for (String itemIndex : itemIndexes) { LayoutItem item = new LayoutItem(null, 0); item.loadFromStudioConfig(layout.node("Items").node(itemIndex)); items.put(item.getLayer(), item); } } @Override public String toString() { return name; } }
false
true
public Image getPreview(int w, int h) { if (preview == null || preview.getWidth() != w || preview.getHeight() != h) { preview = new java.awt.image.BufferedImage(w, h, java.awt.image.BufferedImage.TYPE_INT_ARGB); } Graphics2D buffer = preview.createGraphics(); buffer.setBackground(Color.GRAY); buffer.clearRect(0, 0, w, h); buffer.setStroke(new java.awt.BasicStroke(10f)); buffer.setColor(Color.BLACK); buffer.drawRect(0, 0, w, h); for (LayoutItem item : items.values()) { buffer.setColor(Color.WHITE); if (item.getSource() instanceof VideoSourceV4L || item.getSource() instanceof VideoSourceDV) { buffer.setColor(Color.RED); } else if (item.getSource() instanceof VideoSourceText) { buffer.setColor(Color.DARK_GRAY); } else if (item.getSource() instanceof VideoSourceWidget || item.getSource() instanceof VideoSourceAnimation) { buffer.setColor(Color.GREEN); } else if (item.getSource() instanceof VideoSourceMovie) { buffer.setColor(Color.BLUE); } else if (item.getSource() instanceof VideoSourceImage) { buffer.setColor(Color.YELLOW); } else if (item.getSource() instanceof VideoSourceDesktop) { buffer.setColor(Color.ORANGE); } if (item.getSource().getImage() != null) { buffer.drawImage(item.getSource().getImage(), item.getX(), item.getY(), item.getWidth() + item.getX(), item.getHeight() + item.getY(), 0, 0, item.getSource().getImage().getWidth(), item.getSource().getImage().getHeight(), null); } buffer.drawRect(item.getX(), item.getY(), item.getWidth(), item.getHeight()); } buffer.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, 0.5F)); buffer.setColor(Color.DARK_GRAY); buffer.fillRect(0, 0, w, 34); if (isEntering) { buffer.setColor(Color.YELLOW); } else if (isExiting) { buffer.setColor(Color.RED); } else if (isActive) { buffer.setColor(Color.GREEN); } buffer.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, 1F)); buffer.setFont(new Font("Monospaced", Font.BOLD, 30)); buffer.drawString(name, 5,30); buffer.dispose(); return preview; }
public Image getPreview(int w, int h) { if (preview == null || preview.getWidth() != w || preview.getHeight() != h) { preview = new java.awt.image.BufferedImage(w, h, java.awt.image.BufferedImage.TYPE_INT_ARGB); } Graphics2D buffer = preview.createGraphics(); buffer.setBackground(Color.GRAY); buffer.clearRect(0, 0, w, h); buffer.setStroke(new java.awt.BasicStroke(10f)); buffer.setColor(Color.BLACK); buffer.drawRect(0, 0, w, h); for (LayoutItem item : items.values()) { buffer.setColor(Color.WHITE); if (item.getSource() instanceof VideoSourceV4L || item.getSource() instanceof VideoSourceDV) { buffer.setColor(Color.RED); } else if (item.getSource() instanceof VideoSourceText) { buffer.setColor(Color.DARK_GRAY); } else if (item.getSource() instanceof VideoSourceWidget || item.getSource() instanceof VideoSourceAnimation) { buffer.setColor(Color.GREEN); } else if (item.getSource() instanceof VideoSourceMovie) { buffer.setColor(Color.BLUE); } else if (item.getSource() instanceof VideoSourceImage) { buffer.setColor(Color.YELLOW); } else if (item.getSource() instanceof VideoSourceDesktop) { buffer.setColor(Color.ORANGE); } if (item.getSource().getImage() != null) { buffer.drawImage(item.getSource().getImage(), item.getX(), item.getY(), item.getWidth() + item.getX(), item.getHeight() + item.getY(), 0, 0, item.getSource().getImage().getWidth(), item.getSource().getImage().getHeight(), null); } buffer.drawRect(item.getX(), item.getY(), item.getWidth(), item.getHeight()); } buffer.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, 0.5F)); buffer.setColor(Color.DARK_GRAY); buffer.fillRect(0, 0, w, 17); if (isEntering) { buffer.setColor(Color.YELLOW); } else if (isExiting) { buffer.setColor(Color.RED); } else if (isActive) { buffer.setColor(Color.GREEN); } buffer.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, 1F)); buffer.setFont(new Font("Monospaced", Font.BOLD, 15)); buffer.drawString(name, 5,15); buffer.dispose(); return preview; }
diff --git a/org.xtest/src/org/xtest/interpreter/XTestInterpreter.java b/org.xtest/src/org/xtest/interpreter/XTestInterpreter.java index 28fa18b..f90f8dc 100644 --- a/org.xtest/src/org/xtest/interpreter/XTestInterpreter.java +++ b/org.xtest/src/org/xtest/interpreter/XTestInterpreter.java @@ -1,559 +1,560 @@ package org.xtest.interpreter; import java.lang.reflect.Array; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.concurrent.Callable; import org.eclipse.xtend.core.xtend.XtendFunction; import org.eclipse.xtend.core.xtend.XtendParameter; import org.eclipse.xtext.common.types.JvmDeclaredType; import org.eclipse.xtext.common.types.JvmExecutable; import org.eclipse.xtext.common.types.JvmOperation; import org.eclipse.xtext.common.types.JvmTypeReference; import org.eclipse.xtext.common.types.JvmVoid; import org.eclipse.xtext.common.types.access.impl.ClassFinder; import org.eclipse.xtext.common.types.util.TypeConformanceComputer; import org.eclipse.xtext.common.types.util.TypeReferences; import org.eclipse.xtext.naming.QualifiedName; import org.eclipse.xtext.util.CancelIndicator; import org.eclipse.xtext.xbase.XAssignment; import org.eclipse.xtext.xbase.XClosure; import org.eclipse.xtext.xbase.XExpression; import org.eclipse.xtext.xbase.XFeatureCall; import org.eclipse.xtext.xbase.XReturnExpression; import org.eclipse.xtext.xbase.interpreter.IEvaluationContext; import org.eclipse.xtext.xbase.interpreter.IEvaluationResult; import org.eclipse.xtext.xbase.interpreter.impl.DefaultEvaluationResult; import org.eclipse.xtext.xbase.interpreter.impl.EvaluationException; import org.eclipse.xtext.xbase.interpreter.impl.InterpreterCanceledException; import org.eclipse.xtext.xbase.interpreter.impl.XbaseInterpreter; import org.xtest.XTestAssertionFailure; import org.xtest.XTestEvaluationException; import org.xtest.XtestUtil; import org.xtest.jvmmodel.XtestJvmModelAssociator; import org.xtest.results.XTestResult; import org.xtest.results.XTestState; import org.xtest.xTest.Body; import org.xtest.xTest.UniqueName; import org.xtest.xTest.XAssertExpression; import org.xtest.xTest.XMethodDef; import org.xtest.xTest.XMethodDefExpression; import org.xtest.xTest.XSafeExpression; import org.xtest.xTest.XTestExpression; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.inject.Inject; /** * Xtest interpreter, inherits behavior from Xbase, but adds handling for running tests and keeps * track of the tests being run, returning the final root test * * @author Michael Barry */ @SuppressWarnings("restriction") public class XTestInterpreter extends XbaseInterpreter { @Inject private XtestJvmModelAssociator assocations; private final Stack<XExpression> callStack = new Stack<XExpression>(); // TODO move some of this stuff into custom context private final Set<XExpression> executedExpressions = Sets.newHashSet(); private int inSafeBlock = 0; private final Map<XtendFunction, IEvaluationContext> localMethodContexts = Maps.newHashMap(); private XTestResult result; private StackTraceElement[] startTrace = null; private final Stack<XTestResult> testStack = new Stack<XTestResult>(); @Inject private TypeConformanceComputer typeConformanceComputer; @Inject private TypeReferences typeReferences; @Override public IEvaluationResult evaluate(XExpression expression, IEvaluationContext context, CancelIndicator indicator) { try { IEvaluationResult evaluate; if (expression.eContainer() instanceof XClosure || expression.eContainer() instanceof XMethodDef) { evaluate = evaluateInsideOfClosure(expression, context, indicator); } else { startTrace = Thread.currentThread().getStackTrace(); evaluate = super.evaluate(expression, context, indicator); } return evaluate; } catch (ReturnValue e) { return new DefaultEvaluationResult(e.returnValue, null); } } /** * Returns the list of executed expressions * * @return The list of executed expressions */ public Set<XExpression> getExecutedExpressions() { return executedExpressions; } /** * Returns the test suite result after the tests have run * * @return The test result */ public XTestResult getTestResult() { return result; } /** * Evaluates an assert expression. Throws an {@link XTestAssertionFailure} if the assert does * not succeed * * @param assertExpression * The expression to evaluate * @param context * The evaluation context * @param indicator * The cancel indicator * @return null */ protected Object _evaluateAssertExpression(XAssertExpression assertExpression, IEvaluationContext context, CancelIndicator indicator) { XExpression resultExp = assertExpression.getActual(); JvmTypeReference expected = assertExpression.getThrows(); boolean returnVal = true; if (expected == null) { // normal assert Object result = internalEvaluate(resultExp, context, indicator); if (!(result instanceof Boolean) || !(Boolean) result) { handleAssertionFailure(assertExpression); returnVal = false; } } else { // assert exception try { internalEvaluate(resultExp, context, indicator); handleAssertionFailure(assertExpression); returnVal = false; } catch (XTestEvaluationException exception) { Throwable throwable = exception.getCause(); JvmTypeReference actual = typeReferences.getTypeForName(throwable.getClass(), assertExpression); if (!typeConformanceComputer.isConformant(expected, actual)) { throw new XTestAssertionFailure("Assertion failed"); } } } return returnVal; } @Override protected Object _evaluateAssignment(XAssignment assignment, IEvaluationContext context, CancelIndicator indicator) { if (assignment.getAssignable() instanceof XFeatureCall && assignment.getFeature() == null) { assignment.setFeature(((XFeatureCall) assignment.getAssignable()).getFeature()); } return super._evaluateAssignment(assignment, context, indicator); } /** * Evaluates the xtest script body. Catches any exceptions thrown. * * @param main * The main body to evaluate * @param context * The evaluation context * @param indicator * The cancel indicator * @return null */ protected Object _evaluateBody(Body main, IEvaluationContext context, CancelIndicator indicator) { if (result == null) { // In case this is called outside of the context of XtestDiagnostician result = new XTestResult(main); } testStack.push(result); Object toReturn = null; try { toReturn = super._evaluateBlockExpression(main, context, indicator); if (result.getState() != XTestState.FAIL) { result.pass(); } } catch (ReturnValue e) { toReturn = e.returnValue; result.pass(); } catch (XTestEvaluationException e) { result.addEvaluationException(e); } return toReturn; } /** * Evaluate a method definition. Store its context if local and return null (since methods are * void) * * @param method * The method * @param context * The context * @param indicator * The cancel indicator * @return Null */ protected Object _evaluateMethodDef(XMethodDefExpression method, IEvaluationContext context, CancelIndicator indicator) { if (!method.getMethod().isStatic()) { localMethodContexts.put(method.getMethod(), context); } return null; } @Override protected Object _evaluateReturnExpression(XReturnExpression returnExpr, IEvaluationContext context, CancelIndicator indicator) { // Need to reimplement xbase's return expression since I need to catch all exceptions and // handle return exception but I don't have access to package-protected ReturnValue Object returnValue = internalEvaluate(returnExpr.getExpression(), context, indicator); throw new ReturnValue(returnValue); } /** * Evaluates an expression inside an exception-safe block that marks exceptions in containing * tests but continues execution if an exception occurs * * @param expression * The expression to evaluate * @param context * The context of evaluation * @param indicator * The cancel indicator * @return The result of evaluation the expression, or null if exception was thrown */ protected Object _evaluateSafeExpression(XSafeExpression expression, IEvaluationContext context, CancelIndicator indicator) { XExpression actual = expression.getActual(); inSafeBlock++; Object result = null; try { result = actual == null ? null : internalEvaluate(actual, context, indicator); } finally { inSafeBlock--; } return result; } /** * Evaluates the test. Catches any evaluation exceptions thrown and adds them to the test. * * @param test * The test to evaluate * @param context * The evaluation context * @param indicator * The cancel indicator * @return null */ protected Object _evaluateTestExpression(XTestExpression test, IEvaluationContext context, CancelIndicator indicator) { UniqueName name = test.getName(); String nameStr = getName(name, test, context, indicator); XExpression expression = test.getExpression(); XTestResult peek = testStack.peek(); XTestResult subTest = peek.subTest(nameStr, test); testStack.push(subTest); try { internalEvaluate(expression, context, indicator); if (subTest.getState() != XTestState.FAIL) { subTest.pass(); } } catch (ReturnValue e) { subTest.pass(); } catch (XTestEvaluationException e) { subTest.addEvaluationException(e); } testStack.pop(); return null; } /** * Handles a feature call to retrieve the class of a class * * @param jvmVoid * Void because feature is null in this case * @param featureCall * The feature call expression * @param receiver * The receiver, null in this case * @param context * The context * @param indicator * The cancellation indicator * @return The class of the declared type from {@code featureCall} */ protected Object _featureCallVoid(JvmVoid jvmVoid, XFeatureCall featureCall, Object receiver, IEvaluationContext context, CancelIndicator indicator) { JvmDeclaredType declaringType = featureCall.getDeclaringType(); ClassFinder classFinder = getClassFinder(); Class<?> clazz = null; try { clazz = classFinder.forName(declaringType.getQualifiedName()); } catch (ClassNotFoundException e) { } return clazz; } @Override protected List<Object> evaluateArgumentExpressions(JvmExecutable executable, List<XExpression> expressions, IEvaluationContext context, CancelIndicator indicator) { // Same as XbaseInterpreter.evaluateArgumentExpressions() ... XMethodDef methodDef = assocations.getMethodDef(executable); List<Object> result; if (methodDef != null) { result = Lists.newArrayList(); int paramCount = executable.getParameters().size(); if (executable.isVarArgs()) { paramCount--; } for (int i = 0; i < paramCount; i++) { XExpression arg = expressions.get(i); Object argResult = internalEvaluate(arg, context, indicator); JvmTypeReference parameterType = executable.getParameters().get(i) .getParameterType(); Object argumentValue = coerceArgumentType(argResult, parameterType); result.add(argumentValue); } if (executable.isVarArgs()) { JvmTypeReference parameterType = methodDef.getParameters().get(paramCount) .getParameterType(); // ... except get the var-arg class from the XMethodDef Class<?> componentType = getJavaReflectAccess().getRawType(parameterType.getType()); // end diff if (expressions.size() == executable.getParameters().size()) { XExpression arg = expressions.get(paramCount); Object lastArgResult = internalEvaluate(arg, context, indicator); - if (componentType.isInstance(lastArgResult)) { + if (componentType.isInstance(lastArgResult) + && !lastArgResult.getClass().isArray()) { Object array = Array.newInstance(componentType, 1); Array.set(array, 0, lastArgResult); result.add(array); } else { result.add(lastArgResult); } } else { Object array = Array .newInstance(componentType, expressions.size() - paramCount); for (int i = paramCount; i < expressions.size(); i++) { XExpression arg = expressions.get(i); Object argValue = internalEvaluate(arg, context, indicator); Array.set(array, i - paramCount, argValue); } result.add(array); } } } else { result = super.evaluateArgumentExpressions(executable, expressions, context, indicator); } return result; } /* * Override default expression evaluator to wrap thrown exceptions with an xtest evaluation * exception wrapper that contains the expression that threw the exception */ @Override protected Object internalEvaluate(XExpression expression, IEvaluationContext context, CancelIndicator indicator) throws EvaluationException { Object internalEvaluate; executedExpressions.add(expression); XExpression previous = null; if (!callStack.empty()) { previous = callStack.pop(); } callStack.push(expression); try { // replace top of stack with current expression internalEvaluate = super.internalEvaluate(expression, context, indicator); } catch (ReturnValue value) { throw value; } catch (InterpreterCanceledException e) { throw e; } catch (Throwable e) { if (e instanceof XTestEvaluationException) { throw (RuntimeException) e; } else { Throwable cause = e; while (cause instanceof RuntimeException && !(cause instanceof XTestEvaluationException) && cause.getCause() != null) { cause = cause.getCause(); } if (cause instanceof XTestEvaluationException) { throw (RuntimeException) cause; } internalEvaluate = null; handleEvaluationException(cause, expression); } } finally { callStack.pop(); callStack.push(previous != null ? previous : expression); } return internalEvaluate; } @Override protected Object invokeOperation(JvmOperation operation, Object receiver, List<Object> argumentValues) { XMethodDef method = assocations.getMethodDef(operation); if (method != null) { return invokeXtestMethod(method, argumentValues); } else { return super.invokeOperation(operation, receiver, argumentValues); } } /** * Invokes a method declared in an Xtest file * * @param method * The method * @param argumentValues * The argument values * @return The result of invoking that operation */ protected Object invokeXtestMethod(XMethodDef method, List<Object> argumentValues) { IEvaluationContext context = localMethodContexts.get(method); if (context == null) { context = createContext(); } else { context = context.fork(); } if (argumentValues.size() != method.getParameters().size()) { throw new IllegalStateException("Number of arguments did not match. Expected: " + method.getParameters().size() + " but was: " + argumentValues.size()); } int i = 0; for (XtendParameter param : method.getParameters()) { Object value; value = argumentValues.get(i); context.newValue(QualifiedName.create(param.getName()), value); i++; } IEvaluationResult evaluate = evaluate(method.getExpression(), context, CancelIndicator.NullImpl); return evaluate.getResult(); } private IEvaluationResult evaluateInsideOfClosure(final XExpression expression, final IEvaluationContext context, final CancelIndicator indicator) { // Same as super.internalEvaluate ... // push this layer onto the call stack callStack.push(expression); try { Object result = XtestUtil.runOnNewLevelOfXtestStack(new Callable<Object>() { @Override public Object call() throws Exception { return internalEvaluate(expression, context, indicator != null ? indicator : CancelIndicator.NullImpl); } }); return new DefaultEvaluationResult(result, null); } catch (ReturnValue e) { return new DefaultEvaluationResult(e.returnValue, null); } catch (XTestEvaluationException e) { // ... except throw Xtest evaluation exceptions to be handled by outer expression throw e; } catch (EvaluationException e) { return new DefaultEvaluationResult(null, e.getCause()); } catch (InterpreterCanceledException e) { return null; } catch (Exception e) { return new DefaultEvaluationResult(null, e); } finally { callStack.pop(); } } /** * Evaluates a {@link UniqueName} and returns the result * * @param uniqueName * The {@link UniqueName} object of the test * @param test * The test expression for if no name is given * @param context * The evaluation context * @param indicator * The cancel indicator * @return The name derived from uniqueName */ private String getName(UniqueName uniqueName, XTestExpression test, IEvaluationContext context, CancelIndicator indicator) { String name = uniqueName.getName(); XExpression uidExp = uniqueName.getIdentifier(); if (uidExp != null) { Object nameObj = internalEvaluate(uidExp, context, indicator); if (nameObj != null) { if (name == null) { // no ID specified name = nameObj.toString(); } else { name += " (" + nameObj.toString() + ")"; } } } if (name == null) { XExpression expression = test.getExpression(); name = XtestUtil.getText(expression); } return name; } private void handleAssertionFailure(XAssertExpression assertExpression) { throw new XTestAssertionFailure("Assertion Failed"); } private void handleEvaluationException(Throwable toWrap, XExpression expression) { // Start from the root of the stack and work down until a call has been made that jumps // locations in the file, want to drill down to the most specific expression contained // within the top-level expression that caused the exception XExpression cause = callStack.firstElement(); for (XExpression element : callStack) { if (!org.eclipse.xtext.EcoreUtil2.isAncestor(cause, element)) { break; } cause = element; } toWrap = XtestUtil.getRootCause(toWrap); XTestEvaluationException toThrow = new XTestEvaluationException(toWrap, cause); StackTraceElement[] generatedStack = XtestUtil.generateXtestStackTrace(startTrace, toWrap.getStackTrace(), callStack); toWrap.setStackTrace(generatedStack); if (inSafeBlock > 0) { XTestResult peek = testStack.peek(); peek.addEvaluationException(toThrow); } else { throw toThrow; } } private static class ReturnValue extends RuntimeException { private static final long serialVersionUID = 7864448463694945628L; public Object returnValue; public ReturnValue(Object value) { super(); this.returnValue = value; } } }
true
true
protected List<Object> evaluateArgumentExpressions(JvmExecutable executable, List<XExpression> expressions, IEvaluationContext context, CancelIndicator indicator) { // Same as XbaseInterpreter.evaluateArgumentExpressions() ... XMethodDef methodDef = assocations.getMethodDef(executable); List<Object> result; if (methodDef != null) { result = Lists.newArrayList(); int paramCount = executable.getParameters().size(); if (executable.isVarArgs()) { paramCount--; } for (int i = 0; i < paramCount; i++) { XExpression arg = expressions.get(i); Object argResult = internalEvaluate(arg, context, indicator); JvmTypeReference parameterType = executable.getParameters().get(i) .getParameterType(); Object argumentValue = coerceArgumentType(argResult, parameterType); result.add(argumentValue); } if (executable.isVarArgs()) { JvmTypeReference parameterType = methodDef.getParameters().get(paramCount) .getParameterType(); // ... except get the var-arg class from the XMethodDef Class<?> componentType = getJavaReflectAccess().getRawType(parameterType.getType()); // end diff if (expressions.size() == executable.getParameters().size()) { XExpression arg = expressions.get(paramCount); Object lastArgResult = internalEvaluate(arg, context, indicator); if (componentType.isInstance(lastArgResult)) { Object array = Array.newInstance(componentType, 1); Array.set(array, 0, lastArgResult); result.add(array); } else { result.add(lastArgResult); } } else { Object array = Array .newInstance(componentType, expressions.size() - paramCount); for (int i = paramCount; i < expressions.size(); i++) { XExpression arg = expressions.get(i); Object argValue = internalEvaluate(arg, context, indicator); Array.set(array, i - paramCount, argValue); } result.add(array); } } } else { result = super.evaluateArgumentExpressions(executable, expressions, context, indicator); } return result; }
protected List<Object> evaluateArgumentExpressions(JvmExecutable executable, List<XExpression> expressions, IEvaluationContext context, CancelIndicator indicator) { // Same as XbaseInterpreter.evaluateArgumentExpressions() ... XMethodDef methodDef = assocations.getMethodDef(executable); List<Object> result; if (methodDef != null) { result = Lists.newArrayList(); int paramCount = executable.getParameters().size(); if (executable.isVarArgs()) { paramCount--; } for (int i = 0; i < paramCount; i++) { XExpression arg = expressions.get(i); Object argResult = internalEvaluate(arg, context, indicator); JvmTypeReference parameterType = executable.getParameters().get(i) .getParameterType(); Object argumentValue = coerceArgumentType(argResult, parameterType); result.add(argumentValue); } if (executable.isVarArgs()) { JvmTypeReference parameterType = methodDef.getParameters().get(paramCount) .getParameterType(); // ... except get the var-arg class from the XMethodDef Class<?> componentType = getJavaReflectAccess().getRawType(parameterType.getType()); // end diff if (expressions.size() == executable.getParameters().size()) { XExpression arg = expressions.get(paramCount); Object lastArgResult = internalEvaluate(arg, context, indicator); if (componentType.isInstance(lastArgResult) && !lastArgResult.getClass().isArray()) { Object array = Array.newInstance(componentType, 1); Array.set(array, 0, lastArgResult); result.add(array); } else { result.add(lastArgResult); } } else { Object array = Array .newInstance(componentType, expressions.size() - paramCount); for (int i = paramCount; i < expressions.size(); i++) { XExpression arg = expressions.get(i); Object argValue = internalEvaluate(arg, context, indicator); Array.set(array, i - paramCount, argValue); } result.add(array); } } } else { result = super.evaluateArgumentExpressions(executable, expressions, context, indicator); } return result; }
diff --git a/src/com/mojang/mojam/entity/mob/RailDroid.java b/src/com/mojang/mojam/entity/mob/RailDroid.java index 77262a45..e25153a6 100644 --- a/src/com/mojang/mojam/entity/mob/RailDroid.java +++ b/src/com/mojang/mojam/entity/mob/RailDroid.java @@ -1,265 +1,265 @@ package com.mojang.mojam.entity.mob; import com.mojang.mojam.entity.Entity; import com.mojang.mojam.entity.building.TreasurePile; import com.mojang.mojam.level.tile.*; import com.mojang.mojam.math.Vec2; import com.mojang.mojam.network.TurnSynchronizer; import com.mojang.mojam.screen.*; public class RailDroid extends Mob { private int dir = 0; private int lDir = 4; private int noTurnTime = 0; private int pauseTime = 0; public boolean carrying = false; public int swapTime = 0; public int team; public RailDroid(double x, double y, int team) { super(x, y, team); this.team = team; this.setSize(10, 8); deathPoints = 1; } public void tick() { xBump = yBump = 0; super.tick(); if (freezeTime > 0) return; if (swapTime > 0) swapTime--; boolean hadPaused = pauseTime > 0; if (pauseTime > 0) { pauseTime--; if (pauseTime > 0) return; } int xt = (int) (pos.x / Tile.WIDTH); int yt = (int) (pos.y / Tile.HEIGHT); boolean cr = level.getTile(xt, yt) instanceof RailTile; boolean lr = level.getTile(xt - 1, yt) instanceof RailTile; boolean rr = level.getTile(xt + 1, yt) instanceof RailTile; boolean ur = level.getTile(xt, yt - 1) instanceof RailTile; boolean dr = level.getTile(xt, yt + 1) instanceof RailTile; xd *= 0.4; yd *= 0.4; double xcd = pos.x - (xt * Tile.WIDTH + 16); double ycd = pos.y - (yt * Tile.HEIGHT + 16); boolean centerIsh = xcd * xcd + ycd * ycd < 2 * 2; boolean xcenterIsh = xcd * xcd < 2 * 2; boolean ycenterIsh = ycd * ycd < 2 * 2; if (!xcenterIsh) ur = false; if (!xcenterIsh) dr = false; if (!ycenterIsh) lr = false; if (!ycenterIsh) rr = false; int lWeight = 0; int uWeight = 0; int rWeight = 0; int dWeight = 0; if (noTurnTime > 0) noTurnTime--; if (noTurnTime == 0 && (!cr || dir == 0 || centerIsh)) { noTurnTime = 4; // int nd = 0; if (dir == 1 && lr) lWeight += 16; if (dir == 2 && ur) uWeight += 16; if (dir == 3 && rr) rWeight += 16; if (dir == 4 && dr) dWeight += 16; if (lWeight + uWeight + rWeight + dWeight == 0) { if ((dir == 1 || dir == 3)) { if (ur) uWeight += 4; if (dr) dWeight += 4; } if ((dir == 2 || dir == 4)) { if (lr) lWeight += 4; if (rr) rWeight += 4; } } if (lWeight + uWeight + rWeight + dWeight == 0) { if (lr) lWeight += 1; if (ur) uWeight += 1; if (rr) rWeight += 1; if (dr) dWeight += 1; } if (dir == 1) rWeight = 0; if (dir == 2) dWeight = 0; if (dir == 3) lWeight = 0; if (dir == 4) uWeight = 0; int totalWeight = lWeight + uWeight + rWeight + dWeight; if (totalWeight == 0) { dir = 0; } else { int res = TurnSynchronizer.synchedRandom.nextInt(totalWeight); // dir = 0; dir = (((dir - 1) + 2) & 3) + 1; uWeight += lWeight; rWeight += uWeight; dWeight += rWeight; if (res < lWeight) dir = 1; else if (res < uWeight) dir = 2; else if (res < rWeight) dir = 3; else if (res < dWeight) dir = 4; } // dir = nd; } if (cr) { double r = 1; if (!(dir == 1 || dir == 3) && xcd < -r) xd += 0.3; if (!(dir == 1 || dir == 3) && xcd > +r) xd -= 0.3; if (!(dir == 2 || dir == 4) && ycd < -r) yd += 0.3; if (!(dir == 2 || dir == 4) && ycd > +r) yd -= 0.3; // if (!(dir == 1 || dir == 3) && xcd >= -r && xcd <= r) xd = -xcd; // if (!(dir == 2 || dir == 4) && ycd >= -r && ycd <= r) yd = -ycd; } double speed = 0.7; if (dir > 0) lDir = dir; if (dir == 1) xd -= speed; if (dir == 2) yd -= speed; if (dir == 3) xd += speed; if (dir == 4) yd += speed; Vec2 oldPos = pos.clone(); move(xd, yd); if (dir > 0 && oldPos.distSqr(pos) < 0.1 * 0.1) { if (hadPaused) { dir = (((dir - 1) + 2) & 3) + 1; noTurnTime = 0; } else { pauseTime = 10; noTurnTime = 0; } } if (!carrying && swapTime == 0) { if (level.getEntities(getBB().grow(32), TreasurePile.class).size() > 0) { swapTime = 30; carrying = true; } } if (carrying && swapTime == 0) { - if (pos.y < 7 * Tile.HEIGHT) { + if (pos.y < 8 * Tile.HEIGHT) { carrying = false; level.player2Score += 2; } if (pos.y > (level.height - 7 - 1) * Tile.HEIGHT) { carrying = false; level.player1Score += 2; } } // level.getTile(xt, yt) } @Override public Bitmap getSprite() { if (lDir == 1) return Art.raildroid[1][1]; if (lDir == 2) return Art.raildroid[0][1]; if (lDir == 3) return Art.raildroid[1][0]; if (lDir == 4) return Art.raildroid[0][0]; return Art.raildroid[0][0]; } public void handleCollision(Entity entity, double xa, double ya) { super.handleCollision(entity, xa, ya); if (entity instanceof RailDroid) { RailDroid other = (RailDroid) entity; if (other.carrying != carrying && carrying) { if (lDir == 1 && other.pos.x > pos.x - 4) return; if (lDir == 2 && other.pos.y > pos.y - 4) return; if (lDir == 3 && other.pos.x < pos.x + 4) return; if (lDir == 4 && other.pos.y < pos.y + 4) return; if (other.lDir == 1 && pos.x > other.pos.x - 4) return; if (other.lDir == 2 && pos.y > other.pos.y - 4) return; if (other.lDir == 3 && pos.x < other.pos.x + 4) return; if (other.lDir == 4 && pos.y < other.pos.y + 4) return; if (other.swapTime == 0 && swapTime == 0) { other.swapTime = swapTime = 15; boolean tmp = other.carrying; other.carrying = carrying; carrying = tmp; } } } } @Override protected boolean shouldBlock(Entity e) { // if (e instanceof Player && ((Player) e).team == team) return false; return super.shouldBlock(e); } public void render(Screen screen) { super.render(screen); if (carrying) { screen.blit(Art.bullets[0][0], pos.x - 8, pos.y - 20 - yOffs); } else { screen.blit(Art.bullets[1][1], pos.x - 8, pos.y - 20 - yOffs); } } }
true
true
public void tick() { xBump = yBump = 0; super.tick(); if (freezeTime > 0) return; if (swapTime > 0) swapTime--; boolean hadPaused = pauseTime > 0; if (pauseTime > 0) { pauseTime--; if (pauseTime > 0) return; } int xt = (int) (pos.x / Tile.WIDTH); int yt = (int) (pos.y / Tile.HEIGHT); boolean cr = level.getTile(xt, yt) instanceof RailTile; boolean lr = level.getTile(xt - 1, yt) instanceof RailTile; boolean rr = level.getTile(xt + 1, yt) instanceof RailTile; boolean ur = level.getTile(xt, yt - 1) instanceof RailTile; boolean dr = level.getTile(xt, yt + 1) instanceof RailTile; xd *= 0.4; yd *= 0.4; double xcd = pos.x - (xt * Tile.WIDTH + 16); double ycd = pos.y - (yt * Tile.HEIGHT + 16); boolean centerIsh = xcd * xcd + ycd * ycd < 2 * 2; boolean xcenterIsh = xcd * xcd < 2 * 2; boolean ycenterIsh = ycd * ycd < 2 * 2; if (!xcenterIsh) ur = false; if (!xcenterIsh) dr = false; if (!ycenterIsh) lr = false; if (!ycenterIsh) rr = false; int lWeight = 0; int uWeight = 0; int rWeight = 0; int dWeight = 0; if (noTurnTime > 0) noTurnTime--; if (noTurnTime == 0 && (!cr || dir == 0 || centerIsh)) { noTurnTime = 4; // int nd = 0; if (dir == 1 && lr) lWeight += 16; if (dir == 2 && ur) uWeight += 16; if (dir == 3 && rr) rWeight += 16; if (dir == 4 && dr) dWeight += 16; if (lWeight + uWeight + rWeight + dWeight == 0) { if ((dir == 1 || dir == 3)) { if (ur) uWeight += 4; if (dr) dWeight += 4; } if ((dir == 2 || dir == 4)) { if (lr) lWeight += 4; if (rr) rWeight += 4; } } if (lWeight + uWeight + rWeight + dWeight == 0) { if (lr) lWeight += 1; if (ur) uWeight += 1; if (rr) rWeight += 1; if (dr) dWeight += 1; } if (dir == 1) rWeight = 0; if (dir == 2) dWeight = 0; if (dir == 3) lWeight = 0; if (dir == 4) uWeight = 0; int totalWeight = lWeight + uWeight + rWeight + dWeight; if (totalWeight == 0) { dir = 0; } else { int res = TurnSynchronizer.synchedRandom.nextInt(totalWeight); // dir = 0; dir = (((dir - 1) + 2) & 3) + 1; uWeight += lWeight; rWeight += uWeight; dWeight += rWeight; if (res < lWeight) dir = 1; else if (res < uWeight) dir = 2; else if (res < rWeight) dir = 3; else if (res < dWeight) dir = 4; } // dir = nd; } if (cr) { double r = 1; if (!(dir == 1 || dir == 3) && xcd < -r) xd += 0.3; if (!(dir == 1 || dir == 3) && xcd > +r) xd -= 0.3; if (!(dir == 2 || dir == 4) && ycd < -r) yd += 0.3; if (!(dir == 2 || dir == 4) && ycd > +r) yd -= 0.3; // if (!(dir == 1 || dir == 3) && xcd >= -r && xcd <= r) xd = -xcd; // if (!(dir == 2 || dir == 4) && ycd >= -r && ycd <= r) yd = -ycd; } double speed = 0.7; if (dir > 0) lDir = dir; if (dir == 1) xd -= speed; if (dir == 2) yd -= speed; if (dir == 3) xd += speed; if (dir == 4) yd += speed; Vec2 oldPos = pos.clone(); move(xd, yd); if (dir > 0 && oldPos.distSqr(pos) < 0.1 * 0.1) { if (hadPaused) { dir = (((dir - 1) + 2) & 3) + 1; noTurnTime = 0; } else { pauseTime = 10; noTurnTime = 0; } } if (!carrying && swapTime == 0) { if (level.getEntities(getBB().grow(32), TreasurePile.class).size() > 0) { swapTime = 30; carrying = true; } } if (carrying && swapTime == 0) { if (pos.y < 7 * Tile.HEIGHT) { carrying = false; level.player2Score += 2; } if (pos.y > (level.height - 7 - 1) * Tile.HEIGHT) { carrying = false; level.player1Score += 2; } } // level.getTile(xt, yt) }
public void tick() { xBump = yBump = 0; super.tick(); if (freezeTime > 0) return; if (swapTime > 0) swapTime--; boolean hadPaused = pauseTime > 0; if (pauseTime > 0) { pauseTime--; if (pauseTime > 0) return; } int xt = (int) (pos.x / Tile.WIDTH); int yt = (int) (pos.y / Tile.HEIGHT); boolean cr = level.getTile(xt, yt) instanceof RailTile; boolean lr = level.getTile(xt - 1, yt) instanceof RailTile; boolean rr = level.getTile(xt + 1, yt) instanceof RailTile; boolean ur = level.getTile(xt, yt - 1) instanceof RailTile; boolean dr = level.getTile(xt, yt + 1) instanceof RailTile; xd *= 0.4; yd *= 0.4; double xcd = pos.x - (xt * Tile.WIDTH + 16); double ycd = pos.y - (yt * Tile.HEIGHT + 16); boolean centerIsh = xcd * xcd + ycd * ycd < 2 * 2; boolean xcenterIsh = xcd * xcd < 2 * 2; boolean ycenterIsh = ycd * ycd < 2 * 2; if (!xcenterIsh) ur = false; if (!xcenterIsh) dr = false; if (!ycenterIsh) lr = false; if (!ycenterIsh) rr = false; int lWeight = 0; int uWeight = 0; int rWeight = 0; int dWeight = 0; if (noTurnTime > 0) noTurnTime--; if (noTurnTime == 0 && (!cr || dir == 0 || centerIsh)) { noTurnTime = 4; // int nd = 0; if (dir == 1 && lr) lWeight += 16; if (dir == 2 && ur) uWeight += 16; if (dir == 3 && rr) rWeight += 16; if (dir == 4 && dr) dWeight += 16; if (lWeight + uWeight + rWeight + dWeight == 0) { if ((dir == 1 || dir == 3)) { if (ur) uWeight += 4; if (dr) dWeight += 4; } if ((dir == 2 || dir == 4)) { if (lr) lWeight += 4; if (rr) rWeight += 4; } } if (lWeight + uWeight + rWeight + dWeight == 0) { if (lr) lWeight += 1; if (ur) uWeight += 1; if (rr) rWeight += 1; if (dr) dWeight += 1; } if (dir == 1) rWeight = 0; if (dir == 2) dWeight = 0; if (dir == 3) lWeight = 0; if (dir == 4) uWeight = 0; int totalWeight = lWeight + uWeight + rWeight + dWeight; if (totalWeight == 0) { dir = 0; } else { int res = TurnSynchronizer.synchedRandom.nextInt(totalWeight); // dir = 0; dir = (((dir - 1) + 2) & 3) + 1; uWeight += lWeight; rWeight += uWeight; dWeight += rWeight; if (res < lWeight) dir = 1; else if (res < uWeight) dir = 2; else if (res < rWeight) dir = 3; else if (res < dWeight) dir = 4; } // dir = nd; } if (cr) { double r = 1; if (!(dir == 1 || dir == 3) && xcd < -r) xd += 0.3; if (!(dir == 1 || dir == 3) && xcd > +r) xd -= 0.3; if (!(dir == 2 || dir == 4) && ycd < -r) yd += 0.3; if (!(dir == 2 || dir == 4) && ycd > +r) yd -= 0.3; // if (!(dir == 1 || dir == 3) && xcd >= -r && xcd <= r) xd = -xcd; // if (!(dir == 2 || dir == 4) && ycd >= -r && ycd <= r) yd = -ycd; } double speed = 0.7; if (dir > 0) lDir = dir; if (dir == 1) xd -= speed; if (dir == 2) yd -= speed; if (dir == 3) xd += speed; if (dir == 4) yd += speed; Vec2 oldPos = pos.clone(); move(xd, yd); if (dir > 0 && oldPos.distSqr(pos) < 0.1 * 0.1) { if (hadPaused) { dir = (((dir - 1) + 2) & 3) + 1; noTurnTime = 0; } else { pauseTime = 10; noTurnTime = 0; } } if (!carrying && swapTime == 0) { if (level.getEntities(getBB().grow(32), TreasurePile.class).size() > 0) { swapTime = 30; carrying = true; } } if (carrying && swapTime == 0) { if (pos.y < 8 * Tile.HEIGHT) { carrying = false; level.player2Score += 2; } if (pos.y > (level.height - 7 - 1) * Tile.HEIGHT) { carrying = false; level.player1Score += 2; } } // level.getTile(xt, yt) }
diff --git a/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/linking/EMLinkingService.java b/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/linking/EMLinkingService.java index d4f38385..9fe95764 100644 --- a/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/linking/EMLinkingService.java +++ b/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/linking/EMLinkingService.java @@ -1,356 +1,359 @@ package org.osate.xtext.aadl2.errormodel.linking; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EReference; import org.eclipse.xtext.linking.impl.IllegalNodeException; import org.eclipse.xtext.nodemodel.INode; import org.osate.aadl2.Aadl2Package; import org.osate.aadl2.AadlPackage; import org.osate.aadl2.AnnexLibrary; import org.osate.aadl2.Classifier; import org.osate.aadl2.ContainedNamedElement; import org.osate.aadl2.ContainmentPathElement; import org.osate.aadl2.DirectionType; import org.osate.aadl2.Element; import org.osate.aadl2.Feature; import org.osate.aadl2.FeatureGroup; import org.osate.aadl2.NamedElement; import org.osate.aadl2.PackageSection; import org.osate.aadl2.Subcomponent; import org.osate.aadl2.modelsupport.util.AadlUtil; import org.osate.aadl2.util.Aadl2Util; import org.osate.xtext.aadl2.errormodel.errorModel.ConditionElement; import org.osate.xtext.aadl2.errormodel.errorModel.ConditionExpression; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorStateMachine; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorTransition; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorDetection; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorModelLibrary; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorModelPackage; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorPropagation; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorType; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorTypes; import org.osate.xtext.aadl2.errormodel.errorModel.FeatureorPPReference; import org.osate.xtext.aadl2.errormodel.errorModel.RecoverEvent; import org.osate.xtext.aadl2.errormodel.errorModel.SubcomponentElement; import org.osate.xtext.aadl2.errormodel.errorModel.TypeMappingSet; import org.osate.xtext.aadl2.errormodel.errorModel.TypeSet; import org.osate.xtext.aadl2.errormodel.errorModel.TypeTransformationSet; import org.osate.xtext.aadl2.errormodel.errorModel.TypeUseContext; import org.osate.xtext.aadl2.errormodel.util.EMV2Util; import org.osate.xtext.aadl2.properties.linking.PropertiesLinkingService; import org.osate.xtext.aadl2.properties.util.EMFIndexRetrieval; public class EMLinkingService extends PropertiesLinkingService { public EMLinkingService(){ super(); } @Override public List<EObject> getLinkedObjects(EObject context, EReference reference, INode node) throws IllegalNodeException { final EClass requiredType = reference.getEReferenceType(); EObject searchResult = null; if (requiredType == null) return Collections.<EObject> emptyList(); Element cxt = (Element) context; final String name = getCrossRefNodeAsString(node); if (Aadl2Package.eINSTANCE.getNamedElement() == requiredType) { // containment path element if (context instanceof ContainmentPathElement) { ContainedNamedElement path = (ContainedNamedElement) context.eContainer(); EList<ContainmentPathElement> list = path .getContainmentPathElements(); int idx = list.indexOf(context); Element cxtElement = ((ContainmentPathElement) context).getContainingClassifier(); if (idx > 0) { // find next element in namespace of previous element ContainmentPathElement el = list.get(idx - 1); NamedElement ne = el.getNamedElement(); if (ne instanceof Subcomponent) { cxtElement = ((Subcomponent) ne).getClassifier(); } else if (ne instanceof FeatureGroup) { cxtElement = ((FeatureGroup) ne).getClassifier(); } else { cxtElement = ne; } } + if (cxtElement == null){ + cxtElement = EMV2Util.getContainingErrorModelLibrary((ContainmentPathElement)context); + } // find annex subclause as context for error model identifier lookup if (!Aadl2Util.isNull(cxtElement)){ searchResult = findErrorType(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = findTypeSet(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorPropagation(cxtElement, name,DirectionType.OUT); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorPropagation(cxtElement, name,DirectionType.IN); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findPropagationPoint(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorFlow(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorEvent(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorState(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorTransition(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorDetection(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findOutgoingPropagationCondition(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); // look up subcomponent in classifier of previous subcomponent, or feature group if (cxtElement instanceof Classifier) { NamedElement finding = ((Classifier)cxtElement).findNamedElement(name); if (finding instanceof Subcomponent || finding instanceof FeatureGroup) searchResult = finding; } if (searchResult != null) return Collections.singletonList(searchResult); } } else if (context instanceof RecoverEvent){ Classifier ns = AadlUtil.getContainingClassifier(context); searchResult = ns.findNamedElement(name); } else if (context instanceof FeatureorPPReference){ ErrorPropagation ep = (ErrorPropagation) context.eContainer(); EList<FeatureorPPReference> frefs = ep.getFeatureorPPRefs(); int idx = frefs.indexOf(context); Classifier cl=null; if (idx > 0){ FeatureorPPReference enclosingfg = frefs.get(idx-1); NamedElement fg = enclosingfg.getFeatureorPP(); if (fg instanceof FeatureGroup){ cl = ((FeatureGroup)fg).getFeatureGroupType(); } } else { cl = AadlUtil.getContainingClassifier(context); } if (cl != null){ NamedElement ne = cl.findNamedElement(name); if (ne instanceof Feature){ searchResult = ne; } else { // find propagation point searchResult = EMV2Util.findPropagationPoint(cl,name); } } } } else if (ErrorModelPackage.eINSTANCE.getErrorType() == requiredType) { searchResult = findErrorType(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getTypeSet() == requiredType) { searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorTypes() == requiredType) { searchResult = findErrorType(cxt, name); if (searchResult == null) searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getPropagationPoint() == requiredType) { // find propagation point Classifier cl = AadlUtil.getContainingClassifier(context); searchResult = EMV2Util.findPropagationPoint(cl,name); } else if (ErrorModelPackage.eINSTANCE.getErrorModelLibrary() == requiredType) { // first look it up in global index EObject gobj = getIndexedObject(context, reference, name); if (gobj != null ){ if( gobj.eClass() == requiredType){ return Collections.singletonList(gobj); } else { System.out.println("Global lookup of type did not match "+name); } } searchResult = findErrorModelLibrary(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorStateOrTypeSet() == requiredType) { searchResult = EMV2Util.findErrorBehaviorState(cxt, name); if (searchResult == null) searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorPropagation() == requiredType) { if (reference.getName().equalsIgnoreCase("outgoing")){ searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.OUT); } else if (reference.getName().equalsIgnoreCase("incoming")){ searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.IN); } else { searchResult = EMV2Util.findErrorPropagation(cxt, name,null); } } else if (ErrorModelPackage.eINSTANCE.getTypeMappingSet() == requiredType) { searchResult = findTypeMappingSet(context, name); } else if (ErrorModelPackage.eINSTANCE.getTypeTransformationSet() == requiredType) { searchResult = findTypeTransformationSet(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorStateMachine() == requiredType) { searchResult = findErrorBehaviorStateMachine(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorState() == requiredType) { searchResult = EMV2Util.findErrorBehaviorState((Element)context, name); } else if (ErrorModelPackage.eINSTANCE.getEventOrPropagation() == requiredType) { searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.IN); if (searchResult == null ){ if (context instanceof ConditionExpression && (EMV2Util.getConditionExpressionContext((ConditionExpression)context) instanceof ErrorDetection || EMV2Util.getConditionExpressionContext((ConditionExpression)context) instanceof ErrorBehaviorTransition)){ // find it only for transitions searchResult = EMV2Util.findErrorBehaviorEvent(cxt, name); } } } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorEvent() == requiredType) { searchResult = EMV2Util.findErrorBehaviorEvent(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorTransition() == requiredType) { searchResult = EMV2Util.findErrorBehaviorTransition(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorFlow() == requiredType) { searchResult = EMV2Util.findErrorFlow(cxt.getContainingClassifier(), name); } else if (Aadl2Package.eINSTANCE.getSubcomponent()==requiredType) { // } else if (Aadl2Package.eINSTANCE.getSubcomponent().isSuperTypeOf(requiredType)) { if (context instanceof SubcomponentElement){ ConditionElement ce = (ConditionElement)context.eContainer(); EList<SubcomponentElement> sublist = ce.getSubcomponents(); int idx = sublist.indexOf(context); Classifier ns = AadlUtil.getContainingClassifier(context); if (idx > 0) { SubcomponentElement se = sublist.get(idx-1); Subcomponent subcomponent = se.getSubcomponent(); ns = subcomponent.getAllClassifier(); } EObject res = ns.findNamedElement(name); if (res instanceof Subcomponent) { searchResult = res; } } } if (searchResult != null) { return Collections.singletonList(searchResult); } return Collections.<EObject> emptyList(); } /** * find the error model library. The String name refers to the package and the default EML name is added ("emv2") * @param context context of search to identify package and EML * @param name * @return */ public ErrorModelLibrary findErrorModelLibrary(EObject context, String name){ ErrorModelLibrary eml = (ErrorModelLibrary) EMFIndexRetrieval.getEObjectOfType(context, ErrorModelPackage.eINSTANCE.getErrorModelLibrary(), name+"::"+"emv2"); if (eml != null) return eml; AadlPackage ap = findAadlPackageReference(name, AadlUtil.getContainingPackageSection(context)); if (ap == null) return null; PackageSection ps = ap.getOwnedPublicSection(); EList<AnnexLibrary>all=ps.getOwnedAnnexLibraries(); for (AnnexLibrary al : all){ if (al instanceof ErrorModelLibrary){ return (ErrorModelLibrary)al; } } return null; } public TypeMappingSet findTypeMappingSet(EObject context, String name){ ErrorModelLibrary eml = findErrorModelLibrary(context, EMV2Util.getPackageName(name)); if (eml != null){ EList<TypeMappingSet> tmsl= eml.getMappings(); for (TypeMappingSet tms : tmsl){ if (EMV2Util.getItemNameWithoutQualification(name).equalsIgnoreCase(tms.getName())) return tms; } } return null; } public TypeTransformationSet findTypeTransformationSet(EObject context, String name){ ErrorModelLibrary eml = findErrorModelLibrary(context, EMV2Util.getPackageName(name)); if (eml != null){ EList<TypeTransformationSet> tmsl= eml.getTransformations(); for (TypeTransformationSet tms : tmsl){ if (EMV2Util.getItemNameWithoutQualification(name).equalsIgnoreCase(tms.getName())) return tms; } } return null; } public ErrorBehaviorStateMachine findErrorBehaviorStateMachine(EObject context, String name){ ErrorModelLibrary eml = findErrorModelLibrary(context, EMV2Util.getPackageName(name)); if (eml != null){ EList<ErrorBehaviorStateMachine> ebsml= eml.getBehaviors(); for (ErrorBehaviorStateMachine ebsm : ebsml){ if (EMV2Util.getItemNameWithoutQualification(name).equalsIgnoreCase(ebsm.getName())) return ebsm; } } return null; } public ErrorType findErrorType(Element context, String typeName){ return (ErrorType)findEMLNamedTypeElement(context, typeName, ErrorModelPackage.eINSTANCE.getErrorType()); } public TypeSet findTypeSet(Element context, String typeName){ return (TypeSet)findEMLNamedTypeElement(context, typeName, ErrorModelPackage.eINSTANCE.getTypeSet()); } public EObject findEMLNamedTypeElement(Element context, String qualTypeName, EClass eclass){ String packName = EMV2Util.getPackageName(qualTypeName); String typeName = EMV2Util.getItemNameWithoutQualification(qualTypeName); if (packName != null){ // qualified reference; look there only ErrorModelLibrary eml = findErrorModelLibrary(context, packName); // PHF: change to findNamedElementInThisEML if we do not make inherited names externally visible return findEMLNamedTypeElement(eml, typeName, eclass); } ErrorModelLibrary owneml = EMV2Util.getContainingErrorModelLibrary(context); TypeUseContext tuns = EMV2Util.getContainingTypeUseContext(context); List<ErrorModelLibrary> otheremls = Collections.EMPTY_LIST; if (tuns != null) { // we are in a transformation set, mapping set etc. otheremls = EMV2Util.getUseTypes(tuns); } else if (owneml != null){ // lookup in own EML if we are inside an ErrorModelLibrary EObject res = findNamedTypeElementInThisEML(owneml, typeName, eclass); if (res != null) return res; otheremls = owneml.getExtends(); } for (ErrorModelLibrary etll: otheremls){ // PHF: change to findNamedElementInThisEML if we do not make inherited names externally visible EObject res = findEMLNamedTypeElement(etll, typeName, eclass); if (res != null) { return res; } } return null; } public EObject findNamedTypeElementInThisEML(ErrorModelLibrary eml, String typeName, EClass eclass){ if (eml == null) return null; if (eclass == ErrorModelPackage.eINSTANCE.getErrorType()){ EList<ErrorType> elt = eml.getTypes(); for (ErrorType ets : elt){ if (typeName.equalsIgnoreCase(ets.getName())) return ets; } } else { EList<TypeSet> elt = eml.getTypesets(); for (TypeSet ets : elt){ if (typeName.equalsIgnoreCase(ets.getName())) return ets; } } return null; } }
true
true
public List<EObject> getLinkedObjects(EObject context, EReference reference, INode node) throws IllegalNodeException { final EClass requiredType = reference.getEReferenceType(); EObject searchResult = null; if (requiredType == null) return Collections.<EObject> emptyList(); Element cxt = (Element) context; final String name = getCrossRefNodeAsString(node); if (Aadl2Package.eINSTANCE.getNamedElement() == requiredType) { // containment path element if (context instanceof ContainmentPathElement) { ContainedNamedElement path = (ContainedNamedElement) context.eContainer(); EList<ContainmentPathElement> list = path .getContainmentPathElements(); int idx = list.indexOf(context); Element cxtElement = ((ContainmentPathElement) context).getContainingClassifier(); if (idx > 0) { // find next element in namespace of previous element ContainmentPathElement el = list.get(idx - 1); NamedElement ne = el.getNamedElement(); if (ne instanceof Subcomponent) { cxtElement = ((Subcomponent) ne).getClassifier(); } else if (ne instanceof FeatureGroup) { cxtElement = ((FeatureGroup) ne).getClassifier(); } else { cxtElement = ne; } } // find annex subclause as context for error model identifier lookup if (!Aadl2Util.isNull(cxtElement)){ searchResult = findErrorType(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = findTypeSet(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorPropagation(cxtElement, name,DirectionType.OUT); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorPropagation(cxtElement, name,DirectionType.IN); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findPropagationPoint(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorFlow(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorEvent(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorState(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorTransition(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorDetection(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findOutgoingPropagationCondition(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); // look up subcomponent in classifier of previous subcomponent, or feature group if (cxtElement instanceof Classifier) { NamedElement finding = ((Classifier)cxtElement).findNamedElement(name); if (finding instanceof Subcomponent || finding instanceof FeatureGroup) searchResult = finding; } if (searchResult != null) return Collections.singletonList(searchResult); } } else if (context instanceof RecoverEvent){ Classifier ns = AadlUtil.getContainingClassifier(context); searchResult = ns.findNamedElement(name); } else if (context instanceof FeatureorPPReference){ ErrorPropagation ep = (ErrorPropagation) context.eContainer(); EList<FeatureorPPReference> frefs = ep.getFeatureorPPRefs(); int idx = frefs.indexOf(context); Classifier cl=null; if (idx > 0){ FeatureorPPReference enclosingfg = frefs.get(idx-1); NamedElement fg = enclosingfg.getFeatureorPP(); if (fg instanceof FeatureGroup){ cl = ((FeatureGroup)fg).getFeatureGroupType(); } } else { cl = AadlUtil.getContainingClassifier(context); } if (cl != null){ NamedElement ne = cl.findNamedElement(name); if (ne instanceof Feature){ searchResult = ne; } else { // find propagation point searchResult = EMV2Util.findPropagationPoint(cl,name); } } } } else if (ErrorModelPackage.eINSTANCE.getErrorType() == requiredType) { searchResult = findErrorType(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getTypeSet() == requiredType) { searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorTypes() == requiredType) { searchResult = findErrorType(cxt, name); if (searchResult == null) searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getPropagationPoint() == requiredType) { // find propagation point Classifier cl = AadlUtil.getContainingClassifier(context); searchResult = EMV2Util.findPropagationPoint(cl,name); } else if (ErrorModelPackage.eINSTANCE.getErrorModelLibrary() == requiredType) { // first look it up in global index EObject gobj = getIndexedObject(context, reference, name); if (gobj != null ){ if( gobj.eClass() == requiredType){ return Collections.singletonList(gobj); } else { System.out.println("Global lookup of type did not match "+name); } } searchResult = findErrorModelLibrary(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorStateOrTypeSet() == requiredType) { searchResult = EMV2Util.findErrorBehaviorState(cxt, name); if (searchResult == null) searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorPropagation() == requiredType) { if (reference.getName().equalsIgnoreCase("outgoing")){ searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.OUT); } else if (reference.getName().equalsIgnoreCase("incoming")){ searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.IN); } else { searchResult = EMV2Util.findErrorPropagation(cxt, name,null); } } else if (ErrorModelPackage.eINSTANCE.getTypeMappingSet() == requiredType) { searchResult = findTypeMappingSet(context, name); } else if (ErrorModelPackage.eINSTANCE.getTypeTransformationSet() == requiredType) { searchResult = findTypeTransformationSet(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorStateMachine() == requiredType) { searchResult = findErrorBehaviorStateMachine(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorState() == requiredType) { searchResult = EMV2Util.findErrorBehaviorState((Element)context, name); } else if (ErrorModelPackage.eINSTANCE.getEventOrPropagation() == requiredType) { searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.IN); if (searchResult == null ){ if (context instanceof ConditionExpression && (EMV2Util.getConditionExpressionContext((ConditionExpression)context) instanceof ErrorDetection || EMV2Util.getConditionExpressionContext((ConditionExpression)context) instanceof ErrorBehaviorTransition)){ // find it only for transitions searchResult = EMV2Util.findErrorBehaviorEvent(cxt, name); } } } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorEvent() == requiredType) { searchResult = EMV2Util.findErrorBehaviorEvent(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorTransition() == requiredType) { searchResult = EMV2Util.findErrorBehaviorTransition(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorFlow() == requiredType) { searchResult = EMV2Util.findErrorFlow(cxt.getContainingClassifier(), name); } else if (Aadl2Package.eINSTANCE.getSubcomponent()==requiredType) { // } else if (Aadl2Package.eINSTANCE.getSubcomponent().isSuperTypeOf(requiredType)) { if (context instanceof SubcomponentElement){ ConditionElement ce = (ConditionElement)context.eContainer(); EList<SubcomponentElement> sublist = ce.getSubcomponents(); int idx = sublist.indexOf(context); Classifier ns = AadlUtil.getContainingClassifier(context); if (idx > 0) { SubcomponentElement se = sublist.get(idx-1); Subcomponent subcomponent = se.getSubcomponent(); ns = subcomponent.getAllClassifier(); } EObject res = ns.findNamedElement(name); if (res instanceof Subcomponent) { searchResult = res; } } } if (searchResult != null) { return Collections.singletonList(searchResult); } return Collections.<EObject> emptyList(); }
public List<EObject> getLinkedObjects(EObject context, EReference reference, INode node) throws IllegalNodeException { final EClass requiredType = reference.getEReferenceType(); EObject searchResult = null; if (requiredType == null) return Collections.<EObject> emptyList(); Element cxt = (Element) context; final String name = getCrossRefNodeAsString(node); if (Aadl2Package.eINSTANCE.getNamedElement() == requiredType) { // containment path element if (context instanceof ContainmentPathElement) { ContainedNamedElement path = (ContainedNamedElement) context.eContainer(); EList<ContainmentPathElement> list = path .getContainmentPathElements(); int idx = list.indexOf(context); Element cxtElement = ((ContainmentPathElement) context).getContainingClassifier(); if (idx > 0) { // find next element in namespace of previous element ContainmentPathElement el = list.get(idx - 1); NamedElement ne = el.getNamedElement(); if (ne instanceof Subcomponent) { cxtElement = ((Subcomponent) ne).getClassifier(); } else if (ne instanceof FeatureGroup) { cxtElement = ((FeatureGroup) ne).getClassifier(); } else { cxtElement = ne; } } if (cxtElement == null){ cxtElement = EMV2Util.getContainingErrorModelLibrary((ContainmentPathElement)context); } // find annex subclause as context for error model identifier lookup if (!Aadl2Util.isNull(cxtElement)){ searchResult = findErrorType(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = findTypeSet(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorPropagation(cxtElement, name,DirectionType.OUT); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorPropagation(cxtElement, name,DirectionType.IN); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findPropagationPoint(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorFlow(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorEvent(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorState(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorTransition(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorDetection(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findOutgoingPropagationCondition(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); // look up subcomponent in classifier of previous subcomponent, or feature group if (cxtElement instanceof Classifier) { NamedElement finding = ((Classifier)cxtElement).findNamedElement(name); if (finding instanceof Subcomponent || finding instanceof FeatureGroup) searchResult = finding; } if (searchResult != null) return Collections.singletonList(searchResult); } } else if (context instanceof RecoverEvent){ Classifier ns = AadlUtil.getContainingClassifier(context); searchResult = ns.findNamedElement(name); } else if (context instanceof FeatureorPPReference){ ErrorPropagation ep = (ErrorPropagation) context.eContainer(); EList<FeatureorPPReference> frefs = ep.getFeatureorPPRefs(); int idx = frefs.indexOf(context); Classifier cl=null; if (idx > 0){ FeatureorPPReference enclosingfg = frefs.get(idx-1); NamedElement fg = enclosingfg.getFeatureorPP(); if (fg instanceof FeatureGroup){ cl = ((FeatureGroup)fg).getFeatureGroupType(); } } else { cl = AadlUtil.getContainingClassifier(context); } if (cl != null){ NamedElement ne = cl.findNamedElement(name); if (ne instanceof Feature){ searchResult = ne; } else { // find propagation point searchResult = EMV2Util.findPropagationPoint(cl,name); } } } } else if (ErrorModelPackage.eINSTANCE.getErrorType() == requiredType) { searchResult = findErrorType(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getTypeSet() == requiredType) { searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorTypes() == requiredType) { searchResult = findErrorType(cxt, name); if (searchResult == null) searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getPropagationPoint() == requiredType) { // find propagation point Classifier cl = AadlUtil.getContainingClassifier(context); searchResult = EMV2Util.findPropagationPoint(cl,name); } else if (ErrorModelPackage.eINSTANCE.getErrorModelLibrary() == requiredType) { // first look it up in global index EObject gobj = getIndexedObject(context, reference, name); if (gobj != null ){ if( gobj.eClass() == requiredType){ return Collections.singletonList(gobj); } else { System.out.println("Global lookup of type did not match "+name); } } searchResult = findErrorModelLibrary(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorStateOrTypeSet() == requiredType) { searchResult = EMV2Util.findErrorBehaviorState(cxt, name); if (searchResult == null) searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorPropagation() == requiredType) { if (reference.getName().equalsIgnoreCase("outgoing")){ searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.OUT); } else if (reference.getName().equalsIgnoreCase("incoming")){ searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.IN); } else { searchResult = EMV2Util.findErrorPropagation(cxt, name,null); } } else if (ErrorModelPackage.eINSTANCE.getTypeMappingSet() == requiredType) { searchResult = findTypeMappingSet(context, name); } else if (ErrorModelPackage.eINSTANCE.getTypeTransformationSet() == requiredType) { searchResult = findTypeTransformationSet(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorStateMachine() == requiredType) { searchResult = findErrorBehaviorStateMachine(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorState() == requiredType) { searchResult = EMV2Util.findErrorBehaviorState((Element)context, name); } else if (ErrorModelPackage.eINSTANCE.getEventOrPropagation() == requiredType) { searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.IN); if (searchResult == null ){ if (context instanceof ConditionExpression && (EMV2Util.getConditionExpressionContext((ConditionExpression)context) instanceof ErrorDetection || EMV2Util.getConditionExpressionContext((ConditionExpression)context) instanceof ErrorBehaviorTransition)){ // find it only for transitions searchResult = EMV2Util.findErrorBehaviorEvent(cxt, name); } } } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorEvent() == requiredType) { searchResult = EMV2Util.findErrorBehaviorEvent(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorTransition() == requiredType) { searchResult = EMV2Util.findErrorBehaviorTransition(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorFlow() == requiredType) { searchResult = EMV2Util.findErrorFlow(cxt.getContainingClassifier(), name); } else if (Aadl2Package.eINSTANCE.getSubcomponent()==requiredType) { // } else if (Aadl2Package.eINSTANCE.getSubcomponent().isSuperTypeOf(requiredType)) { if (context instanceof SubcomponentElement){ ConditionElement ce = (ConditionElement)context.eContainer(); EList<SubcomponentElement> sublist = ce.getSubcomponents(); int idx = sublist.indexOf(context); Classifier ns = AadlUtil.getContainingClassifier(context); if (idx > 0) { SubcomponentElement se = sublist.get(idx-1); Subcomponent subcomponent = se.getSubcomponent(); ns = subcomponent.getAllClassifier(); } EObject res = ns.findNamedElement(name); if (res instanceof Subcomponent) { searchResult = res; } } } if (searchResult != null) { return Collections.singletonList(searchResult); } return Collections.<EObject> emptyList(); }
diff --git a/contrib/Quote.java b/contrib/Quote.java index 18f3c5b..95426d1 100644 --- a/contrib/Quote.java +++ b/contrib/Quote.java @@ -1,1414 +1,1414 @@ import uk.co.uwcs.choob.*; import uk.co.uwcs.choob.modules.*; import uk.co.uwcs.choob.support.*; import uk.co.uwcs.choob.support.events.*; import java.util.*; import java.util.regex.*; import java.text.*; public class QuoteObject { public int id; public String quoter; public String hostmask; public int lines; public int score; public int up; public int down; public long time; } public class QuoteLine { public int id; public int quoteID; public int lineNumber; public String nick; public String message; public boolean isAction; } public class RecentQuote { public QuoteObject quote; // No sense in caching the lines here. public long time; /* * 0 = displayed * 1 = quoted */ public int type; } public class Quote { private static int MINLENGTH = 7; // Minimum length of a line to be quotable using simple syntax. private static int MINWORDS = 2; // Minimum words in a line to be quotable using simple syntax. private static int HISTORY = 100; // Lines of history to search. private static int EXCERPT = 40; // Maximum length of excerpt text in replies to create. private static int MAXLINES = 10; // Maximum allowed lines in a quote. private static int MAXCLAUSES = 20; // Maximum allowed lines in a quote. private static int MAXJOINS = 6; // Maximum allowed lines in a quote. private static int RECENTLENGTH = 20; // Maximum length of "recent quotes" list for a context. private static String IGNORE = "quoteme|quote|quoten|quote.create"; // Ignore these when searching for regex quotes. private static int THRESHOLD = -3; // Lowest karma of displayed quote. private HashMap<String,List<RecentQuote>> recentQuotes; private Modules mods; private IRCInterface irc; final private Pattern ignorePattern; public Quote( Modules mods, IRCInterface irc ) { this.mods = mods; this.irc = irc; this.ignorePattern = Pattern.compile( "^(?:" + irc.getTriggerRegex() + ")" + "(?:" + IGNORE + ")", Pattern.CASE_INSENSITIVE); recentQuotes = new HashMap<String,List<RecentQuote>>(); } public String[] info() { return new String[] { "Plugin to allow users to create a database of infamous quotes.", "The Choob Team", "[email protected]", "$Rev$$Date$" }; } public String[] helpTopics = { "UsingCreate", "CreateExamples", "UsingGet" }; public String[] helpUsingCreate = { "There's 4 ways of calling Quote.Create.", "If you pass no parameters (or action: or privmsg:), the most recent line (or action) that's long enough will be quoted.", "With just a nickname (or privmsg:<Nick>), the most recent line from that nick will be quoted.", "With action:<Nick>, the most recent action from that nick will be quoted.", "Finally, you can specify one or 2 regular expression searches. If" + " you specify just one, the most recent matching line will be quoted." + " With 2, the first one matches the start of the quote, and the" + " second matches the end. Previous quote commands are skipped when doing" + " any regex matching.", "'Long enough' in this context means at least " + MINLENGTH + " characters, and at least " + MINWORDS + " words.", "Note that nicknames are always made into their short form: 'privmsg:fred|bed' will quote people called 'fred', 'fred|busy', etc.", "See CreateExamples for some examples." }; public String[] helpCreateExamples = { "'Quote.Create action:Fred' will quote the most recent action from Fred, regardless of length.", "'Quote.Create privmsg:' will quote the most recent line that's long enough.", "'Quote.Create fred:/blizzard/ /suck/' will quote the most recent possible quote starting with fred saying 'Blizzard', ending with the first line containing 'suck'." }; public String[] helpUsingGet = { "There are several clauses you can use to select quotes.", "You can specify a number, which will be used as a quote ID.", "A clause '<Selector>:<Relation><Number>', where <Selector> is one of 'score' or 'length', <Relation> is '>', '<' or '=' and <Number> is some number.", "You can use 'quoter:<Nick>' to get quotes made by <Nick>.", "Finally, you can use '<Nick>', '/<Regex>/' or '<Nick>:/<Regex>/' to match only quotes from <Nick>, quotes matching <Regex> or quotes where <Nick> said something matching <Regex>." }; public String[] helpCommandCreate = { "Create a new quote. See Quote.UsingCreate for more info.", "[ [privmsg:][<Nick>] | action:[<Nick>] | [<Nick>:]/<Regex>/ [[<Nick>:]/<Regex>/] ]", "<Nick> is a nickname to quote", "<Regex> is a regular expression to use to match lines" }; public void commandCreate( Message mes ) throws ChoobException { if (!(mes instanceof ChannelEvent)) { irc.sendContextReply( mes, "Sorry, this command can only be used in a channel" ); return; } String chan = ((ChannelEvent)mes).getChannel(); List<Message> history = mods.history.getLastMessages( mes, HISTORY ); String param = mods.util.getParamString(mes).trim(); // Default is privmsg if ( param.equals("") || ((param.charAt(0) < '0' || param.charAt(0) > '9') && param.charAt(0) != '/' && param.indexOf(':') == -1 && param.indexOf(' ') == -1) ) param = "privmsg:" + param; final List<Message> lines = new ArrayList<Message>(); if (param.charAt(0) >= '0' && param.charAt(0) <= '9') { // First digit is a number. That means the rest are, too! (Or at least, we assume so.) String bits[] = param.split(" +"); int offset = 0; int size; if (bits.length > 2) { irc.sendContextReply(mes, "When quoting by offset, you must supply only 1 or 2 parameters."); return; } else if (bits.length == 2) { try { offset = Integer.parseInt(bits[1]); } catch (NumberFormatException e) { irc.sendContextReply(mes, "Numeric offset " + bits[1] + " was not a valid integer..."); return; } } try { size = Integer.parseInt(bits[0]); } catch (NumberFormatException e) { irc.sendContextReply(mes, "Numeric size " + bits[0] + " was not a valid integer..."); return; } if (offset < 0) { irc.sendContextReply(mes, "Can't quote things that haven't happened yet!"); return; } else if (size < 1) { irc.sendContextReply(mes, "Can't quote an empty quote!"); return; } else if (offset + size > history.size()) { irc.sendContextReply(mes, "Can't quote -- memory like a seive!"); return; } // Must do this backwards for(int i=offset + size - 1; i>=offset; i--) lines.add(history.get(i)); } else if (param.charAt(0) != '/' && param.indexOf(':') == -1 && param.indexOf(' ') == -1) { // It's a nickname. String bits[] = param.split("\\s+"); if (bits.length > 2) { irc.sendContextReply(mes, "When quoting by nickname, you must supply only 1 parameter."); return; } String findNick = mods.nick.getBestPrimaryNick( bits[0] ).toLowerCase(); for(int i=0; i<history.size(); i++) { Message line = history.get(i); String text = line.getMessage(); -// if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS) -// continue; + if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS) + continue; String guessNick = mods.nick.getBestPrimaryNick( line.getNick() ); if ( guessNick.toLowerCase().equals(findNick) ) { lines.add(line); break; } } if (lines.size() == 0) { irc.sendContextReply(mes, "No quote found for nickname " + findNick + "."); return; } } else if (param.toLowerCase().startsWith("action:") || param.toLowerCase().startsWith("privmsg:")) { Class thing; if (param.toLowerCase().startsWith("action:")) thing = ChannelAction.class; else thing = ChannelMessage.class; // It's an action from a nickname String bits[] = param.split("\\s+"); if (bits.length > 2) { irc.sendContextReply(mes, "When quoting by type, you must supply only 1 parameter."); return; } bits = bits[0].split(":"); String findNick; if (bits.length == 2) findNick = mods.nick.getBestPrimaryNick( bits[1] ).toLowerCase(); else findNick = null; for(int i=0; i<history.size(); i++) { Message line = history.get(i); String text = line.getMessage(); if (!thing.isInstance(line)) continue; if (findNick != null) { String guessNick = mods.nick.getBestPrimaryNick( line.getNick() ); if ( guessNick.toLowerCase().equals(findNick) ) { lines.add(line); break; } } else { // Check length etc. if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS) continue; lines.add(line); break; } } if (lines.size() == 0) { if (findNick != null) irc.sendContextReply(mes, "No quotes found for nickname " + findNick + "."); else irc.sendContextReply(mes, "No recent quotes of that type!"); return; } } else { // Final case: Regex quoting. // Matches anything of the form [NICK{:| }]/REGEX/ [[NICK{:| }]/REGEX/] // What's allowed in the //s: final String slashslashcontent="[^/]"; // The '[NICK{:| }]/REGEX/' bit: final String token="(?:([^\\s:/]+)[:\\s])?/(" + slashslashcontent + "+)/"; // The '[NICK{:| }]/REGEX/ [[NICK{:| }]/REGEX/]' bit: Matcher ma = Pattern.compile(token + "(?:\\s+" + token + ")?", Pattern.CASE_INSENSITIVE).matcher(param); if (!ma.matches()) { irc.sendContextReply(mes, "Sorry, your string looked like a regex quote but I couldn't decipher it."); return; } String startNick, startRegex, endNick, endRegex; if (ma.group(4) != null) { // The second parameter exists ==> multiline quote startNick = ma.group(1); startRegex = "(?i).*" + ma.group(2) + ".*"; endNick = ma.group(3); endRegex = "(?i).*" + ma.group(4) + ".*"; } else { startNick = null; startRegex = null; endNick = ma.group(1); endRegex = "(?i).*" + ma.group(2) + ".*"; } if (startNick != null) startNick = mods.nick.getBestPrimaryNick( startNick ).toLowerCase(); if (endNick != null) endNick = mods.nick.getBestPrimaryNick( endNick ).toLowerCase(); // OK, do the match! int endIndex = -1, startIndex = -1; for(int i=0; i<history.size(); i++) { final Message line = history.get(i); // Completely disregard lines that are quotey. if (ignorePattern.matcher(line.getMessage()).find()) continue; System.out.println("<" + line.getNick() + "> " + line.getMessage()); final String nick = mods.nick.getBestPrimaryNick( line.getNick() ).toLowerCase(); if ( endRegex != null ) { // Not matched the end yet (the regex being null is an indicator for us having matched it, obviously. But only the end regex). if ((endNick == null || endNick.equals(nick)) && line.getMessage().matches(endRegex)) { // But have matched now... endRegex = null; endIndex = i; // If we weren't doing a multiline regex quote, this is actually the start index. if ( startRegex == null ) { startIndex = i; // And hence we're done. break; } } } else // ..the end has been matched, and we're doing a multiline, so we're looking for the start: { if ((startNick == null || startNick.equals(nick)) && line.getMessage().matches(startRegex)) { // It matches, huzzah, we're done: startIndex = i; break; } } } if (endIndex == -1) // We failed to match the 'first' line: { if (startRegex == null) // We wern't going for a multi-line match: irc.sendContextReply(mes, "Sorry, couldn't find the line you were after."); else irc.sendContextReply(mes, "Sorry, the second regex (for the ending line) didn't match anything, not checking for the start line."); return; } if (startIndex == -1) { final Message endLine=history.get(endIndex); irc.sendContextReply(mes, "Sorry, the first regex (for the start line) couldn't be matched before the end-line I chose: " + formatPreviewLine(endLine.getNick(), endLine.getMessage(), endLine instanceof ChannelAction)); return; } for(int i=startIndex; i>=endIndex; i--) lines.add(history.get(i)); } // Have some lines. // Is it a sensible size? if (lines.size() > MAXLINES) { irc.sendContextReply(mes, "Sorry, this quote is longer than the maximum size of " + MAXLINES + " lines."); return; } // Check for people suspiciously quoting themselves. // For now, that's just if they are the final line in the quote. Message last = lines.get(lines.size() - 1); //*/ Remove the first slash to comment me out. if (last.getLogin().compareToIgnoreCase(mes.getLogin()) == 0 && last.getHostname().compareToIgnoreCase(mes.getHostname()) == 0) { // Suspicious! irc.sendContextReply(mes, "Sorry, no quoting yourself!"); return; } //*/ // OK, build a QuoteObject... final QuoteObject quote = new QuoteObject(); quote.quoter = mods.nick.getBestPrimaryNick(mes.getNick()); quote.hostmask = (mes.getLogin() + "@" + mes.getHostname()).toLowerCase(); quote.lines = lines.size(); quote.score = 0; quote.up = 0; quote.down = 0; quote.time = System.currentTimeMillis(); // QuoteLine object; quoteID will be filled in later. final List quoteLines = new ArrayList(lines.size()); mods.odb.runTransaction( new ObjectDBTransaction() { public void run() { quote.id = 0; save(quote); // Now have a quote ID! quoteLines.clear(); for(int i=0; i<lines.size(); i++) { QuoteLine quoteLine = new QuoteLine(); quoteLine.quoteID = quote.id; quoteLine.id = 0; quoteLine.lineNumber = i; quoteLine.nick = mods.nick.getBestPrimaryNick(lines.get(i).getNick()); quoteLine.message = lines.get(i).getMessage(); quoteLine.isAction = (lines.get(i) instanceof ChannelAction); save(quoteLine); quoteLines.add(quoteLine); } }}); // Remember this quote for later... addLastQuote(mes.getContext(), quote, 1); irc.sendContextReply( mes, "OK, added " + quote.lines + " line quote #" + quote.id + ": " + formatPreview(quoteLines) ); } public String[] helpCommandAdd = { "Add a quote to the database.", "<Nick> <Text> [ ||| <Nick> <Text> ... ]", "the nickname of the person who said the text (of the form '<nick>' or '* nick' or just simply 'nick')", "the text that was actually said" }; public java.security.Permission permissionCommandAdd = new ChoobPermission("plugins.quote.add"); public void commandAdd(Message mes) { mods.security.checkNickPerm(permissionCommandAdd, mes); String params = mods.util.getParamString( mes ); String[] lines = params.split("\\s+\\|\\|\\|\\s+"); final QuoteLine[] content = new QuoteLine[lines.length]; for(int i=0; i<lines.length; i++) { String line = lines[i]; String nick, text; boolean action = false; if (line.charAt(0) == '*') { int spacePos1 = line.indexOf(' '); if (spacePos1 == -1) { irc.sendContextReply(mes, "Line " + i + " was invalid!"); return; } int spacePos2 = line.indexOf(' ', spacePos1 + 1); if (spacePos2 == -1) { irc.sendContextReply(mes, "Line " + i + " was invalid!"); return; } nick = line.substring(spacePos1 + 1, spacePos2); text = line.substring(spacePos2 + 1); action = true; } else if (line.charAt(0) == '<') { int spacePos = line.indexOf(' '); if (spacePos == -1) { irc.sendContextReply(mes, "Line " + i + " was invalid!"); return; } else if (line.charAt(spacePos - 1) != '>') { irc.sendContextReply(mes, "Line " + i + " was invalid!"); return; } nick = line.substring(1, spacePos - 1); text = line.substring(spacePos + 1); } else { int spacePos = line.indexOf(' '); if (spacePos == -1) { irc.sendContextReply(mes, "Line " + i + " was invalid!"); return; } nick = line.substring(0, spacePos); text = line.substring(spacePos + 1); } QuoteLine quoteLine = new QuoteLine(); quoteLine.lineNumber = i; quoteLine.nick = mods.nick.getBestPrimaryNick(nick); quoteLine.message = text; quoteLine.isAction = action; content[i] = quoteLine; } final QuoteObject quote = new QuoteObject(); quote.quoter = mods.nick.getBestPrimaryNick(mes.getNick()); quote.hostmask = (mes.getLogin() + "@" + mes.getHostname()).toLowerCase(); quote.lines = lines.length; quote.score = 0; quote.up = 0; quote.down = 0; quote.time = System.currentTimeMillis(); // QuoteLine object; quoteID will be filled in later. final List quoteLines = new ArrayList(lines.length); mods.odb.runTransaction( new ObjectDBTransaction() { public void run() { // Have to set ID etc. here in case transaction blows up. quote.id = 0; save(quote); // Now have a quote ID! quoteLines.clear(); for(int i=0; i<content.length; i++) { QuoteLine quoteLine = content[i]; quoteLine.quoteID = quote.id; quoteLine.id = 0; save(quoteLine); quoteLines.add(quoteLine); } }}); addLastQuote(mes.getContext(), quote, 1); irc.sendContextReply( mes, "OK, added quote " + quote.id + ": " + formatPreview(quoteLines) ); } private final String formatPreviewLine(final String nick, final String message, final boolean isAction) { String text, prefix; if (message.length() > EXCERPT) text = message.substring(0, 27) + "..."; else text = message; if (isAction) prefix = "* " + nick; else prefix = "<" + nick + ">"; return prefix + " " + text; } private String formatPreview(List<QuoteLine> lines) { if (lines.size() == 1) { final QuoteLine line = lines.get(0); return formatPreviewLine(line.nick, line.message, line.isAction); } else { // last is initalised above QuoteLine first = lines.get(0); String firstText; if (first.isAction) firstText = "* " + first.nick; else firstText = "<" + first.nick + ">"; if (first.message.length() > EXCERPT) firstText += " " + first.message.substring(0, 27) + "..."; else firstText += " " + first.message; QuoteLine last = lines.get(lines.size() - 1); String lastText; if (last.isAction) lastText = "* " + last.nick; else lastText = "<" + last.nick + ">"; if (last.message.length() > EXCERPT) lastText += " " + last.message.substring(0, 27) + "..."; else lastText += " " + last.message; return firstText + " -> " + lastText; } } public String[] helpCommandGet = { "Get a random quote from the database.", "[ <Clause> [ <Clause> ... ]]", "<Clause> is a clause to select quotes with (see Quote.UsingGet)" }; public void commandGet( Message mes ) throws ChoobException { String whereClause = getClause( mods.util.getParamString( mes ) ); List quotes; try { quotes = mods.odb.retrieve( QuoteObject.class, "SORT BY RANDOM LIMIT (1) " + whereClause ); } catch (ObjectDBError e) { if (e.getCause() instanceof java.sql.SQLException) { irc.sendContextReply( mes, "Could not retrieve: " + e.getCause() ); return; } else throw e; } if (quotes.size() == 0) { irc.sendContextReply( mes, "No quotes found!" ); return; } QuoteObject quote = (QuoteObject)quotes.get(0); List lines = mods.odb.retrieve( QuoteLine.class, "WHERE quoteID = " + quote.id + " ORDER BY lineNumber"); Iterator l = lines.iterator(); if (!l.hasNext()) { irc.sendContextReply( mes, "Found quote " + quote.id + " but it was empty!" ); return; } while(l.hasNext()) { QuoteLine line = (QuoteLine)l.next(); if (line.isAction) irc.sendContextMessage( mes, "* " + line.nick + " " + line.message ); else irc.sendContextMessage( mes, "<" + line.nick + "> " + line.message ); } // Remember this quote for later... addLastQuote(mes.getContext(), quote, 0); } public String[] helpApiSingleLineQuote = { "Get a single line quote from the specified nickname, optionally adding it to the recent quotes list for the passed context.", "Either the single line quote, or null if there was none.", "<nick> [<context>]", "the nickname to get a quote from", "the optional context in which the quote will be displayed" }; public String apiSingleLineQuote(String nick) { return apiSingleLineQuote(nick, null); } public String apiSingleLineQuote(String nick, String context) { String whereClause = getClause(nick + " length:=1"); List quotes = mods.odb.retrieve( QuoteObject.class, "SORT BY RANDOM LIMIT (1) " + whereClause ); if (quotes.size() == 0) return null; QuoteObject quote = (QuoteObject)quotes.get(0); List <QuoteLine>lines = mods.odb.retrieve( QuoteLine.class, "WHERE quoteID = " + quote.id ); if (lines.size() == 0) { System.err.println("Found quote " + quote.id + " but it was empty!" ); return null; } if (context != null) addLastQuote(context, quote, 0); QuoteLine line = lines.get(0); if (line.isAction) return "/me " + line.message; else return line.message; } private void addLastQuote(String context, QuoteObject quote, int type) { synchronized(recentQuotes) { List<RecentQuote> recent = recentQuotes.get(context); if (recent == null) { recent = new LinkedList<RecentQuote>(); recentQuotes.put( context, recent ); } RecentQuote info = new RecentQuote(); info.quote = quote; info.time = System.currentTimeMillis(); info.type = type; recent.add(0, info); while (recent.size() > RECENTLENGTH) recent.remove( RECENTLENGTH ); } } public String[] helpCommandCount = { "Get the number of matching quotes.", "[ <Clause> [ <Clause> ... ]]", "<Clause> is a clause to select quotes with (see Quote.UsingGet)" }; public void commandCount( Message mes ) throws ChoobException { final String whereClause = getClause( mods.util.getParamString( mes ) ); final List<QuoteObject> quoteCounts = mods.odb.retrieve( QuoteObject.class, whereClause ); final Set<Integer> ids = new HashSet<Integer>(); for (QuoteObject q : quoteCounts) ids.add(q.id); final int count = ids.size(); if (count == 0) irc.sendContextReply( mes, "Sorry, no quotes match!" ); else if (count == 1) irc.sendContextReply( mes, "There's just the one quote..." ); else irc.sendContextReply( mes, "There are " + count + " quotes!" ); } // quotekarma, quotesummary public String[] helpCommandSummary = { "Get a summary of matching quotes.", "[ <Clause> [ <Clause> ... ]]", "<Clause> is a clause to select quotes with (see Quote.UsingGet)" }; public void commandSummary( Message mes ) throws ChoobException { String whereClause = getClause( mods.util.getParamString(mes) ); List<QuoteObject> quoteKarmasSpam = mods.odb.retrieve( QuoteObject.class, whereClause ); Map<Integer, QuoteObject> quoteKarmaIds = new HashMap<Integer, QuoteObject>(); for (QuoteObject q : quoteKarmasSpam) quoteKarmaIds.put(q.id, q); List<Integer> quoteKarmas = new ArrayList<Integer>(); for (QuoteObject q : quoteKarmaIds.values()) quoteKarmas.add(q.score); int count = quoteKarmas.size(); int nonZeroCount = 0; int total = 0; int max = 0, min = 0; for(Integer i: quoteKarmas) { total += i; if (i != 0) { nonZeroCount++; if (i < min) min = i; else if (i > max) max = i; } } DecimalFormat format = new DecimalFormat("##0.00"); String avKarma = format.format((double) total / (double) count); String avNonZeroKarma = format.format((double) total / (double) nonZeroCount); if (count == 0) irc.sendContextReply( mes, "Sorry, no quotes found!" ); else if (count == 1) irc.sendContextReply( mes, "I only found one quote; karma is " + total + "." ); else irc.sendContextReply( mes, "Found " + count + " quotes. The total karma is " + total + ", average " + avKarma + ". " + nonZeroCount + " quotes had a karma; average for these is " + avNonZeroKarma + ". Min karma is " + min + " and max is " + max + "." ); } public String[] helpCommandInfo = { "Get info about a particular quote.", "[ <QuoteID> ]", "<QuoteID> is the ID of a quote" }; public void commandInfo( Message mes ) throws ChoobException { int quoteID = -1; List<String> params = mods.util.getParams(mes); if ( params.size() > 2 ) { irc.sendContextReply( mes, "Syntax: 'Quote.Info " + helpCommandInfo[1] + "'." ); return; } // Check input try { if ( params.size() == 2 ) quoteID = Integer.parseInt( params.get(1) ); } catch ( NumberFormatException e ) { irc.sendContextReply( mes, "Syntax: 'Quote.Info " + helpCommandInfo[1] + "'." ); return; } if (quoteID == -1) { synchronized(recentQuotes) { String context = mes.getContext(); List<RecentQuote> recent = recentQuotes.get(context); if (recent == null || recent.size() == 0) { irc.sendContextReply( mes, "Sorry, no quotes seen from here!" ); return; } quoteID = recent.get(0).quote.id; } } List<QuoteObject> quotes = mods.odb.retrieve( QuoteObject.class, "WHERE id = " + quoteID ); if (quotes.size() == 0) { irc.sendContextReply( mes, "Quote " + quoteID + " does not exist!" ); return; } QuoteObject quote = quotes.get(0); if (quote.time == 0) irc.sendContextReply(mes, "Quote #" + quote.id + ": Quoted by " + quote.quoter + " at Bob knows when. This is a " + quote.lines + " line quote with a karma of " + quote.score + " (" + quote.up + " up, " + quote.down + " down)." ); else irc.sendContextReply(mes, "Quote #" + quote.id + ": Quoted by " + quote.quoter + " on " + (new Date(quote.time)) + ". This is a " + quote.lines + " line quote with a karma of " + quote.score + " (" + quote.up + " up, " + quote.down + " down)." ); } public String[] helpCommandRemove = { "Remove your most recently added quote.", }; public void commandRemove( Message mes ) throws ChoobException { // Quotes are stored by context... synchronized(recentQuotes) { String context = mes.getContext(); List<RecentQuote> recent = recentQuotes.get(context); if (recent == null || recent.size() == 0) { irc.sendContextReply( mes, "Sorry, no quotes seen from here!" ); return; } String nick = mods.nick.getBestPrimaryNick(mes.getNick()).toLowerCase(); String hostmask = (mes.getLogin() + "@" + mes.getHostname()).toLowerCase(); Iterator<RecentQuote> iter = recent.iterator(); QuoteObject quote = null; RecentQuote info = null; while(iter.hasNext()) { info = iter.next(); if (info.type == 1 && info.quote.quoter.toLowerCase().equals(nick) && info.quote.hostmask.equals(hostmask)) { quote = info.quote; break; } } if (quote == null) { irc.sendContextReply( mes, "Sorry, you haven't quoted anything recently here!" ); return; } final QuoteObject theQuote = quote; final List<QuoteLine> quoteLines = mods.odb.retrieve( QuoteLine.class, "WHERE quoteID = " + quote.id ); mods.odb.runTransaction( new ObjectDBTransaction() { public void run() { delete(theQuote); // Now have a quote ID! for(QuoteLine line: quoteLines) { delete(line); } }}); recent.remove(info); // So the next unquote doesn't hit it irc.sendContextReply( mes, "OK, unquoted quote " + quote.id + " (" + formatPreview(quoteLines) + ")." ); } } public String[] helpCommandLast = { "Get a list of recent quote IDs.", "[<Count>]", "<Count> is the maximum number to return (default is 1)" }; public void commandLast( Message mes ) throws ChoobException { // Get a count... int count = 1; String param = mods.util.getParamString(mes); try { if ( param.length() > 0 ) count = Integer.parseInt( param ); } catch ( NumberFormatException e ) { irc.sendContextReply( mes, "'" + param + "' is not a valid integer!" ); return; } synchronized(recentQuotes) { String context = mes.getContext(); List<RecentQuote> recent = recentQuotes.get(context); if (recent == null || recent.size() == 0) { irc.sendContextReply( mes, "Sorry, no quotes seen from here!" ); return; } // Ugly hack to avoid lack of last()... ListIterator<RecentQuote> iter = recent.listIterator(); RecentQuote info = null; QuoteObject quote = null; boolean first = true; String output = null; int remain = count; while(iter.hasNext() && remain-- > 0) { info = iter.next(); if (!first) output = output + ", " + info.quote.id; else output = "" + info.quote.id; first = false; } if (count == 1) irc.sendContextReply( mes, "Most recent quote ID: " + output + "." ); else irc.sendContextReply( mes, "Most recent quote IDs (most recent first): " + output + "." ); } } public String[] helpCommandKarmaMod = { "Increase or decrease the karma of a quote.", "<Direction> [<ID>]", "<Direction> is 'up' or 'down'", "<ID> is an optional quote ID (default is to use the most recent)" }; public synchronized void commandKarmaMod( Message mes ) throws ChoobException { int quoteID = -1; boolean up = true; List<String> params = mods.util.getParams(mes); if (params.size() == 1 || params.size() > 3) { irc.sendContextReply( mes, "Syntax: quote.KarmaMod {up|down} [number]" ); return; } // Check input try { if ( params.size() == 3 ) quoteID = Integer.parseInt( params.get(2) ); } catch ( NumberFormatException e ) { // History dictates that this be ignored. } if ( params.get(1).toLowerCase().equals("down") ) up = false; else if ( params.get(1).toLowerCase().equals("up") ) up = true; else { irc.sendContextReply( mes, "Syntax: quote.KarmaMod {up|down} [number]" ); return; } String leet; if (up) leet = "l33t"; else leet = "lame"; if (quoteID == -1) { synchronized(recentQuotes) { String context = mes.getContext(); List<RecentQuote> recent = recentQuotes.get(context); if (recent == null || recent.size() == 0) { irc.sendContextReply( mes, "Sorry, no quotes seen from here!" ); return; } quoteID = recent.get(0).quote.id; } } List quotes = mods.odb.retrieve( QuoteObject.class, "WHERE id = " + quoteID ); if (quotes.size() == 0) { irc.sendContextReply( mes, "No such quote to " + leet + "!" ); return; } QuoteObject quote = (QuoteObject)quotes.get(0); if (up) { if (quote.score == THRESHOLD - 1) { if (mods.security.hasNickPerm( new ChoobPermission( "quote.delete" ), mes )) { quote.score++; quote.up++; irc.sendContextReply( mes, "OK, quote " + quoteID + " is now leet enough to be seen! Current karma is " + quote.score + "." ); } else { irc.sendContextReply( mes, "Sorry, that quote is on the karma threshold. Only an admin can make it more leet!" ); return; } } else { quote.score++; quote.up++; irc.sendContextReply( mes, "OK, quote " + quoteID + " is now more leet! Current karma is " + quote.score + "." ); } } else if (quote.score == THRESHOLD) { if (mods.security.hasNickPerm( new ChoobPermission( "quote.delete" ), mes )) { quote.score--; quote.down++; irc.sendContextReply( mes, "OK, quote " + quoteID + " is now too lame to be seen! Current karma is " + quote.score + "." ); } else { irc.sendContextReply( mes, "Sorry, that quote is on the karma threshold. Only an admin can make it more lame!" ); return; } } else { quote.score--; quote.down++; irc.sendContextReply( mes, "OK, quote " + quoteID + " is now more lame! Current karma is " + quote.score + "." ); } mods.odb.update(quote); } /** * Simple parser for quote searches... */ private String getClause(String text) { List<String> clauses = new ArrayList<String>(); boolean score = false; // True if score clause added. int pos = text.equals("") ? -1 : 0; int joins = 0; while(pos != -1) { // Avoid problems with initial zero value... if (pos != 0) pos++; // Initially, cut at space int endPos = text.indexOf(' ', pos); if (endPos == -1) endPos = text.length(); String param = text.substring(pos, endPos); String user = null; // User for regexes. Used later. int colon = param.indexOf(':'); int slash = param.indexOf('/'); // If there is a /, make sure the color is before it. if ((slash >= 0) && (colon > slash)) colon = -1; boolean fiddled = false; // Set to true if param already parsed if (colon != -1) { String first = param.substring(0, colon).toLowerCase(); param = param.substring(colon + 1); if (param.length()==0) throw new ChoobError("Empty selector: " + first); if (param.charAt(0) == '/') { // This must be a regex with a user parameter. Save for later. user = mods.nick.getBestPrimaryNick( first ); pos = pos + colon + 1; } // OK, not a regex. What else might it be? else if (first.equals("length")) { // Length modifier. if (param.length() <= 1) throw new ChoobError("Invalid/empty length selector."); char op = param.charAt(0); if (op != '>' && op != '<' && op != '=') throw new ChoobError("Invalid length selector: " + param); int length; try { length = Integer.parseInt(param.substring(1)); } catch (NumberFormatException e) { throw new ChoobError("Invalid length selector: " + param); } clauses.add("lines " + op + " " + length); fiddled = true; } else if (first.equals("quoter")) { if (param.length() < 1) throw new ChoobError("Empty quoter nickname."); clauses.add("quoter = \"" + mods.odb.escapeString(param) + "\""); fiddled = true; } else if (first.equals("score")) { if (param.length() <= 1) throw new ChoobError("Invalid/empty score selector."); char op = param.charAt(0); if (op != '>' && op != '<' && op != '=') throw new ChoobError("Invalid score selector: " + param); int value; try { value = Integer.parseInt(param.substring(1)); } catch (NumberFormatException e) { throw new ChoobError("Invalid score selector: " + param); } clauses.add("score " + op + " " + value); score = true; fiddled = true; } else if (first.equals("id")) { if (param.length() <= 1) throw new ChoobError("Invalid/empty id selector."); char op = param.charAt(0); if (op != '>' && op != '<' && op != '=') throw new ChoobError("Invalid id selector: " + param); int value; try { value = Integer.parseInt(param.substring(1)); } catch (NumberFormatException e) { throw new ChoobError("Invalid id selector: " + param); } clauses.add("id " + op + " " + value); fiddled = true; } // That's all the special cases out of the way. If we're still // here, were's screwed... else { throw new ChoobError("Unknown selector type: " + first); } } if (fiddled) { } // Do nothing // Right. We know that we either have a quoted nickname or a regex... else if (param.charAt(0) == '/') { // This is a regex, then. // Get a matcher on th region from here to the end of the string... Matcher ma = Pattern.compile("^(?:\\\\.|[^\\\\/])*?/", Pattern.CASE_INSENSITIVE).matcher(text).region(pos+1,text.length()); if (!ma.find()) throw new ChoobError("Regular expression has no end!"); int end = ma.end(); String regex = text.substring(pos + 1, end - 1); clauses.add("join"+joins+".message RLIKE \"" + mods.odb.escapeString(regex) + "\""); if (user != null) clauses.add("join"+joins+".nick = \"" + mods.odb.escapeString(user) + "\""); clauses.add("join"+joins+".quoteID = id"); joins++; pos = end-1; // In case there's a space, this is the / } else if (param.charAt(0) >= '0' && param.charAt(0) <= '9') { // Number -> Quote-by-ID int value; try { value = Integer.parseInt(param); } catch (NumberFormatException e) { throw new ChoobError("Invalid quote number: " + param); } clauses.add("id = " + value); } else { // This is a name user = mods.nick.getBestPrimaryNick( param ); clauses.add("join"+joins+".nick = \"" + mods.odb.escapeString(user) + "\""); clauses.add("join"+joins+".quoteID = id"); joins++; } // Make sure we skip any double spaces... pos = text.indexOf(' ', pos + 1); while( pos < text.length() - 1 && text.charAt(pos + 1) == ' ') { pos++; } // And that we haven't hopped off the end... if (pos == text.length() - 1) pos = -1; } // All those joins hate MySQL. if (joins > MAXJOINS) throw new ChoobError("Sorry, due to MySQL being whorish, only " + MAXJOINS + " nickname or line clause(s) allowed for now."); else if (clauses.size() > MAXCLAUSES) throw new ChoobError("Sorry, due to MySQL being whorish, only " + MAXCLAUSES + " clause(s) allowed for now."); if (!score) clauses.add("score > " + (THRESHOLD - 1)); StringBuffer search = new StringBuffer(); for(int i=0; i<joins; i++) search.append("WITH " + QuoteLine.class.getName() + " AS join" + i + " "); if (clauses.size() > 0) { search.append("WHERE "); for(int i=0; i<clauses.size(); i++) { if (i != 0) search.append(" AND "); search.append(clauses.get(i)); } } return search.toString(); } public String[] optionsUser = { "JoinMessage", "JoinQuote" }; public String[] optionsUserDefaults = { "1", "1" }; public boolean optionCheckUserJoinQuote( String optionValue, String userName ) { return _optionCheck( optionValue ); } public boolean optionCheckUserJoinMessage( String optionValue, String userName ) { return _optionCheck( optionValue ); } public String[] optionsGeneral = { "JoinMessage", "JoinQuote" }; public String[] optionsGeneralDefaults = { "1", "1" }; public boolean optionCheckGeneralJoinQuote( String optionValue ) { return _optionCheck( optionValue ); } public boolean optionCheckGeneralJoinMessage( String optionValue ) { return _optionCheck( optionValue ); } public String[] helpOptionJoinQuote = { "Determine whether or not you recieve a quote upon joining a channel.", "Set this to \"0\" to disable quotes, \"1\" to enable them (default)," + " or \"<N>:<Chans>\" with <N> \"0\" or \"1\" and <Chans> a" + " comma-seperated list of channels to apply <N> to. Other channels get" + " the opposite.", "Example: \"1:#bots\" to enable only for #bots, or \"0:#compsoc,#tech\"" + " to enable everywhere but #compsoc and #tech." }; public String[] helpOptionJoinMessage = { "Determine whether or not you recieve a message upon joining a channel.", "Set this to \"0\" to disable quotes, \"1\" to enable them (default)," + " or \"<N>:<Chans>\" with <N> \"0\" or \"1\" and <Chans> a" + " comma-seperated list of channels to apply <N> to. Other channels get" + " the opposite.", "Example: \"1:#bots\" to enable only for #bots, or \"0:#compsoc,#tech\"" + " to enable everywhere but #compsoc and #tech." }; // format: {0,1}[:<chanlist>] private boolean _optionCheck(String optionValue) { String[] parts = optionValue.split(":", -1); if (parts.length > 2) return false; if (!parts[0].equals("1") && !parts[0].equals("0")) return false; if (parts.length > 1) { // Make sure they're all channels. String[] chans = parts[1].split(","); for(int i=0; i<chans.length; i++) { if (!chans[i].startsWith("#")) return false; } return true; } else return true; } private boolean shouldMessage( ChannelJoin ev ) { return checkOption( ev, "JoinMessage" ); } private boolean shouldQuote( ChannelJoin ev ) { return checkOption( ev, "JoinQuote" ); } private boolean checkOption( ChannelJoin ev, String name ) { return checkOption(ev, name, true) && checkOption(ev, name, false); } private boolean checkOption( ChannelJoin ev, String name, boolean global ) { try { String value; if (global) value = (String)mods.plugin.callAPI("Options", "GetGeneralOption", name, "1"); else value = (String)mods.plugin.callAPI("Options", "GetUserOption", ev.getNick(), name, "1"); String[] parts = value.split(":", -1); boolean soFar; if (parts[0].equals("1")) soFar = true; else soFar = false; if (parts.length > 1) { // If it's in the list, same, else invert. String[] chans = parts[1].split(","); String lcChan = ev.getChannel().toLowerCase(); for(int i=0; i<chans.length; i++) { if (chans[i].toLowerCase().equals(lcChan)) return soFar; } return !soFar; } else // No list, so always same as first param. return soFar; } catch (ChoobNoSuchCallException e) { return true; } } public void onJoin( ChannelJoin ev, Modules mods, IRCInterface irc ) { if (ev.getLogin().equals("Choob")) // XXX return; if (shouldMessage(ev)) { String quote; if ( shouldQuote(ev) ) quote = apiSingleLineQuote( ev.getNick(), ev.getContext() ); else quote = null; final String greeting="Hello, "; if (quote == null) irc.sendContextMessage( ev, greeting + ev.getNick() + "!"); else irc.sendContextMessage( ev, greeting + ev.getNick() + ": \"" + quote + "\""); } } }
true
true
public void commandCreate( Message mes ) throws ChoobException { if (!(mes instanceof ChannelEvent)) { irc.sendContextReply( mes, "Sorry, this command can only be used in a channel" ); return; } String chan = ((ChannelEvent)mes).getChannel(); List<Message> history = mods.history.getLastMessages( mes, HISTORY ); String param = mods.util.getParamString(mes).trim(); // Default is privmsg if ( param.equals("") || ((param.charAt(0) < '0' || param.charAt(0) > '9') && param.charAt(0) != '/' && param.indexOf(':') == -1 && param.indexOf(' ') == -1) ) param = "privmsg:" + param; final List<Message> lines = new ArrayList<Message>(); if (param.charAt(0) >= '0' && param.charAt(0) <= '9') { // First digit is a number. That means the rest are, too! (Or at least, we assume so.) String bits[] = param.split(" +"); int offset = 0; int size; if (bits.length > 2) { irc.sendContextReply(mes, "When quoting by offset, you must supply only 1 or 2 parameters."); return; } else if (bits.length == 2) { try { offset = Integer.parseInt(bits[1]); } catch (NumberFormatException e) { irc.sendContextReply(mes, "Numeric offset " + bits[1] + " was not a valid integer..."); return; } } try { size = Integer.parseInt(bits[0]); } catch (NumberFormatException e) { irc.sendContextReply(mes, "Numeric size " + bits[0] + " was not a valid integer..."); return; } if (offset < 0) { irc.sendContextReply(mes, "Can't quote things that haven't happened yet!"); return; } else if (size < 1) { irc.sendContextReply(mes, "Can't quote an empty quote!"); return; } else if (offset + size > history.size()) { irc.sendContextReply(mes, "Can't quote -- memory like a seive!"); return; } // Must do this backwards for(int i=offset + size - 1; i>=offset; i--) lines.add(history.get(i)); } else if (param.charAt(0) != '/' && param.indexOf(':') == -1 && param.indexOf(' ') == -1) { // It's a nickname. String bits[] = param.split("\\s+"); if (bits.length > 2) { irc.sendContextReply(mes, "When quoting by nickname, you must supply only 1 parameter."); return; } String findNick = mods.nick.getBestPrimaryNick( bits[0] ).toLowerCase(); for(int i=0; i<history.size(); i++) { Message line = history.get(i); String text = line.getMessage(); // if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS) // continue; String guessNick = mods.nick.getBestPrimaryNick( line.getNick() ); if ( guessNick.toLowerCase().equals(findNick) ) { lines.add(line); break; } } if (lines.size() == 0) { irc.sendContextReply(mes, "No quote found for nickname " + findNick + "."); return; } } else if (param.toLowerCase().startsWith("action:") || param.toLowerCase().startsWith("privmsg:")) { Class thing; if (param.toLowerCase().startsWith("action:")) thing = ChannelAction.class; else thing = ChannelMessage.class; // It's an action from a nickname String bits[] = param.split("\\s+"); if (bits.length > 2) { irc.sendContextReply(mes, "When quoting by type, you must supply only 1 parameter."); return; } bits = bits[0].split(":"); String findNick; if (bits.length == 2) findNick = mods.nick.getBestPrimaryNick( bits[1] ).toLowerCase(); else findNick = null; for(int i=0; i<history.size(); i++) { Message line = history.get(i); String text = line.getMessage(); if (!thing.isInstance(line)) continue; if (findNick != null) { String guessNick = mods.nick.getBestPrimaryNick( line.getNick() ); if ( guessNick.toLowerCase().equals(findNick) ) { lines.add(line); break; } } else { // Check length etc. if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS) continue; lines.add(line); break; } } if (lines.size() == 0) { if (findNick != null) irc.sendContextReply(mes, "No quotes found for nickname " + findNick + "."); else irc.sendContextReply(mes, "No recent quotes of that type!"); return; } } else { // Final case: Regex quoting. // Matches anything of the form [NICK{:| }]/REGEX/ [[NICK{:| }]/REGEX/] // What's allowed in the //s: final String slashslashcontent="[^/]"; // The '[NICK{:| }]/REGEX/' bit: final String token="(?:([^\\s:/]+)[:\\s])?/(" + slashslashcontent + "+)/"; // The '[NICK{:| }]/REGEX/ [[NICK{:| }]/REGEX/]' bit: Matcher ma = Pattern.compile(token + "(?:\\s+" + token + ")?", Pattern.CASE_INSENSITIVE).matcher(param); if (!ma.matches()) { irc.sendContextReply(mes, "Sorry, your string looked like a regex quote but I couldn't decipher it."); return; } String startNick, startRegex, endNick, endRegex; if (ma.group(4) != null) { // The second parameter exists ==> multiline quote startNick = ma.group(1); startRegex = "(?i).*" + ma.group(2) + ".*"; endNick = ma.group(3); endRegex = "(?i).*" + ma.group(4) + ".*"; } else { startNick = null; startRegex = null; endNick = ma.group(1); endRegex = "(?i).*" + ma.group(2) + ".*"; } if (startNick != null) startNick = mods.nick.getBestPrimaryNick( startNick ).toLowerCase(); if (endNick != null) endNick = mods.nick.getBestPrimaryNick( endNick ).toLowerCase(); // OK, do the match! int endIndex = -1, startIndex = -1; for(int i=0; i<history.size(); i++) { final Message line = history.get(i); // Completely disregard lines that are quotey. if (ignorePattern.matcher(line.getMessage()).find()) continue; System.out.println("<" + line.getNick() + "> " + line.getMessage()); final String nick = mods.nick.getBestPrimaryNick( line.getNick() ).toLowerCase(); if ( endRegex != null ) { // Not matched the end yet (the regex being null is an indicator for us having matched it, obviously. But only the end regex). if ((endNick == null || endNick.equals(nick)) && line.getMessage().matches(endRegex)) { // But have matched now... endRegex = null; endIndex = i; // If we weren't doing a multiline regex quote, this is actually the start index. if ( startRegex == null ) { startIndex = i; // And hence we're done. break; } } } else // ..the end has been matched, and we're doing a multiline, so we're looking for the start: { if ((startNick == null || startNick.equals(nick)) && line.getMessage().matches(startRegex)) { // It matches, huzzah, we're done: startIndex = i; break; } } } if (endIndex == -1) // We failed to match the 'first' line: { if (startRegex == null) // We wern't going for a multi-line match: irc.sendContextReply(mes, "Sorry, couldn't find the line you were after."); else irc.sendContextReply(mes, "Sorry, the second regex (for the ending line) didn't match anything, not checking for the start line."); return; } if (startIndex == -1) { final Message endLine=history.get(endIndex); irc.sendContextReply(mes, "Sorry, the first regex (for the start line) couldn't be matched before the end-line I chose: " + formatPreviewLine(endLine.getNick(), endLine.getMessage(), endLine instanceof ChannelAction)); return; } for(int i=startIndex; i>=endIndex; i--) lines.add(history.get(i)); } // Have some lines. // Is it a sensible size? if (lines.size() > MAXLINES) { irc.sendContextReply(mes, "Sorry, this quote is longer than the maximum size of " + MAXLINES + " lines."); return; } // Check for people suspiciously quoting themselves. // For now, that's just if they are the final line in the quote. Message last = lines.get(lines.size() - 1); //*/ Remove the first slash to comment me out. if (last.getLogin().compareToIgnoreCase(mes.getLogin()) == 0 && last.getHostname().compareToIgnoreCase(mes.getHostname()) == 0) { // Suspicious! irc.sendContextReply(mes, "Sorry, no quoting yourself!"); return; } //*/ // OK, build a QuoteObject... final QuoteObject quote = new QuoteObject(); quote.quoter = mods.nick.getBestPrimaryNick(mes.getNick()); quote.hostmask = (mes.getLogin() + "@" + mes.getHostname()).toLowerCase(); quote.lines = lines.size(); quote.score = 0; quote.up = 0; quote.down = 0; quote.time = System.currentTimeMillis(); // QuoteLine object; quoteID will be filled in later. final List quoteLines = new ArrayList(lines.size()); mods.odb.runTransaction( new ObjectDBTransaction() { public void run() { quote.id = 0; save(quote); // Now have a quote ID! quoteLines.clear(); for(int i=0; i<lines.size(); i++) { QuoteLine quoteLine = new QuoteLine(); quoteLine.quoteID = quote.id; quoteLine.id = 0; quoteLine.lineNumber = i; quoteLine.nick = mods.nick.getBestPrimaryNick(lines.get(i).getNick()); quoteLine.message = lines.get(i).getMessage(); quoteLine.isAction = (lines.get(i) instanceof ChannelAction); save(quoteLine); quoteLines.add(quoteLine); } }}); // Remember this quote for later... addLastQuote(mes.getContext(), quote, 1); irc.sendContextReply( mes, "OK, added " + quote.lines + " line quote #" + quote.id + ": " + formatPreview(quoteLines) ); }
public void commandCreate( Message mes ) throws ChoobException { if (!(mes instanceof ChannelEvent)) { irc.sendContextReply( mes, "Sorry, this command can only be used in a channel" ); return; } String chan = ((ChannelEvent)mes).getChannel(); List<Message> history = mods.history.getLastMessages( mes, HISTORY ); String param = mods.util.getParamString(mes).trim(); // Default is privmsg if ( param.equals("") || ((param.charAt(0) < '0' || param.charAt(0) > '9') && param.charAt(0) != '/' && param.indexOf(':') == -1 && param.indexOf(' ') == -1) ) param = "privmsg:" + param; final List<Message> lines = new ArrayList<Message>(); if (param.charAt(0) >= '0' && param.charAt(0) <= '9') { // First digit is a number. That means the rest are, too! (Or at least, we assume so.) String bits[] = param.split(" +"); int offset = 0; int size; if (bits.length > 2) { irc.sendContextReply(mes, "When quoting by offset, you must supply only 1 or 2 parameters."); return; } else if (bits.length == 2) { try { offset = Integer.parseInt(bits[1]); } catch (NumberFormatException e) { irc.sendContextReply(mes, "Numeric offset " + bits[1] + " was not a valid integer..."); return; } } try { size = Integer.parseInt(bits[0]); } catch (NumberFormatException e) { irc.sendContextReply(mes, "Numeric size " + bits[0] + " was not a valid integer..."); return; } if (offset < 0) { irc.sendContextReply(mes, "Can't quote things that haven't happened yet!"); return; } else if (size < 1) { irc.sendContextReply(mes, "Can't quote an empty quote!"); return; } else if (offset + size > history.size()) { irc.sendContextReply(mes, "Can't quote -- memory like a seive!"); return; } // Must do this backwards for(int i=offset + size - 1; i>=offset; i--) lines.add(history.get(i)); } else if (param.charAt(0) != '/' && param.indexOf(':') == -1 && param.indexOf(' ') == -1) { // It's a nickname. String bits[] = param.split("\\s+"); if (bits.length > 2) { irc.sendContextReply(mes, "When quoting by nickname, you must supply only 1 parameter."); return; } String findNick = mods.nick.getBestPrimaryNick( bits[0] ).toLowerCase(); for(int i=0; i<history.size(); i++) { Message line = history.get(i); String text = line.getMessage(); if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS) continue; String guessNick = mods.nick.getBestPrimaryNick( line.getNick() ); if ( guessNick.toLowerCase().equals(findNick) ) { lines.add(line); break; } } if (lines.size() == 0) { irc.sendContextReply(mes, "No quote found for nickname " + findNick + "."); return; } } else if (param.toLowerCase().startsWith("action:") || param.toLowerCase().startsWith("privmsg:")) { Class thing; if (param.toLowerCase().startsWith("action:")) thing = ChannelAction.class; else thing = ChannelMessage.class; // It's an action from a nickname String bits[] = param.split("\\s+"); if (bits.length > 2) { irc.sendContextReply(mes, "When quoting by type, you must supply only 1 parameter."); return; } bits = bits[0].split(":"); String findNick; if (bits.length == 2) findNick = mods.nick.getBestPrimaryNick( bits[1] ).toLowerCase(); else findNick = null; for(int i=0; i<history.size(); i++) { Message line = history.get(i); String text = line.getMessage(); if (!thing.isInstance(line)) continue; if (findNick != null) { String guessNick = mods.nick.getBestPrimaryNick( line.getNick() ); if ( guessNick.toLowerCase().equals(findNick) ) { lines.add(line); break; } } else { // Check length etc. if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS) continue; lines.add(line); break; } } if (lines.size() == 0) { if (findNick != null) irc.sendContextReply(mes, "No quotes found for nickname " + findNick + "."); else irc.sendContextReply(mes, "No recent quotes of that type!"); return; } } else { // Final case: Regex quoting. // Matches anything of the form [NICK{:| }]/REGEX/ [[NICK{:| }]/REGEX/] // What's allowed in the //s: final String slashslashcontent="[^/]"; // The '[NICK{:| }]/REGEX/' bit: final String token="(?:([^\\s:/]+)[:\\s])?/(" + slashslashcontent + "+)/"; // The '[NICK{:| }]/REGEX/ [[NICK{:| }]/REGEX/]' bit: Matcher ma = Pattern.compile(token + "(?:\\s+" + token + ")?", Pattern.CASE_INSENSITIVE).matcher(param); if (!ma.matches()) { irc.sendContextReply(mes, "Sorry, your string looked like a regex quote but I couldn't decipher it."); return; } String startNick, startRegex, endNick, endRegex; if (ma.group(4) != null) { // The second parameter exists ==> multiline quote startNick = ma.group(1); startRegex = "(?i).*" + ma.group(2) + ".*"; endNick = ma.group(3); endRegex = "(?i).*" + ma.group(4) + ".*"; } else { startNick = null; startRegex = null; endNick = ma.group(1); endRegex = "(?i).*" + ma.group(2) + ".*"; } if (startNick != null) startNick = mods.nick.getBestPrimaryNick( startNick ).toLowerCase(); if (endNick != null) endNick = mods.nick.getBestPrimaryNick( endNick ).toLowerCase(); // OK, do the match! int endIndex = -1, startIndex = -1; for(int i=0; i<history.size(); i++) { final Message line = history.get(i); // Completely disregard lines that are quotey. if (ignorePattern.matcher(line.getMessage()).find()) continue; System.out.println("<" + line.getNick() + "> " + line.getMessage()); final String nick = mods.nick.getBestPrimaryNick( line.getNick() ).toLowerCase(); if ( endRegex != null ) { // Not matched the end yet (the regex being null is an indicator for us having matched it, obviously. But only the end regex). if ((endNick == null || endNick.equals(nick)) && line.getMessage().matches(endRegex)) { // But have matched now... endRegex = null; endIndex = i; // If we weren't doing a multiline regex quote, this is actually the start index. if ( startRegex == null ) { startIndex = i; // And hence we're done. break; } } } else // ..the end has been matched, and we're doing a multiline, so we're looking for the start: { if ((startNick == null || startNick.equals(nick)) && line.getMessage().matches(startRegex)) { // It matches, huzzah, we're done: startIndex = i; break; } } } if (endIndex == -1) // We failed to match the 'first' line: { if (startRegex == null) // We wern't going for a multi-line match: irc.sendContextReply(mes, "Sorry, couldn't find the line you were after."); else irc.sendContextReply(mes, "Sorry, the second regex (for the ending line) didn't match anything, not checking for the start line."); return; } if (startIndex == -1) { final Message endLine=history.get(endIndex); irc.sendContextReply(mes, "Sorry, the first regex (for the start line) couldn't be matched before the end-line I chose: " + formatPreviewLine(endLine.getNick(), endLine.getMessage(), endLine instanceof ChannelAction)); return; } for(int i=startIndex; i>=endIndex; i--) lines.add(history.get(i)); } // Have some lines. // Is it a sensible size? if (lines.size() > MAXLINES) { irc.sendContextReply(mes, "Sorry, this quote is longer than the maximum size of " + MAXLINES + " lines."); return; } // Check for people suspiciously quoting themselves. // For now, that's just if they are the final line in the quote. Message last = lines.get(lines.size() - 1); //*/ Remove the first slash to comment me out. if (last.getLogin().compareToIgnoreCase(mes.getLogin()) == 0 && last.getHostname().compareToIgnoreCase(mes.getHostname()) == 0) { // Suspicious! irc.sendContextReply(mes, "Sorry, no quoting yourself!"); return; } //*/ // OK, build a QuoteObject... final QuoteObject quote = new QuoteObject(); quote.quoter = mods.nick.getBestPrimaryNick(mes.getNick()); quote.hostmask = (mes.getLogin() + "@" + mes.getHostname()).toLowerCase(); quote.lines = lines.size(); quote.score = 0; quote.up = 0; quote.down = 0; quote.time = System.currentTimeMillis(); // QuoteLine object; quoteID will be filled in later. final List quoteLines = new ArrayList(lines.size()); mods.odb.runTransaction( new ObjectDBTransaction() { public void run() { quote.id = 0; save(quote); // Now have a quote ID! quoteLines.clear(); for(int i=0; i<lines.size(); i++) { QuoteLine quoteLine = new QuoteLine(); quoteLine.quoteID = quote.id; quoteLine.id = 0; quoteLine.lineNumber = i; quoteLine.nick = mods.nick.getBestPrimaryNick(lines.get(i).getNick()); quoteLine.message = lines.get(i).getMessage(); quoteLine.isAction = (lines.get(i) instanceof ChannelAction); save(quoteLine); quoteLines.add(quoteLine); } }}); // Remember this quote for later... addLastQuote(mes.getContext(), quote, 1); irc.sendContextReply( mes, "OK, added " + quote.lines + " line quote #" + quote.id + ": " + formatPreview(quoteLines) ); }
diff --git a/src/main/java/net/lahwran/capsystem/Capsystem.java b/src/main/java/net/lahwran/capsystem/Capsystem.java index 45da027..fac1e59 100644 --- a/src/main/java/net/lahwran/capsystem/Capsystem.java +++ b/src/main/java/net/lahwran/capsystem/Capsystem.java @@ -1,138 +1,138 @@ /** * */ package net.lahwran.capsystem; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.lahwran.mcclient.capsystem.Sendable; /** * @author lahwran * */ public class Capsystem { public static final int protocolVersion = 0; private static Caplist serverCaplist = null; private static final Caplist caplist = new Caplist(protocolVersion); public static final int maxLength=100; public static final String colorchar = "\u00a7"; public static final String prefix = "/@caps "; public static Sendable server; public static boolean connected = false; public static boolean capableServer = false; public static void sendCaps() { StringBuilder toSend = null; for (Capability c:caplist.capabilities.values()) { String curCap = c.toString(); if(toSend == null) { toSend = new StringBuilder(prefix); if (toSend.length() + curCap.length() > maxLength) throw new RuntimeException("Impossibly long capability error"); toSend.append(curCap); continue; } else if(toSend.length() + curCap.length() + 1 > maxLength) { System.out.println("Sending "+toSend.length()+": "+toSend.toString()); server.send(toSend.toString()); toSend=null; } else { toSend.append(" "+curCap); } } if (toSend != null) { System.out.println("Sending: "+toSend.toString()); server.send(toSend.toString()); } - server.send("/@caps done"); + server.send("/@cap done"); } public static void registerCap(Capability c) { caplist.capabilities.put(c.type+c.name, c); } public static void registerCap(String strc) { Capability c = new Capability(strc); caplist.capabilities.put(c.type+c.name, c); } public static void unregisterCap(Capability c) { caplist.capabilities.remove(c.type+c.name); } public static void unregisterCap(String c) { caplist.capabilities.remove(c); } public static boolean hasCap(String c) { return serverCaplist != null && serverCaplist.capabilities.containsKey(c); } public static boolean hasCap(Capability c) { return serverCaplist != null && serverCaplist.capabilities.containsKey(c.type+c.name); } public static Capability getCap(String c) { return serverCaplist != null ? serverCaplist.capabilities.get(c) : null; } public static Caplist getCapList() { return serverCaplist; } public static final Pattern cappattern = Pattern.compile("^(.)([^:]*):?(.*)?$"); /** * Add a capability that was sent by the server * @param cap */ public static void _addCap(String cap) { Matcher match = cappattern.matcher(cap); if (!match.matches()) throw new RuntimeException("String is not a capability: "+cap); String type = match.group(1); String name = match.group(2); String args = match.group(3); serverCaplist.capabilities.put(type+name, new Capability(type, name, args)); } public static void _initCaps(int version) { serverCaplist = new Caplist(version); capableServer = true; sendCaps(); } public static void _disconnected() { serverCaplist = null; server = null; connected = false; capableServer = false; } public static void _connected(Sendable server) { Capsystem.server = server; connected = true; } }
true
true
public static void sendCaps() { StringBuilder toSend = null; for (Capability c:caplist.capabilities.values()) { String curCap = c.toString(); if(toSend == null) { toSend = new StringBuilder(prefix); if (toSend.length() + curCap.length() > maxLength) throw new RuntimeException("Impossibly long capability error"); toSend.append(curCap); continue; } else if(toSend.length() + curCap.length() + 1 > maxLength) { System.out.println("Sending "+toSend.length()+": "+toSend.toString()); server.send(toSend.toString()); toSend=null; } else { toSend.append(" "+curCap); } } if (toSend != null) { System.out.println("Sending: "+toSend.toString()); server.send(toSend.toString()); } server.send("/@caps done"); }
public static void sendCaps() { StringBuilder toSend = null; for (Capability c:caplist.capabilities.values()) { String curCap = c.toString(); if(toSend == null) { toSend = new StringBuilder(prefix); if (toSend.length() + curCap.length() > maxLength) throw new RuntimeException("Impossibly long capability error"); toSend.append(curCap); continue; } else if(toSend.length() + curCap.length() + 1 > maxLength) { System.out.println("Sending "+toSend.length()+": "+toSend.toString()); server.send(toSend.toString()); toSend=null; } else { toSend.append(" "+curCap); } } if (toSend != null) { System.out.println("Sending: "+toSend.toString()); server.send(toSend.toString()); } server.send("/@cap done"); }
diff --git a/src/org/rascalmpl/library/lang/java/m3/internal/BindingsResolver.java b/src/org/rascalmpl/library/lang/java/m3/internal/BindingsResolver.java index 039c696144..5cc1876682 100644 --- a/src/org/rascalmpl/library/lang/java/m3/internal/BindingsResolver.java +++ b/src/org/rascalmpl/library/lang/java/m3/internal/BindingsResolver.java @@ -1,588 +1,589 @@ /******************************************************************************* * Copyright (c) 2009-2013 CWI * 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: * * Anastasia Izmaylova - [email protected] - CWI *******************************************************************************/ package org.rascalmpl.library.lang.java.m3.internal; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import org.eclipse.imp.pdb.facts.IConstructor; import org.eclipse.imp.pdb.facts.IList; import org.eclipse.imp.pdb.facts.IListWriter; import org.eclipse.imp.pdb.facts.ISourceLocation; import org.eclipse.imp.pdb.facts.IValueFactory; import org.eclipse.imp.pdb.facts.type.TypeFactory; import org.eclipse.imp.pdb.facts.type.TypeStore; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration; import org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration; import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; import org.eclipse.jdt.core.dom.ClassInstanceCreation; import org.eclipse.jdt.core.dom.ConstructorInvocation; import org.eclipse.jdt.core.dom.EnumConstantDeclaration; import org.eclipse.jdt.core.dom.EnumDeclaration; import org.eclipse.jdt.core.dom.FieldAccess; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.IPackageBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.Initializer; import org.eclipse.jdt.core.dom.MemberRef; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.MethodRef; import org.eclipse.jdt.core.dom.PackageDeclaration; import org.eclipse.jdt.core.dom.QualifiedName; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.SuperConstructorInvocation; import org.eclipse.jdt.core.dom.SuperFieldAccess; import org.eclipse.jdt.core.dom.SuperMethodInvocation; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.TypeDeclarationStatement; import org.eclipse.jdt.core.dom.TypeParameter; import org.eclipse.jdt.core.dom.VariableDeclaration; import org.rascalmpl.values.ValueFactoryFactory; public class BindingsResolver { private TypeStore store; private final IValueFactory values = ValueFactoryFactory.getValueFactory(); private final TypeFactory tf = TypeFactory.getInstance(); private final boolean collectBindings; private final Map<String, Integer> anonymousClassCounter = new HashMap<String, Integer>(); private final Map<String, String> resolvedAnonymousClasses = new HashMap<String, String>(); private final Map<ISourceLocation, Integer> initializerCounter = new HashMap<ISourceLocation, Integer>(); private final Map<Initializer, ISourceLocation> initializerLookUp = new HashMap<>(); private org.eclipse.imp.pdb.facts.type.Type typeSymbol; BindingsResolver(final TypeStore store, boolean collectBindings) { this.collectBindings = collectBindings; this.store = store; } public ISourceLocation resolveBinding(ASTNode node) { if (collectBindings) { if (node instanceof TypeDeclaration) { return resolveBinding(((TypeDeclaration) node).resolveBinding()); } else if (node instanceof EnumDeclaration) { return resolveBinding(((EnumDeclaration) node).resolveBinding()); } else if (node instanceof AnnotationTypeDeclaration) { return resolveBinding(((AnnotationTypeDeclaration) node).resolveBinding()); } else if (node instanceof AnnotationTypeMemberDeclaration) { return resolveBinding(((AnnotationTypeMemberDeclaration) node).resolveBinding()); } else if (node instanceof AnonymousClassDeclaration) { return resolveBinding(((AnonymousClassDeclaration) node).resolveBinding()); } else if (node instanceof EnumConstantDeclaration) { return resolveBinding(((EnumConstantDeclaration) node).resolveVariable()); } else if (node instanceof ClassInstanceCreation) { return resolveBinding(((ClassInstanceCreation) node).resolveConstructorBinding()); } else if (node instanceof FieldAccess) { return resolveBinding(((FieldAccess) node).resolveFieldBinding()); } else if (node instanceof MethodInvocation) { return resolveBinding(((MethodInvocation) node).resolveMethodBinding()); } else if (node instanceof QualifiedName) { return resolveQualifiedName((QualifiedName) node); } else if (node instanceof SimpleName) { return resolveBinding(((SimpleName) node).resolveBinding()); } else if (node instanceof SuperFieldAccess) { return resolveBinding(((SuperFieldAccess) node).resolveFieldBinding()); } else if (node instanceof SuperMethodInvocation) { return resolveBinding(((SuperMethodInvocation) node).resolveMethodBinding()); // } else if (node instanceof Expression) { // return resolveBinding(((Expression) node).resolveTypeBinding()); } else if (node instanceof MemberRef) { return resolveBinding(((MemberRef) node).resolveBinding()); } else if (node instanceof MethodDeclaration) { return resolveBinding(((MethodDeclaration) node).resolveBinding()); } else if (node instanceof MethodRef) { return resolveBinding(((MethodRef) node).resolveBinding()); } else if (node instanceof PackageDeclaration) { return resolveBinding(((PackageDeclaration) node).resolveBinding()); } else if (node instanceof Type) { return resolveBinding(((Type) node).resolveBinding()); } else if (node instanceof TypeParameter) { return resolveBinding(((TypeParameter) node).resolveBinding()); } else if (node instanceof VariableDeclaration) { VariableDeclaration n = (VariableDeclaration) node; ISourceLocation result = resolveBinding(n.resolveBinding()); // Have to move towards parent to make the binding unique if (result.getScheme() == "unresolved") { result = resolveBinding(n.getParent(), n.getName().getIdentifier()); } return result; } else if (node instanceof ConstructorInvocation) { return resolveBinding(((ConstructorInvocation) node).resolveConstructorBinding()); } else if (node instanceof SuperConstructorInvocation) { return resolveBinding(((SuperConstructorInvocation) node).resolveConstructorBinding()); } else if (node instanceof TypeDeclarationStatement) { return resolveBinding(((TypeDeclarationStatement) node).resolveBinding()); } else if (node instanceof Initializer) { return resolveInitializer((Initializer) node); } } return convertBinding("unknown", null, null); } private ISourceLocation resolveBinding(ASTNode parentNode, String childName) { ISourceLocation parentBinding = resolveBinding(parentNode); // Something has to declare it!!! while(parentBinding.getScheme().equals("unknown") || parentBinding.getScheme().equals("unresolved")) { if (parentNode == null) { //truely unresolved/unknown return convertBinding("unresolved", null, null); } parentNode = parentNode.getParent(); parentBinding = resolveBinding(parentNode); } String key = ""; for (String storedKey: EclipseJavaCompiler.cache.keySet()) { if (EclipseJavaCompiler.cache.get(storedKey).equals(parentBinding)) { key = storedKey; break; } } key += "#".concat(childName); if (EclipseJavaCompiler.cache.containsKey(key)) { return EclipseJavaCompiler.cache.get(key); } // FIXME: May not be variable only!!! ISourceLocation childBinding = convertBinding("java+variable", null, parentBinding.getPath().concat("/").concat(childName)); EclipseJavaCompiler.cache.put(key, childBinding); return childBinding; } private ISourceLocation resolveQualifiedName(QualifiedName node) { ISourceLocation parent = resolveBinding(node.getQualifier().resolveTypeBinding()); ISourceLocation name = resolveBinding(node.getName()); if (parent.getScheme().equals("java+array") && name.getScheme().equals("unresolved")) { return convertBinding("java+field", null, resolveBinding(node.getQualifier()).getPath() + "/" + node.getName().getIdentifier()); } return name; } private ISourceLocation resolveInitializer(Initializer node) { if (initializerLookUp.containsKey(node)) { return initializerLookUp.get(node); } int initCounter = 1; ISourceLocation parent = resolveBinding(node.getParent()); if (initializerCounter.containsKey(parent)) { initCounter = initializerCounter.get(parent) + 1; } initializerCounter.put(parent, initCounter); String key = ""; for (String storedKey: EclipseJavaCompiler.cache.keySet()) { if (EclipseJavaCompiler.cache.get(storedKey).equals(parent)) { key = storedKey; break; } } key += "$initializer" + initCounter; ISourceLocation result = convertBinding("java+initializer", null, parent.getPath() + "$initializer" + initCounter); EclipseJavaCompiler.cache.put(key, result); initializerLookUp.put(node, result); return result; } public ISourceLocation resolveBinding(IBinding binding) { if (binding == null) { return convertBinding("unresolved", null, null); } if (binding instanceof ITypeBinding) { return resolveBinding((ITypeBinding) binding); } else if (binding instanceof IMethodBinding) { return resolveBinding((IMethodBinding) binding); } else if (binding instanceof IPackageBinding) { return resolveBinding((IPackageBinding) binding); } else if (binding instanceof IVariableBinding) { return resolveBinding((IVariableBinding) binding); } return convertBinding("unknown", null, null); } public IConstructor resolveType(ISourceLocation uri, IBinding binding, boolean isDeclaration) { if (binding == null) { return null; } if (binding instanceof ITypeBinding) { return computeTypeSymbol(uri, (ITypeBinding) binding, isDeclaration); } else if (binding instanceof IMethodBinding) { return computeMethodTypeSymbol(uri, (IMethodBinding) binding, isDeclaration); } else if (binding instanceof IVariableBinding) { return resolveType(uri, ((IVariableBinding) binding).getType(), isDeclaration); } return null; } public IConstructor computeMethodTypeSymbol(IMethodBinding binding, boolean isDeclaration) { if (binding == null) return null; ISourceLocation decl = resolveBinding(binding); return computeMethodTypeSymbol(decl, binding, isDeclaration); } private IConstructor computeMethodTypeSymbol(ISourceLocation decl, IMethodBinding binding, boolean isDeclaration) { IList parameters = computeTypes(binding.getParameterTypes(), false); if (binding.isConstructor()) { return constructorSymbol(decl, parameters); } else { IList typeParameters = computeTypes(isDeclaration ? binding.getTypeParameters() : binding.getTypeArguments(), isDeclaration); IConstructor retSymbol = computeTypeSymbol(binding.getReturnType(), false); return methodSymbol(decl, typeParameters, retSymbol, parameters); } } private IList computeTypes(ITypeBinding[] bindings, boolean isDeclaration) { IListWriter parameters = values.listWriter(); for (ITypeBinding parameterType: bindings) { parameters.append(computeTypeSymbol(parameterType, isDeclaration)); } return parameters.done(); } private org.eclipse.imp.pdb.facts.type.Type getTypeSymbol() { if (typeSymbol == null) { typeSymbol = store.lookupAbstractDataType("TypeSymbol"); } return typeSymbol; } private IConstructor methodSymbol(ISourceLocation decl, IList typeParameters, IConstructor retSymbol, IList parameters) { org.eclipse.imp.pdb.facts.type.Type cons = store.lookupConstructor(getTypeSymbol(), "method", tf.tupleType(decl.getType(), typeParameters.getType(), retSymbol.getType(), parameters.getType())); return values.constructor(cons, decl, typeParameters, retSymbol, parameters); } private IConstructor constructorSymbol(ISourceLocation decl, IList parameters) { org.eclipse.imp.pdb.facts.type.Type cons = store.lookupConstructor(getTypeSymbol(), "constructor", tf.tupleType(decl.getType(), parameters.getType())); return values.constructor(cons, decl, parameters); } private IConstructor parameterNode(ISourceLocation decl, ITypeBinding bound, boolean isDeclaration) { if (bound != null) { IConstructor boundSym = boundSymbol(bound, isDeclaration); org.eclipse.imp.pdb.facts.type.Type cons = store.lookupConstructor(getTypeSymbol(), "typeParameter", tf.tupleType(decl.getType(), boundSym.getType())); return values.constructor(cons, decl, boundSym); } else { return parameterNode(decl); } } private IConstructor parameterNode(ISourceLocation decl) { IConstructor boundSym = unboundedSym(); org.eclipse.imp.pdb.facts.type.Type cons = store.lookupConstructor(getTypeSymbol(), "typeParameter", tf.tupleType(decl.getType(), boundSym.getType())); return values.constructor(cons, decl, boundSym); } private IConstructor unboundedSym() { org.eclipse.imp.pdb.facts.type.Type boundType = store.lookupAbstractDataType("Bound"); org.eclipse.imp.pdb.facts.type.Type cons = store.lookupConstructor(boundType, "unbounded", tf.voidType()); return values.constructor(cons); } public IConstructor computeTypeSymbol(ITypeBinding binding, boolean isDeclaration) { if (binding == null) return null; ISourceLocation decl = resolveBinding(binding); return computeTypeSymbol(decl, binding, isDeclaration); } private IConstructor computeTypeSymbol(ISourceLocation decl, ITypeBinding binding, boolean isDeclaration) { if (binding.isPrimitive()) { return primitiveSymbol(binding.getName()); } else if (binding.isArray()) { return arraySymbol(computeTypeSymbol(binding.getComponentType(), isDeclaration), binding.getDimensions()); } else if (binding.isNullType()) { return nullSymbol(); } else if (binding.isEnum()) { return enumSymbol(decl); } else if (binding.isTypeVariable()) { ITypeBinding bound = binding.getBound(); if (bound == null) { return parameterNode(decl); } else { return parameterNode(decl, bound, isDeclaration); } } else if (binding.isWildcardType()) { ITypeBinding bound = binding.getBound(); if (bound == null) { return wildcardSymbol(unboundedSym()); } else { return wildcardSymbol(boundSymbol(binding.getBound(), isDeclaration)); } } else if (binding.isClass()) { return classSymbol(decl, computeTypes(isDeclaration ? binding.getTypeParameters() : binding.getTypeArguments(), isDeclaration)); } else if (binding.isCapture()) { ITypeBinding[] typeBounds = binding.getTypeBounds(); ITypeBinding wildcard = binding.getWildcard(); if (typeBounds.length == 0) { return captureSymbol(unboundedSym(), computeTypeSymbol(wildcard, isDeclaration)); } else { return captureSymbol(boundSymbol(typeBounds[0], isDeclaration), computeTypeSymbol(wildcard, isDeclaration)); } } else if (binding.isInterface()) { return interfaceSymbol(decl, computeTypes(binding.getTypeArguments(), isDeclaration)); } return null; } private IConstructor captureSymbol(IConstructor bound, IConstructor wildcard) { org.eclipse.imp.pdb.facts.type.Type cons = store.lookupConstructor(getTypeSymbol(), "capture", tf.tupleType(bound.getType(), wildcard.getType())); return values.constructor(cons, bound, wildcard); } private IConstructor wildcardSymbol(IConstructor boundSymbol) { org.eclipse.imp.pdb.facts.type.Type cons = store.lookupConstructor(getTypeSymbol(), "wildcard", tf.tupleType(boundSymbol.getType())); return values.constructor(cons, boundSymbol); } private IConstructor boundSymbol(ITypeBinding bound, boolean isDeclaration) { IConstructor boundSym = computeTypeSymbol(bound, isDeclaration); org.eclipse.imp.pdb.facts.type.Type boundType = store.lookupAbstractDataType("Bound"); if (bound.isUpperbound()) { org.eclipse.imp.pdb.facts.type.Type sup = store.lookupConstructor(boundType, "super", tf.tupleType(boundSym.getType())); return values.constructor(sup, boundSym); } else { org.eclipse.imp.pdb.facts.type.Type ext = store.lookupConstructor(boundType, "extends", tf.tupleType(boundSym.getType())); return values.constructor(ext, boundSym); } } private IConstructor enumSymbol(ISourceLocation decl) { org.eclipse.imp.pdb.facts.type.Type cons = store.lookupConstructor(getTypeSymbol(), "enum", tf.tupleType(decl.getType())); return values.constructor(cons, decl); } private IConstructor interfaceSymbol(ISourceLocation decl, IList typeParameters) { org.eclipse.imp.pdb.facts.type.Type cons = store.lookupConstructor(getTypeSymbol(), "interface", tf.tupleType(decl.getType(), typeParameters.getType())); return values.constructor(cons, decl, typeParameters); } private IConstructor classSymbol(ISourceLocation decl, IList typeParameters) { if (decl.getURI().getPath().equals("/java/lang/Object")) { org.eclipse.imp.pdb.facts.type.Type obj = store.lookupConstructor(getTypeSymbol(), "object", tf.voidType()); return values.constructor(obj); } else { org.eclipse.imp.pdb.facts.type.Type cons = store.lookupConstructor(getTypeSymbol(), "class", tf.tupleType(decl.getType(), typeParameters.getType())); return values.constructor(cons, decl, typeParameters); } } private IConstructor nullSymbol() { org.eclipse.imp.pdb.facts.type.Type cons = store.lookupConstructor(getTypeSymbol(), "null", tf.voidType()); return values.constructor(cons); } private IConstructor primitiveSymbol(String name) { org.eclipse.imp.pdb.facts.type.Type cons = store.lookupConstructor(getTypeSymbol(), name, tf.voidType()); return values.constructor(cons); } private IConstructor arraySymbol(IConstructor elem, int dimensions) { org.eclipse.imp.pdb.facts.type.Type cons = store.lookupConstructor(getTypeSymbol(), "array", tf.tupleType(elem.getType(), tf.integerType())); return values.constructor(cons, elem, values.integer(dimensions)); } private ISourceLocation resolveBinding(IMethodBinding binding) { if (binding == null) { return convertBinding("unresolved", null, null); } if (EclipseJavaCompiler.cache.containsKey(binding.getKey())) return EclipseJavaCompiler.cache.get(binding.getKey()); String signature = resolveBinding(binding.getDeclaringClass()).getPath(); if (!signature.isEmpty()) { signature = signature.concat("/"); } String params = ""; for (ITypeBinding parameterType: binding.getMethodDeclaration().getParameterTypes()) { if (!params.isEmpty()) { params = params.concat(","); } if (parameterType.isTypeVariable()) { params = params.concat(parameterType.getName()); } else { params = params.concat(getPath(resolveBinding(parameterType)).replaceAll("/", ".")); } } signature = signature.concat(binding.getName() + "(" + params + ")"); String scheme = "unknown"; if (binding.isConstructor()) { scheme = "java+constructor"; } else { scheme = "java+method"; } ISourceLocation result = convertBinding(scheme, null, signature); EclipseJavaCompiler.cache.put(binding.getKey(), result); return result; } private ISourceLocation resolveBinding(IPackageBinding binding) { if (binding == null) { return convertBinding("unresolved", null, null); } if (EclipseJavaCompiler.cache.containsKey(binding.getKey())) return EclipseJavaCompiler.cache.get(binding.getKey()); ISourceLocation result = convertBinding("java+package", null, binding.getName().replaceAll("\\.", "/")); EclipseJavaCompiler.cache.put(binding.getKey(), result); return result; } private ISourceLocation resolveBinding(ITypeBinding binding) { if (binding == null) { return convertBinding("unresolved", null, null); } if (EclipseJavaCompiler.cache.containsKey(binding.getKey())) return EclipseJavaCompiler.cache.get(binding.getKey()); String scheme = binding.isInterface() ? "java+interface" : "java+class"; String qualifiedName = binding.getTypeDeclaration().getQualifiedName(); if (qualifiedName.isEmpty()) { if (binding.getDeclaringMethod() != null) { qualifiedName = resolveBinding(binding.getDeclaringMethod()).getPath(); } else if (binding.getDeclaringClass() != null) { qualifiedName = resolveBinding(binding.getDeclaringClass()).getPath(); } else { - System.err.println("Should not happen"); + System.err.println("No defining class or method for " + binding.getClass().getCanonicalName()); + System.err.println("Most probably anonymous class in initializer"); } } if (binding.isEnum()) { scheme = "java+enum"; } if (binding.isArray()) { scheme = "java+array"; } if (binding.isTypeVariable()) { scheme = "java+typeVariable"; } if (binding.isPrimitive()) { scheme = "java+primitiveType"; } if (binding.isWildcardType()) { return convertBinding("unknown", null, null); } if (binding.isLocal()) { qualifiedName = qualifiedName.concat("/").concat(binding.getName()); } if (binding.isAnonymous()) { String key = binding.getKey(); if (resolvedAnonymousClasses.containsKey(key)) { qualifiedName = resolvedAnonymousClasses.get(key); } else { int anonCounter = 1; if (anonymousClassCounter.containsKey(qualifiedName)) { anonCounter = anonymousClassCounter.get(qualifiedName) + 1; } else { anonCounter = 1; } anonymousClassCounter.put(qualifiedName, anonCounter); qualifiedName += "$anonymous" + anonCounter; resolvedAnonymousClasses.put(key, qualifiedName); } scheme = "java+anonymousClass"; } ISourceLocation result = convertBinding(scheme, null, qualifiedName.replaceAll("\\.", "/")); EclipseJavaCompiler.cache.put(binding.getKey(), result); return result; } private ISourceLocation resolveBinding(IVariableBinding binding) { if (binding == null) { return convertBinding("unresolved", null, null); } if (EclipseJavaCompiler.cache.containsKey(binding.getKey())) return EclipseJavaCompiler.cache.get(binding.getKey()); String qualifiedName = ""; ITypeBinding declaringClass = binding.getDeclaringClass(); if (declaringClass != null) { qualifiedName = getPath(resolveBinding(declaringClass)); } else { IMethodBinding declaringMethod = binding.getDeclaringMethod(); if (declaringMethod != null) { qualifiedName = getPath(resolveBinding(declaringMethod)); } } if (!qualifiedName.isEmpty()) { qualifiedName = qualifiedName.concat("/"); } else { return convertBinding("unresolved", null, null); } String scheme = "java+variable"; if (binding.isEnumConstant()) { scheme = "java+enumConstant"; } else if (binding.isParameter()) { scheme = "java+parameter"; } else if (binding.isField()) { scheme = "java+field"; } ISourceLocation result = convertBinding(scheme, null, qualifiedName.concat(binding.getName())); EclipseJavaCompiler.cache.put(binding.getKey(), result); return result; } protected ISourceLocation convertBinding(String scheme, String authority, String path) { try { return values.sourceLocation(scheme, authority, path); } catch (URISyntaxException | UnsupportedOperationException e) { throw new RuntimeException("Should not happen", e); } } private String getPath(ISourceLocation iSourceLocation) { String path = iSourceLocation.getPath(); return path.substring(1, path.length()); } }
true
true
private ISourceLocation resolveBinding(ITypeBinding binding) { if (binding == null) { return convertBinding("unresolved", null, null); } if (EclipseJavaCompiler.cache.containsKey(binding.getKey())) return EclipseJavaCompiler.cache.get(binding.getKey()); String scheme = binding.isInterface() ? "java+interface" : "java+class"; String qualifiedName = binding.getTypeDeclaration().getQualifiedName(); if (qualifiedName.isEmpty()) { if (binding.getDeclaringMethod() != null) { qualifiedName = resolveBinding(binding.getDeclaringMethod()).getPath(); } else if (binding.getDeclaringClass() != null) { qualifiedName = resolveBinding(binding.getDeclaringClass()).getPath(); } else { System.err.println("Should not happen"); } } if (binding.isEnum()) { scheme = "java+enum"; } if (binding.isArray()) { scheme = "java+array"; } if (binding.isTypeVariable()) { scheme = "java+typeVariable"; } if (binding.isPrimitive()) { scheme = "java+primitiveType"; } if (binding.isWildcardType()) { return convertBinding("unknown", null, null); } if (binding.isLocal()) { qualifiedName = qualifiedName.concat("/").concat(binding.getName()); } if (binding.isAnonymous()) { String key = binding.getKey(); if (resolvedAnonymousClasses.containsKey(key)) { qualifiedName = resolvedAnonymousClasses.get(key); } else { int anonCounter = 1; if (anonymousClassCounter.containsKey(qualifiedName)) { anonCounter = anonymousClassCounter.get(qualifiedName) + 1; } else { anonCounter = 1; } anonymousClassCounter.put(qualifiedName, anonCounter); qualifiedName += "$anonymous" + anonCounter; resolvedAnonymousClasses.put(key, qualifiedName); } scheme = "java+anonymousClass"; } ISourceLocation result = convertBinding(scheme, null, qualifiedName.replaceAll("\\.", "/")); EclipseJavaCompiler.cache.put(binding.getKey(), result); return result; }
private ISourceLocation resolveBinding(ITypeBinding binding) { if (binding == null) { return convertBinding("unresolved", null, null); } if (EclipseJavaCompiler.cache.containsKey(binding.getKey())) return EclipseJavaCompiler.cache.get(binding.getKey()); String scheme = binding.isInterface() ? "java+interface" : "java+class"; String qualifiedName = binding.getTypeDeclaration().getQualifiedName(); if (qualifiedName.isEmpty()) { if (binding.getDeclaringMethod() != null) { qualifiedName = resolveBinding(binding.getDeclaringMethod()).getPath(); } else if (binding.getDeclaringClass() != null) { qualifiedName = resolveBinding(binding.getDeclaringClass()).getPath(); } else { System.err.println("No defining class or method for " + binding.getClass().getCanonicalName()); System.err.println("Most probably anonymous class in initializer"); } } if (binding.isEnum()) { scheme = "java+enum"; } if (binding.isArray()) { scheme = "java+array"; } if (binding.isTypeVariable()) { scheme = "java+typeVariable"; } if (binding.isPrimitive()) { scheme = "java+primitiveType"; } if (binding.isWildcardType()) { return convertBinding("unknown", null, null); } if (binding.isLocal()) { qualifiedName = qualifiedName.concat("/").concat(binding.getName()); } if (binding.isAnonymous()) { String key = binding.getKey(); if (resolvedAnonymousClasses.containsKey(key)) { qualifiedName = resolvedAnonymousClasses.get(key); } else { int anonCounter = 1; if (anonymousClassCounter.containsKey(qualifiedName)) { anonCounter = anonymousClassCounter.get(qualifiedName) + 1; } else { anonCounter = 1; } anonymousClassCounter.put(qualifiedName, anonCounter); qualifiedName += "$anonymous" + anonCounter; resolvedAnonymousClasses.put(key, qualifiedName); } scheme = "java+anonymousClass"; } ISourceLocation result = convertBinding(scheme, null, qualifiedName.replaceAll("\\.", "/")); EclipseJavaCompiler.cache.put(binding.getKey(), result); return result; }
diff --git a/CubicTestPlugin/src/main/java/org/cubictest/runner/cubicunit/delegates/ElementConverter.java b/CubicTestPlugin/src/main/java/org/cubictest/runner/cubicunit/delegates/ElementConverter.java index 32ab2216..262cff5e 100644 --- a/CubicTestPlugin/src/main/java/org/cubictest/runner/cubicunit/delegates/ElementConverter.java +++ b/CubicTestPlugin/src/main/java/org/cubictest/runner/cubicunit/delegates/ElementConverter.java @@ -1,111 +1,111 @@ /* * Created on 4.aug.2006 * * This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE * Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html * */ package org.cubictest.runner.cubicunit.delegates; import static org.cubicunit.InputType.BUTTON; import static org.cubicunit.InputType.CHECKBOX; import static org.cubicunit.InputType.PASSWORD; import static org.cubicunit.InputType.RADIO; import static org.cubicunit.InputType.SELECT; import static org.cubicunit.InputType.TEXT; import static org.cubicunit.InputType.TEXTAREA; import org.cubictest.export.converters.IPageElementConverter; import org.cubictest.model.FormElement; import org.cubictest.model.Image; import org.cubictest.model.Link; import org.cubictest.model.PageElement; import org.cubictest.model.TestPartStatus; import org.cubictest.model.Text; import org.cubictest.model.Title; import org.cubictest.model.context.IContext; import org.cubictest.model.formElement.Button; import org.cubictest.model.formElement.Checkbox; import org.cubictest.model.formElement.Password; import org.cubictest.model.formElement.RadioButton; import org.cubictest.model.formElement.Select; import org.cubictest.model.formElement.TextArea; import org.cubictest.model.formElement.TextField; import org.cubicunit.Container; import org.cubicunit.Document; import org.cubicunit.Element; import org.cubicunit.IdentifierType; import org.cubicunit.Input; import org.cubicunit.InputType; public class ElementConverter implements IPageElementConverter<Holder> { public void handlePageElement(Holder holder,PageElement pe) { Container container = holder.getContainer(); Element element = null; String text = pe.getText(); boolean not = pe.isNot(); try{ if (pe instanceof Text) { if (not) container.assertTextNotPresent(text); else container.assertTextPresent(text); }else if (pe instanceof Link) { if(not) container.assertLinkNotPresent(text); else element = container.assertLinkPresent(text); }else if (pe instanceof Image) { if(not) container.assertImageNotPresent(text); else element = container.assertImagePresent(text); }else if (pe instanceof Title){ Document doc = holder.getDocument(); if(not) doc.assertNotTitle(text); else doc.assertTitle(text); }else if (pe instanceof FormElement){ FormElement formElement = (FormElement)pe; IdentifierType it = IdentifierType.valueOf(formElement. - getIdentifierType().toString().toUpperCase()); + getDirectEditIdentifier().getType().toString().toUpperCase()); InputType type; if(pe instanceof TextArea) type = TEXTAREA; else if (pe instanceof Button) type = BUTTON; else if (pe instanceof Select) type = SELECT; else if (pe instanceof Checkbox) type = CHECKBOX; else if (pe instanceof RadioButton) type = RADIO; else if (pe instanceof Password) type = PASSWORD; else if (pe instanceof TextField) type = TEXT; else type = TEXT; if(not) container.assertInputNotPresent(type, it, text); else element = (Input)container.assertInputPresent(type, it, text); }else if (pe instanceof IContext){ throw new IllegalArgumentException(); }else{ System.err.println("Error could not convert: " + pe); } holder.put(pe,element); pe.setStatus(TestPartStatus.PASS); }catch(AssertionError e){ pe.setStatus(TestPartStatus.FAIL); throw e; }catch(RuntimeException e){ pe.setStatus(TestPartStatus.EXCEPTION); throw e; } } }
true
true
public void handlePageElement(Holder holder,PageElement pe) { Container container = holder.getContainer(); Element element = null; String text = pe.getText(); boolean not = pe.isNot(); try{ if (pe instanceof Text) { if (not) container.assertTextNotPresent(text); else container.assertTextPresent(text); }else if (pe instanceof Link) { if(not) container.assertLinkNotPresent(text); else element = container.assertLinkPresent(text); }else if (pe instanceof Image) { if(not) container.assertImageNotPresent(text); else element = container.assertImagePresent(text); }else if (pe instanceof Title){ Document doc = holder.getDocument(); if(not) doc.assertNotTitle(text); else doc.assertTitle(text); }else if (pe instanceof FormElement){ FormElement formElement = (FormElement)pe; IdentifierType it = IdentifierType.valueOf(formElement. getIdentifierType().toString().toUpperCase()); InputType type; if(pe instanceof TextArea) type = TEXTAREA; else if (pe instanceof Button) type = BUTTON; else if (pe instanceof Select) type = SELECT; else if (pe instanceof Checkbox) type = CHECKBOX; else if (pe instanceof RadioButton) type = RADIO; else if (pe instanceof Password) type = PASSWORD; else if (pe instanceof TextField) type = TEXT; else type = TEXT; if(not) container.assertInputNotPresent(type, it, text); else element = (Input)container.assertInputPresent(type, it, text); }else if (pe instanceof IContext){ throw new IllegalArgumentException(); }else{ System.err.println("Error could not convert: " + pe); } holder.put(pe,element); pe.setStatus(TestPartStatus.PASS); }catch(AssertionError e){ pe.setStatus(TestPartStatus.FAIL); throw e; }catch(RuntimeException e){ pe.setStatus(TestPartStatus.EXCEPTION); throw e; } }
public void handlePageElement(Holder holder,PageElement pe) { Container container = holder.getContainer(); Element element = null; String text = pe.getText(); boolean not = pe.isNot(); try{ if (pe instanceof Text) { if (not) container.assertTextNotPresent(text); else container.assertTextPresent(text); }else if (pe instanceof Link) { if(not) container.assertLinkNotPresent(text); else element = container.assertLinkPresent(text); }else if (pe instanceof Image) { if(not) container.assertImageNotPresent(text); else element = container.assertImagePresent(text); }else if (pe instanceof Title){ Document doc = holder.getDocument(); if(not) doc.assertNotTitle(text); else doc.assertTitle(text); }else if (pe instanceof FormElement){ FormElement formElement = (FormElement)pe; IdentifierType it = IdentifierType.valueOf(formElement. getDirectEditIdentifier().getType().toString().toUpperCase()); InputType type; if(pe instanceof TextArea) type = TEXTAREA; else if (pe instanceof Button) type = BUTTON; else if (pe instanceof Select) type = SELECT; else if (pe instanceof Checkbox) type = CHECKBOX; else if (pe instanceof RadioButton) type = RADIO; else if (pe instanceof Password) type = PASSWORD; else if (pe instanceof TextField) type = TEXT; else type = TEXT; if(not) container.assertInputNotPresent(type, it, text); else element = (Input)container.assertInputPresent(type, it, text); }else if (pe instanceof IContext){ throw new IllegalArgumentException(); }else{ System.err.println("Error could not convert: " + pe); } holder.put(pe,element); pe.setStatus(TestPartStatus.PASS); }catch(AssertionError e){ pe.setStatus(TestPartStatus.FAIL); throw e; }catch(RuntimeException e){ pe.setStatus(TestPartStatus.EXCEPTION); throw e; } }
diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/StatefulRetryStepFactoryBean.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/StatefulRetryStepFactoryBean.java index 53f168856..1132ccedb 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/StatefulRetryStepFactoryBean.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/StatefulRetryStepFactoryBean.java @@ -1,236 +1,236 @@ /* * Copyright 2006-2007 the original author or authors. * * 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.springframework.batch.core.step.item; import org.springframework.batch.core.Step; import org.springframework.batch.core.StepContribution; import org.springframework.batch.item.AbstractItemWriter; import org.springframework.batch.item.ItemKeyGenerator; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemRecoverer; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.retry.RetryException; import org.springframework.batch.retry.RetryListener; import org.springframework.batch.retry.RetryOperations; import org.springframework.batch.retry.RetryPolicy; import org.springframework.batch.retry.backoff.BackOffPolicy; import org.springframework.batch.retry.callback.ItemWriterRetryCallback; import org.springframework.batch.retry.policy.ItemWriterRetryPolicy; import org.springframework.batch.retry.policy.SimpleRetryPolicy; import org.springframework.batch.retry.support.RetryTemplate; /** * Factory bean for step that executes its item processing with a stateful * retry. Failed items are never skipped, but always cause a rollback. Before a * rollback, the {@link Step} makes a record of the failed item, caching it * under a key given by the {@link ItemKeyGenerator}. Then when it is * re-presented by the {@link ItemReader} it is recognised and retried up to a * limit given by the {@link RetryPolicy}. When the retry is exhausted instead * of the item being skipped it is handled by an {@link ItemRecoverer}.<br/> * * The skipLimit property is still used to control the overall exception * handling policy. Only exhausted retries count against the exception handler, * instead of counting all exceptions.<br/> * * This class is not designed for extension. Do not subclass it. * * @author Dave Syer * */ public class StatefulRetryStepFactoryBean extends SkipLimitStepFactoryBean { private ItemRecoverer itemRecoverer; private int retryLimit; private Class[] retryableExceptionClasses; private BackOffPolicy backOffPolicy; private RetryListener[] retryListeners; /** * Public setter for the retry limit. Each item can be retried up to this * limit. * @param retryLimit the retry limit to set */ public void setRetryLimit(int retryLimit) { this.retryLimit = retryLimit; } /** * Public setter for the Class[]. * @param retryableExceptionClasses the retryableExceptionClasses to set */ public void setRetryableExceptionClasses(Class[] retryableExceptionClasses) { this.retryableExceptionClasses = retryableExceptionClasses; } /** * Public setter for the {@link BackOffPolicy}. * @param backOffPolicy the {@link BackOffPolicy} to set */ public void setBackOffPolicy(BackOffPolicy backOffPolicy) { this.backOffPolicy = backOffPolicy; } /** * Public setter for the {@link RetryListener}s. * @param retryListeners the {@link RetryListener}s to set */ public void setRetryListeners(RetryListener[] retryListeners) { this.retryListeners = retryListeners; } /** * Public setter for the {@link ItemRecoverer}. If this is set the * {@link ItemRecoverer#recover(Object, Throwable)} will be called when * retry is exhausted, and within the business transaction (which will not * roll back because of any other item-related errors). * * @param itemRecoverer the {@link ItemRecoverer} to set */ public void setItemRecoverer(ItemRecoverer itemRecoverer) { this.itemRecoverer = itemRecoverer; } /** * @param step * */ protected void applyConfiguration(ItemOrientedStep step) { super.applyConfiguration(step); if (retryLimit > 0) { addFatalExceptionIfMissing(RetryException.class); SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(retryLimit); if (retryableExceptionClasses != null) { retryPolicy.setRetryableExceptionClasses(retryableExceptionClasses); retryPolicy.setFatalExceptionClasses(getFatalExceptionClasses()); } // Co-ordinate the retry policy with the exception handler: getStepOperations() .setExceptionHandler(new SimpleRetryExceptionHandler(retryPolicy, getExceptionHandler(), getFatalExceptionClasses())); - ItemWriterRetryPolicy itemProviderRetryPolicy = new ItemWriterRetryPolicy(retryPolicy); + ItemWriterRetryPolicy itemWriterRetryPolicy = new ItemWriterRetryPolicy(retryPolicy); RetryTemplate retryTemplate = new RetryTemplate(); if (retryListeners != null) { retryTemplate.setListeners(retryListeners); } - retryTemplate.setRetryPolicy(itemProviderRetryPolicy); + retryTemplate.setRetryPolicy(itemWriterRetryPolicy); if (backOffPolicy != null) { retryTemplate.setBackOffPolicy(backOffPolicy); } StatefulRetryItemHandler itemHandler = new StatefulRetryItemHandler(getItemReader(), getItemWriter(), retryTemplate, getItemKeyGenerator(), itemRecoverer); step.setItemHandler(itemHandler); } } /** * Extend the skipping handler because we want to take advantage of that * behaviour as well as the retry. So if there is an exception on input it * is skipped if allowed. If there is an exception on output, it will be * re-thrown in any case, and the behaviour when the item is next * encountered depends on the retryable and skippable exception * configuration. Skip takes precedence, so if the exception was skippable * the item will be skipped on input and the reader moves to the next item. * If the exception is retryable but not skippable, then the write will be * attempted up again up to the retry limit. Beyond the retry limit recovery * takes over. * * @author Dave Syer * */ private static class StatefulRetryItemHandler extends ItemSkipPolicyItemHandler { final private RetryOperations retryOperations; final private ItemKeyGenerator itemKeyGenerator; final private ItemRecoverer itemRecoverer; /** * @param itemReader * @param itemWriter * @param retryCallback * @param retryTemplate * @param itemRecoverer */ public StatefulRetryItemHandler(ItemReader itemReader, ItemWriter itemWriter, RetryOperations retryTemplate, ItemKeyGenerator itemKeyGenerator, ItemRecoverer itemRecoverer) { super(itemReader, itemWriter); this.retryOperations = retryTemplate; this.itemKeyGenerator = itemKeyGenerator; this.itemRecoverer = itemRecoverer; } /** * Execute the business logic, delegating to the writer.<br/> * * Process the item with the {@link ItemWriter} in a stateful retry. The * {@link ItemRecoverer} is used (if provided) in the case of an * exception to apply alternate processing to the item. If the stateful * retry is in place then the recovery will happen in the next * transaction automatically, otherwise it might be necessary for * clients to make the recover method transactional with appropriate * propagation behaviour (probably REQUIRES_NEW because the call will * happen in the context of a transaction that is about to rollback).<br/> * * @see org.springframework.batch.core.step.item.SimpleItemHandler#write(java.lang.Object, * org.springframework.batch.core.StepContribution) */ protected void write(Object item, final StepContribution contribution) throws Exception { ItemWriter writer = new RetryableItemWriter(contribution); ItemWriterRetryCallback retryCallback = new ItemWriterRetryCallback(item, writer); retryCallback.setKeyGenerator(itemKeyGenerator); retryCallback.setRecoverer(itemRecoverer); retryOperations.execute(retryCallback); } /** * @author Dave Syer * */ private class RetryableItemWriter extends AbstractItemWriter { private StepContribution contribution; /** * @param contribution */ public RetryableItemWriter(StepContribution contribution) { this.contribution = contribution; } public void write(Object item) throws Exception { doWriteWithSkip(item, contribution); } } } }
false
true
protected void applyConfiguration(ItemOrientedStep step) { super.applyConfiguration(step); if (retryLimit > 0) { addFatalExceptionIfMissing(RetryException.class); SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(retryLimit); if (retryableExceptionClasses != null) { retryPolicy.setRetryableExceptionClasses(retryableExceptionClasses); retryPolicy.setFatalExceptionClasses(getFatalExceptionClasses()); } // Co-ordinate the retry policy with the exception handler: getStepOperations() .setExceptionHandler(new SimpleRetryExceptionHandler(retryPolicy, getExceptionHandler(), getFatalExceptionClasses())); ItemWriterRetryPolicy itemProviderRetryPolicy = new ItemWriterRetryPolicy(retryPolicy); RetryTemplate retryTemplate = new RetryTemplate(); if (retryListeners != null) { retryTemplate.setListeners(retryListeners); } retryTemplate.setRetryPolicy(itemProviderRetryPolicy); if (backOffPolicy != null) { retryTemplate.setBackOffPolicy(backOffPolicy); } StatefulRetryItemHandler itemHandler = new StatefulRetryItemHandler(getItemReader(), getItemWriter(), retryTemplate, getItemKeyGenerator(), itemRecoverer); step.setItemHandler(itemHandler); } }
protected void applyConfiguration(ItemOrientedStep step) { super.applyConfiguration(step); if (retryLimit > 0) { addFatalExceptionIfMissing(RetryException.class); SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(retryLimit); if (retryableExceptionClasses != null) { retryPolicy.setRetryableExceptionClasses(retryableExceptionClasses); retryPolicy.setFatalExceptionClasses(getFatalExceptionClasses()); } // Co-ordinate the retry policy with the exception handler: getStepOperations() .setExceptionHandler(new SimpleRetryExceptionHandler(retryPolicy, getExceptionHandler(), getFatalExceptionClasses())); ItemWriterRetryPolicy itemWriterRetryPolicy = new ItemWriterRetryPolicy(retryPolicy); RetryTemplate retryTemplate = new RetryTemplate(); if (retryListeners != null) { retryTemplate.setListeners(retryListeners); } retryTemplate.setRetryPolicy(itemWriterRetryPolicy); if (backOffPolicy != null) { retryTemplate.setBackOffPolicy(backOffPolicy); } StatefulRetryItemHandler itemHandler = new StatefulRetryItemHandler(getItemReader(), getItemWriter(), retryTemplate, getItemKeyGenerator(), itemRecoverer); step.setItemHandler(itemHandler); } }
diff --git a/src/main/java/net/lahwran/mcclient/capsystem/ChatProcessor.java b/src/main/java/net/lahwran/mcclient/capsystem/ChatProcessor.java index 3cd4591..f91d563 100644 --- a/src/main/java/net/lahwran/mcclient/capsystem/ChatProcessor.java +++ b/src/main/java/net/lahwran/mcclient/capsystem/ChatProcessor.java @@ -1,65 +1,65 @@ /** * */ package net.lahwran.mcclient.capsystem; /** * @author lahwran * */ public class ChatProcessor { private static final String cap = Capsystem.colorchar + "0" + Capsystem.colorchar + "0" + Capsystem.colorchar + "0" + Capsystem.colorchar + "0"; private static final String comm = Capsystem.colorchar + "0" + Capsystem.colorchar + "0"; private static int colorDecode(String encoded) { StringBuilder hex = new StringBuilder(); char colorchar = Capsystem.colorchar; //shouldn't it be a char to begin with? for(int i=0; i<encoded.length(); i++) { if(encoded.charAt(i) != colorchar) { hex.append(encoded.charAt(i)); } } return Integer.parseInt(hex.toString(), 16); } public static boolean processChat(String chat) { if(chat.startsWith(cap)) { chat = chat.substring(cap.length()); if(Capsystem.instance.connected && !Capsystem.instance.capableServer) { Capsystem.instance._initCaps(colorDecode(chat)); } else if (chat.equals("done")) { Commsystem._ready(); } else { - String[] split = chat.substring(1).split(" "); + String[] split = chat.trim().split(" "); for (String s:split) { Capsystem.instance._addCap(s); } } return true; } else if(chat.startsWith(comm)) { chat = chat.substring(comm.length()); Commsystem.dispatch(chat); return true; } return false; } static { Commsystem.instance.equals(null); Capsystem.instance.equals(null); } }
true
true
public static boolean processChat(String chat) { if(chat.startsWith(cap)) { chat = chat.substring(cap.length()); if(Capsystem.instance.connected && !Capsystem.instance.capableServer) { Capsystem.instance._initCaps(colorDecode(chat)); } else if (chat.equals("done")) { Commsystem._ready(); } else { String[] split = chat.substring(1).split(" "); for (String s:split) { Capsystem.instance._addCap(s); } } return true; } else if(chat.startsWith(comm)) { chat = chat.substring(comm.length()); Commsystem.dispatch(chat); return true; } return false; }
public static boolean processChat(String chat) { if(chat.startsWith(cap)) { chat = chat.substring(cap.length()); if(Capsystem.instance.connected && !Capsystem.instance.capableServer) { Capsystem.instance._initCaps(colorDecode(chat)); } else if (chat.equals("done")) { Commsystem._ready(); } else { String[] split = chat.trim().split(" "); for (String s:split) { Capsystem.instance._addCap(s); } } return true; } else if(chat.startsWith(comm)) { chat = chat.substring(comm.length()); Commsystem.dispatch(chat); return true; } return false; }
diff --git a/src/org/pentaho/hdfs/vfs/HDFSFileSystem.java b/src/org/pentaho/hdfs/vfs/HDFSFileSystem.java index 7efac1b..b5c4b6a 100644 --- a/src/org/pentaho/hdfs/vfs/HDFSFileSystem.java +++ b/src/org/pentaho/hdfs/vfs/HDFSFileSystem.java @@ -1,63 +1,63 @@ /* * Copyright 2010 Pentaho Corporation. 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. * * @author Michael D'Amour */ package org.pentaho.hdfs.vfs; import java.util.Collection; import org.apache.commons.vfs.FileName; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.FileSystem; import org.apache.commons.vfs.FileSystemOptions; import org.apache.commons.vfs.provider.AbstractFileSystem; import org.apache.commons.vfs.provider.GenericFileName; import org.apache.hadoop.conf.Configuration; public class HDFSFileSystem extends AbstractFileSystem implements FileSystem { private org.apache.hadoop.fs.FileSystem hdfs; protected HDFSFileSystem(final FileName rootName, final FileSystemOptions fileSystemOptions) { super(rootName, null, fileSystemOptions); } @SuppressWarnings("unchecked") protected void addCapabilities(Collection caps) { caps.addAll(HDFSFileProvider.capabilities); } protected FileObject createFile(FileName name) throws Exception { return new HDFSFileObject(name, this); } public org.apache.hadoop.fs.FileSystem getHDFSFileSystem() { if (hdfs == null) { Configuration conf = new Configuration(); GenericFileName genericFileName = (GenericFileName) getRootName(); String url = "hdfs://" + genericFileName.getHostName() + ":" + genericFileName.getPort(); conf.set("fs.default.name", url); try { hdfs = org.apache.hadoop.fs.FileSystem.get(conf); } catch (Throwable t) { - System.out.println("Could not getHDFSFileSystem()!"); + System.out.println("Could not getHDFSFileSystem() for " + url); t.printStackTrace(); } } return hdfs; } }
true
true
public org.apache.hadoop.fs.FileSystem getHDFSFileSystem() { if (hdfs == null) { Configuration conf = new Configuration(); GenericFileName genericFileName = (GenericFileName) getRootName(); String url = "hdfs://" + genericFileName.getHostName() + ":" + genericFileName.getPort(); conf.set("fs.default.name", url); try { hdfs = org.apache.hadoop.fs.FileSystem.get(conf); } catch (Throwable t) { System.out.println("Could not getHDFSFileSystem()!"); t.printStackTrace(); } } return hdfs; }
public org.apache.hadoop.fs.FileSystem getHDFSFileSystem() { if (hdfs == null) { Configuration conf = new Configuration(); GenericFileName genericFileName = (GenericFileName) getRootName(); String url = "hdfs://" + genericFileName.getHostName() + ":" + genericFileName.getPort(); conf.set("fs.default.name", url); try { hdfs = org.apache.hadoop.fs.FileSystem.get(conf); } catch (Throwable t) { System.out.println("Could not getHDFSFileSystem() for " + url); t.printStackTrace(); } } return hdfs; }
diff --git a/supervisor/model/Model.java b/supervisor/model/Model.java index 6d07e735..0682da4f 100644 --- a/supervisor/model/Model.java +++ b/supervisor/model/Model.java @@ -1,1229 +1,1236 @@ /** * This file is part of VoteBox. * * VoteBox is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as published by * the Free Software Foundation. * * You should have received a copy of the GNU General Public License * along with VoteBox, found in the root of any distribution or * repository containing all or part of VoteBox. * * THIS SOFTWARE IS PROVIDED BY WILLIAM MARSH RICE UNIVERSITY, HOUSTON, * TX AND IS PROVIDED 'AS IS' AND WITHOUT ANY EXPRESS, IMPLIED OR * STATUTORY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF * ACCURACY, COMPLETENESS, AND NONINFRINGEMENT. THE SOFTWARE USER SHALL * INDEMNIFY, DEFEND AND HOLD HARMLESS RICE UNIVERSITY AND ITS FACULTY, * STAFF AND STUDENTS FROM ANY AND ALL CLAIMS, ACTIONS, DAMAGES, LOSSES, * LIABILITIES, COSTS AND EXPENSES, INCLUDING ATTORNEYS' FEES AND COURT * COSTS, DIRECTLY OR INDIRECTLY ARISING OUR OF OR IN CONNECTION WITH * ACCESS OR USE OF THE SOFTWARE. */ package supervisor.model; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.math.BigInteger; import java.util.*; import javax.swing.*; import javax.swing.Timer; import edu.uconn.cse.adder.PrivateKey; import edu.uconn.cse.adder.PublicKey; import sexpression.ASExpression; import sexpression.NoMatch; import sexpression.StringExpression; import supervisor.model.tallier.ChallengeDelayedTallier; import supervisor.model.tallier.ChallengeDelayedWithNIZKsTallier; import supervisor.model.tallier.EncryptedTallier; import supervisor.model.tallier.EncryptedTallierWithNIZKs; import supervisor.model.tallier.ITallier; import supervisor.model.tallier.Tallier; import votebox.crypto.interop.AdderKeyManipulator; import votebox.events.*; import auditorium.AuditoriumCryptoException; import auditorium.Key; import auditorium.NetworkException; import auditorium.IAuditoriumParams; /** * The main model of the Supervisor. Contains the status of the machines, and of * the election in general. Also contains a link to Auditorium, for broadcasting * (and hearing) messages on the network. * * @author cshaw */ public class Model { private TreeSet<AMachine> machines; private ObservableEvent machinesChangedObs; private VoteBoxAuditoriumConnector auditorium; private int mySerial; private boolean activated; private ObservableEvent activatedObs; private boolean connected; private ObservableEvent connectedObs; private boolean pollsOpen; private ObservableEvent pollsOpenObs; private int numConnected; private String keyword; private String ballotLocation; private ITallier tallier; private Timer statusTimer; private IAuditoriumParams auditoriumParams; private HashMap<String, ASExpression> committedBids; private BallotManager bManager; private ArrayList<Integer> expectedBallots; //private Key privateKey = null; /** * Equivalent to Model(-1, params); * * @param params IAuditoriumParams to use for determining settings on this Supervisor model. */ public Model(IAuditoriumParams params){ this(-1, params); } /** * Constructs a new model with the given serial * * @param serial serial number to identify as * @param params parameters to use for configuration purposes */ public Model(int serial, IAuditoriumParams params) { auditoriumParams = params; if(serial != -1) this.mySerial = serial; else this.mySerial = params.getDefaultSerialNumber(); if(mySerial == -1) throw new RuntimeException("Expected serial number in configuration file if not on command line"); machines = new TreeSet<AMachine>(); machinesChangedObs = new ObservableEvent(); activatedObs = new ObservableEvent(); connectedObs = new ObservableEvent(); pollsOpenObs = new ObservableEvent(); expectedBallots = new ArrayList<Integer>(); bManager = new BallotManager(); keyword = ""; ballotLocation = "ballot.zip"; tallier = new Tallier(); committedBids = new HashMap<String, ASExpression>(); statusTimer = new Timer(300000, new ActionListener() { public void actionPerformed(ActionEvent e) { if (isConnected()) { auditorium.announce(getStatus()); } } }); } /** * Activates this supervisor.<br> * Formats the activated message (containing the statuses of known * machines), and labels any unlabeled machines. */ public void activate() { ArrayList<StatusEvent> statuses = new ArrayList<StatusEvent>(); ArrayList<AMachine> unlabeled = new ArrayList<AMachine>(); int maxlabel = 0; for (AMachine m : machines) { if (m.isOnline()) { IAnnounceEvent s = null; if (m instanceof SupervisorMachine) { SupervisorMachine ma = (SupervisorMachine) m; if (ma.getStatus() == SupervisorMachine.ACTIVE) s = new SupervisorEvent(0, 0, "active"); else if (ma.getStatus() == SupervisorMachine.INACTIVE) s = new SupervisorEvent(0, 0, "inactive"); } else if (m instanceof VoteBoxBooth) { VoteBoxBooth ma = (VoteBoxBooth) m; if (ma.getStatus() == VoteBoxBooth.READY) s = new VoteBoxEvent(0, ma.getLabel(), "ready", ma .getBattery(), ma.getProtectedCount(), ma .getPublicCount()); else if (ma.getStatus() == VoteBoxBooth.IN_USE) s = new VoteBoxEvent(0, ma.getLabel(), "in-use", ma .getBattery(), ma.getProtectedCount(), ma .getPublicCount()); if (ma.getLabel() == 0) unlabeled.add(ma); else if (ma.getLabel() > maxlabel) maxlabel = ma.getLabel(); } else if(m instanceof BallotScannerMachine) { BallotScannerMachine ma = (BallotScannerMachine)m; if(ma.getStatus() == BallotScannerMachine.ACTIVE) { s = new BallotScannerEvent(ma.getSerial(), ma.getLabel(), "active", ma.getBattery(), ma.getProtectedCount(), ma.getPublicCount()); } else if(ma.getStatus() == BallotScannerMachine.INACTIVE) { s = new BallotScannerEvent(ma.getSerial(), ma.getLabel(), "inactive", ma.getBattery(), ma.getProtectedCount(), ma.getPublicCount()); } if (ma.getLabel() == 0) unlabeled.add(ma); else if (ma.getLabel() > maxlabel) maxlabel = ma.getLabel(); } if (s == null) throw new IllegalStateException("Unknown machine or status"); statuses.add(new StatusEvent(0, m.getSerial(), s)); } } auditorium.announce(new ActivatedEvent(mySerial, statuses)); for (AMachine machine : unlabeled) { auditorium.announce(new AssignLabelEvent(mySerial, machine.getSerial(), ++maxlabel)); } if (!pollsOpen) auditorium.announce(new PollsOpenQEvent(mySerial, keyword)); sendStartScannerEvent(); } /** * Sends a StartScannerEvent. */ public void sendStartScannerEvent () { auditorium.announce(new StartScannerEvent( mySerial )); } /** * Authorizes a VoteBox booth * * @param node * the serial number of the booth * @throws IOException */ public void authorize(int node) throws IOException { byte[] nonce = new byte[256]; for (int i = 0; i < 256; i++) nonce[i] = (byte) (Math.random() * 256); File file = new File(ballotLocation); FileInputStream fin = new FileInputStream(file); byte[] ballot = new byte[(int) file.length()]; fin.read(ballot); if(!this.auditoriumParams.getEnableNIZKs()){ auditorium.announce(new AuthorizedToCastEvent(mySerial, node, nonce, ballot)); }else{ auditorium.announce(new AuthorizedToCastWithNIZKsEvent(mySerial, node, nonce, ballot, AdderKeyManipulator.generateFinalPublicKey((PublicKey)auditoriumParams.getKeyStore().loadAdderKey("public")))); } } /** * Authorizes a VoteBox booth for a provisional voting session * * @param node * the serial number of the booth * @throws IOException */ private void provisionalAuthorize(int node) throws IOException{ byte[] nonce = new byte[256]; for (int i = 0; i < 256; i++) nonce[i] = (byte) (Math.random() * 256); File file = new File(ballotLocation); FileInputStream fin = new FileInputStream(file); byte[] ballot = new byte[(int) file.length()]; fin.read(ballot); auditorium.announce(new ProvisionalAuthorizeEvent(mySerial, node, nonce, ballot)); } /** * Closes the polls * * @return the output from the tally */ public Map<String, BigInteger> closePolls() { auditorium .announce(new PollsClosedEvent(mySerial, new Date().getTime())); //return tallier.getReport(privateKey); return tallier.getReport(); } /** * Gets the index in the list of machines of the machine with the given * serial * * @param serial * @return the index */ public int getIndexForSerial(int serial) { int i = 0; for (AMachine m : machines) if (m.getSerial() == serial) return i; else ++i; return -1; } /** * Gets today's election keyword (entered at program launch) * * @return the keyword */ public String getKeyword() { return keyword; } /** * Gets an AMachine from the list of machines by its serial number * * @param serial * @return the machine */ public AMachine getMachineForSerial(int serial) { for (AMachine m : machines) if (m.getSerial() == serial) return m; return null; } /** * Gets the list of machines, in serial number order * * @return the machines */ public TreeSet<AMachine> getMachines() { return machines; } /** * @return this machine's serial */ public int getMySerial() { return mySerial; } /** * @return the number of active connections */ public int getNumConnected() { return numConnected; } /** * @return a SupervisorEvent with this machine's status (used for periodic * broadcasts) */ public SupervisorEvent getStatus() { SupervisorEvent event; if (isActivated()) event = new SupervisorEvent(mySerial, new Date().getTime(), "active"); else event = new SupervisorEvent(mySerial, new Date().getTime(), "inactive"); return event; } /** * @return whether this supervisor is active */ public boolean isActivated() { return activated; } /** * @return whether this supervisor is connected to any machines */ public boolean isConnected() { return connected; } /** * @return whether the polls are open */ public boolean isPollsOpen() { return pollsOpen; } /** * Opens the polls. */ public void openPolls() { auditorium.announce(new PollsOpenEvent(mySerial, new Date().getTime(), keyword)); } /** * Sends an override-cancel request to a VoteBox booth * * @param node * the serial number of the booth */ public void overrideCancel(int node) { byte[] nonce = ((VoteBoxBooth) getMachineForSerial(node)).getNonce(); if (nonce == null) { System.err.println("ERROR: VoteBox machine has no associated nonce!"); throw new RuntimeException("VoteBox machine has no associated nonce!"); } auditorium.announce(new OverrideCancelEvent(mySerial, node, nonce)); } /** * Sends an override-cast request to a VoteBox booth * * @param node * the serial number of the booth */ public void overrideCast(int node) { byte[] nonce = ((VoteBoxBooth) getMachineForSerial(node)).getNonce(); auditorium.announce(new OverrideCastEvent(mySerial, node, nonce)); } /** * Register to be notified when this supervisor's active status changes * * @param obs * the observer */ public void registerForActivated(Observer obs) { activatedObs.addObserver(obs); } /** * Register to be notified when this supervisor's connected status changes * * @param obs * the observer */ public void registerForConnected(Observer obs) { connectedObs.addObserver(obs); } /** * Register to be notified when the list of machines changes * * @param obs * the observer */ public void registerForMachinesChanged(Observer obs) { machinesChangedObs.addObserver(obs); } /** * Register to be notified when the polls open status changes * * @param obs * the observer */ public void registerForPollsOpen(Observer obs) { pollsOpenObs.addObserver(obs); } /** * Sets this supervisor's active status * * @param activated * the activated to set */ public void setActivated(boolean activated) { this.activated = activated; activatedObs.notifyObservers(); } /** * Sets this supervisor's ballot location * * @param newLoc * the ballot location */ public void setBallotLocation(String newLoc) { ballotLocation = newLoc; } /** * Sets this supervisor's connected status * * @param connected * the connected to set */ public void setConnected(boolean connected) { this.connected = connected; connectedObs.notifyObservers(); } /** * Sets the election keyword * * @param keyword * the keyword to set */ public void setKeyword(String keyword) { this.keyword = keyword; } /** * Sets this supervisor's polls open status * * @param pollsOpen * the pollsOpen to set */ public void setPollsOpen(boolean pollsOpen) { this.pollsOpen = pollsOpen; pollsOpenObs.notifyObservers(); } /** * Starts auditorium, registers the event listener, and connects to the * network. */ public void start() { try { auditorium = new VoteBoxAuditoriumConnector(mySerial, auditoriumParams, ActivatedEvent.getMatcher(), AssignLabelEvent.getMatcher(), AuthorizedToCastEvent.getMatcher(), CastCommittedBallotEvent.getMatcher(), LastPollsOpenEvent.getMatcher(), OverrideCastConfirmEvent.getMatcher(), PollsClosedEvent.getMatcher(), PollsOpenEvent.getMatcher(), PollsOpenQEvent.getMatcher(), SupervisorEvent.getMatcher(), VoteBoxEvent.getMatcher(), EncryptedCastBallotEvent.getMatcher(), CommitBallotEvent.getMatcher(), CastCommittedBallotEvent.getMatcher(), ChallengeResponseEvent.getMatcher(), ChallengeEvent.getMatcher(), EncryptedCastBallotWithNIZKsEvent.getMatcher(), AuthorizedToCastWithNIZKsEvent.getMatcher(), AdderChallengeEvent.getMatcher(), PINEnteredEvent.getMatcher(), InvalidPinEvent.getMatcher(), PollStatusEvent.getMatcher(), BallotPrintSuccessEvent.getMatcher(), BallotScannedEvent.getMatcher(), BallotScannerEvent.getMatcher(), - ProvisionalCommitEvent.getMatcher()); + ProvisionalCommitEvent.getMatcher(), ProvisionalAuthorizeEvent.getMatcher()); } catch (NetworkException e1) { throw new RuntimeException(e1); } auditorium.addListener(new VoteBoxEventListener() { public void ballotCounted(BallotCountedEvent e){ //NO-OP } /** * Handler for the activated message. Sets all other supervisors * (including this one, if necessary) to the inactive state. Also * checks to see if this machine's status is listed, and responds * with it if not. */ public void activated(ActivatedEvent e) { for (AMachine m : machines) { if (m instanceof SupervisorMachine) { if (m.getSerial() == e.getSerial()) m.setStatus(SupervisorMachine.ACTIVE); else m.setStatus(SupervisorMachine.INACTIVE); } } if (e.getSerial() == mySerial) setActivated(true); else { setActivated(false); boolean found = false; for (StatusEvent ae : e.getStatuses()) { if (ae.getNode() == mySerial) { SupervisorEvent se = (SupervisorEvent) ae .getStatus(); if (!se.getStatus().equals("inactive")) broadcastStatus(); found = true; } } if (!found) broadcastStatus(); } } /** * Handler for the assign-label message. Sets that machine's label. */ public void assignLabel(AssignLabelEvent e) { AMachine m = getMachineForSerial(e.getNode()); if (m != null) { m.setLabel(e.getLabel()); machines.remove(m); machines.add(m); machinesChangedObs.notifyObservers(); } } /** * Handler for the authorized-to-cast message. Sets the nonce for * that machine. */ public void authorizedToCast(AuthorizedToCastEvent e) { AMachine m = getMachineForSerial(e.getNode()); if (m != null && m instanceof VoteBoxBooth) { ((VoteBoxBooth) m).setNonce(e.getNonce()); } } public void ballotReceived(BallotReceivedEvent e) { //NO-OP } /** * Handler for the cast-ballot message. Increments the booth's * public and protected counts, replies with ballot-received, and * stores the votes in the tallier. */ public void castCommittedBallot(CastCommittedBallotEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null && m instanceof BallotScannerMachine) { auditorium.announce(new BallotCountedEvent(mySerial, e .getSerial(), ((StringExpression) e.getNonce()) .getBytes())); tallier.confirmed(e.getNonce()); } } /** * Handler for a joined event. When a new machine joins, check and * see if it exists, and set it to online if so. Also increment the * number of connections. */ public void joined(JoinEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null) { m.setOnline(true); } numConnected++; setConnected(true); machinesChangedObs.notifyObservers(); } /** * Handler for the last-polls-open message. If the keywords match, * set the polls to open (without sending a message). */ public void lastPollsOpen(LastPollsOpenEvent e) { PollsOpenEvent e2 = e.getPollsOpenMsg(); if (e2.getKeyword().equals(keyword)) setPollsOpen(true); } /** * Handler for a left event. Set the machine to offline, and * decrement the number of connections. If we are no longer * connected to any machines, assume we're offline and deactivate.<br> * The supervisor needs to deactivate when it goes offline so that * when it comes back on, it needs to be activated again so it can * get a fresh list of machines and their statuses. Also, that way * you cannot have two machines activate separately and then join * the network, giving you two active supervisors. */ public void left(LeaveEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null) { m.setOnline(false); }else{ throw new RuntimeException("WARNING: Machine left without having been registered"); } numConnected--; // if (numConnected == 0) { // setConnected(false); // setActivated(false); // } machinesChangedObs.notifyObservers(); } public void overrideCancel(OverrideCancelEvent e) { // NO-OP } public void overrideCancelConfirm(OverrideCancelConfirmEvent e) { // NO-OP } public void overrideCancelDeny(OverrideCancelDenyEvent e) { // NO-OP } public void overrideCast(OverrideCastEvent e) { // NO-OP } /** * Handler for the override-cast-confirm event. Similar to * cast-ballot, but no received reply is sent. */ public void overrideCastConfirm(OverrideCastConfirmEvent e) { /*AMachine m = getMachineForSerial(e.getSerial()); if (m != null && m instanceof VoteBoxBooth) { VoteBoxBooth booth = (VoteBoxBooth) m; booth.setPublicCount(booth.getPublicCount() + 1); booth.setProtectedCount(booth.getProtectedCount() + 1); tallier.recordVotes(e.getBallot(), StringExpression.makeString(e.getNonce())); }*/ } public void overrideCastDeny(OverrideCastDenyEvent e) { // NO-OP } /** * Handler for the polls-closed event. Sets the polls to closed. */ public void pollsClosed(PollsClosedEvent e) { setPollsOpen(false); } /** * Handler for the polls-open event. Sets the polls to open, and * gets a fresh tallier. * @throws AuditoriumCryptoException */ public void pollsOpen(PollsOpenEvent e){ if(auditoriumParams.getUseCommitChallengeModel()){ try { if(!auditoriumParams.getEnableNIZKs()){ //Loading privateKey well in advance so the whole affair is "fail-fast" Key privateKey = auditoriumParams.getKeyStore().loadKey("private"); tallier = new ChallengeDelayedTallier(privateKey); }else{ //Loading privateKey well in advance so the whole affair is "fail-fast" PrivateKey privateKey = (PrivateKey)auditoriumParams.getKeyStore().loadAdderKey("private"); PublicKey publicKey = (PublicKey)auditoriumParams.getKeyStore().loadAdderKey("public"); tallier = new ChallengeDelayedWithNIZKsTallier(publicKey, privateKey); }//if } catch (AuditoriumCryptoException e1) { System.err.println("Crypto error encountered: "+e1.getMessage()); e1.printStackTrace(); } }else{ //If Encryption is not enabled, use a vanilla tallier if(!auditoriumParams.getCastBallotEncryptionEnabled()){ if(auditoriumParams.getEnableNIZKs()) throw new RuntimeException("Encryption must be enabled to use NIZKs"); //privateKey = null; tallier = new Tallier(); }else{ //Otherwise, grab the private key and allocate an encrypted tallier try{ if(!auditoriumParams.getEnableNIZKs()){ //Loading privateKey well in advance so the whole affair is "fail-fast" Key privateKey = auditoriumParams.getKeyStore().loadKey("private"); tallier = new EncryptedTallier(privateKey); }else{ //Loading privateKey well in advance so the whole affair is "fail-fast" PrivateKey privateKey = (PrivateKey)auditoriumParams.getKeyStore().loadAdderKey("private"); PublicKey publicKey = (PublicKey)auditoriumParams.getKeyStore().loadAdderKey("public"); tallier = new EncryptedTallierWithNIZKs(publicKey, privateKey); }//if }catch(AuditoriumCryptoException e1){ System.err.println("Crypto error encountered: "+e1.getMessage()); e1.printStackTrace(); }//catch }//if }//if setPollsOpen(true); } /** * Handler for the polls-open? event. Searches the machine's log, * and replies with a last-polls-open message if an appropriate * polls-open message is found. */ public void pollsOpenQ(PollsOpenQEvent e) { if (e.getSerial() != mySerial) { // TODO: Search the log and extract an appropriate polls-open message ASExpression res = null; if (res != null && res != NoMatch.SINGLETON) { VoteBoxEventMatcher matcher = new VoteBoxEventMatcher( PollsOpenEvent.getMatcher()); PollsOpenEvent event = (PollsOpenEvent) matcher.match( 0, res); if (event != null && event.getKeyword().equals(e.getKeyword())) auditorium.announce(new LastPollsOpenEvent( mySerial, event)); } } } /** * Handler for a ballotscanner (status) event. Adds the machine if it * hasn't been seen, and updates its status if it has. */ public void ballotscanner(BallotScannerEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null && !(m instanceof BallotScannerMachine)) throw new IllegalStateException( "Machine " + e.getSerial() + " is not a ballotscanner, but broadcasted ballotscanner message"); if (m == null) { m = new BallotScannerMachine(e.getSerial()); System.out.println("Ballot Scanner Added: " + m); machines.add(m); machinesChangedObs.notifyObservers(); } BallotScannerMachine bsm = (BallotScannerMachine) m; if(e.getStatus().equals("active")) { bsm.setStatus(BallotScannerMachine.ACTIVE); } else if (e.getStatus().equals("inactive")) bsm.setStatus(BallotScannerMachine.INACTIVE); else throw new IllegalStateException("Invalid BallotScanner Status: " + e.getStatus()); bsm.setBattery(e.getBattery()); bsm.setProtectedCount(e.getProtectedCount()); bsm.setPublicCount(e.getPublicCount()); bsm.setOnline(true); //Check to see if this votebox has a conflicting label if (e.getLabel() > 0){ for(AMachine machine : machines){ if(machine.getLabel() == e.getLabel() && machine != m){ //If there is a conflict, relabel this (the event generator) machine. int maxlabel = 0; for(AMachine ma : machines){ if(ma instanceof BallotScannerMachine) maxlabel = Math.max(maxlabel, ma.getLabel()); }//for auditorium.announce(new AssignLabelEvent(mySerial, e.getSerial(), maxlabel + 1)); return; } } }//if if (e.getLabel() > 0) bsm.setLabel(e.getLabel()); else { if (activated) { if (bsm.getLabel() > 0) { auditorium.announce(new AssignLabelEvent(mySerial, e.getSerial(), bsm.getLabel())); } else { int maxlabel = 0; for (AMachine ma : machines) { if (ma instanceof BallotScannerMachine && ma.getLabel() > maxlabel) { maxlabel = ma.getLabel(); } } auditorium.announce(new AssignLabelEvent(mySerial, e .getSerial(), maxlabel + 1)); } auditorium.announce(new PollStatusEvent(mySerial, e.getSerial(), pollsOpen ? 1:0 )); } } } /** * Handler for a supervisor (status) event. Adds the machine if it * hasn't been seen, and updates its status if it has. */ public void supervisor(SupervisorEvent e) { auditorium.announce(new PollMachinesEvent(mySerial, new Date().getTime(), keyword)); AMachine m = getMachineForSerial(e.getSerial()); if (m != null && !(m instanceof SupervisorMachine)) throw new IllegalStateException( "Machine " + e.getSerial() + " is not a supervisor, but broadcasted supervisor message"); if (m == null) { m = new SupervisorMachine(e.getSerial(), e.getSerial() == mySerial); machines.add(m); machinesChangedObs.notifyObservers(); } SupervisorMachine sup = (SupervisorMachine) m; if (e.getStatus().equals("active")) { sup.setStatus(SupervisorMachine.ACTIVE); if (e.getSerial() != mySerial) setActivated(false); } else if (e.getStatus().equals("inactive")) sup.setStatus(SupervisorMachine.INACTIVE); else throw new IllegalStateException( "Invalid Supervisor Status: " + e.getStatus()); sup.setOnline(true); } /** * Handler for a votebox (status) event. Adds the machine if it * hasn't been seen, or updates the status if it has. Also, if the * booth is unlabeled and this is the active supervisor, labels the * booth with its previous label if known, or the next available * number. */ public void votebox(VoteBoxEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null && !(m instanceof VoteBoxBooth)) throw new IllegalStateException( "Machine " + e.getSerial() + " is not a booth, but broadcasted votebox message"); if (m == null) { m = new VoteBoxBooth(e.getSerial()); System.out.println("Vote Box Added: " + m); machines.add(m); machinesChangedObs.notifyObservers(); } VoteBoxBooth booth = (VoteBoxBooth) m; if (e.getStatus().equals("ready")) booth.setStatus(VoteBoxBooth.READY); else if (e.getStatus().equals("in-use")) booth.setStatus(VoteBoxBooth.IN_USE); else if (e.getStatus().equals("provisional-in-use")) booth.setStatus(VoteBoxBooth.PROVISIONAL); else throw new IllegalStateException("Invalid VoteBox Status: " + e.getStatus()); booth.setBattery(e.getBattery()); booth.setProtectedCount(e.getProtectedCount()); booth.setPublicCount(e.getPublicCount()); booth.setOnline(true); //Check to see if this votebox has a conflicting label if (e.getLabel() > 0){ for(AMachine machine : machines){ if(machine.getLabel() == e.getLabel() && machine != m){ //If there is a conflict, relabel this (the event generator) machine. int maxlabel = 0; for(AMachine ma : machines){ if(ma instanceof VoteBoxBooth) maxlabel = Math.max(maxlabel, ma.getLabel()); }//for auditorium.announce(new AssignLabelEvent(mySerial, e.getSerial(), maxlabel + 1)); return; } } }//if if (e.getLabel() > 0) booth.setLabel(e.getLabel()); else { if (activated) { if (booth.getLabel() > 0) auditorium.announce(new AssignLabelEvent(mySerial, e .getSerial(), booth.getLabel())); else { int maxlabel = 0; for (AMachine ma : machines) { if (ma instanceof VoteBoxBooth && ma.getLabel() > maxlabel) maxlabel = ma.getLabel(); } auditorium.announce(new AssignLabelEvent(mySerial, e .getSerial(), maxlabel + 1)); } auditorium.announce(new PollStatusEvent(mySerial, e.getSerial(), pollsOpen ? 1:0 )); } } } /** * Indicate to the tallier that the vote in question is being challenged, * and as such should be excluded from the final tally. */ public void challengeResponse(ChallengeResponseEvent e) { //NO-OP } /** * Indicate to the tallier that the vote in question is being challenged, * and as such should be excluded from the final tally. */ public void challenge(ChallengeEvent e) { System.out.println("Received challenge: "+e); tallier.challenged(e.getNonce()); auditorium.announce(new ChallengeResponseEvent(mySerial, e.getSerial(), e.getNonce())); } /** * Record the vote received in the commit event. * It should not yet be tallied. */ public void commitBallot(CommitBallotEvent e) { //System.err.println("Ballot committed! BID: " + e.getBID()); AMachine m = getMachineForSerial(e.getSerial()); if (m != null && m instanceof VoteBoxBooth) { VoteBoxBooth booth = (VoteBoxBooth) m; booth.setPublicCount(booth.getPublicCount() + 1); booth.setProtectedCount(booth.getProtectedCount() + 1); BallotStore.addBallot(e.getBID().toString(), e.getBallot()); auditorium.announce(new BallotReceivedEvent(mySerial, e .getSerial(), ((StringExpression) e.getNonce()) .getBytes())); tallier.recordVotes(e.getBallot().toVerbatim(), e.getNonce()); String bid = e.getBID().toString(); committedBids.put(bid, e.getNonce()); } } public void provisionalCommitBallot(ProvisionalCommitEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null && m instanceof VoteBoxBooth) { VoteBoxBooth booth = (VoteBoxBooth) m; booth.setPublicCount(booth.getPublicCount() + 1); booth.setProtectedCount(booth.getProtectedCount() + 1); auditorium.announce(new BallotReceivedEvent(mySerial, e .getSerial(), ((StringExpression) e.getNonce()) .getBytes())); } } public void ballotScanned(BallotScannedEvent e) { String bid = e.getBID(); int serial = e.getSerial(); if (committedBids.containsKey(bid)){ //ASExpression nonce = committedBids.get(bid); ASExpression nonce = committedBids.remove(bid); BallotStore.castCommittedBallot(e.getBID()); // used to be in voteBox registerForCommit listener. auditorium.announce(new CastCommittedBallotEvent(serial, nonce, StringExpression.makeString(e.getBID()))); // that should trigger my own castBallot listener. System.out.println("Sending scan confirmation!"); System.out.println("BID: " + bid); auditorium.announce(new BallotScanAcceptedEvent(mySerial, bid)); } else { System.out.println("Sending scan rejection!"); System.out.println("BID: " + bid); auditorium.announce(new BallotScanRejectedEvent(mySerial, bid)); } } public void pinEntered(PINEnteredEvent e){ if(isPollsOpen()) { System.out.println(">>> PIN entered: " + e.getPin()); String ballot = bManager.getBallotByPin(e.getPin()); System.out.println(ballot); if(ballot!=null){ try { System.out.println(bManager.getPrecinctByBallot(ballot)); setBallotLocation(ballot); if(bManager.getPrecinctByBallot(ballot).contains("provisional")) { provisionalAuthorize(e.getSerial()); System.out.println(">>>>>>> It's working!"); } else authorize(e.getSerial()); } catch(IOException ex) { System.out.println(ex.getMessage()); } } else { auditorium.announce(new InvalidPinEvent(mySerial, e.getNonce())); } } } public void invalidPin(InvalidPinEvent e) {} public void pollStatus(PollStatusEvent pollStatusEvent) { pollsOpen = pollStatusEvent.getPollStatus()==1; sendStartScannerEvent(); } public void ballotAccepted(BallotScanAcceptedEvent e){ //NO-OP } public void ballotRejected(BallotScanRejectedEvent e){ //NO-OP } public void ballotPrinting(BallotPrintingEvent e) { //NO-OP } public void ballotPrintSuccess(BallotPrintSuccessEvent e) { expectedBallots.add(Integer.valueOf(e.getBID())); } public void ballotPrintFail(BallotPrintFailEvent e) { //NO-OP } public void uploadCastBallots(CastBallotUploadEvent e) { // NO-OP } public void uploadChallengedBallots(ChallengedBallotUploadEvent e) { // NO-OP } public void scannerstart(StartScannerEvent e) { // NO-OP for (AMachine machine:machines) { if (machine instanceof BallotScannerMachine) { machine.setStatus(BallotScannerMachine.ACTIVE); } } } public void pollMachines(PollMachinesEvent e) { // NO-OP } public void spoilBallot(SpoilBallotEvent e) { // NO-OP } public void announceProvisionalBallot(ProvisionalBallotEvent e) { // NO-OP } - public void provisionalAuthorizedToCast(ProvisionalAuthorizeEvent provisionalAuthorizeEvent) { - // NO-OP + /** + * Handler for the provisional-authorize message. Sets the nonce for + * that machine. + */ + public void provisionalAuthorizedToCast(ProvisionalAuthorizeEvent e) { + AMachine m = getMachineForSerial(e.getNode()); + if (m != null && m instanceof VoteBoxBooth) { + ((VoteBoxBooth) m).setNonce(e.getNonce()); + } } }); try { auditorium.connect(); auditorium.announce(getStatus()); } catch (NetworkException e1) { //NetworkException represents a recoverable error // so just note it and continue System.out.println("Recoverable error occurred: "+e1.getMessage()); e1.printStackTrace(System.err); } statusTimer.start(); } /** * Broadcasts this supervisor's status, and resets the status timer */ public void broadcastStatus() { auditorium.announce(getStatus()); statusTimer.restart(); } public VoteBoxAuditoriumConnector getAuditoriumConnector() { return auditorium; } /** * A method for retrieving the parameters of the election */ public IAuditoriumParams getParams(){ return auditoriumParams; } //adds a new ballot to the ballot manager public void addBallot(File fileIn) { String fileName = fileIn.getName(); try{ String precinct = fileName.substring(fileName.length()-7,fileName.length()-4); bManager.addBallot(precinct, fileIn.getAbsolutePath()); }catch(NumberFormatException e){ JOptionPane.showMessageDialog(null, "Please choose a valid ballot"); } } /** * Will spoil ballot by removing it from the commtedBids structure, return true if a bid was removed * @param bid * @return whether or not a bid was actually spoiled */ public boolean spoilBallot(String bid){ if(committedBids.containsKey(bid)){ ASExpression nonce = committedBids.remove(bid); auditorium.announce(new SpoilBallotEvent(mySerial, bid, nonce)); return true; } else return false; } public String generatePin(String precinct){ return bManager.generatePin(precinct); } public String generateProvisionalPin(String precinct){ return bManager.generateProvisionalPin(precinct); } public String[] getSelections(){ return bManager.getSelections(); } public String getInitialSelection(){ return bManager.getInitialSelection(); } /** * A method that will generate a random pin for the voter to enter into his votebox machine */ }
false
true
public void start() { try { auditorium = new VoteBoxAuditoriumConnector(mySerial, auditoriumParams, ActivatedEvent.getMatcher(), AssignLabelEvent.getMatcher(), AuthorizedToCastEvent.getMatcher(), CastCommittedBallotEvent.getMatcher(), LastPollsOpenEvent.getMatcher(), OverrideCastConfirmEvent.getMatcher(), PollsClosedEvent.getMatcher(), PollsOpenEvent.getMatcher(), PollsOpenQEvent.getMatcher(), SupervisorEvent.getMatcher(), VoteBoxEvent.getMatcher(), EncryptedCastBallotEvent.getMatcher(), CommitBallotEvent.getMatcher(), CastCommittedBallotEvent.getMatcher(), ChallengeResponseEvent.getMatcher(), ChallengeEvent.getMatcher(), EncryptedCastBallotWithNIZKsEvent.getMatcher(), AuthorizedToCastWithNIZKsEvent.getMatcher(), AdderChallengeEvent.getMatcher(), PINEnteredEvent.getMatcher(), InvalidPinEvent.getMatcher(), PollStatusEvent.getMatcher(), BallotPrintSuccessEvent.getMatcher(), BallotScannedEvent.getMatcher(), BallotScannerEvent.getMatcher(), ProvisionalCommitEvent.getMatcher()); } catch (NetworkException e1) { throw new RuntimeException(e1); } auditorium.addListener(new VoteBoxEventListener() { public void ballotCounted(BallotCountedEvent e){ //NO-OP } /** * Handler for the activated message. Sets all other supervisors * (including this one, if necessary) to the inactive state. Also * checks to see if this machine's status is listed, and responds * with it if not. */ public void activated(ActivatedEvent e) { for (AMachine m : machines) { if (m instanceof SupervisorMachine) { if (m.getSerial() == e.getSerial()) m.setStatus(SupervisorMachine.ACTIVE); else m.setStatus(SupervisorMachine.INACTIVE); } } if (e.getSerial() == mySerial) setActivated(true); else { setActivated(false); boolean found = false; for (StatusEvent ae : e.getStatuses()) { if (ae.getNode() == mySerial) { SupervisorEvent se = (SupervisorEvent) ae .getStatus(); if (!se.getStatus().equals("inactive")) broadcastStatus(); found = true; } } if (!found) broadcastStatus(); } } /** * Handler for the assign-label message. Sets that machine's label. */ public void assignLabel(AssignLabelEvent e) { AMachine m = getMachineForSerial(e.getNode()); if (m != null) { m.setLabel(e.getLabel()); machines.remove(m); machines.add(m); machinesChangedObs.notifyObservers(); } } /** * Handler for the authorized-to-cast message. Sets the nonce for * that machine. */ public void authorizedToCast(AuthorizedToCastEvent e) { AMachine m = getMachineForSerial(e.getNode()); if (m != null && m instanceof VoteBoxBooth) { ((VoteBoxBooth) m).setNonce(e.getNonce()); } } public void ballotReceived(BallotReceivedEvent e) { //NO-OP } /** * Handler for the cast-ballot message. Increments the booth's * public and protected counts, replies with ballot-received, and * stores the votes in the tallier. */ public void castCommittedBallot(CastCommittedBallotEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null && m instanceof BallotScannerMachine) { auditorium.announce(new BallotCountedEvent(mySerial, e .getSerial(), ((StringExpression) e.getNonce()) .getBytes())); tallier.confirmed(e.getNonce()); } } /** * Handler for a joined event. When a new machine joins, check and * see if it exists, and set it to online if so. Also increment the * number of connections. */ public void joined(JoinEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null) { m.setOnline(true); } numConnected++; setConnected(true); machinesChangedObs.notifyObservers(); } /** * Handler for the last-polls-open message. If the keywords match, * set the polls to open (without sending a message). */ public void lastPollsOpen(LastPollsOpenEvent e) { PollsOpenEvent e2 = e.getPollsOpenMsg(); if (e2.getKeyword().equals(keyword)) setPollsOpen(true); } /** * Handler for a left event. Set the machine to offline, and * decrement the number of connections. If we are no longer * connected to any machines, assume we're offline and deactivate.<br> * The supervisor needs to deactivate when it goes offline so that * when it comes back on, it needs to be activated again so it can * get a fresh list of machines and their statuses. Also, that way * you cannot have two machines activate separately and then join * the network, giving you two active supervisors. */ public void left(LeaveEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null) { m.setOnline(false); }else{ throw new RuntimeException("WARNING: Machine left without having been registered"); } numConnected--; // if (numConnected == 0) { // setConnected(false); // setActivated(false); // } machinesChangedObs.notifyObservers(); } public void overrideCancel(OverrideCancelEvent e) { // NO-OP } public void overrideCancelConfirm(OverrideCancelConfirmEvent e) { // NO-OP } public void overrideCancelDeny(OverrideCancelDenyEvent e) { // NO-OP } public void overrideCast(OverrideCastEvent e) { // NO-OP } /** * Handler for the override-cast-confirm event. Similar to * cast-ballot, but no received reply is sent. */ public void overrideCastConfirm(OverrideCastConfirmEvent e) { /*AMachine m = getMachineForSerial(e.getSerial()); if (m != null && m instanceof VoteBoxBooth) { VoteBoxBooth booth = (VoteBoxBooth) m; booth.setPublicCount(booth.getPublicCount() + 1); booth.setProtectedCount(booth.getProtectedCount() + 1); tallier.recordVotes(e.getBallot(), StringExpression.makeString(e.getNonce())); }*/ } public void overrideCastDeny(OverrideCastDenyEvent e) { // NO-OP } /** * Handler for the polls-closed event. Sets the polls to closed. */ public void pollsClosed(PollsClosedEvent e) { setPollsOpen(false); } /** * Handler for the polls-open event. Sets the polls to open, and * gets a fresh tallier. * @throws AuditoriumCryptoException */ public void pollsOpen(PollsOpenEvent e){ if(auditoriumParams.getUseCommitChallengeModel()){ try { if(!auditoriumParams.getEnableNIZKs()){ //Loading privateKey well in advance so the whole affair is "fail-fast" Key privateKey = auditoriumParams.getKeyStore().loadKey("private"); tallier = new ChallengeDelayedTallier(privateKey); }else{ //Loading privateKey well in advance so the whole affair is "fail-fast" PrivateKey privateKey = (PrivateKey)auditoriumParams.getKeyStore().loadAdderKey("private"); PublicKey publicKey = (PublicKey)auditoriumParams.getKeyStore().loadAdderKey("public"); tallier = new ChallengeDelayedWithNIZKsTallier(publicKey, privateKey); }//if } catch (AuditoriumCryptoException e1) { System.err.println("Crypto error encountered: "+e1.getMessage()); e1.printStackTrace(); } }else{ //If Encryption is not enabled, use a vanilla tallier if(!auditoriumParams.getCastBallotEncryptionEnabled()){ if(auditoriumParams.getEnableNIZKs()) throw new RuntimeException("Encryption must be enabled to use NIZKs"); //privateKey = null; tallier = new Tallier(); }else{ //Otherwise, grab the private key and allocate an encrypted tallier try{ if(!auditoriumParams.getEnableNIZKs()){ //Loading privateKey well in advance so the whole affair is "fail-fast" Key privateKey = auditoriumParams.getKeyStore().loadKey("private"); tallier = new EncryptedTallier(privateKey); }else{ //Loading privateKey well in advance so the whole affair is "fail-fast" PrivateKey privateKey = (PrivateKey)auditoriumParams.getKeyStore().loadAdderKey("private"); PublicKey publicKey = (PublicKey)auditoriumParams.getKeyStore().loadAdderKey("public"); tallier = new EncryptedTallierWithNIZKs(publicKey, privateKey); }//if }catch(AuditoriumCryptoException e1){ System.err.println("Crypto error encountered: "+e1.getMessage()); e1.printStackTrace(); }//catch }//if }//if setPollsOpen(true); } /** * Handler for the polls-open? event. Searches the machine's log, * and replies with a last-polls-open message if an appropriate * polls-open message is found. */ public void pollsOpenQ(PollsOpenQEvent e) { if (e.getSerial() != mySerial) { // TODO: Search the log and extract an appropriate polls-open message ASExpression res = null; if (res != null && res != NoMatch.SINGLETON) { VoteBoxEventMatcher matcher = new VoteBoxEventMatcher( PollsOpenEvent.getMatcher()); PollsOpenEvent event = (PollsOpenEvent) matcher.match( 0, res); if (event != null && event.getKeyword().equals(e.getKeyword())) auditorium.announce(new LastPollsOpenEvent( mySerial, event)); } } } /** * Handler for a ballotscanner (status) event. Adds the machine if it * hasn't been seen, and updates its status if it has. */ public void ballotscanner(BallotScannerEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null && !(m instanceof BallotScannerMachine)) throw new IllegalStateException( "Machine " + e.getSerial() + " is not a ballotscanner, but broadcasted ballotscanner message"); if (m == null) { m = new BallotScannerMachine(e.getSerial()); System.out.println("Ballot Scanner Added: " + m); machines.add(m); machinesChangedObs.notifyObservers(); } BallotScannerMachine bsm = (BallotScannerMachine) m; if(e.getStatus().equals("active")) { bsm.setStatus(BallotScannerMachine.ACTIVE); } else if (e.getStatus().equals("inactive")) bsm.setStatus(BallotScannerMachine.INACTIVE); else throw new IllegalStateException("Invalid BallotScanner Status: " + e.getStatus()); bsm.setBattery(e.getBattery()); bsm.setProtectedCount(e.getProtectedCount()); bsm.setPublicCount(e.getPublicCount()); bsm.setOnline(true); //Check to see if this votebox has a conflicting label if (e.getLabel() > 0){ for(AMachine machine : machines){ if(machine.getLabel() == e.getLabel() && machine != m){ //If there is a conflict, relabel this (the event generator) machine. int maxlabel = 0; for(AMachine ma : machines){ if(ma instanceof BallotScannerMachine) maxlabel = Math.max(maxlabel, ma.getLabel()); }//for auditorium.announce(new AssignLabelEvent(mySerial, e.getSerial(), maxlabel + 1)); return; } } }//if if (e.getLabel() > 0) bsm.setLabel(e.getLabel()); else { if (activated) { if (bsm.getLabel() > 0) { auditorium.announce(new AssignLabelEvent(mySerial, e.getSerial(), bsm.getLabel())); } else { int maxlabel = 0; for (AMachine ma : machines) { if (ma instanceof BallotScannerMachine && ma.getLabel() > maxlabel) { maxlabel = ma.getLabel(); } } auditorium.announce(new AssignLabelEvent(mySerial, e .getSerial(), maxlabel + 1)); } auditorium.announce(new PollStatusEvent(mySerial, e.getSerial(), pollsOpen ? 1:0 )); } } } /** * Handler for a supervisor (status) event. Adds the machine if it * hasn't been seen, and updates its status if it has. */ public void supervisor(SupervisorEvent e) { auditorium.announce(new PollMachinesEvent(mySerial, new Date().getTime(), keyword)); AMachine m = getMachineForSerial(e.getSerial()); if (m != null && !(m instanceof SupervisorMachine)) throw new IllegalStateException( "Machine " + e.getSerial() + " is not a supervisor, but broadcasted supervisor message"); if (m == null) { m = new SupervisorMachine(e.getSerial(), e.getSerial() == mySerial); machines.add(m); machinesChangedObs.notifyObservers(); } SupervisorMachine sup = (SupervisorMachine) m; if (e.getStatus().equals("active")) { sup.setStatus(SupervisorMachine.ACTIVE); if (e.getSerial() != mySerial) setActivated(false); } else if (e.getStatus().equals("inactive")) sup.setStatus(SupervisorMachine.INACTIVE); else throw new IllegalStateException( "Invalid Supervisor Status: " + e.getStatus()); sup.setOnline(true); } /** * Handler for a votebox (status) event. Adds the machine if it * hasn't been seen, or updates the status if it has. Also, if the * booth is unlabeled and this is the active supervisor, labels the * booth with its previous label if known, or the next available * number. */ public void votebox(VoteBoxEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null && !(m instanceof VoteBoxBooth)) throw new IllegalStateException( "Machine " + e.getSerial() + " is not a booth, but broadcasted votebox message"); if (m == null) { m = new VoteBoxBooth(e.getSerial()); System.out.println("Vote Box Added: " + m); machines.add(m); machinesChangedObs.notifyObservers(); } VoteBoxBooth booth = (VoteBoxBooth) m; if (e.getStatus().equals("ready")) booth.setStatus(VoteBoxBooth.READY); else if (e.getStatus().equals("in-use")) booth.setStatus(VoteBoxBooth.IN_USE); else if (e.getStatus().equals("provisional-in-use")) booth.setStatus(VoteBoxBooth.PROVISIONAL); else throw new IllegalStateException("Invalid VoteBox Status: " + e.getStatus()); booth.setBattery(e.getBattery()); booth.setProtectedCount(e.getProtectedCount()); booth.setPublicCount(e.getPublicCount()); booth.setOnline(true); //Check to see if this votebox has a conflicting label if (e.getLabel() > 0){ for(AMachine machine : machines){ if(machine.getLabel() == e.getLabel() && machine != m){ //If there is a conflict, relabel this (the event generator) machine. int maxlabel = 0; for(AMachine ma : machines){ if(ma instanceof VoteBoxBooth) maxlabel = Math.max(maxlabel, ma.getLabel()); }//for auditorium.announce(new AssignLabelEvent(mySerial, e.getSerial(), maxlabel + 1)); return; } } }//if if (e.getLabel() > 0) booth.setLabel(e.getLabel()); else { if (activated) { if (booth.getLabel() > 0) auditorium.announce(new AssignLabelEvent(mySerial, e .getSerial(), booth.getLabel())); else { int maxlabel = 0; for (AMachine ma : machines) { if (ma instanceof VoteBoxBooth && ma.getLabel() > maxlabel) maxlabel = ma.getLabel(); } auditorium.announce(new AssignLabelEvent(mySerial, e .getSerial(), maxlabel + 1)); } auditorium.announce(new PollStatusEvent(mySerial, e.getSerial(), pollsOpen ? 1:0 )); } } } /** * Indicate to the tallier that the vote in question is being challenged, * and as such should be excluded from the final tally. */ public void challengeResponse(ChallengeResponseEvent e) { //NO-OP } /** * Indicate to the tallier that the vote in question is being challenged, * and as such should be excluded from the final tally. */ public void challenge(ChallengeEvent e) { System.out.println("Received challenge: "+e); tallier.challenged(e.getNonce()); auditorium.announce(new ChallengeResponseEvent(mySerial, e.getSerial(), e.getNonce())); } /** * Record the vote received in the commit event. * It should not yet be tallied. */ public void commitBallot(CommitBallotEvent e) { //System.err.println("Ballot committed! BID: " + e.getBID()); AMachine m = getMachineForSerial(e.getSerial()); if (m != null && m instanceof VoteBoxBooth) { VoteBoxBooth booth = (VoteBoxBooth) m; booth.setPublicCount(booth.getPublicCount() + 1); booth.setProtectedCount(booth.getProtectedCount() + 1); BallotStore.addBallot(e.getBID().toString(), e.getBallot()); auditorium.announce(new BallotReceivedEvent(mySerial, e .getSerial(), ((StringExpression) e.getNonce()) .getBytes())); tallier.recordVotes(e.getBallot().toVerbatim(), e.getNonce()); String bid = e.getBID().toString(); committedBids.put(bid, e.getNonce()); } } public void provisionalCommitBallot(ProvisionalCommitEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null && m instanceof VoteBoxBooth) { VoteBoxBooth booth = (VoteBoxBooth) m; booth.setPublicCount(booth.getPublicCount() + 1); booth.setProtectedCount(booth.getProtectedCount() + 1); auditorium.announce(new BallotReceivedEvent(mySerial, e .getSerial(), ((StringExpression) e.getNonce()) .getBytes())); } } public void ballotScanned(BallotScannedEvent e) { String bid = e.getBID(); int serial = e.getSerial(); if (committedBids.containsKey(bid)){ //ASExpression nonce = committedBids.get(bid); ASExpression nonce = committedBids.remove(bid); BallotStore.castCommittedBallot(e.getBID()); // used to be in voteBox registerForCommit listener. auditorium.announce(new CastCommittedBallotEvent(serial, nonce, StringExpression.makeString(e.getBID()))); // that should trigger my own castBallot listener. System.out.println("Sending scan confirmation!"); System.out.println("BID: " + bid); auditorium.announce(new BallotScanAcceptedEvent(mySerial, bid)); } else { System.out.println("Sending scan rejection!"); System.out.println("BID: " + bid); auditorium.announce(new BallotScanRejectedEvent(mySerial, bid)); } } public void pinEntered(PINEnteredEvent e){ if(isPollsOpen()) { System.out.println(">>> PIN entered: " + e.getPin()); String ballot = bManager.getBallotByPin(e.getPin()); System.out.println(ballot); if(ballot!=null){ try { System.out.println(bManager.getPrecinctByBallot(ballot)); setBallotLocation(ballot); if(bManager.getPrecinctByBallot(ballot).contains("provisional")) { provisionalAuthorize(e.getSerial()); System.out.println(">>>>>>> It's working!"); } else authorize(e.getSerial()); } catch(IOException ex) { System.out.println(ex.getMessage()); } } else { auditorium.announce(new InvalidPinEvent(mySerial, e.getNonce())); } } } public void invalidPin(InvalidPinEvent e) {} public void pollStatus(PollStatusEvent pollStatusEvent) { pollsOpen = pollStatusEvent.getPollStatus()==1; sendStartScannerEvent(); } public void ballotAccepted(BallotScanAcceptedEvent e){ //NO-OP } public void ballotRejected(BallotScanRejectedEvent e){ //NO-OP } public void ballotPrinting(BallotPrintingEvent e) { //NO-OP } public void ballotPrintSuccess(BallotPrintSuccessEvent e) { expectedBallots.add(Integer.valueOf(e.getBID())); } public void ballotPrintFail(BallotPrintFailEvent e) { //NO-OP } public void uploadCastBallots(CastBallotUploadEvent e) { // NO-OP } public void uploadChallengedBallots(ChallengedBallotUploadEvent e) { // NO-OP } public void scannerstart(StartScannerEvent e) { // NO-OP for (AMachine machine:machines) { if (machine instanceof BallotScannerMachine) { machine.setStatus(BallotScannerMachine.ACTIVE); } } } public void pollMachines(PollMachinesEvent e) { // NO-OP } public void spoilBallot(SpoilBallotEvent e) { // NO-OP } public void announceProvisionalBallot(ProvisionalBallotEvent e) { // NO-OP } public void provisionalAuthorizedToCast(ProvisionalAuthorizeEvent provisionalAuthorizeEvent) { // NO-OP } }); try { auditorium.connect(); auditorium.announce(getStatus()); } catch (NetworkException e1) { //NetworkException represents a recoverable error // so just note it and continue System.out.println("Recoverable error occurred: "+e1.getMessage()); e1.printStackTrace(System.err); } statusTimer.start(); }
public void start() { try { auditorium = new VoteBoxAuditoriumConnector(mySerial, auditoriumParams, ActivatedEvent.getMatcher(), AssignLabelEvent.getMatcher(), AuthorizedToCastEvent.getMatcher(), CastCommittedBallotEvent.getMatcher(), LastPollsOpenEvent.getMatcher(), OverrideCastConfirmEvent.getMatcher(), PollsClosedEvent.getMatcher(), PollsOpenEvent.getMatcher(), PollsOpenQEvent.getMatcher(), SupervisorEvent.getMatcher(), VoteBoxEvent.getMatcher(), EncryptedCastBallotEvent.getMatcher(), CommitBallotEvent.getMatcher(), CastCommittedBallotEvent.getMatcher(), ChallengeResponseEvent.getMatcher(), ChallengeEvent.getMatcher(), EncryptedCastBallotWithNIZKsEvent.getMatcher(), AuthorizedToCastWithNIZKsEvent.getMatcher(), AdderChallengeEvent.getMatcher(), PINEnteredEvent.getMatcher(), InvalidPinEvent.getMatcher(), PollStatusEvent.getMatcher(), BallotPrintSuccessEvent.getMatcher(), BallotScannedEvent.getMatcher(), BallotScannerEvent.getMatcher(), ProvisionalCommitEvent.getMatcher(), ProvisionalAuthorizeEvent.getMatcher()); } catch (NetworkException e1) { throw new RuntimeException(e1); } auditorium.addListener(new VoteBoxEventListener() { public void ballotCounted(BallotCountedEvent e){ //NO-OP } /** * Handler for the activated message. Sets all other supervisors * (including this one, if necessary) to the inactive state. Also * checks to see if this machine's status is listed, and responds * with it if not. */ public void activated(ActivatedEvent e) { for (AMachine m : machines) { if (m instanceof SupervisorMachine) { if (m.getSerial() == e.getSerial()) m.setStatus(SupervisorMachine.ACTIVE); else m.setStatus(SupervisorMachine.INACTIVE); } } if (e.getSerial() == mySerial) setActivated(true); else { setActivated(false); boolean found = false; for (StatusEvent ae : e.getStatuses()) { if (ae.getNode() == mySerial) { SupervisorEvent se = (SupervisorEvent) ae .getStatus(); if (!se.getStatus().equals("inactive")) broadcastStatus(); found = true; } } if (!found) broadcastStatus(); } } /** * Handler for the assign-label message. Sets that machine's label. */ public void assignLabel(AssignLabelEvent e) { AMachine m = getMachineForSerial(e.getNode()); if (m != null) { m.setLabel(e.getLabel()); machines.remove(m); machines.add(m); machinesChangedObs.notifyObservers(); } } /** * Handler for the authorized-to-cast message. Sets the nonce for * that machine. */ public void authorizedToCast(AuthorizedToCastEvent e) { AMachine m = getMachineForSerial(e.getNode()); if (m != null && m instanceof VoteBoxBooth) { ((VoteBoxBooth) m).setNonce(e.getNonce()); } } public void ballotReceived(BallotReceivedEvent e) { //NO-OP } /** * Handler for the cast-ballot message. Increments the booth's * public and protected counts, replies with ballot-received, and * stores the votes in the tallier. */ public void castCommittedBallot(CastCommittedBallotEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null && m instanceof BallotScannerMachine) { auditorium.announce(new BallotCountedEvent(mySerial, e .getSerial(), ((StringExpression) e.getNonce()) .getBytes())); tallier.confirmed(e.getNonce()); } } /** * Handler for a joined event. When a new machine joins, check and * see if it exists, and set it to online if so. Also increment the * number of connections. */ public void joined(JoinEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null) { m.setOnline(true); } numConnected++; setConnected(true); machinesChangedObs.notifyObservers(); } /** * Handler for the last-polls-open message. If the keywords match, * set the polls to open (without sending a message). */ public void lastPollsOpen(LastPollsOpenEvent e) { PollsOpenEvent e2 = e.getPollsOpenMsg(); if (e2.getKeyword().equals(keyword)) setPollsOpen(true); } /** * Handler for a left event. Set the machine to offline, and * decrement the number of connections. If we are no longer * connected to any machines, assume we're offline and deactivate.<br> * The supervisor needs to deactivate when it goes offline so that * when it comes back on, it needs to be activated again so it can * get a fresh list of machines and their statuses. Also, that way * you cannot have two machines activate separately and then join * the network, giving you two active supervisors. */ public void left(LeaveEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null) { m.setOnline(false); }else{ throw new RuntimeException("WARNING: Machine left without having been registered"); } numConnected--; // if (numConnected == 0) { // setConnected(false); // setActivated(false); // } machinesChangedObs.notifyObservers(); } public void overrideCancel(OverrideCancelEvent e) { // NO-OP } public void overrideCancelConfirm(OverrideCancelConfirmEvent e) { // NO-OP } public void overrideCancelDeny(OverrideCancelDenyEvent e) { // NO-OP } public void overrideCast(OverrideCastEvent e) { // NO-OP } /** * Handler for the override-cast-confirm event. Similar to * cast-ballot, but no received reply is sent. */ public void overrideCastConfirm(OverrideCastConfirmEvent e) { /*AMachine m = getMachineForSerial(e.getSerial()); if (m != null && m instanceof VoteBoxBooth) { VoteBoxBooth booth = (VoteBoxBooth) m; booth.setPublicCount(booth.getPublicCount() + 1); booth.setProtectedCount(booth.getProtectedCount() + 1); tallier.recordVotes(e.getBallot(), StringExpression.makeString(e.getNonce())); }*/ } public void overrideCastDeny(OverrideCastDenyEvent e) { // NO-OP } /** * Handler for the polls-closed event. Sets the polls to closed. */ public void pollsClosed(PollsClosedEvent e) { setPollsOpen(false); } /** * Handler for the polls-open event. Sets the polls to open, and * gets a fresh tallier. * @throws AuditoriumCryptoException */ public void pollsOpen(PollsOpenEvent e){ if(auditoriumParams.getUseCommitChallengeModel()){ try { if(!auditoriumParams.getEnableNIZKs()){ //Loading privateKey well in advance so the whole affair is "fail-fast" Key privateKey = auditoriumParams.getKeyStore().loadKey("private"); tallier = new ChallengeDelayedTallier(privateKey); }else{ //Loading privateKey well in advance so the whole affair is "fail-fast" PrivateKey privateKey = (PrivateKey)auditoriumParams.getKeyStore().loadAdderKey("private"); PublicKey publicKey = (PublicKey)auditoriumParams.getKeyStore().loadAdderKey("public"); tallier = new ChallengeDelayedWithNIZKsTallier(publicKey, privateKey); }//if } catch (AuditoriumCryptoException e1) { System.err.println("Crypto error encountered: "+e1.getMessage()); e1.printStackTrace(); } }else{ //If Encryption is not enabled, use a vanilla tallier if(!auditoriumParams.getCastBallotEncryptionEnabled()){ if(auditoriumParams.getEnableNIZKs()) throw new RuntimeException("Encryption must be enabled to use NIZKs"); //privateKey = null; tallier = new Tallier(); }else{ //Otherwise, grab the private key and allocate an encrypted tallier try{ if(!auditoriumParams.getEnableNIZKs()){ //Loading privateKey well in advance so the whole affair is "fail-fast" Key privateKey = auditoriumParams.getKeyStore().loadKey("private"); tallier = new EncryptedTallier(privateKey); }else{ //Loading privateKey well in advance so the whole affair is "fail-fast" PrivateKey privateKey = (PrivateKey)auditoriumParams.getKeyStore().loadAdderKey("private"); PublicKey publicKey = (PublicKey)auditoriumParams.getKeyStore().loadAdderKey("public"); tallier = new EncryptedTallierWithNIZKs(publicKey, privateKey); }//if }catch(AuditoriumCryptoException e1){ System.err.println("Crypto error encountered: "+e1.getMessage()); e1.printStackTrace(); }//catch }//if }//if setPollsOpen(true); } /** * Handler for the polls-open? event. Searches the machine's log, * and replies with a last-polls-open message if an appropriate * polls-open message is found. */ public void pollsOpenQ(PollsOpenQEvent e) { if (e.getSerial() != mySerial) { // TODO: Search the log and extract an appropriate polls-open message ASExpression res = null; if (res != null && res != NoMatch.SINGLETON) { VoteBoxEventMatcher matcher = new VoteBoxEventMatcher( PollsOpenEvent.getMatcher()); PollsOpenEvent event = (PollsOpenEvent) matcher.match( 0, res); if (event != null && event.getKeyword().equals(e.getKeyword())) auditorium.announce(new LastPollsOpenEvent( mySerial, event)); } } } /** * Handler for a ballotscanner (status) event. Adds the machine if it * hasn't been seen, and updates its status if it has. */ public void ballotscanner(BallotScannerEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null && !(m instanceof BallotScannerMachine)) throw new IllegalStateException( "Machine " + e.getSerial() + " is not a ballotscanner, but broadcasted ballotscanner message"); if (m == null) { m = new BallotScannerMachine(e.getSerial()); System.out.println("Ballot Scanner Added: " + m); machines.add(m); machinesChangedObs.notifyObservers(); } BallotScannerMachine bsm = (BallotScannerMachine) m; if(e.getStatus().equals("active")) { bsm.setStatus(BallotScannerMachine.ACTIVE); } else if (e.getStatus().equals("inactive")) bsm.setStatus(BallotScannerMachine.INACTIVE); else throw new IllegalStateException("Invalid BallotScanner Status: " + e.getStatus()); bsm.setBattery(e.getBattery()); bsm.setProtectedCount(e.getProtectedCount()); bsm.setPublicCount(e.getPublicCount()); bsm.setOnline(true); //Check to see if this votebox has a conflicting label if (e.getLabel() > 0){ for(AMachine machine : machines){ if(machine.getLabel() == e.getLabel() && machine != m){ //If there is a conflict, relabel this (the event generator) machine. int maxlabel = 0; for(AMachine ma : machines){ if(ma instanceof BallotScannerMachine) maxlabel = Math.max(maxlabel, ma.getLabel()); }//for auditorium.announce(new AssignLabelEvent(mySerial, e.getSerial(), maxlabel + 1)); return; } } }//if if (e.getLabel() > 0) bsm.setLabel(e.getLabel()); else { if (activated) { if (bsm.getLabel() > 0) { auditorium.announce(new AssignLabelEvent(mySerial, e.getSerial(), bsm.getLabel())); } else { int maxlabel = 0; for (AMachine ma : machines) { if (ma instanceof BallotScannerMachine && ma.getLabel() > maxlabel) { maxlabel = ma.getLabel(); } } auditorium.announce(new AssignLabelEvent(mySerial, e .getSerial(), maxlabel + 1)); } auditorium.announce(new PollStatusEvent(mySerial, e.getSerial(), pollsOpen ? 1:0 )); } } } /** * Handler for a supervisor (status) event. Adds the machine if it * hasn't been seen, and updates its status if it has. */ public void supervisor(SupervisorEvent e) { auditorium.announce(new PollMachinesEvent(mySerial, new Date().getTime(), keyword)); AMachine m = getMachineForSerial(e.getSerial()); if (m != null && !(m instanceof SupervisorMachine)) throw new IllegalStateException( "Machine " + e.getSerial() + " is not a supervisor, but broadcasted supervisor message"); if (m == null) { m = new SupervisorMachine(e.getSerial(), e.getSerial() == mySerial); machines.add(m); machinesChangedObs.notifyObservers(); } SupervisorMachine sup = (SupervisorMachine) m; if (e.getStatus().equals("active")) { sup.setStatus(SupervisorMachine.ACTIVE); if (e.getSerial() != mySerial) setActivated(false); } else if (e.getStatus().equals("inactive")) sup.setStatus(SupervisorMachine.INACTIVE); else throw new IllegalStateException( "Invalid Supervisor Status: " + e.getStatus()); sup.setOnline(true); } /** * Handler for a votebox (status) event. Adds the machine if it * hasn't been seen, or updates the status if it has. Also, if the * booth is unlabeled and this is the active supervisor, labels the * booth with its previous label if known, or the next available * number. */ public void votebox(VoteBoxEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null && !(m instanceof VoteBoxBooth)) throw new IllegalStateException( "Machine " + e.getSerial() + " is not a booth, but broadcasted votebox message"); if (m == null) { m = new VoteBoxBooth(e.getSerial()); System.out.println("Vote Box Added: " + m); machines.add(m); machinesChangedObs.notifyObservers(); } VoteBoxBooth booth = (VoteBoxBooth) m; if (e.getStatus().equals("ready")) booth.setStatus(VoteBoxBooth.READY); else if (e.getStatus().equals("in-use")) booth.setStatus(VoteBoxBooth.IN_USE); else if (e.getStatus().equals("provisional-in-use")) booth.setStatus(VoteBoxBooth.PROVISIONAL); else throw new IllegalStateException("Invalid VoteBox Status: " + e.getStatus()); booth.setBattery(e.getBattery()); booth.setProtectedCount(e.getProtectedCount()); booth.setPublicCount(e.getPublicCount()); booth.setOnline(true); //Check to see if this votebox has a conflicting label if (e.getLabel() > 0){ for(AMachine machine : machines){ if(machine.getLabel() == e.getLabel() && machine != m){ //If there is a conflict, relabel this (the event generator) machine. int maxlabel = 0; for(AMachine ma : machines){ if(ma instanceof VoteBoxBooth) maxlabel = Math.max(maxlabel, ma.getLabel()); }//for auditorium.announce(new AssignLabelEvent(mySerial, e.getSerial(), maxlabel + 1)); return; } } }//if if (e.getLabel() > 0) booth.setLabel(e.getLabel()); else { if (activated) { if (booth.getLabel() > 0) auditorium.announce(new AssignLabelEvent(mySerial, e .getSerial(), booth.getLabel())); else { int maxlabel = 0; for (AMachine ma : machines) { if (ma instanceof VoteBoxBooth && ma.getLabel() > maxlabel) maxlabel = ma.getLabel(); } auditorium.announce(new AssignLabelEvent(mySerial, e .getSerial(), maxlabel + 1)); } auditorium.announce(new PollStatusEvent(mySerial, e.getSerial(), pollsOpen ? 1:0 )); } } } /** * Indicate to the tallier that the vote in question is being challenged, * and as such should be excluded from the final tally. */ public void challengeResponse(ChallengeResponseEvent e) { //NO-OP } /** * Indicate to the tallier that the vote in question is being challenged, * and as such should be excluded from the final tally. */ public void challenge(ChallengeEvent e) { System.out.println("Received challenge: "+e); tallier.challenged(e.getNonce()); auditorium.announce(new ChallengeResponseEvent(mySerial, e.getSerial(), e.getNonce())); } /** * Record the vote received in the commit event. * It should not yet be tallied. */ public void commitBallot(CommitBallotEvent e) { //System.err.println("Ballot committed! BID: " + e.getBID()); AMachine m = getMachineForSerial(e.getSerial()); if (m != null && m instanceof VoteBoxBooth) { VoteBoxBooth booth = (VoteBoxBooth) m; booth.setPublicCount(booth.getPublicCount() + 1); booth.setProtectedCount(booth.getProtectedCount() + 1); BallotStore.addBallot(e.getBID().toString(), e.getBallot()); auditorium.announce(new BallotReceivedEvent(mySerial, e .getSerial(), ((StringExpression) e.getNonce()) .getBytes())); tallier.recordVotes(e.getBallot().toVerbatim(), e.getNonce()); String bid = e.getBID().toString(); committedBids.put(bid, e.getNonce()); } } public void provisionalCommitBallot(ProvisionalCommitEvent e) { AMachine m = getMachineForSerial(e.getSerial()); if (m != null && m instanceof VoteBoxBooth) { VoteBoxBooth booth = (VoteBoxBooth) m; booth.setPublicCount(booth.getPublicCount() + 1); booth.setProtectedCount(booth.getProtectedCount() + 1); auditorium.announce(new BallotReceivedEvent(mySerial, e .getSerial(), ((StringExpression) e.getNonce()) .getBytes())); } } public void ballotScanned(BallotScannedEvent e) { String bid = e.getBID(); int serial = e.getSerial(); if (committedBids.containsKey(bid)){ //ASExpression nonce = committedBids.get(bid); ASExpression nonce = committedBids.remove(bid); BallotStore.castCommittedBallot(e.getBID()); // used to be in voteBox registerForCommit listener. auditorium.announce(new CastCommittedBallotEvent(serial, nonce, StringExpression.makeString(e.getBID()))); // that should trigger my own castBallot listener. System.out.println("Sending scan confirmation!"); System.out.println("BID: " + bid); auditorium.announce(new BallotScanAcceptedEvent(mySerial, bid)); } else { System.out.println("Sending scan rejection!"); System.out.println("BID: " + bid); auditorium.announce(new BallotScanRejectedEvent(mySerial, bid)); } } public void pinEntered(PINEnteredEvent e){ if(isPollsOpen()) { System.out.println(">>> PIN entered: " + e.getPin()); String ballot = bManager.getBallotByPin(e.getPin()); System.out.println(ballot); if(ballot!=null){ try { System.out.println(bManager.getPrecinctByBallot(ballot)); setBallotLocation(ballot); if(bManager.getPrecinctByBallot(ballot).contains("provisional")) { provisionalAuthorize(e.getSerial()); System.out.println(">>>>>>> It's working!"); } else authorize(e.getSerial()); } catch(IOException ex) { System.out.println(ex.getMessage()); } } else { auditorium.announce(new InvalidPinEvent(mySerial, e.getNonce())); } } } public void invalidPin(InvalidPinEvent e) {} public void pollStatus(PollStatusEvent pollStatusEvent) { pollsOpen = pollStatusEvent.getPollStatus()==1; sendStartScannerEvent(); } public void ballotAccepted(BallotScanAcceptedEvent e){ //NO-OP } public void ballotRejected(BallotScanRejectedEvent e){ //NO-OP } public void ballotPrinting(BallotPrintingEvent e) { //NO-OP } public void ballotPrintSuccess(BallotPrintSuccessEvent e) { expectedBallots.add(Integer.valueOf(e.getBID())); } public void ballotPrintFail(BallotPrintFailEvent e) { //NO-OP } public void uploadCastBallots(CastBallotUploadEvent e) { // NO-OP } public void uploadChallengedBallots(ChallengedBallotUploadEvent e) { // NO-OP } public void scannerstart(StartScannerEvent e) { // NO-OP for (AMachine machine:machines) { if (machine instanceof BallotScannerMachine) { machine.setStatus(BallotScannerMachine.ACTIVE); } } } public void pollMachines(PollMachinesEvent e) { // NO-OP } public void spoilBallot(SpoilBallotEvent e) { // NO-OP } public void announceProvisionalBallot(ProvisionalBallotEvent e) { // NO-OP } /** * Handler for the provisional-authorize message. Sets the nonce for * that machine. */ public void provisionalAuthorizedToCast(ProvisionalAuthorizeEvent e) { AMachine m = getMachineForSerial(e.getNode()); if (m != null && m instanceof VoteBoxBooth) { ((VoteBoxBooth) m).setNonce(e.getNonce()); } } }); try { auditorium.connect(); auditorium.announce(getStatus()); } catch (NetworkException e1) { //NetworkException represents a recoverable error // so just note it and continue System.out.println("Recoverable error occurred: "+e1.getMessage()); e1.printStackTrace(System.err); } statusTimer.start(); }
diff --git a/GradeBook/src/GradeBook/GradeBook.java b/GradeBook/src/GradeBook/GradeBook.java index 044314e..499d7ca 100644 --- a/GradeBook/src/GradeBook/GradeBook.java +++ b/GradeBook/src/GradeBook/GradeBook.java @@ -1,59 +1,59 @@ package GradeBook; import java.util.Scanner; /** * @author Dan Haag * */ public class GradeBook { private String courseName; public GradeBook( String name ) { courseName = name; } public void setCourseName( String name ) { courseName = name; } public String getCourseName() { return courseName; } public void displayMessage() { System.out.printf( "Welcome to the grade book for %s!\n", getCourseName() ); } public void determineClassAverage() { Scanner input = new Scanner( System.in ); int total; int gradeCounter; int grade; int average; total = 0; gradeCounter = 1; while ( gradeCounter <= 10 ) { System.out.print( "enter grade: " ); grade = input.nextInt(); total = total + grade; gradeCounter = gradeCounter + 1; } average = total/10; System.out.printf( "\nTotal of all 10 grades is %d\n", total ); - System.out.printf( "Class average is %d\n", average ); + System.out.printf( "Class average is %d\n", average ); input.close(); } }
true
true
public void determineClassAverage() { Scanner input = new Scanner( System.in ); int total; int gradeCounter; int grade; int average; total = 0; gradeCounter = 1; while ( gradeCounter <= 10 ) { System.out.print( "enter grade: " ); grade = input.nextInt(); total = total + grade; gradeCounter = gradeCounter + 1; } average = total/10; System.out.printf( "\nTotal of all 10 grades is %d\n", total ); System.out.printf( "Class average is %d\n", average ); input.close(); }
public void determineClassAverage() { Scanner input = new Scanner( System.in ); int total; int gradeCounter; int grade; int average; total = 0; gradeCounter = 1; while ( gradeCounter <= 10 ) { System.out.print( "enter grade: " ); grade = input.nextInt(); total = total + grade; gradeCounter = gradeCounter + 1; } average = total/10; System.out.printf( "\nTotal of all 10 grades is %d\n", total ); System.out.printf( "Class average is %d\n", average ); input.close(); }
diff --git a/BTransitHelper/src/org/mad/bus/Bus_AroundMe.java b/BTransitHelper/src/org/mad/bus/Bus_AroundMe.java index 6c0d7ef..5b1aa77 100644 --- a/BTransitHelper/src/org/mad/bus/Bus_AroundMe.java +++ b/BTransitHelper/src/org/mad/bus/Bus_AroundMe.java @@ -1,199 +1,199 @@ package org.mad.bus; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.graphics.drawable.Drawable; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.Toast; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockMapActivity; import com.actionbarsherlock.view.MenuItem; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.Overlay; import com.google.android.maps.OverlayItem; public class Bus_AroundMe extends SherlockMapActivity { private MapView mapView; private List<Overlay> mapOverlays; private Drawable drawable; private Bus_StopOverlay itemizedOverlay; private MapController mc; private LocationManager lm; private MyLocationListener ll; private static final int centerLat = (int) (37.2277 * 1E6); private static final int centerLng = (int) (-80.422037 * 1E6); boolean gps_enabled = false; boolean network_enabled = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.maps); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayUseLogoEnabled(true); actionBar.setLogo(R.drawable.ic_launcher); actionBar.setDisplayShowHomeEnabled(true); actionBar.setTitle("Around Me"); lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); try { gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch (Exception ex) { Toast.makeText( this, "GPS Provider not available.", Toast.LENGTH_SHORT).show(); } try { network_enabled = lm .isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (Exception ex) { Toast.makeText( this, "Network Provider not available.", Toast.LENGTH_SHORT).show(); } if (gps_enabled == true || network_enabled == true) refreshMap(); else Toast.makeText( this, "GPS or Network Provider not available.", Toast.LENGTH_SHORT).show(); } protected void refreshMap() { mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); mc = mapView.getController(); GeoPoint mapCenter = new GeoPoint(centerLat, centerLng); mc.setCenter(mapCenter); mapOverlays = mapView.getOverlays(); mapView.getOverlays().clear(); drawable = this.getResources().getDrawable(R.drawable.stop); itemizedOverlay = new Bus_StopOverlay(drawable, this, true); // //Standard view of the map(map/sat) // mapView.setSatellite(false); // //get controller of the map for zooming in/out mc = mapView.getController(); // // Zoom Level mc.setZoom(7); // MyLocationOverlay myLocationOverlay = new MyLocationOverlay(this, mapView); myLocationOverlay.enableMyLocation(); mapView.getOverlays().add(myLocationOverlay); List<Overlay> overlayList = mapView.getOverlays(); overlayList.add(myLocationOverlay); ll = new MyLocationListener(); GeoPoint initGeoPoint = null; if (network_enabled) { lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll); initGeoPoint = new GeoPoint( (int) (lm.getLastKnownLocation( LocationManager.NETWORK_PROVIDER).getLatitude() * 1000000), (int) (lm.getLastKnownLocation( LocationManager.NETWORK_PROVIDER).getLongitude() * 1000000)); } else if (gps_enabled) { lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); initGeoPoint = new GeoPoint( (int) (lm .getLastKnownLocation(LocationManager.GPS_PROVIDER) .getLatitude() * 1000000), (int) (lm .getLastKnownLocation( - LocationManager.NETWORK_PROVIDER) + LocationManager.GPS_PROVIDER) .getLongitude() * 1000000)); } /* * 37.2552,-80.484518 37.253287,-80.343069 37.114884,-80.466322 * 37.1168,-80.370878 */ // initGeoPoint = new GeoPoint(37227582, -80422165); if (initGeoPoint.getLatitudeE6() < 37255200 && initGeoPoint.getLatitudeE6() > 37114884 && initGeoPoint.getLongitudeE6() > -80484518 && initGeoPoint.getLongitudeE6() < -80370878) { mc.setZoom(18); @SuppressWarnings({ "rawtypes", "unchecked" }) ArrayList<Bus_Record> list = new ArrayList( Bus_Constants.DB.get(initGeoPoint.getLatitudeE6(), initGeoPoint.getLongitudeE6(), 4000)); for (Bus_Record rec : list) { GeoPoint point = new GeoPoint(rec.getX(), rec.getY()); OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!"); itemizedOverlay.addOverlay(overlayitem); mapOverlays.add(itemizedOverlay); } } else { Toast.makeText(this, "There are no bus stops close to you!", Toast.LENGTH_SHORT).show(); } // Get the current location in start-up mc.animateTo(initGeoPoint); // mapView.invalidate(); } @Override protected boolean isRouteDisplayed() { return false; } private class MyLocationListener implements LocationListener { public void onLocationChanged(Location argLocation) { // TODO Auto-generated method stub @SuppressWarnings("unused") GeoPoint myGeoPoint = new GeoPoint( (int) (argLocation.getLatitude() * 1000000), (int) (argLocation.getLongitude() * 1000000)); /* * it will show a message on location change * Toast.makeText(getBaseContext(), "New location latitude [" * +argLocation.getLatitude() + "] longitude [" + * argLocation.getLongitude()+"]", Toast.LENGTH_SHORT).show(); */ // mc.animateTo(myGeoPoint); // refreshMap(); } public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } } /** * Handles the clicking of action bar icons. */ public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return false; } }
true
true
protected void refreshMap() { mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); mc = mapView.getController(); GeoPoint mapCenter = new GeoPoint(centerLat, centerLng); mc.setCenter(mapCenter); mapOverlays = mapView.getOverlays(); mapView.getOverlays().clear(); drawable = this.getResources().getDrawable(R.drawable.stop); itemizedOverlay = new Bus_StopOverlay(drawable, this, true); // //Standard view of the map(map/sat) // mapView.setSatellite(false); // //get controller of the map for zooming in/out mc = mapView.getController(); // // Zoom Level mc.setZoom(7); // MyLocationOverlay myLocationOverlay = new MyLocationOverlay(this, mapView); myLocationOverlay.enableMyLocation(); mapView.getOverlays().add(myLocationOverlay); List<Overlay> overlayList = mapView.getOverlays(); overlayList.add(myLocationOverlay); ll = new MyLocationListener(); GeoPoint initGeoPoint = null; if (network_enabled) { lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll); initGeoPoint = new GeoPoint( (int) (lm.getLastKnownLocation( LocationManager.NETWORK_PROVIDER).getLatitude() * 1000000), (int) (lm.getLastKnownLocation( LocationManager.NETWORK_PROVIDER).getLongitude() * 1000000)); } else if (gps_enabled) { lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); initGeoPoint = new GeoPoint( (int) (lm .getLastKnownLocation(LocationManager.GPS_PROVIDER) .getLatitude() * 1000000), (int) (lm .getLastKnownLocation( LocationManager.NETWORK_PROVIDER) .getLongitude() * 1000000)); } /* * 37.2552,-80.484518 37.253287,-80.343069 37.114884,-80.466322 * 37.1168,-80.370878 */ // initGeoPoint = new GeoPoint(37227582, -80422165); if (initGeoPoint.getLatitudeE6() < 37255200 && initGeoPoint.getLatitudeE6() > 37114884 && initGeoPoint.getLongitudeE6() > -80484518 && initGeoPoint.getLongitudeE6() < -80370878) { mc.setZoom(18); @SuppressWarnings({ "rawtypes", "unchecked" }) ArrayList<Bus_Record> list = new ArrayList( Bus_Constants.DB.get(initGeoPoint.getLatitudeE6(), initGeoPoint.getLongitudeE6(), 4000)); for (Bus_Record rec : list) { GeoPoint point = new GeoPoint(rec.getX(), rec.getY()); OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!"); itemizedOverlay.addOverlay(overlayitem); mapOverlays.add(itemizedOverlay); } } else { Toast.makeText(this, "There are no bus stops close to you!", Toast.LENGTH_SHORT).show(); } // Get the current location in start-up mc.animateTo(initGeoPoint); // mapView.invalidate(); }
protected void refreshMap() { mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); mc = mapView.getController(); GeoPoint mapCenter = new GeoPoint(centerLat, centerLng); mc.setCenter(mapCenter); mapOverlays = mapView.getOverlays(); mapView.getOverlays().clear(); drawable = this.getResources().getDrawable(R.drawable.stop); itemizedOverlay = new Bus_StopOverlay(drawable, this, true); // //Standard view of the map(map/sat) // mapView.setSatellite(false); // //get controller of the map for zooming in/out mc = mapView.getController(); // // Zoom Level mc.setZoom(7); // MyLocationOverlay myLocationOverlay = new MyLocationOverlay(this, mapView); myLocationOverlay.enableMyLocation(); mapView.getOverlays().add(myLocationOverlay); List<Overlay> overlayList = mapView.getOverlays(); overlayList.add(myLocationOverlay); ll = new MyLocationListener(); GeoPoint initGeoPoint = null; if (network_enabled) { lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll); initGeoPoint = new GeoPoint( (int) (lm.getLastKnownLocation( LocationManager.NETWORK_PROVIDER).getLatitude() * 1000000), (int) (lm.getLastKnownLocation( LocationManager.NETWORK_PROVIDER).getLongitude() * 1000000)); } else if (gps_enabled) { lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); initGeoPoint = new GeoPoint( (int) (lm .getLastKnownLocation(LocationManager.GPS_PROVIDER) .getLatitude() * 1000000), (int) (lm .getLastKnownLocation( LocationManager.GPS_PROVIDER) .getLongitude() * 1000000)); } /* * 37.2552,-80.484518 37.253287,-80.343069 37.114884,-80.466322 * 37.1168,-80.370878 */ // initGeoPoint = new GeoPoint(37227582, -80422165); if (initGeoPoint.getLatitudeE6() < 37255200 && initGeoPoint.getLatitudeE6() > 37114884 && initGeoPoint.getLongitudeE6() > -80484518 && initGeoPoint.getLongitudeE6() < -80370878) { mc.setZoom(18); @SuppressWarnings({ "rawtypes", "unchecked" }) ArrayList<Bus_Record> list = new ArrayList( Bus_Constants.DB.get(initGeoPoint.getLatitudeE6(), initGeoPoint.getLongitudeE6(), 4000)); for (Bus_Record rec : list) { GeoPoint point = new GeoPoint(rec.getX(), rec.getY()); OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!"); itemizedOverlay.addOverlay(overlayitem); mapOverlays.add(itemizedOverlay); } } else { Toast.makeText(this, "There are no bus stops close to you!", Toast.LENGTH_SHORT).show(); } // Get the current location in start-up mc.animateTo(initGeoPoint); // mapView.invalidate(); }
diff --git a/src/main/java/com/ba/languagechecker/App.java b/src/main/java/com/ba/languagechecker/App.java index 37a1634..868386a 100644 --- a/src/main/java/com/ba/languagechecker/App.java +++ b/src/main/java/com/ba/languagechecker/App.java @@ -1,52 +1,53 @@ package com.ba.languagechecker; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.log4j.Logger; import com.ba.languagechecker.pagechecker.output.CVSCrawlerOutputStream; import com.ba.languagechecker.pagechecker.output.ICrawlerOutputStream; import com.ba.languagechecker.properties.CrawlerProperties; import com.ba.languagechecker.properties.TaskProperties; public class App { private static final String RESULT_FOLDER = "results/"; private final static String TASK_PROPERTIES_FILE_NAME = "task.properties"; private final static String CRAWLER_PROPERTIES_FILE_NAME = "crawler.properties"; private static Logger _log = Logger.getLogger(App.class.getCanonicalName()); public static void main(String[] args) throws FileNotFoundException, IOException { try (final FileInputStream crawlerPropertiesFileStream = new FileInputStream( CRAWLER_PROPERTIES_FILE_NAME)) { final CrawlerProperties crawlerProperties = new CrawlerProperties(); crawlerProperties.load(crawlerPropertiesFileStream); final String taskPropertiesFileName = (args.length > 0) ? args[0] : TASK_PROPERTIES_FILE_NAME; - try (final FileInputStream faskPropertiesFileStream = new FileInputStream( + try (final FileInputStream taskPropertiesFileStream = new FileInputStream( taskPropertiesFileName)) { final TaskProperties taskProperties = new TaskProperties(); + taskProperties.load(taskPropertiesFileStream); try (final OutputStream os = new FileOutputStream(RESULT_FOLDER + taskProperties.getOutputFileName())) { try (final ICrawlerOutputStream crawlerOutputStream = new CVSCrawlerOutputStream( os)) { LanguageCheckerCrawlerRunner languageCheckerCrawlerRunner = new LanguageCheckerCrawlerRunner( taskProperties, crawlerProperties, crawlerOutputStream); languageCheckerCrawlerRunner.run(); } } } catch (Exception e) { _log.error(e, e); } } catch (Exception e1) { _log.error(e1, e1); } } }
false
true
public static void main(String[] args) throws FileNotFoundException, IOException { try (final FileInputStream crawlerPropertiesFileStream = new FileInputStream( CRAWLER_PROPERTIES_FILE_NAME)) { final CrawlerProperties crawlerProperties = new CrawlerProperties(); crawlerProperties.load(crawlerPropertiesFileStream); final String taskPropertiesFileName = (args.length > 0) ? args[0] : TASK_PROPERTIES_FILE_NAME; try (final FileInputStream faskPropertiesFileStream = new FileInputStream( taskPropertiesFileName)) { final TaskProperties taskProperties = new TaskProperties(); try (final OutputStream os = new FileOutputStream(RESULT_FOLDER + taskProperties.getOutputFileName())) { try (final ICrawlerOutputStream crawlerOutputStream = new CVSCrawlerOutputStream( os)) { LanguageCheckerCrawlerRunner languageCheckerCrawlerRunner = new LanguageCheckerCrawlerRunner( taskProperties, crawlerProperties, crawlerOutputStream); languageCheckerCrawlerRunner.run(); } } } catch (Exception e) { _log.error(e, e); } } catch (Exception e1) { _log.error(e1, e1); } }
public static void main(String[] args) throws FileNotFoundException, IOException { try (final FileInputStream crawlerPropertiesFileStream = new FileInputStream( CRAWLER_PROPERTIES_FILE_NAME)) { final CrawlerProperties crawlerProperties = new CrawlerProperties(); crawlerProperties.load(crawlerPropertiesFileStream); final String taskPropertiesFileName = (args.length > 0) ? args[0] : TASK_PROPERTIES_FILE_NAME; try (final FileInputStream taskPropertiesFileStream = new FileInputStream( taskPropertiesFileName)) { final TaskProperties taskProperties = new TaskProperties(); taskProperties.load(taskPropertiesFileStream); try (final OutputStream os = new FileOutputStream(RESULT_FOLDER + taskProperties.getOutputFileName())) { try (final ICrawlerOutputStream crawlerOutputStream = new CVSCrawlerOutputStream( os)) { LanguageCheckerCrawlerRunner languageCheckerCrawlerRunner = new LanguageCheckerCrawlerRunner( taskProperties, crawlerProperties, crawlerOutputStream); languageCheckerCrawlerRunner.run(); } } } catch (Exception e) { _log.error(e, e); } } catch (Exception e1) { _log.error(e1, e1); } }
diff --git a/src/java/org/codehaus/groovy/grails/web/converters/marshaller/json/MapMarshaller.java b/src/java/org/codehaus/groovy/grails/web/converters/marshaller/json/MapMarshaller.java index 266baab50..1984ef137 100644 --- a/src/java/org/codehaus/groovy/grails/web/converters/marshaller/json/MapMarshaller.java +++ b/src/java/org/codehaus/groovy/grails/web/converters/marshaller/json/MapMarshaller.java @@ -1,48 +1,49 @@ /* * Copyright 2004-2008 the original author or authors. * * 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.codehaus.groovy.grails.web.converters.marshaller.json; import grails.converters.JSON; import org.codehaus.groovy.grails.web.converters.exceptions.ConverterException; import org.codehaus.groovy.grails.web.converters.marshaller.ObjectMarshaller; import org.codehaus.groovy.grails.web.json.JSONWriter; import java.util.Map; /** * @author Siegfried Puchbauer * @since 1.1 */ public class MapMarshaller implements ObjectMarshaller<JSON> { public boolean supports(Object object) { return object instanceof Map; } @SuppressWarnings("unchecked") public void marshalObject(Object o, JSON converter) throws ConverterException { JSONWriter writer = converter.getWriter(); writer.object(); Map<Object,Object> map = (Map<Object,Object>) o; for (Map.Entry<Object,Object> entry : map.entrySet()) { Object key = entry.getKey(); if(key != null) { + writer.key(key.toString()); converter.convertAnother(entry.getValue()); } } writer.endObject(); } }
true
true
public void marshalObject(Object o, JSON converter) throws ConverterException { JSONWriter writer = converter.getWriter(); writer.object(); Map<Object,Object> map = (Map<Object,Object>) o; for (Map.Entry<Object,Object> entry : map.entrySet()) { Object key = entry.getKey(); if(key != null) { converter.convertAnother(entry.getValue()); } } writer.endObject(); }
public void marshalObject(Object o, JSON converter) throws ConverterException { JSONWriter writer = converter.getWriter(); writer.object(); Map<Object,Object> map = (Map<Object,Object>) o; for (Map.Entry<Object,Object> entry : map.entrySet()) { Object key = entry.getKey(); if(key != null) { writer.key(key.toString()); converter.convertAnother(entry.getValue()); } } writer.endObject(); }
diff --git a/src/com/randrdevelopment/propertygroup/command/commands/CreatePropertyCommand.java b/src/com/randrdevelopment/propertygroup/command/commands/CreatePropertyCommand.java index 90fa9c8..af04544 100644 --- a/src/com/randrdevelopment/propertygroup/command/commands/CreatePropertyCommand.java +++ b/src/com/randrdevelopment/propertygroup/command/commands/CreatePropertyCommand.java @@ -1,97 +1,97 @@ package com.randrdevelopment.propertygroup.command.commands; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import com.randrdevelopment.propertygroup.command.BaseCommand; import com.randrdevelopment.propertygroup.PropertyGroup; import com.randrdevelopment.propertygroup.regions.RegionTools; import com.randrdevelopment.propertygroup.regions.SchematicTools; public class CreatePropertyCommand extends BaseCommand{ FileConfiguration propertyConfig; public CreatePropertyCommand(PropertyGroup plugin) { super(plugin); name = "CreateProperty"; description = "Creates a Property Manually."; usage = "/property createproperty <groupname> [user]"; minArgs = 1; maxArgs = 2; identifiers.add("property createproperty"); } @Override public void execute(CommandSender sender, String[] args) { propertyConfig = plugin.getPropertyConfig(); String propertyGroup = args[0].toLowerCase(); // Validate permissions level if (!sender.hasPermission("propertygroup.create")) { sender.sendMessage(plugin.getTag() + ChatColor.RED + "You do not have permission to use this command"); return; } // Verify Property Group Exists if (propertyConfig.getConfigurationSection(propertyGroup) == null) { sender.sendMessage(plugin.getTag()+ChatColor.RED+"Property Group '"+propertyGroup+"' does not exist."); return; } // Lets get the row and column of the next free property.. int Rows = propertyConfig.getInt(propertyGroup+".rows"); int Cols = propertyConfig.getInt(propertyGroup+".cols"); int qty = Rows * Cols; boolean noproperties = true; for(int i=1; i<=qty; i++){ if (propertyConfig.getBoolean(propertyGroup+".properties."+i+".created") == false){ noproperties = false; // Found an empty spot.. int x = propertyConfig.getInt(propertyGroup+".startlocation.x"); int y = propertyConfig.getInt(propertyGroup+".startlocation.y"); int z = propertyConfig.getInt(propertyGroup+".startlocation.z"); String worldname = propertyConfig.getString(propertyGroup+".startlocation.world"); int width = propertyConfig.getInt(propertyGroup+".width"); int length = propertyConfig.getInt(propertyGroup+".length"); int height = propertyConfig.getInt(propertyGroup+".height"); int spacing = propertyConfig.getInt(propertyGroup+".propertyspacing"); int row = propertyConfig.getInt(propertyGroup+".properties."+i+".row"); int col = propertyConfig.getInt(propertyGroup+".properties."+i+".col"); // Set Starting Point... x = ((width + spacing) * (row - 1)) + x; z = ((length + spacing) * (col - 1)) + z; int blocks = length * width * height; SchematicTools.reload(propertyGroup, worldname, x, y, z, blocks); // Create Region if configured to do so... if (propertyConfig.getBoolean(propertyGroup+".createregion")) { String playerName = null; - if (args[1].length() == 2) + if (args.length == 2) playerName = args[1]; if (!RegionTools.createProtectedRegion(propertyGroup+"-"+row+"-"+col, worldname, x, x+width-1, 0, 255, z, z+length-1, 10, playerName, propertyConfig, propertyGroup)) sender.sendMessage(plugin.getTag()+ChatColor.RED+"Error creating region..."); } propertyConfig.set(propertyGroup+".properties."+i+".created", true); plugin.savePropertyConfig(); break; } } if (noproperties){ sender.sendMessage(plugin.getTag()+ChatColor.RED+"Property Group '"+propertyGroup+"' is full."); } else { sender.sendMessage(plugin.getTag()+"Property Created"); } } }
true
true
public void execute(CommandSender sender, String[] args) { propertyConfig = plugin.getPropertyConfig(); String propertyGroup = args[0].toLowerCase(); // Validate permissions level if (!sender.hasPermission("propertygroup.create")) { sender.sendMessage(plugin.getTag() + ChatColor.RED + "You do not have permission to use this command"); return; } // Verify Property Group Exists if (propertyConfig.getConfigurationSection(propertyGroup) == null) { sender.sendMessage(plugin.getTag()+ChatColor.RED+"Property Group '"+propertyGroup+"' does not exist."); return; } // Lets get the row and column of the next free property.. int Rows = propertyConfig.getInt(propertyGroup+".rows"); int Cols = propertyConfig.getInt(propertyGroup+".cols"); int qty = Rows * Cols; boolean noproperties = true; for(int i=1; i<=qty; i++){ if (propertyConfig.getBoolean(propertyGroup+".properties."+i+".created") == false){ noproperties = false; // Found an empty spot.. int x = propertyConfig.getInt(propertyGroup+".startlocation.x"); int y = propertyConfig.getInt(propertyGroup+".startlocation.y"); int z = propertyConfig.getInt(propertyGroup+".startlocation.z"); String worldname = propertyConfig.getString(propertyGroup+".startlocation.world"); int width = propertyConfig.getInt(propertyGroup+".width"); int length = propertyConfig.getInt(propertyGroup+".length"); int height = propertyConfig.getInt(propertyGroup+".height"); int spacing = propertyConfig.getInt(propertyGroup+".propertyspacing"); int row = propertyConfig.getInt(propertyGroup+".properties."+i+".row"); int col = propertyConfig.getInt(propertyGroup+".properties."+i+".col"); // Set Starting Point... x = ((width + spacing) * (row - 1)) + x; z = ((length + spacing) * (col - 1)) + z; int blocks = length * width * height; SchematicTools.reload(propertyGroup, worldname, x, y, z, blocks); // Create Region if configured to do so... if (propertyConfig.getBoolean(propertyGroup+".createregion")) { String playerName = null; if (args[1].length() == 2) playerName = args[1]; if (!RegionTools.createProtectedRegion(propertyGroup+"-"+row+"-"+col, worldname, x, x+width-1, 0, 255, z, z+length-1, 10, playerName, propertyConfig, propertyGroup)) sender.sendMessage(plugin.getTag()+ChatColor.RED+"Error creating region..."); } propertyConfig.set(propertyGroup+".properties."+i+".created", true); plugin.savePropertyConfig(); break; } } if (noproperties){ sender.sendMessage(plugin.getTag()+ChatColor.RED+"Property Group '"+propertyGroup+"' is full."); } else { sender.sendMessage(plugin.getTag()+"Property Created"); } }
public void execute(CommandSender sender, String[] args) { propertyConfig = plugin.getPropertyConfig(); String propertyGroup = args[0].toLowerCase(); // Validate permissions level if (!sender.hasPermission("propertygroup.create")) { sender.sendMessage(plugin.getTag() + ChatColor.RED + "You do not have permission to use this command"); return; } // Verify Property Group Exists if (propertyConfig.getConfigurationSection(propertyGroup) == null) { sender.sendMessage(plugin.getTag()+ChatColor.RED+"Property Group '"+propertyGroup+"' does not exist."); return; } // Lets get the row and column of the next free property.. int Rows = propertyConfig.getInt(propertyGroup+".rows"); int Cols = propertyConfig.getInt(propertyGroup+".cols"); int qty = Rows * Cols; boolean noproperties = true; for(int i=1; i<=qty; i++){ if (propertyConfig.getBoolean(propertyGroup+".properties."+i+".created") == false){ noproperties = false; // Found an empty spot.. int x = propertyConfig.getInt(propertyGroup+".startlocation.x"); int y = propertyConfig.getInt(propertyGroup+".startlocation.y"); int z = propertyConfig.getInt(propertyGroup+".startlocation.z"); String worldname = propertyConfig.getString(propertyGroup+".startlocation.world"); int width = propertyConfig.getInt(propertyGroup+".width"); int length = propertyConfig.getInt(propertyGroup+".length"); int height = propertyConfig.getInt(propertyGroup+".height"); int spacing = propertyConfig.getInt(propertyGroup+".propertyspacing"); int row = propertyConfig.getInt(propertyGroup+".properties."+i+".row"); int col = propertyConfig.getInt(propertyGroup+".properties."+i+".col"); // Set Starting Point... x = ((width + spacing) * (row - 1)) + x; z = ((length + spacing) * (col - 1)) + z; int blocks = length * width * height; SchematicTools.reload(propertyGroup, worldname, x, y, z, blocks); // Create Region if configured to do so... if (propertyConfig.getBoolean(propertyGroup+".createregion")) { String playerName = null; if (args.length == 2) playerName = args[1]; if (!RegionTools.createProtectedRegion(propertyGroup+"-"+row+"-"+col, worldname, x, x+width-1, 0, 255, z, z+length-1, 10, playerName, propertyConfig, propertyGroup)) sender.sendMessage(plugin.getTag()+ChatColor.RED+"Error creating region..."); } propertyConfig.set(propertyGroup+".properties."+i+".created", true); plugin.savePropertyConfig(); break; } } if (noproperties){ sender.sendMessage(plugin.getTag()+ChatColor.RED+"Property Group '"+propertyGroup+"' is full."); } else { sender.sendMessage(plugin.getTag()+"Property Created"); } }
diff --git a/src/org/mozilla/javascript/Synchronizer.java b/src/org/mozilla/javascript/Synchronizer.java index cef0fb5c..f2fca522 100644 --- a/src/org/mozilla/javascript/Synchronizer.java +++ b/src/org/mozilla/javascript/Synchronizer.java @@ -1,81 +1,81 @@ /* -*- 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 Delegator.java, released * Sep 27, 2000. * * The Initial Developer of the Original Code is * Matthias Radestock. <[email protected]>. * Portions created by the Initial Developer are Copyright (C) 2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * 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 ***** */ // API class package org.mozilla.javascript; /** * This class provides support for implementing Java-style synchronized * methods in Javascript. * * Synchronized functions are created from ordinary Javascript * functions by the <code>Synchronizer</code> constructor, e.g. * <code>new Packages.org.mozilla.javascript.Synchronizer(fun)</code>. * The resulting object is a function that establishes an exclusive * lock on the <code>this</code> object of its invocation. * * The Rhino shell provides a short-cut for the creation of * synchronized methods: <code>sync(fun)</code> has the same effect as * calling the above constructor. * * @see org.mozilla.javascript.Delegator * @author Matthias Radestock */ public class Synchronizer extends Delegator { /** * Create a new synchronized function from an existing one. * * @param obj the existing function */ public Synchronizer(Scriptable obj) { super(obj); } /** * @see org.mozilla.javascript.Function#call */ public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { - synchronized(thisObj) { + synchronized(thisObj instanceof Wrapper ? ((Wrapper)thisObj).unwrap() : thisObj) { return ((Function)obj).call(cx,scope,thisObj,args); } } }
true
true
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { synchronized(thisObj) { return ((Function)obj).call(cx,scope,thisObj,args); } }
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { synchronized(thisObj instanceof Wrapper ? ((Wrapper)thisObj).unwrap() : thisObj) { return ((Function)obj).call(cx,scope,thisObj,args); } }
diff --git a/src/main/java/com/herokuapp/webgalleryshowcase/web/gallery/AlbumController.java b/src/main/java/com/herokuapp/webgalleryshowcase/web/gallery/AlbumController.java index e45e2b0..a589034 100644 --- a/src/main/java/com/herokuapp/webgalleryshowcase/web/gallery/AlbumController.java +++ b/src/main/java/com/herokuapp/webgalleryshowcase/web/gallery/AlbumController.java @@ -1,114 +1,114 @@ package com.herokuapp.webgalleryshowcase.web.gallery; import com.herokuapp.webgalleryshowcase.dao.AlbumDao; import com.herokuapp.webgalleryshowcase.domain.Album; import com.herokuapp.webgalleryshowcase.domain.dto.AlbumResponseDto; import com.herokuapp.webgalleryshowcase.service.validators.AlbumValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.security.Principal; import java.util.List; @Controller public class AlbumController { private final Logger log = LoggerFactory.getLogger(AlbumController.class); @Autowired private AlbumDao albumDao; @InitBinder protected void initBinder(WebDataBinder binder) { binder.setValidator(new AlbumValidator()); } @RequestMapping(value = "/albums", method = RequestMethod.GET, produces = "application/json") public @ResponseBody List<Album> listAlbums(Principal principal) { log.debug("Album list in JSON"); String userEmail = principal.getName(); return albumDao.retrieveUserAlbums(userEmail); } @RequestMapping(value = "/albums", method = RequestMethod.GET) public String showUserAlbums(Model model, Principal principal) { String userOwner = principal.getName(); List<Album> albums = albumDao.retrieveUserAlbums(userOwner); model.addAttribute("albums", albums); model.addAttribute("userOwner", userOwner); return "showUserAlbumList"; } @RequestMapping(value = "/albums/manage", method = RequestMethod.GET) public String manageUserAlbums(Model model, Principal principal) { String userOwner = principal.getName(); List<Album> albums = albumDao.retrieveUserAlbums(userOwner); model.addAttribute("albums", albums); model.addAttribute("userOwner", userOwner); return "manageAlbumList"; } @RequestMapping(value = "/albums/{id}") private String displayAlbum(@PathVariable int id, Model model) { model.addAttribute(albumDao.retrieveAlbum(id)); return "showAlbumPictures"; } @RequestMapping(value = "/albums/{id}", method = RequestMethod.GET, produces = "application/json") public @ResponseBody Album getAlbum(@PathVariable int id) { return albumDao.retrieveAlbum(id); } @RequestMapping(value = "/albums/{id}", method = RequestMethod.DELETE) public ResponseEntity<String> deleteAlbum(@PathVariable int id) { - log.debug("Delete."); + log.debug("Delete album. ID: " + id); ResponseEntity<String> response; if (albumDao.deleteAlbum(id)) { response = new ResponseEntity<>("Album has been deleted successfully.", HttpStatus.OK); } else { response = new ResponseEntity<>(HttpStatus.NO_CONTENT); } return response; } @RequestMapping(value = "/albums/{id}", method = RequestMethod.PUT) public ResponseEntity<AlbumResponseDto> editAlbumE(@RequestBody @Valid Album album, @PathVariable int id) { log.debug("editAlbum method PUT"); album.setId(id); Album updatedAlbum = albumDao.updateAlbum(album); String message = "Album has been edited."; AlbumResponseDto albumResponse = new AlbumResponseDto(message, updatedAlbum); return new ResponseEntity<>(albumResponse, HttpStatus.OK); } @RequestMapping(value = "/albums", method = RequestMethod.POST) public ResponseEntity<AlbumResponseDto> createAlbum(@RequestBody @Valid Album album, Principal principal) { album.setUserOwner(principal.getName()); Album createdAlbum = albumDao.createAlbum(album); String message = "Album has been created successfully."; AlbumResponseDto albumResponse = new AlbumResponseDto(message, createdAlbum); return new ResponseEntity<>(albumResponse, HttpStatus.CREATED); } }
true
true
public ResponseEntity<String> deleteAlbum(@PathVariable int id) { log.debug("Delete."); ResponseEntity<String> response; if (albumDao.deleteAlbum(id)) { response = new ResponseEntity<>("Album has been deleted successfully.", HttpStatus.OK); } else { response = new ResponseEntity<>(HttpStatus.NO_CONTENT); } return response; }
public ResponseEntity<String> deleteAlbum(@PathVariable int id) { log.debug("Delete album. ID: " + id); ResponseEntity<String> response; if (albumDao.deleteAlbum(id)) { response = new ResponseEntity<>("Album has been deleted successfully.", HttpStatus.OK); } else { response = new ResponseEntity<>(HttpStatus.NO_CONTENT); } return response; }
diff --git a/src/cz/vutbr/fit/gja/gjaddr/gui/ContactWindow.java b/src/cz/vutbr/fit/gja/gjaddr/gui/ContactWindow.java index e6dc35f..8c0d2d3 100644 --- a/src/cz/vutbr/fit/gja/gjaddr/gui/ContactWindow.java +++ b/src/cz/vutbr/fit/gja/gjaddr/gui/ContactWindow.java @@ -1,573 +1,582 @@ package cz.vutbr.fit.gja.gjaddr.gui; import cz.vutbr.fit.gja.gjaddr.gui.util.Validators; import cz.vutbr.fit.gja.gjaddr.persistancelayer.*; import cz.vutbr.fit.gja.gjaddr.persistancelayer.util.MessengersEnum; import cz.vutbr.fit.gja.gjaddr.persistancelayer.util.NameDays; import cz.vutbr.fit.gja.gjaddr.persistancelayer.util.TypesEnum; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javax.swing.*; import org.jdesktop.swingx.JXDatePicker; import org.slf4j.LoggerFactory; /** * Contact editing window. * * @author Bc. Jan Kaláb <[email protected],vutbr.cz> * @author Bc. Radek Gajdusek <[email protected],vutbr.cz> * @author Bc. Drahomira Herrmannova <[email protected]> */ class ContactWindow extends JDialog { static final long serialVersionUID = 0; /** * Database instance. */ private final Database db = Database.getInstance(); /** * Currently edited contact. */ private Contact contact; private final JButton button = new JButton(); private final PhotoButton photo = new PhotoButton(); private final JTextField nameField = new JTextField(); private final JTextField surnameField = new JTextField(); private final JTextField nicknameField = new JTextField(); private final JTextField addressField = new JTextField(); private final JTextField workEmailField = new JTextField(); private final JTextField homeEmailField = new JTextField(); private final JTextField otherEmailField = new JTextField(); private final JTextField workUrlField = new JTextField(); private final JTextField homeUrlField = new JTextField(); private final JTextField otherUrlField = new JTextField(); private final JTextField workPhoneField = new JTextField(); private final JTextField homePhoneField = new JTextField(); private final JTextField otherPhoneField = new JTextField(); private final JTextField icqField = new JTextField(); private final JTextField jabberField = new JTextField(); private final JTextField skypeField = new JTextField(); private final JTextArea noteField = new JTextArea(); private final JXDatePicker birthdayPicker = new JXDatePicker(); private final JXDatePicker namedayPicker = new JXDatePicker(); private final JXDatePicker celebrationPicker = new JXDatePicker(); /** * Constructor for adding new contact */ public ContactWindow() { super(); super.setTitle("Add contact"); super.setPreferredSize(new Dimension(480, 480)); super.setModal(true); setIconImage(new ImageIcon(getClass().getResource("/res/plus.png"), "+").getImage()); button.setText("Add contact"); button.addActionListener(new NewContactActionListener()); contact = new Contact(); prepare(); log("Opening new contact window."); } /** * Constructor for editing contact */ public ContactWindow(Contact contact) { super(); super.setTitle("Edit contact"); super.setPreferredSize(new Dimension(480, 480)); super.setModal(true); this.contact = contact; setIconImage(new ImageIcon(getClass().getResource("/res/edit.png"), "Edit").getImage()); photo.setContact(contact); button.setText("Edit contact"); button.addActionListener(new EditContactActionListener()); nameField.setText(contact.getFirstName()); surnameField.setText(contact.getSurName()); nicknameField.setText(contact.getNickName()); addressField.setText(contact.getAllAddresses()); birthdayPicker.setDate(contact.getBirthday() != null ? contact.getBirthday().getDate() : null); namedayPicker.setDate(contact.getNameDay() != null ? contact.getNameDay().getDate() : null); celebrationPicker.setDate(contact.getCelebration() != null ? contact.getCelebration().getDate() : null); noteField.setText(contact.getNote()); for (Url u : contact.getUrls()) { if (u.getValue() != null) { switch (u.getType()) { case WORK: workUrlField.setText(u.getValue().toString()); break; case HOME: homeUrlField.setText(u.getValue().toString()); break; case OTHER: otherUrlField.setText(u.getValue().toString()); break; } } } for (Email e : contact.getEmails()) { switch (e.getType()) { case WORK: workEmailField.setText(e.getEmail()); break; case HOME: homeEmailField.setText(e.getEmail()); break; case OTHER: otherEmailField.setText(e.getEmail()); break; } } for (PhoneNumber p : contact.getPhoneNumbers()) { switch (p.getType()) { case WORK: workPhoneField.setText(p.getNumber()); break; case HOME: homePhoneField.setText(p.getNumber()); break; case OTHER: otherPhoneField.setText(p.getNumber()); break; } } for (Messenger m : contact.getMessenger()) { if (m.getValue() != null) { switch (m.getType()) { case ICQ: icqField.setText(m.getValue()); break; case JABBER: jabberField.setText(m.getValue()); break; case SKYPE: skypeField.setText(m.getValue()); break; } } } prepare(); log("Opening edit contact window."); } /** * Make window escapable. * * @return */ @Override protected JRootPane createRootPane() { JRootPane rp = new JRootPane(); KeyStroke stroke = KeyStroke.getKeyStroke("ESCAPE"); Action actionListener = new AbstractAction() { static final long serialVersionUID = 0; @Override public void actionPerformed(ActionEvent actionEvent) { dispose(); } }; InputMap inputMap = rp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(stroke, "ESCAPE"); rp.getActionMap().put("ESCAPE", actionListener); return rp; } /** * Method for creating window content layout. */ private void prepare() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println(e); } final JPanel form = new JPanel(new GridBagLayout()); form.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); final GridBagConstraints c = new GridBagConstraints(); final JPanel formContact = new JPanel(new GridBagLayout()); formContact.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); final GridBagConstraints cDetails = new GridBagConstraints(); final JPanel formNote = new JPanel(new GridBagLayout()); formNote.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); final GridBagConstraints cNote = new GridBagConstraints(); final JPanel formPhoto = new JPanel(new GridBagLayout()); formPhoto.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); final GridBagConstraints cPhoto = new GridBagConstraints(); // create tabs JTabbedPane tabs = new JTabbedPane(); tabs.addTab("Basic details", form); tabs.addTab("Contact details", formContact); tabs.addTab("Notes", formNote); tabs.addTab("Photo", formPhoto); // basic details c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(1, 1, 1, 1); c.weightx = 0; c.anchor = GridBagConstraints.NORTHWEST; c.gridx = 0; c.gridy = 0; form.add(new JLabel("Name"), c); c.gridx = 1; c.weightx = 1; form.add(nameField, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Surname"), c); c.gridx = 1; c.weightx = 1; form.add(surnameField, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Nickname"), c); c.gridx = 1; c.weightx = 1; form.add(nicknameField, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Address"), c); c.gridx = 1; c.weightx = 1; form.add(addressField, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Birthday"), c); c.gridx = 1; c.weightx = 1; birthdayPicker.setFormats(new String[]{"d. M. yyyy"}); form.add(birthdayPicker, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Nameday"), c); c.gridx = 1; c.weightx = 1; namedayPicker.setFormats(new String[]{"d. M."}); form.add(namedayPicker, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Anniversary"), c); c.gridx = 1; c.weightx = 1; celebrationPicker.setFormats(new String[]{"d. M. yyyy"}); form.add(celebrationPicker, c); c.gridy++; c.weighty = 1.0; form.add(Box.createHorizontalGlue(), c); // contact details cDetails.fill = GridBagConstraints.HORIZONTAL; cDetails.insets = new Insets(1, 1, 1, 1); cDetails.weightx = 0; cDetails.anchor = GridBagConstraints.NORTHWEST; cDetails.gridy = 0; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Work E-mail"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(workEmailField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Home E-mail"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(homeEmailField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Other E-mail"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(otherEmailField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Work URL"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(workUrlField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Home URL"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(homeUrlField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Other URL"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(otherUrlField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Work Phone"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(workPhoneField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Home Phone"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(homePhoneField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Other Phone"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(otherPhoneField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("ICQ"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(icqField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Jabber"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(jabberField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Skype"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(skypeField, cDetails); + cDetails.gridy++; + cDetails.weighty = 1.0; + formContact.add(Box.createHorizontalGlue(), c); // note cNote.fill = GridBagConstraints.HORIZONTAL; cNote.insets = new Insets(1, 1, 1, 1); cNote.weightx = 0; cNote.anchor = GridBagConstraints.NORTHWEST; cNote.gridy = 0; cNote.gridx = 0; cNote.weightx = 0; JLabel nl = new JLabel("Note"); nl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10)); formNote.add(nl, cNote); cNote.gridx = 1; cNote.weightx = 1; noteField.setLineWrap(true); noteField.setWrapStyleWord(true); noteField.setRows(10); noteField.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY)); formNote.add(noteField, cNote); cNote.weighty = 1.0; cNote.gridy++; formNote.add(Box.createHorizontalGlue(), cNote); // photo cPhoto.insets = new Insets(1, 1, 1, 1); cPhoto.weightx = 0; cPhoto.anchor = GridBagConstraints.NORTHWEST; cPhoto.gridy = 0; cPhoto.gridx = 0; cPhoto.weightx = 0; JLabel pl = new JLabel("Photo"); pl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10)); formPhoto.add(pl, cPhoto); cPhoto.gridx = 1; cPhoto.weightx = 1; formPhoto.add(photo, cPhoto); + cPhoto.gridy++; + JButton photoButton = new JButton("Change Photo"); + // FUJ! + ActionListener[] actionListeners = this.photo.getActionListeners(); + photoButton.addActionListener(actionListeners[0]); + formPhoto.add(photoButton); cPhoto.weighty = 1.0; cPhoto.gridy++; formPhoto.add(Box.createHorizontalGlue(), cPhoto); // finish add(tabs, BorderLayout.CENTER); add(button, BorderLayout.PAGE_END); setLocationRelativeTo(null); pack(); setVisible(true); } /** * Resolving contact data from user form input. * * @return true if is all correct, in error case returns false */ private boolean resolvecontact() { boolean valid = this.validateData(); if (valid) { contact.setFirstName(nameField.getText()); contact.setSurName(surnameField.getText()); contact.setNickName(nicknameField.getText()); contact.setBirthday(birthdayPicker.getDate()); if (namedayPicker.getDate() != null) { contact.setNameDay(namedayPicker.getDate()); } else { if (!contact.getFirstName().isEmpty()) { Calendar nameDay = NameDays.getInstance().getNameDay(contact.getFirstName()); if (nameDay != null) { contact.setNameDay(nameDay.getTime()); } } } contact.setCelebration(celebrationPicker.getDate()); contact.setNote(noteField.getText()); contact.setPhoto((ImageIcon) photo.getIcon()); final ArrayList<Address> addresses = new ArrayList<Address>(); addresses.add(new Address(TypesEnum.HOME, addressField.getText())); contact.setAdresses(addresses); final ArrayList<Url> urls = new ArrayList<Url>(); urls.add(new Url(TypesEnum.WORK, workUrlField.getText())); urls.add(new Url(TypesEnum.HOME, homeUrlField.getText())); urls.add(new Url(TypesEnum.OTHER, otherUrlField.getText())); contact.setUrls(urls); final ArrayList<PhoneNumber> phones = new ArrayList<PhoneNumber>(); phones.add(new PhoneNumber(TypesEnum.WORK, workPhoneField.getText())); phones.add(new PhoneNumber(TypesEnum.HOME, homePhoneField.getText())); phones.add(new PhoneNumber(TypesEnum.OTHER, otherPhoneField.getText())); contact.setPhoneNumbers(phones); final ArrayList<Email> emails = new ArrayList<Email>(); emails.add(new Email(TypesEnum.WORK, workEmailField.getText())); emails.add(new Email(TypesEnum.HOME, homeEmailField.getText())); emails.add(new Email(TypesEnum.OTHER, otherEmailField.getText())); contact.setEmails(emails); final ArrayList<Messenger> messengers = new ArrayList<Messenger>(); messengers.add(new Messenger(MessengersEnum.ICQ, icqField.getText())); messengers.add(new Messenger(MessengersEnum.JABBER, jabberField.getText())); messengers.add(new Messenger(MessengersEnum.SKYPE, skypeField.getText())); contact.setMessenger(messengers); } return valid; } /** * Check if is email and url valid, if is not valid, display a message. * * @return true if is validation successfull, otherwise false. */ private boolean validateData() { StringBuilder message = new StringBuilder(); // required entry is one of these - nick, name, surname if (nameField.getText().isEmpty() && surnameField.getText().isEmpty() && nicknameField.getText().isEmpty()) { message.append("Name, Surname or Nickname shouldn't be empty. Please fill at least one item."); } if (!Validators.isEmailValid(workEmailField.getText())) { message.append("Work email address is not valid\r\n"); } if (!Validators.isEmailValid(homeEmailField.getText())) { message.append("Home email address is not valid\r\n"); } if (!Validators.isEmailValid(otherEmailField.getText())) { message.append("Other email address is not valid\r\n"); } if (!Validators.isUrlValid(workUrlField.getText())) { message.append("Work URL is not valid\r\n"); } if (!Validators.isUrlValid(homeUrlField.getText())) { message.append("Home URL is not valid\r\n"); } if (!Validators.isUrlValid(otherUrlField.getText())) { message.append("Other URL is not valid\r\n"); } if (!Validators.isPhoneNumberValid(workPhoneField.getText())) { message.append("Work phone is not valid\r\n"); } if (!Validators.isPhoneNumberValid(homePhoneField.getText())) { message.append("Home phone is not valid\r\n"); } if (!Validators.isPhoneNumberValid(otherPhoneField.getText())) { message.append("Other phone is not valid\r\n"); } if (!Validators.isPhoneNumberValid(otherPhoneField.getText())) { message.append("Other phone is not valid\r\n"); } if (!Validators.isIcqValid(icqField.getText())) { message.append("Icq number is not valid\r\n"); } if (!Validators.isJabberValid(jabberField.getText())) { message.append("Jabber acount is not valid\r\n"); } if (!Validators.isSkypeValid(skypeField.getText())) { message.append("Skype acount is not valid\r\n"); } // display message if is there same error if (message.length() > 0) { JOptionPane.showMessageDialog(this, message, "Validation failed!", JOptionPane.WARNING_MESSAGE); } return message.length() == 0; } /** * Submiting new contact action */ private class NewContactActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if (resolvecontact()) { List<Contact> newContacts = new ArrayList<Contact>(); newContacts.add(contact); db.addNewContacts(newContacts); // update tables ContactsPanel.fillTable(false, true); GroupsPanel.fillList(); log("Closing new contact window."); dispose(); } } } /** * Confirming contact change action */ private class EditContactActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if (resolvecontact()) { db.updateContact(contact); ContactsPanel.fillTable(true, false); log("Closing edit contact window."); dispose(); } } } /** * Method for messages logging. * * @param msg message to log */ private void log(String msg) { LoggerFactory.getLogger(this.getClass()).info(msg); } }
false
true
private void prepare() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println(e); } final JPanel form = new JPanel(new GridBagLayout()); form.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); final GridBagConstraints c = new GridBagConstraints(); final JPanel formContact = new JPanel(new GridBagLayout()); formContact.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); final GridBagConstraints cDetails = new GridBagConstraints(); final JPanel formNote = new JPanel(new GridBagLayout()); formNote.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); final GridBagConstraints cNote = new GridBagConstraints(); final JPanel formPhoto = new JPanel(new GridBagLayout()); formPhoto.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); final GridBagConstraints cPhoto = new GridBagConstraints(); // create tabs JTabbedPane tabs = new JTabbedPane(); tabs.addTab("Basic details", form); tabs.addTab("Contact details", formContact); tabs.addTab("Notes", formNote); tabs.addTab("Photo", formPhoto); // basic details c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(1, 1, 1, 1); c.weightx = 0; c.anchor = GridBagConstraints.NORTHWEST; c.gridx = 0; c.gridy = 0; form.add(new JLabel("Name"), c); c.gridx = 1; c.weightx = 1; form.add(nameField, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Surname"), c); c.gridx = 1; c.weightx = 1; form.add(surnameField, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Nickname"), c); c.gridx = 1; c.weightx = 1; form.add(nicknameField, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Address"), c); c.gridx = 1; c.weightx = 1; form.add(addressField, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Birthday"), c); c.gridx = 1; c.weightx = 1; birthdayPicker.setFormats(new String[]{"d. M. yyyy"}); form.add(birthdayPicker, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Nameday"), c); c.gridx = 1; c.weightx = 1; namedayPicker.setFormats(new String[]{"d. M."}); form.add(namedayPicker, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Anniversary"), c); c.gridx = 1; c.weightx = 1; celebrationPicker.setFormats(new String[]{"d. M. yyyy"}); form.add(celebrationPicker, c); c.gridy++; c.weighty = 1.0; form.add(Box.createHorizontalGlue(), c); // contact details cDetails.fill = GridBagConstraints.HORIZONTAL; cDetails.insets = new Insets(1, 1, 1, 1); cDetails.weightx = 0; cDetails.anchor = GridBagConstraints.NORTHWEST; cDetails.gridy = 0; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Work E-mail"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(workEmailField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Home E-mail"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(homeEmailField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Other E-mail"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(otherEmailField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Work URL"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(workUrlField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Home URL"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(homeUrlField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Other URL"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(otherUrlField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Work Phone"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(workPhoneField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Home Phone"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(homePhoneField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Other Phone"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(otherPhoneField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("ICQ"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(icqField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Jabber"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(jabberField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Skype"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(skypeField, cDetails); // note cNote.fill = GridBagConstraints.HORIZONTAL; cNote.insets = new Insets(1, 1, 1, 1); cNote.weightx = 0; cNote.anchor = GridBagConstraints.NORTHWEST; cNote.gridy = 0; cNote.gridx = 0; cNote.weightx = 0; JLabel nl = new JLabel("Note"); nl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10)); formNote.add(nl, cNote); cNote.gridx = 1; cNote.weightx = 1; noteField.setLineWrap(true); noteField.setWrapStyleWord(true); noteField.setRows(10); noteField.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY)); formNote.add(noteField, cNote); cNote.weighty = 1.0; cNote.gridy++; formNote.add(Box.createHorizontalGlue(), cNote); // photo cPhoto.insets = new Insets(1, 1, 1, 1); cPhoto.weightx = 0; cPhoto.anchor = GridBagConstraints.NORTHWEST; cPhoto.gridy = 0; cPhoto.gridx = 0; cPhoto.weightx = 0; JLabel pl = new JLabel("Photo"); pl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10)); formPhoto.add(pl, cPhoto); cPhoto.gridx = 1; cPhoto.weightx = 1; formPhoto.add(photo, cPhoto); cPhoto.weighty = 1.0; cPhoto.gridy++; formPhoto.add(Box.createHorizontalGlue(), cPhoto); // finish add(tabs, BorderLayout.CENTER); add(button, BorderLayout.PAGE_END); setLocationRelativeTo(null); pack(); setVisible(true); }
private void prepare() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println(e); } final JPanel form = new JPanel(new GridBagLayout()); form.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); final GridBagConstraints c = new GridBagConstraints(); final JPanel formContact = new JPanel(new GridBagLayout()); formContact.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); final GridBagConstraints cDetails = new GridBagConstraints(); final JPanel formNote = new JPanel(new GridBagLayout()); formNote.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); final GridBagConstraints cNote = new GridBagConstraints(); final JPanel formPhoto = new JPanel(new GridBagLayout()); formPhoto.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); final GridBagConstraints cPhoto = new GridBagConstraints(); // create tabs JTabbedPane tabs = new JTabbedPane(); tabs.addTab("Basic details", form); tabs.addTab("Contact details", formContact); tabs.addTab("Notes", formNote); tabs.addTab("Photo", formPhoto); // basic details c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(1, 1, 1, 1); c.weightx = 0; c.anchor = GridBagConstraints.NORTHWEST; c.gridx = 0; c.gridy = 0; form.add(new JLabel("Name"), c); c.gridx = 1; c.weightx = 1; form.add(nameField, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Surname"), c); c.gridx = 1; c.weightx = 1; form.add(surnameField, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Nickname"), c); c.gridx = 1; c.weightx = 1; form.add(nicknameField, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Address"), c); c.gridx = 1; c.weightx = 1; form.add(addressField, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Birthday"), c); c.gridx = 1; c.weightx = 1; birthdayPicker.setFormats(new String[]{"d. M. yyyy"}); form.add(birthdayPicker, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Nameday"), c); c.gridx = 1; c.weightx = 1; namedayPicker.setFormats(new String[]{"d. M."}); form.add(namedayPicker, c); c.gridy++; c.gridx = 0; c.weightx = 0; form.add(new JLabel("Anniversary"), c); c.gridx = 1; c.weightx = 1; celebrationPicker.setFormats(new String[]{"d. M. yyyy"}); form.add(celebrationPicker, c); c.gridy++; c.weighty = 1.0; form.add(Box.createHorizontalGlue(), c); // contact details cDetails.fill = GridBagConstraints.HORIZONTAL; cDetails.insets = new Insets(1, 1, 1, 1); cDetails.weightx = 0; cDetails.anchor = GridBagConstraints.NORTHWEST; cDetails.gridy = 0; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Work E-mail"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(workEmailField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Home E-mail"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(homeEmailField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Other E-mail"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(otherEmailField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Work URL"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(workUrlField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Home URL"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(homeUrlField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Other URL"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(otherUrlField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Work Phone"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(workPhoneField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Home Phone"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(homePhoneField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Other Phone"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(otherPhoneField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("ICQ"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(icqField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Jabber"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(jabberField, cDetails); cDetails.gridy++; cDetails.gridx = 0; cDetails.weightx = 0; formContact.add(new JLabel("Skype"), cDetails); cDetails.gridx = 1; cDetails.weightx = 1; formContact.add(skypeField, cDetails); cDetails.gridy++; cDetails.weighty = 1.0; formContact.add(Box.createHorizontalGlue(), c); // note cNote.fill = GridBagConstraints.HORIZONTAL; cNote.insets = new Insets(1, 1, 1, 1); cNote.weightx = 0; cNote.anchor = GridBagConstraints.NORTHWEST; cNote.gridy = 0; cNote.gridx = 0; cNote.weightx = 0; JLabel nl = new JLabel("Note"); nl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10)); formNote.add(nl, cNote); cNote.gridx = 1; cNote.weightx = 1; noteField.setLineWrap(true); noteField.setWrapStyleWord(true); noteField.setRows(10); noteField.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY)); formNote.add(noteField, cNote); cNote.weighty = 1.0; cNote.gridy++; formNote.add(Box.createHorizontalGlue(), cNote); // photo cPhoto.insets = new Insets(1, 1, 1, 1); cPhoto.weightx = 0; cPhoto.anchor = GridBagConstraints.NORTHWEST; cPhoto.gridy = 0; cPhoto.gridx = 0; cPhoto.weightx = 0; JLabel pl = new JLabel("Photo"); pl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10)); formPhoto.add(pl, cPhoto); cPhoto.gridx = 1; cPhoto.weightx = 1; formPhoto.add(photo, cPhoto); cPhoto.gridy++; JButton photoButton = new JButton("Change Photo"); // FUJ! ActionListener[] actionListeners = this.photo.getActionListeners(); photoButton.addActionListener(actionListeners[0]); formPhoto.add(photoButton); cPhoto.weighty = 1.0; cPhoto.gridy++; formPhoto.add(Box.createHorizontalGlue(), cPhoto); // finish add(tabs, BorderLayout.CENTER); add(button, BorderLayout.PAGE_END); setLocationRelativeTo(null); pack(); setVisible(true); }
diff --git a/editor/src/main/java/kkckkc/jsourcepad/util/action/KeyStrokeUtils.java b/editor/src/main/java/kkckkc/jsourcepad/util/action/KeyStrokeUtils.java index 37f667d..3847f7d 100644 --- a/editor/src/main/java/kkckkc/jsourcepad/util/action/KeyStrokeUtils.java +++ b/editor/src/main/java/kkckkc/jsourcepad/util/action/KeyStrokeUtils.java @@ -1,25 +1,28 @@ package kkckkc.jsourcepad.util.action; import java.awt.Event; import java.awt.Toolkit; import javax.swing.KeyStroke; public class KeyStrokeUtils { public static Object getKeyStroke(String value) { if (Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() == Event.CTRL_MASK) { - value = value.replaceAll("menu2", "alt"); + value = value.replaceAll("virtual-alt", "alt"); + value = value.replaceAll("virtual-ctrl", "meta"); value = value.replaceAll("menu", "ctrl"); } else if (Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() == Event.META_MASK) { - value = value.replaceAll("menu2", "alt"); + value = value.replaceAll("virtual-alt", "alt"); + value = value.replaceAll("virtual-ctrl", "ctrl"); value = value.replaceAll("menu", "meta"); } else { - value = value.replaceAll("menu2", "ctrl"); + value = value.replaceAll("virtual-alt", "meta"); + value = value.replaceAll("virtual-ctrl", "ctrl"); value = value.replaceAll("menu", "alt"); } return KeyStroke.getKeyStroke(value); } }
false
true
public static Object getKeyStroke(String value) { if (Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() == Event.CTRL_MASK) { value = value.replaceAll("menu2", "alt"); value = value.replaceAll("menu", "ctrl"); } else if (Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() == Event.META_MASK) { value = value.replaceAll("menu2", "alt"); value = value.replaceAll("menu", "meta"); } else { value = value.replaceAll("menu2", "ctrl"); value = value.replaceAll("menu", "alt"); } return KeyStroke.getKeyStroke(value); }
public static Object getKeyStroke(String value) { if (Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() == Event.CTRL_MASK) { value = value.replaceAll("virtual-alt", "alt"); value = value.replaceAll("virtual-ctrl", "meta"); value = value.replaceAll("menu", "ctrl"); } else if (Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() == Event.META_MASK) { value = value.replaceAll("virtual-alt", "alt"); value = value.replaceAll("virtual-ctrl", "ctrl"); value = value.replaceAll("menu", "meta"); } else { value = value.replaceAll("virtual-alt", "meta"); value = value.replaceAll("virtual-ctrl", "ctrl"); value = value.replaceAll("menu", "alt"); } return KeyStroke.getKeyStroke(value); }
diff --git a/src/com/serotonin/bacnet4j/npdu/ip/IpMessageControl.java b/src/com/serotonin/bacnet4j/npdu/ip/IpMessageControl.java index 1645688..4d48717 100644 --- a/src/com/serotonin/bacnet4j/npdu/ip/IpMessageControl.java +++ b/src/com/serotonin/bacnet4j/npdu/ip/IpMessageControl.java @@ -1,670 +1,671 @@ package com.serotonin.bacnet4j.npdu.ip; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.LinkedList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import com.serotonin.bacnet4j.LocalDevice; import com.serotonin.bacnet4j.apdu.APDU; import com.serotonin.bacnet4j.apdu.AckAPDU; import com.serotonin.bacnet4j.apdu.ComplexACK; import com.serotonin.bacnet4j.apdu.ConfirmedRequest; import com.serotonin.bacnet4j.apdu.Error; import com.serotonin.bacnet4j.apdu.Reject; import com.serotonin.bacnet4j.apdu.SegmentACK; import com.serotonin.bacnet4j.apdu.Segmentable; import com.serotonin.bacnet4j.apdu.SimpleACK; import com.serotonin.bacnet4j.apdu.UnconfirmedRequest; import com.serotonin.bacnet4j.base.BACnetUtils; import com.serotonin.bacnet4j.enums.MaxApduLength; import com.serotonin.bacnet4j.exception.BACnetErrorException; import com.serotonin.bacnet4j.exception.BACnetException; import com.serotonin.bacnet4j.exception.BACnetRejectException; import com.serotonin.bacnet4j.exception.BACnetTimeoutException; import com.serotonin.bacnet4j.npdu.NPCI; import com.serotonin.bacnet4j.npdu.RequestHandler; import com.serotonin.bacnet4j.npdu.WaitingRoom; import com.serotonin.bacnet4j.npdu.WaitingRoom.Key; import com.serotonin.bacnet4j.service.acknowledgement.AcknowledgementService; import com.serotonin.bacnet4j.service.confirmed.ConfirmedRequestService; import com.serotonin.bacnet4j.service.unconfirmed.UnconfirmedRequestService; import com.serotonin.bacnet4j.type.constructed.Address; import com.serotonin.bacnet4j.type.constructed.BACnetError; import com.serotonin.bacnet4j.type.enumerated.ErrorClass; import com.serotonin.bacnet4j.type.enumerated.ErrorCode; import com.serotonin.bacnet4j.type.enumerated.Segmentation; import com.serotonin.bacnet4j.type.error.BaseError; import com.serotonin.bacnet4j.type.primitive.OctetString; import com.serotonin.bacnet4j.type.primitive.UnsignedInteger; import com.serotonin.util.queue.ByteQueue; /** * @author mlohbihler */ public class IpMessageControl extends Thread { private static final MaxApduLength APDU_LENGTH = MaxApduLength.UP_TO_1476; private static final int MESSAGE_LENGTH = 2048; private static final int MAX_SEGMENTS = 7; // Greater than 64. // Config private int port; private String broadcastAddress = "255.255.255.255"; private int timeout = 5000; private int segTimeout = 1000; private int segWindow = 5; private int retries = 2; private RequestHandler requestHandler; // Runtime private byte nextInvokeId; private DatagramSocket socket; private final WaitingRoom waitingRoom = new WaitingRoom(); private ExecutorService incomingExecutorService; public RequestHandler getRequestHandler() { return requestHandler; } public void setRequestHandler(RequestHandler requestHandler) { this.requestHandler = requestHandler; } public void setPort(int port) { this.port = port; } public int getPort() { return port; } public void setBroadcastAddress(String broadcastAddress) { this.broadcastAddress = broadcastAddress; } public String getBroadcastAddress() { return broadcastAddress; } public void setTimeout(int timeout) { this.timeout = timeout; } public int getTimeout() { return timeout; } public void setSegTimeout(int segTimeout) { this.segTimeout = segTimeout; } public int getSegTimeout() { return segTimeout; } public void setRetries(int retries) { this.retries = retries; } public int getRetries() { return retries; } public void setSegWindow(int segWindow) { this.segWindow = segWindow; } public int getSegWindow() { return segWindow; } public void initialize() throws IOException { incomingExecutorService = Executors.newCachedThreadPool(); socket = new DatagramSocket(port); start(); } public void terminate() { if (socket != null) socket.close(); // Close the executor service. incomingExecutorService.shutdown(); try { incomingExecutorService.awaitTermination(3, TimeUnit.SECONDS); } catch (InterruptedException e) { LocalDevice.getExceptionListener().receivedException(e); } } private byte getNextInvokeId() { return nextInvokeId++; } public AckAPDU send(String host, int maxAPDULengthAccepted, Segmentation segmentationSupported, ConfirmedRequestService serviceRequest) throws BACnetException { return send(host, port, maxAPDULengthAccepted, segmentationSupported, serviceRequest); } public AckAPDU send(String host, int port, int maxAPDULengthAccepted, Segmentation segmentationSupported, ConfirmedRequestService serviceRequest) throws BACnetException { return send(new InetSocketAddress(host, port), maxAPDULengthAccepted, segmentationSupported, serviceRequest); } public AckAPDU send(byte[] host, int port, int maxAPDULengthAccepted, Segmentation segmentationSupported, ConfirmedRequestService serviceRequest) throws BACnetException { try { return send(new InetSocketAddress(InetAddress.getByAddress(host), port), maxAPDULengthAccepted, segmentationSupported, serviceRequest); } catch (UnknownHostException e) { throw new BACnetException(e); } } public AckAPDU send(InetSocketAddress addr, int maxAPDULengthAccepted, Segmentation segmentationSupported, ConfirmedRequestService serviceRequest) throws BACnetException { // Get an invoke id. byte id = getNextInvokeId(); // Serialize the service request. ByteQueue serviceData = new ByteQueue(); serviceRequest.write(serviceData); // Check if we need to segment the message. if (serviceData.size() > maxAPDULengthAccepted - ConfirmedRequest.getHeaderSize(false)) { int maxServiceData = maxAPDULengthAccepted - ConfirmedRequest.getHeaderSize(true); // Check if the device can accept what we want to send. if (segmentationSupported.intValue() == Segmentation.noSegmentation.intValue() || segmentationSupported.intValue() == Segmentation.segmentedTransmit.intValue()) throw new BACnetException("Request too big to send to device without segmentation"); int segmentsRequired = serviceData.size() / maxServiceData + 1; if (segmentsRequired > 128) throw new BACnetException("Request too big to send to device; too many segments required"); Key key = waitingRoom.enter(addr, id, false); try { return sendSegmentedRequest(key, maxAPDULengthAccepted, maxServiceData, serviceRequest.getChoiceId(), serviceData); } finally { waitingRoom.leave(key); } } else { // We can send the whole APDU in one shot. ConfirmedRequest apdu = new ConfirmedRequest(false, false, true, MAX_SEGMENTS, APDU_LENGTH, id, (byte)0, 0, serviceRequest.getChoiceId(), serviceData); return send(addr, id, timeout, apdu, false); } } private void sendResponse(InetSocketAddress addr, ConfirmedRequest request, AcknowledgementService response) throws BACnetException { if (response == null) { sendImpl(new SimpleACK(request.getInvokeId(), request.getServiceRequest().getChoiceId()), false, addr); return; } // A complex ack response. Serialize the data. ByteQueue serviceData = new ByteQueue(); response.write(serviceData); // Check if we need to segment the message. if (serviceData.size() > request.getMaxApduLengthAccepted().getMaxLength() - ComplexACK.getHeaderSize(false)) { int maxServiceData = request.getMaxApduLengthAccepted().getMaxLength() - ComplexACK.getHeaderSize(true); // Check if the device can accept what we want to send. if (!request.isSegmentedResponseAccepted()) throw new BACnetException("Response too big to send to device without segmentation"); int segmentsRequired = serviceData.size() / maxServiceData + 1; if (segmentsRequired > request.getMaxSegmentsAccepted() || segmentsRequired > 128) throw new BACnetException("Response too big to send to device; too many segments required"); Key key = waitingRoom.enter(addr, request.getInvokeId(), true); try { sendSegmentedResponse(key, request.getMaxApduLengthAccepted().getMaxLength(), maxServiceData, response.getChoiceId(), serviceData); } finally { waitingRoom.leave(key); } } else // We can send the whole APDU in one shot. sendImpl(new ComplexACK(false, false, request.getInvokeId(), 0, 0, response), false, addr); } private AckAPDU send(InetSocketAddress addr, byte id, int timeout, APDU apdu, boolean server) throws BACnetException { Key key = waitingRoom.enter(addr, id, server); try { return send(key, timeout, new APDU[] {apdu}); } finally { waitingRoom.leave(key); } } private AckAPDU send(Key key, int timeout, APDU[] apdu) throws BACnetException { byte[][] data = new byte[apdu.length][]; for (int i=0; i<data.length; i++) data[i] = createMessageData(apdu[i], false); AckAPDU response = null; int attempts = retries + 1; // The retry loop. while (true) { for (int i=0; i<data.length; i++) sendImpl(data[i], key.getPeer()); response = waitForAck(key, timeout, false); if (response == null) { attempts--; if (attempts > 0) // Try again continue; // Give up throw new BACnetTimeoutException("Timeout while waiting for response for id "+ key.getInvokeId()); } // We got the response break; } return response; } public void sendUnconfirmed(String host, UnconfirmedRequestService serviceRequest) throws BACnetException { sendUnconfirmed(host, port, serviceRequest); } public void sendUnconfirmed(String host, int port, UnconfirmedRequestService serviceRequest) throws BACnetException { sendUnconfirmed(new InetSocketAddress(host, port), serviceRequest); } public void sendUnconfirmed(byte[] host, int port, UnconfirmedRequestService serviceRequest) throws BACnetException { try { sendUnconfirmed(new InetSocketAddress(InetAddress.getByAddress(host), port), serviceRequest); } catch (UnknownHostException e) { throw new BACnetException(e); } } public void sendUnconfirmed(InetSocketAddress addr, UnconfirmedRequestService serviceRequest) throws BACnetException { UnconfirmedRequest apdu = new UnconfirmedRequest(serviceRequest); byte[] data = createMessageData(apdu, false); sendImpl(data, addr); } public void sendBroadcast(UnconfirmedRequestService serviceRequest) throws BACnetException { sendBroadcast(port, serviceRequest); } public void sendBroadcast(int port, UnconfirmedRequestService serviceRequest) throws BACnetException { UnconfirmedRequest apdu = new UnconfirmedRequest(serviceRequest); byte[] data = createMessageData(apdu, true); sendImpl(data, new InetSocketAddress(broadcastAddress, port)); } private void sendImpl(APDU apdu, boolean broadcast, InetSocketAddress addr) throws BACnetException { sendImpl(createMessageData(apdu, broadcast), addr); } private void sendImpl(byte[] data, InetSocketAddress addr) throws BACnetException { try { DatagramPacket packet = new DatagramPacket(data, data.length, addr); socket.send(packet); } catch (Exception e) { throw new BACnetException(e); } } private byte[] createMessageData(APDU apdu, boolean broadcast) { ByteQueue apduQueue = new ByteQueue(); apdu.write(apduQueue); ByteQueue queue = new ByteQueue(); // BACnet virtual link layer detail // BACnet/IP queue.push(0x81); // Original-Unicast-NPDU queue.push(broadcast ? 0xb : 0xa); // Length including the BACnet/IP identifier, function, length, protocol version, response expected and the // apdu BACnetUtils.pushShort(queue, apduQueue.size() + 6); // Protocol version, always 1. queue.push((byte)1); // Responses are expected for confirmed requests. queue.push((byte)(apdu.expectsReply() ? 4 : 0)); // Add the apdu queue.push(apduQueue); return queue.popAll(); } // For receiving @Override public void run() { // Create some reusable variables. DatagramPacket p = new DatagramPacket(new byte[MESSAGE_LENGTH], MESSAGE_LENGTH); while (!socket.isClosed()) { try { socket.receive(p); incomingExecutorService.execute(new IncomingMessageExecutor(p)); } catch (IOException e) { // no op. This happens if the socket gets closed by the destroy method. } } } class IncomingMessageExecutor implements Runnable { ByteQueue originalQueue; ByteQueue queue; InetAddress fromAddr; int fromPort; IncomingMessageExecutor(DatagramPacket p) { originalQueue = new ByteQueue(p.getData(), 0, p.getLength()); queue = new ByteQueue(p.getData(), 0, p.getLength()); fromAddr = p.getAddress(); fromPort = p.getPort(); } // Added for testing with the main method below. // IncomingMessageExecutor() { // // } // public void run() { try { runImpl(); } catch (Exception e) { LocalDevice.getExceptionListener().receivedException(e); } catch (Throwable t) { LocalDevice.getExceptionListener().receivedThrowable(t); } } private void runImpl() throws Exception { // Initial parsing of IP message. // BACnet/IP if (queue.pop() != (byte)0x81) throw new MessageValidationAssertionException("Protocol id is not BACnet/IP (0x81)"); byte function = queue.pop(); if (function != 0xa && function != 0xb) throw new MessageValidationAssertionException("Function is not unicast or broadcast (0xa or 0xb)"); int length = BACnetUtils.popShort(queue); if (length != queue.size() + 4) throw new MessageValidationAssertionException("Length field does not match data: given="+ length +", expected="+ (queue.size() + 4)); // Network layer protocol control information. See 6.2.2 NPCI npci = new NPCI(queue); if (npci.getVersion() != 1) throw new MessageValidationAssertionException("Invalid protocol version: "+ npci.getVersion()); if (npci.isNetworkMessage()) throw new MessageValidationAssertionException("Network messages are not supported"); // Create the APDU. APDU apdu; try { apdu = APDU.createAPDU(queue); } catch (Exception e) { throw new BACnetException("Error while creating APDU: ", e); } // if (apdu.expectsReply() != npci.isExpectingReply()) // throw new MessageValidationAssertionException("Inconsistent message: APDU expectsReply="+ // apdu.expectsReply() +" while NPCI isExpectingReply="+ npci.isExpectingReply()); if (apdu instanceof ConfirmedRequest) { ConfirmedRequest confAPDU = (ConfirmedRequest)apdu; InetSocketAddress from = new InetSocketAddress(fromAddr, fromPort); byte invokeId = confAPDU.getInvokeId(); if (confAPDU.isSegmentedMessage() && confAPDU.getSequenceNumber() > 0) // This is a subsequent part of a segmented message. Notify the waiting room. waitingRoom.notifyMember(from, invokeId, false, confAPDU); else { if (confAPDU.isSegmentedMessage()) { // This is the initial part of a segmented message. Go and receive the subsequent parts. Key key = waitingRoom.enter(from, invokeId, true); try { receiveSegmented(key, confAPDU); } finally { waitingRoom.leave(key); } } // Handle the request. try { confAPDU.parseServiceData(); AcknowledgementService ackService = requestHandler.handleConfirmedRequest( new Address(new UnsignedInteger(fromPort), new OctetString(fromAddr.getAddress())), invokeId, confAPDU.getServiceRequest()); sendResponse(from, confAPDU, ackService); } catch (BACnetErrorException e) { sendImpl(new Error(invokeId, e.getError()), false, from); } catch (BACnetRejectException e) { sendImpl(new Reject(invokeId, e.getRejectReason()), false, from); } catch (BACnetException e) { sendImpl(new Error(confAPDU.getInvokeId(), new BaseError((byte)127, new BACnetError(ErrorClass.services, ErrorCode.inconsistentParameters))), false, from); + LocalDevice.getExceptionListener().receivedThrowable(e.getCause()); } } } else if (apdu instanceof UnconfirmedRequest) { requestHandler.handleUnconfirmedRequest( new Address(new UnsignedInteger(fromPort), new OctetString(fromAddr.getAddress())), ((UnconfirmedRequest)apdu).getService()); } else { // An acknowledgement. AckAPDU ack = (AckAPDU)apdu; waitingRoom.notifyMember(new InetSocketAddress(fromAddr, fromPort), ack.getOriginalInvokeId(), ack.isServer(), ack); } } } class MessageValidationAssertionException extends Exception { private static final long serialVersionUID = -1; public MessageValidationAssertionException(String message) { super(message); } } private AckAPDU sendSegmentedRequest(Key key, int maxAPDULengthAccepted, int maxServiceData, byte serviceChoice, ByteQueue serviceData) throws BACnetException { ConfirmedRequest template = new ConfirmedRequest(true, true, true, MAX_SEGMENTS, APDU_LENGTH, key.getInvokeId(), 0, segWindow, serviceChoice, (ByteQueue)null); AckAPDU ack = sendSegmented(key, maxAPDULengthAccepted, maxServiceData, serviceData, template); if (ack != null) return ack; // Go to the waiting room to wait for a response. return waitForAck(key, timeout, true); } private void sendSegmentedResponse(Key key, int maxAPDULengthAccepted, int maxServiceData, byte serviceChoice, ByteQueue serviceData) throws BACnetException { ComplexACK template = new ComplexACK(true, true, key.getInvokeId(), (byte)0, segWindow, serviceChoice, (ByteQueue)null); AckAPDU ack = sendSegmented(key, maxAPDULengthAccepted, maxServiceData, serviceData, template); if (ack != null) throw new BACnetException("Invalid response from client while sending segmented response: "+ ack); } private AckAPDU sendSegmented(Key key, int maxAPDULengthAccepted, int maxServiceData, ByteQueue serviceData, Segmentable segmentTemplate) throws BACnetException { System.out.println("Send segmented: "+ (serviceData.size() / maxServiceData + 1) +" segments required"); // Send an initial message to negotiate communication terms. ByteQueue segData = new ByteQueue(maxServiceData); byte[] data = new byte[maxServiceData]; serviceData.pop(data); segData.push(data); APDU apdu = segmentTemplate.clone(true, 0, segmentTemplate.getProposedWindowSize(), segData); System.out.println("Sending segment 0"); AckAPDU response = send(key, segTimeout, new APDU[] {apdu}); if (!(response instanceof SegmentACK)) return response; SegmentACK ack = (SegmentACK)response; int actualSegWindow = ack.getActualWindowSize(); // Create a queue of messages to send. LinkedList<APDU> apduQueue = new LinkedList<APDU>(); boolean finalMessage; byte sequenceNumber = 1; while (serviceData.size() > 0) { finalMessage = serviceData.size() <= maxAPDULengthAccepted; segData = new ByteQueue(); int count = serviceData.pop(data); segData.push(data, 0, count); apdu = segmentTemplate.clone(!finalMessage, sequenceNumber++, actualSegWindow, segData); apduQueue.add(apdu); } // Send the data in windows of size given by the recipient. while (apduQueue.size() > 0) { APDU[] window = new APDU[Math.min(apduQueue.size(), actualSegWindow)]; System.out.println("Sending "+ window.length +" segments"); for (int i=0; i<window.length; i++) window[i] = apduQueue.poll(); response = send(key, segTimeout, window); if (response instanceof SegmentACK) { ack = (SegmentACK)response; if (ack.isNegativeAck()) System.out.println("NAK received: "+ ack); int receivedSeq = ack.getSequenceNumber() & 0xff; while (apduQueue.size() > 0 && (((Segmentable)apduQueue.peek()).getSequenceNumber() & 0xff) <= receivedSeq) apduQueue.poll(); } else return response; } return null; } private AckAPDU waitForAck(Key key, long timeout, boolean throwTimeout) throws BACnetException { AckAPDU ack = waitingRoom.getAck(key, timeout, throwTimeout); if (!(ack instanceof ComplexACK)) return ack; ComplexACK firstPart = (ComplexACK)ack; if (firstPart.isSegmentedMessage()) receiveSegmented(key, firstPart); firstPart.parseServiceData(); return firstPart; } private void receiveSegmented(Key key, Segmentable firstPart) throws BACnetException { boolean server = !key.isFromServer(); InetSocketAddress peer = key.getPeer(); byte id = firstPart.getInvokeId(); int window = firstPart.getProposedWindowSize(); int lastSeq = firstPart.getSequenceNumber() & 0xff; //System.out.println("Receiving segmented: window="+ window); // Send a segment ack. Go with whatever window size was proposed. sendImpl(new SegmentACK(false, server, id, lastSeq, window, true), false, peer); // The loop for receiving windows of request parts. Segmentable segment; SegmentWindow segmentWindow = new SegmentWindow(window, lastSeq + 1); while (true) { segment = segmentWindow.getSegment(lastSeq + 1); if (segment == null) { // Wait for the next part of the message to arrive. segment = waitingRoom.getSegmentable(key, segTimeout*4, false); if (segment == null) { // We timed out waiting for a segment. if (segmentWindow.isEmpty()) // We didn't receive anything, so throw a timeout exception. throw new BACnetTimeoutException("Timeout while waiting for segment part: invokeId="+ id +", sequenceId="+ (lastSeq + 1)); // Return a NAK with the last sequence id received in order and start over. sendImpl(new SegmentACK(true, server, id, lastSeq, window, true), false, peer); segmentWindow.clear(lastSeq + 1); } else if (segmentWindow.fitsInWindow(segment)) segmentWindow.setSegment(segment); continue; } // We have the required segment. Append the part to the first part. //System.out.println("Received segment "+ segment.getSequenceNumber()); firstPart.appendServiceData(segment.getServiceData()); lastSeq++; // Do we need to send an ack? if (!segment.isMoreFollows() || segmentWindow.isLastSegment(lastSeq)) { // Return an acknowledgement sendImpl(new SegmentACK(false, server, id, lastSeq, window, segment.isMoreFollows()), false, peer); segmentWindow.clear(lastSeq + 1); } if (!segment.isMoreFollows()) // We're done. break; } //System.out.println("Finished receiving segmented"); } // Testing // public static void main(String[] args) throws Exception { // IpMessageControl ipMessageControl = new IpMessageControl(); // IncomingMessageExecutor ime = ipMessageControl.new IncomingMessageExecutor(); // //ime.queue = new ByteQueue(new byte[] {(byte)0x81, 0xb, 0x0, 0x9, 0x1, (byte)0x81, 0x0, 0x0, 0x1}); // //ime.queue = new ByteQueue(new byte[] {(byte)0x81,0xb,0x0,0x18,0x1,0x20,(byte)0xff,(byte)0xff,0x0,(byte)0xff,0x10,0x0,(byte)0xc4,0x2,0x0,0x0,0x65,0x22,0x5,(byte)0xc4,(byte)0x91,0x0,0x21,0x24}); // //ime.queue = new ByteQueue(new byte[] {(byte)0x81,0xa,0x0,0x14,0x1,0x0,0x10,0x0,(byte)0xc4,0x2,0x0,0x0,0x65,0x22,0x5,(byte)0xc4,(byte)0x91,0x0,0x21,(byte)0xec}); // ime.queue = new ByteQueue(new byte[] {(byte)0x81, 0xa, 0x0, 0x11, 0x1, 0x4, 0x2, 0x75, 0x0, 0xc, 0xc, 0x2, 0x0, 0x0, 0x69 , 0x19, 0x61}); // // // ime.runImpl(); // } }
true
true
private void runImpl() throws Exception { // Initial parsing of IP message. // BACnet/IP if (queue.pop() != (byte)0x81) throw new MessageValidationAssertionException("Protocol id is not BACnet/IP (0x81)"); byte function = queue.pop(); if (function != 0xa && function != 0xb) throw new MessageValidationAssertionException("Function is not unicast or broadcast (0xa or 0xb)"); int length = BACnetUtils.popShort(queue); if (length != queue.size() + 4) throw new MessageValidationAssertionException("Length field does not match data: given="+ length +", expected="+ (queue.size() + 4)); // Network layer protocol control information. See 6.2.2 NPCI npci = new NPCI(queue); if (npci.getVersion() != 1) throw new MessageValidationAssertionException("Invalid protocol version: "+ npci.getVersion()); if (npci.isNetworkMessage()) throw new MessageValidationAssertionException("Network messages are not supported"); // Create the APDU. APDU apdu; try { apdu = APDU.createAPDU(queue); } catch (Exception e) { throw new BACnetException("Error while creating APDU: ", e); } // if (apdu.expectsReply() != npci.isExpectingReply()) // throw new MessageValidationAssertionException("Inconsistent message: APDU expectsReply="+ // apdu.expectsReply() +" while NPCI isExpectingReply="+ npci.isExpectingReply()); if (apdu instanceof ConfirmedRequest) { ConfirmedRequest confAPDU = (ConfirmedRequest)apdu; InetSocketAddress from = new InetSocketAddress(fromAddr, fromPort); byte invokeId = confAPDU.getInvokeId(); if (confAPDU.isSegmentedMessage() && confAPDU.getSequenceNumber() > 0) // This is a subsequent part of a segmented message. Notify the waiting room. waitingRoom.notifyMember(from, invokeId, false, confAPDU); else { if (confAPDU.isSegmentedMessage()) { // This is the initial part of a segmented message. Go and receive the subsequent parts. Key key = waitingRoom.enter(from, invokeId, true); try { receiveSegmented(key, confAPDU); } finally { waitingRoom.leave(key); } } // Handle the request. try { confAPDU.parseServiceData(); AcknowledgementService ackService = requestHandler.handleConfirmedRequest( new Address(new UnsignedInteger(fromPort), new OctetString(fromAddr.getAddress())), invokeId, confAPDU.getServiceRequest()); sendResponse(from, confAPDU, ackService); } catch (BACnetErrorException e) { sendImpl(new Error(invokeId, e.getError()), false, from); } catch (BACnetRejectException e) { sendImpl(new Reject(invokeId, e.getRejectReason()), false, from); } catch (BACnetException e) { sendImpl(new Error(confAPDU.getInvokeId(), new BaseError((byte)127, new BACnetError(ErrorClass.services, ErrorCode.inconsistentParameters))), false, from); } } } else if (apdu instanceof UnconfirmedRequest) { requestHandler.handleUnconfirmedRequest( new Address(new UnsignedInteger(fromPort), new OctetString(fromAddr.getAddress())), ((UnconfirmedRequest)apdu).getService()); } else { // An acknowledgement. AckAPDU ack = (AckAPDU)apdu; waitingRoom.notifyMember(new InetSocketAddress(fromAddr, fromPort), ack.getOriginalInvokeId(), ack.isServer(), ack); } }
private void runImpl() throws Exception { // Initial parsing of IP message. // BACnet/IP if (queue.pop() != (byte)0x81) throw new MessageValidationAssertionException("Protocol id is not BACnet/IP (0x81)"); byte function = queue.pop(); if (function != 0xa && function != 0xb) throw new MessageValidationAssertionException("Function is not unicast or broadcast (0xa or 0xb)"); int length = BACnetUtils.popShort(queue); if (length != queue.size() + 4) throw new MessageValidationAssertionException("Length field does not match data: given="+ length +", expected="+ (queue.size() + 4)); // Network layer protocol control information. See 6.2.2 NPCI npci = new NPCI(queue); if (npci.getVersion() != 1) throw new MessageValidationAssertionException("Invalid protocol version: "+ npci.getVersion()); if (npci.isNetworkMessage()) throw new MessageValidationAssertionException("Network messages are not supported"); // Create the APDU. APDU apdu; try { apdu = APDU.createAPDU(queue); } catch (Exception e) { throw new BACnetException("Error while creating APDU: ", e); } // if (apdu.expectsReply() != npci.isExpectingReply()) // throw new MessageValidationAssertionException("Inconsistent message: APDU expectsReply="+ // apdu.expectsReply() +" while NPCI isExpectingReply="+ npci.isExpectingReply()); if (apdu instanceof ConfirmedRequest) { ConfirmedRequest confAPDU = (ConfirmedRequest)apdu; InetSocketAddress from = new InetSocketAddress(fromAddr, fromPort); byte invokeId = confAPDU.getInvokeId(); if (confAPDU.isSegmentedMessage() && confAPDU.getSequenceNumber() > 0) // This is a subsequent part of a segmented message. Notify the waiting room. waitingRoom.notifyMember(from, invokeId, false, confAPDU); else { if (confAPDU.isSegmentedMessage()) { // This is the initial part of a segmented message. Go and receive the subsequent parts. Key key = waitingRoom.enter(from, invokeId, true); try { receiveSegmented(key, confAPDU); } finally { waitingRoom.leave(key); } } // Handle the request. try { confAPDU.parseServiceData(); AcknowledgementService ackService = requestHandler.handleConfirmedRequest( new Address(new UnsignedInteger(fromPort), new OctetString(fromAddr.getAddress())), invokeId, confAPDU.getServiceRequest()); sendResponse(from, confAPDU, ackService); } catch (BACnetErrorException e) { sendImpl(new Error(invokeId, e.getError()), false, from); } catch (BACnetRejectException e) { sendImpl(new Reject(invokeId, e.getRejectReason()), false, from); } catch (BACnetException e) { sendImpl(new Error(confAPDU.getInvokeId(), new BaseError((byte)127, new BACnetError(ErrorClass.services, ErrorCode.inconsistentParameters))), false, from); LocalDevice.getExceptionListener().receivedThrowable(e.getCause()); } } } else if (apdu instanceof UnconfirmedRequest) { requestHandler.handleUnconfirmedRequest( new Address(new UnsignedInteger(fromPort), new OctetString(fromAddr.getAddress())), ((UnconfirmedRequest)apdu).getService()); } else { // An acknowledgement. AckAPDU ack = (AckAPDU)apdu; waitingRoom.notifyMember(new InetSocketAddress(fromAddr, fromPort), ack.getOriginalInvokeId(), ack.isServer(), ack); } }
diff --git a/src/pet/hp/impl/HistoryUtil.java b/src/pet/hp/impl/HistoryUtil.java index 995b9ca..6346c00 100644 --- a/src/pet/hp/impl/HistoryUtil.java +++ b/src/pet/hp/impl/HistoryUtil.java @@ -1,52 +1,52 @@ package pet.hp.impl; import java.io.File; import pet.hp.Parser; public class HistoryUtil { public static File getTiltPath(FTParser parser) { // "/Users/alex/Documents/HandHistory/Keynell" String home = System.getProperty("user.home"); return getDir(home + "/Documents/HandHistory", parser); } /** get the pokerstars hand history directory */ public static File getStarsPath(PSParser parser) { // C:\Users\Alex\AppData\Local\PokerStars\HandHistory\ // /Users/alex/Library/Application Support/PokerStars/HandHistory/tawvx String home = System.getProperty("user.home"); String os = System.getProperty("os.name"); String path = null; if (os.equals("Mac OS X")) { path = home + "/Library/Application Support/PokerStars/HandHistory"; } else if (os.contains("Windows")) { // could be something like PokerStars.FR instead path = home + "\\AppData\\Local\\PokerStars\\HandHistory"; } return getDir(path, parser); } /** * get dir within dir with files matching regex. * return home dir if none found. */ private static File getDir(String path, Parser parser) { File f = new File(path); if (f.exists() && f.isDirectory()) { // get the first directory containing files matching the regex for (File f2 : f.listFiles()) { if (f2.isDirectory()) { for (String f3 : f2.list()) { if (parser.isHistoryFile(f3)) { return f2; } } } } } - return new File(System.getProperty("home.dir")); + return new File(System.getProperty("user.home")); } }
true
true
private static File getDir(String path, Parser parser) { File f = new File(path); if (f.exists() && f.isDirectory()) { // get the first directory containing files matching the regex for (File f2 : f.listFiles()) { if (f2.isDirectory()) { for (String f3 : f2.list()) { if (parser.isHistoryFile(f3)) { return f2; } } } } } return new File(System.getProperty("home.dir")); }
private static File getDir(String path, Parser parser) { File f = new File(path); if (f.exists() && f.isDirectory()) { // get the first directory containing files matching the regex for (File f2 : f.listFiles()) { if (f2.isDirectory()) { for (String f3 : f2.list()) { if (parser.isHistoryFile(f3)) { return f2; } } } } } return new File(System.getProperty("user.home")); }
diff --git a/tests/src/com/android/providers/contacts/ContactsProvider2Test.java b/tests/src/com/android/providers/contacts/ContactsProvider2Test.java index da3a125d..74d0e691 100644 --- a/tests/src/com/android/providers/contacts/ContactsProvider2Test.java +++ b/tests/src/com/android/providers/contacts/ContactsProvider2Test.java @@ -1,7945 +1,7945 @@ /* * 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 static com.android.providers.contacts.TestUtils.cv; import android.accounts.Account; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Entity; import android.content.EntityIterator; import android.content.res.AssetFileDescriptor; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.provider.ContactsContract; import android.provider.ContactsContract.AggregationExceptions; import android.provider.ContactsContract.CommonDataKinds.Callable; import android.provider.ContactsContract.CommonDataKinds.Contactables; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.provider.ContactsContract.CommonDataKinds.Im; 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.Data; import android.provider.ContactsContract.DataUsageFeedback; import android.provider.ContactsContract.Directory; import android.provider.ContactsContract.DisplayNameSources; import android.provider.ContactsContract.DisplayPhoto; import android.provider.ContactsContract.FullNameStyle; import android.provider.ContactsContract.Groups; import android.provider.ContactsContract.PhoneLookup; import android.provider.ContactsContract.PhoneticNameStyle; 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.test.MoreAsserts; import android.test.suitebuilder.annotation.LargeTest; import android.text.TextUtils; import com.android.internal.util.ArrayUtils; import com.android.providers.contacts.ContactsDatabaseHelper.AggregationExceptionColumns; import com.android.providers.contacts.ContactsDatabaseHelper.ContactsColumns; import com.android.providers.contacts.ContactsDatabaseHelper.DataUsageStatColumns; import com.android.providers.contacts.ContactsDatabaseHelper.DbProperties; import com.android.providers.contacts.ContactsDatabaseHelper.PresenceColumns; import com.android.providers.contacts.ContactsDatabaseHelper.RawContactsColumns; import com.android.providers.contacts.ContactsDatabaseHelper.Tables; import com.android.providers.contacts.testutil.CommonDatabaseUtils; import com.android.providers.contacts.testutil.ContactUtil; import com.android.providers.contacts.testutil.DataUtil; import com.android.providers.contacts.testutil.DatabaseAsserts; import com.android.providers.contacts.testutil.DeletedContactUtil; import com.android.providers.contacts.testutil.RawContactUtil; import com.android.providers.contacts.testutil.TestUtil; import com.android.providers.contacts.tests.R; import com.google.android.collect.Lists; import com.google.android.collect.Sets; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; /** * Unit tests for {@link ContactsProvider2}. * * Run the test like this: * <code> adb shell am instrument -e class com.android.providers.contacts.ContactsProvider2Test -w \ com.android.providers.contacts.tests/android.test.InstrumentationTestRunner * </code> */ @LargeTest public class ContactsProvider2Test extends BaseContactsProvider2Test { private static final String TAG = ContactsProvider2Test.class.getSimpleName(); public void testContactsProjection() { assertProjection(Contacts.CONTENT_URI, new String[]{ Contacts._ID, Contacts.DISPLAY_NAME_PRIMARY, Contacts.DISPLAY_NAME_ALTERNATIVE, Contacts.DISPLAY_NAME_SOURCE, Contacts.PHONETIC_NAME, Contacts.PHONETIC_NAME_STYLE, Contacts.SORT_KEY_PRIMARY, Contacts.SORT_KEY_ALTERNATIVE, ContactsColumns.PHONEBOOK_LABEL_PRIMARY, ContactsColumns.PHONEBOOK_BUCKET_PRIMARY, ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, ContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE, Contacts.LAST_TIME_CONTACTED, Contacts.TIMES_CONTACTED, Contacts.STARRED, Contacts.IN_VISIBLE_GROUP, Contacts.PHOTO_ID, Contacts.PHOTO_FILE_ID, Contacts.PHOTO_URI, Contacts.PHOTO_THUMBNAIL_URI, Contacts.CUSTOM_RINGTONE, Contacts.HAS_PHONE_NUMBER, Contacts.SEND_TO_VOICEMAIL, Contacts.IS_USER_PROFILE, Contacts.LOOKUP_KEY, Contacts.NAME_RAW_CONTACT_ID, Contacts.CONTACT_PRESENCE, Contacts.CONTACT_CHAT_CAPABILITY, Contacts.CONTACT_STATUS, Contacts.CONTACT_STATUS_TIMESTAMP, Contacts.CONTACT_STATUS_RES_PACKAGE, Contacts.CONTACT_STATUS_LABEL, Contacts.CONTACT_STATUS_ICON, Contacts.CONTACT_LAST_UPDATED_TIMESTAMP }); } public void testContactsStrequentProjection() { assertProjection(Contacts.CONTENT_STREQUENT_URI, new String[]{ Contacts._ID, Contacts.DISPLAY_NAME_PRIMARY, Contacts.DISPLAY_NAME_ALTERNATIVE, Contacts.DISPLAY_NAME_SOURCE, Contacts.PHONETIC_NAME, Contacts.PHONETIC_NAME_STYLE, Contacts.SORT_KEY_PRIMARY, Contacts.SORT_KEY_ALTERNATIVE, ContactsColumns.PHONEBOOK_LABEL_PRIMARY, ContactsColumns.PHONEBOOK_BUCKET_PRIMARY, ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, ContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE, Contacts.LAST_TIME_CONTACTED, Contacts.TIMES_CONTACTED, Contacts.STARRED, Contacts.IN_VISIBLE_GROUP, Contacts.PHOTO_ID, Contacts.PHOTO_FILE_ID, Contacts.PHOTO_URI, Contacts.PHOTO_THUMBNAIL_URI, Contacts.CUSTOM_RINGTONE, Contacts.HAS_PHONE_NUMBER, Contacts.SEND_TO_VOICEMAIL, Contacts.IS_USER_PROFILE, Contacts.LOOKUP_KEY, Contacts.NAME_RAW_CONTACT_ID, Contacts.CONTACT_PRESENCE, Contacts.CONTACT_CHAT_CAPABILITY, Contacts.CONTACT_STATUS, Contacts.CONTACT_STATUS_TIMESTAMP, Contacts.CONTACT_STATUS_RES_PACKAGE, Contacts.CONTACT_STATUS_LABEL, Contacts.CONTACT_STATUS_ICON, Contacts.CONTACT_LAST_UPDATED_TIMESTAMP, DataUsageStatColumns.TIMES_USED, DataUsageStatColumns.LAST_TIME_USED, }); } public void testContactsStrequentPhoneOnlyProjection() { assertProjection(Contacts.CONTENT_STREQUENT_URI.buildUpon() .appendQueryParameter(ContactsContract.STREQUENT_PHONE_ONLY, "true").build(), new String[] { Contacts._ID, Contacts.DISPLAY_NAME_PRIMARY, Contacts.DISPLAY_NAME_ALTERNATIVE, Contacts.DISPLAY_NAME_SOURCE, Contacts.PHONETIC_NAME, Contacts.PHONETIC_NAME_STYLE, Contacts.SORT_KEY_PRIMARY, Contacts.SORT_KEY_ALTERNATIVE, ContactsColumns.PHONEBOOK_LABEL_PRIMARY, ContactsColumns.PHONEBOOK_BUCKET_PRIMARY, ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, ContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE, Contacts.LAST_TIME_CONTACTED, Contacts.TIMES_CONTACTED, Contacts.STARRED, Contacts.IN_VISIBLE_GROUP, Contacts.PHOTO_ID, Contacts.PHOTO_FILE_ID, Contacts.PHOTO_URI, Contacts.PHOTO_THUMBNAIL_URI, Contacts.CUSTOM_RINGTONE, Contacts.HAS_PHONE_NUMBER, Contacts.SEND_TO_VOICEMAIL, Contacts.IS_USER_PROFILE, Contacts.LOOKUP_KEY, Contacts.NAME_RAW_CONTACT_ID, Contacts.CONTACT_PRESENCE, Contacts.CONTACT_CHAT_CAPABILITY, Contacts.CONTACT_STATUS, Contacts.CONTACT_STATUS_TIMESTAMP, Contacts.CONTACT_STATUS_RES_PACKAGE, Contacts.CONTACT_STATUS_LABEL, Contacts.CONTACT_STATUS_ICON, Contacts.CONTACT_LAST_UPDATED_TIMESTAMP, DataUsageStatColumns.TIMES_USED, DataUsageStatColumns.LAST_TIME_USED, Phone.NUMBER, Phone.TYPE, Phone.LABEL, }); } public void testContactsWithSnippetProjection() { assertProjection(Contacts.CONTENT_FILTER_URI.buildUpon().appendPath("nothing").build(), new String[]{ Contacts._ID, Contacts.DISPLAY_NAME_PRIMARY, Contacts.DISPLAY_NAME_ALTERNATIVE, Contacts.DISPLAY_NAME_SOURCE, Contacts.PHONETIC_NAME, Contacts.PHONETIC_NAME_STYLE, Contacts.SORT_KEY_PRIMARY, Contacts.SORT_KEY_ALTERNATIVE, ContactsColumns.PHONEBOOK_LABEL_PRIMARY, ContactsColumns.PHONEBOOK_BUCKET_PRIMARY, ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, ContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE, Contacts.LAST_TIME_CONTACTED, Contacts.TIMES_CONTACTED, Contacts.STARRED, Contacts.IN_VISIBLE_GROUP, Contacts.PHOTO_ID, Contacts.PHOTO_FILE_ID, Contacts.PHOTO_URI, Contacts.PHOTO_THUMBNAIL_URI, Contacts.CUSTOM_RINGTONE, Contacts.HAS_PHONE_NUMBER, Contacts.SEND_TO_VOICEMAIL, Contacts.IS_USER_PROFILE, Contacts.LOOKUP_KEY, Contacts.NAME_RAW_CONTACT_ID, Contacts.CONTACT_PRESENCE, Contacts.CONTACT_CHAT_CAPABILITY, Contacts.CONTACT_STATUS, Contacts.CONTACT_STATUS_TIMESTAMP, Contacts.CONTACT_STATUS_RES_PACKAGE, Contacts.CONTACT_STATUS_LABEL, Contacts.CONTACT_STATUS_ICON, Contacts.CONTACT_LAST_UPDATED_TIMESTAMP, SearchSnippetColumns.SNIPPET, }); } public void testRawContactsProjection() { assertProjection(RawContacts.CONTENT_URI, new String[]{ RawContacts._ID, RawContacts.CONTACT_ID, RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE, RawContacts.DATA_SET, RawContacts.ACCOUNT_TYPE_AND_DATA_SET, RawContacts.SOURCE_ID, RawContacts.VERSION, RawContacts.RAW_CONTACT_IS_USER_PROFILE, RawContacts.DIRTY, RawContacts.DELETED, RawContacts.DISPLAY_NAME_PRIMARY, RawContacts.DISPLAY_NAME_ALTERNATIVE, RawContacts.DISPLAY_NAME_SOURCE, RawContacts.PHONETIC_NAME, RawContacts.PHONETIC_NAME_STYLE, RawContacts.NAME_VERIFIED, RawContacts.SORT_KEY_PRIMARY, RawContacts.SORT_KEY_ALTERNATIVE, RawContactsColumns.PHONEBOOK_LABEL_PRIMARY, RawContactsColumns.PHONEBOOK_BUCKET_PRIMARY, RawContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, RawContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE, RawContacts.TIMES_CONTACTED, RawContacts.LAST_TIME_CONTACTED, RawContacts.CUSTOM_RINGTONE, RawContacts.SEND_TO_VOICEMAIL, RawContacts.STARRED, RawContacts.AGGREGATION_MODE, RawContacts.SYNC1, RawContacts.SYNC2, RawContacts.SYNC3, RawContacts.SYNC4, }); } public void testDataProjection() { assertProjection(Data.CONTENT_URI, new String[]{ Data._ID, Data.RAW_CONTACT_ID, Data.DATA_VERSION, Data.IS_PRIMARY, Data.IS_SUPER_PRIMARY, Data.RES_PACKAGE, Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3, Data.DATA4, Data.DATA5, Data.DATA6, Data.DATA7, Data.DATA8, Data.DATA9, Data.DATA10, Data.DATA11, Data.DATA12, Data.DATA13, Data.DATA14, Data.DATA15, Data.SYNC1, Data.SYNC2, Data.SYNC3, Data.SYNC4, Data.CONTACT_ID, Data.PRESENCE, Data.CHAT_CAPABILITY, Data.STATUS, Data.STATUS_TIMESTAMP, Data.STATUS_RES_PACKAGE, Data.STATUS_LABEL, Data.STATUS_ICON, Data.TIMES_USED, Data.LAST_TIME_USED, RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE, RawContacts.DATA_SET, RawContacts.ACCOUNT_TYPE_AND_DATA_SET, RawContacts.SOURCE_ID, RawContacts.VERSION, RawContacts.DIRTY, RawContacts.NAME_VERIFIED, RawContacts.RAW_CONTACT_IS_USER_PROFILE, Contacts._ID, Contacts.DISPLAY_NAME_PRIMARY, Contacts.DISPLAY_NAME_ALTERNATIVE, Contacts.DISPLAY_NAME_SOURCE, Contacts.PHONETIC_NAME, Contacts.PHONETIC_NAME_STYLE, Contacts.SORT_KEY_PRIMARY, Contacts.SORT_KEY_ALTERNATIVE, ContactsColumns.PHONEBOOK_LABEL_PRIMARY, ContactsColumns.PHONEBOOK_BUCKET_PRIMARY, ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, ContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE, Contacts.LAST_TIME_CONTACTED, Contacts.TIMES_CONTACTED, Contacts.STARRED, Contacts.IN_VISIBLE_GROUP, Contacts.PHOTO_ID, Contacts.PHOTO_FILE_ID, Contacts.PHOTO_URI, Contacts.PHOTO_THUMBNAIL_URI, Contacts.CUSTOM_RINGTONE, Contacts.SEND_TO_VOICEMAIL, Contacts.LOOKUP_KEY, Contacts.NAME_RAW_CONTACT_ID, Contacts.HAS_PHONE_NUMBER, Contacts.CONTACT_PRESENCE, Contacts.CONTACT_CHAT_CAPABILITY, Contacts.CONTACT_STATUS, Contacts.CONTACT_STATUS_TIMESTAMP, Contacts.CONTACT_STATUS_RES_PACKAGE, Contacts.CONTACT_STATUS_LABEL, Contacts.CONTACT_STATUS_ICON, Contacts.CONTACT_LAST_UPDATED_TIMESTAMP, GroupMembership.GROUP_SOURCE_ID, }); } public void testDistinctDataProjection() { assertProjection(Phone.CONTENT_FILTER_URI.buildUpon().appendPath("123").build(), new String[]{ Data._ID, Data.DATA_VERSION, Data.IS_PRIMARY, Data.IS_SUPER_PRIMARY, Data.RES_PACKAGE, Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3, Data.DATA4, Data.DATA5, Data.DATA6, Data.DATA7, Data.DATA8, Data.DATA9, Data.DATA10, Data.DATA11, Data.DATA12, Data.DATA13, Data.DATA14, Data.DATA15, Data.SYNC1, Data.SYNC2, Data.SYNC3, Data.SYNC4, Data.CONTACT_ID, Data.PRESENCE, Data.CHAT_CAPABILITY, Data.STATUS, Data.STATUS_TIMESTAMP, Data.STATUS_RES_PACKAGE, Data.STATUS_LABEL, Data.STATUS_ICON, Data.TIMES_USED, Data.LAST_TIME_USED, RawContacts.RAW_CONTACT_IS_USER_PROFILE, Contacts._ID, Contacts.DISPLAY_NAME_PRIMARY, Contacts.DISPLAY_NAME_ALTERNATIVE, Contacts.DISPLAY_NAME_SOURCE, Contacts.PHONETIC_NAME, Contacts.PHONETIC_NAME_STYLE, Contacts.SORT_KEY_PRIMARY, Contacts.SORT_KEY_ALTERNATIVE, ContactsColumns.PHONEBOOK_LABEL_PRIMARY, ContactsColumns.PHONEBOOK_BUCKET_PRIMARY, ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, ContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE, Contacts.LAST_TIME_CONTACTED, Contacts.TIMES_CONTACTED, Contacts.STARRED, Contacts.IN_VISIBLE_GROUP, Contacts.PHOTO_ID, Contacts.PHOTO_FILE_ID, Contacts.PHOTO_URI, Contacts.PHOTO_THUMBNAIL_URI, Contacts.HAS_PHONE_NUMBER, Contacts.CUSTOM_RINGTONE, Contacts.SEND_TO_VOICEMAIL, Contacts.LOOKUP_KEY, Contacts.CONTACT_PRESENCE, Contacts.CONTACT_CHAT_CAPABILITY, Contacts.CONTACT_STATUS, Contacts.CONTACT_STATUS_TIMESTAMP, Contacts.CONTACT_STATUS_RES_PACKAGE, Contacts.CONTACT_STATUS_LABEL, Contacts.CONTACT_STATUS_ICON, Contacts.CONTACT_LAST_UPDATED_TIMESTAMP, GroupMembership.GROUP_SOURCE_ID, }); } public void testEntityProjection() { assertProjection( Uri.withAppendedPath(ContentUris.withAppendedId(Contacts.CONTENT_URI, 0), Contacts.Entity.CONTENT_DIRECTORY), new String[]{ Contacts.Entity._ID, Contacts.Entity.DATA_ID, Contacts.Entity.RAW_CONTACT_ID, Data.DATA_VERSION, Data.IS_PRIMARY, Data.IS_SUPER_PRIMARY, Data.RES_PACKAGE, Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3, Data.DATA4, Data.DATA5, Data.DATA6, Data.DATA7, Data.DATA8, Data.DATA9, Data.DATA10, Data.DATA11, Data.DATA12, Data.DATA13, Data.DATA14, Data.DATA15, Data.SYNC1, Data.SYNC2, Data.SYNC3, Data.SYNC4, Data.CONTACT_ID, Data.PRESENCE, Data.CHAT_CAPABILITY, Data.STATUS, Data.STATUS_TIMESTAMP, Data.STATUS_RES_PACKAGE, Data.STATUS_LABEL, Data.STATUS_ICON, RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE, RawContacts.DATA_SET, RawContacts.ACCOUNT_TYPE_AND_DATA_SET, RawContacts.SOURCE_ID, RawContacts.VERSION, RawContacts.DELETED, RawContacts.DIRTY, RawContacts.NAME_VERIFIED, RawContacts.SYNC1, RawContacts.SYNC2, RawContacts.SYNC3, RawContacts.SYNC4, Contacts._ID, Contacts.DISPLAY_NAME_PRIMARY, Contacts.DISPLAY_NAME_ALTERNATIVE, Contacts.DISPLAY_NAME_SOURCE, Contacts.PHONETIC_NAME, Contacts.PHONETIC_NAME_STYLE, Contacts.SORT_KEY_PRIMARY, Contacts.SORT_KEY_ALTERNATIVE, ContactsColumns.PHONEBOOK_LABEL_PRIMARY, ContactsColumns.PHONEBOOK_BUCKET_PRIMARY, ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, ContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE, Contacts.LAST_TIME_CONTACTED, Contacts.TIMES_CONTACTED, Contacts.STARRED, Contacts.IN_VISIBLE_GROUP, Contacts.PHOTO_ID, Contacts.PHOTO_FILE_ID, Contacts.PHOTO_URI, Contacts.PHOTO_THUMBNAIL_URI, Contacts.CUSTOM_RINGTONE, Contacts.SEND_TO_VOICEMAIL, Contacts.IS_USER_PROFILE, Contacts.LOOKUP_KEY, Contacts.NAME_RAW_CONTACT_ID, Contacts.HAS_PHONE_NUMBER, Contacts.CONTACT_PRESENCE, Contacts.CONTACT_CHAT_CAPABILITY, Contacts.CONTACT_STATUS, Contacts.CONTACT_STATUS_TIMESTAMP, Contacts.CONTACT_STATUS_RES_PACKAGE, Contacts.CONTACT_STATUS_LABEL, Contacts.CONTACT_STATUS_ICON, Contacts.CONTACT_LAST_UPDATED_TIMESTAMP, GroupMembership.GROUP_SOURCE_ID, }); } public void testRawEntityProjection() { assertProjection(RawContactsEntity.CONTENT_URI, new String[]{ RawContacts.Entity.DATA_ID, RawContacts._ID, RawContacts.CONTACT_ID, RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE, RawContacts.DATA_SET, RawContacts.ACCOUNT_TYPE_AND_DATA_SET, RawContacts.SOURCE_ID, RawContacts.VERSION, RawContacts.DIRTY, RawContacts.NAME_VERIFIED, RawContacts.DELETED, RawContacts.SYNC1, RawContacts.SYNC2, RawContacts.SYNC3, RawContacts.SYNC4, RawContacts.STARRED, RawContacts.RAW_CONTACT_IS_USER_PROFILE, Data.DATA_VERSION, Data.IS_PRIMARY, Data.IS_SUPER_PRIMARY, Data.RES_PACKAGE, Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3, Data.DATA4, Data.DATA5, Data.DATA6, Data.DATA7, Data.DATA8, Data.DATA9, Data.DATA10, Data.DATA11, Data.DATA12, Data.DATA13, Data.DATA14, Data.DATA15, Data.SYNC1, Data.SYNC2, Data.SYNC3, Data.SYNC4, GroupMembership.GROUP_SOURCE_ID, }); } public void testPhoneLookupProjection() { assertProjection(PhoneLookup.CONTENT_FILTER_URI.buildUpon().appendPath("123").build(), new String[]{ PhoneLookup._ID, PhoneLookup.LOOKUP_KEY, PhoneLookup.DISPLAY_NAME, PhoneLookup.LAST_TIME_CONTACTED, PhoneLookup.TIMES_CONTACTED, PhoneLookup.STARRED, PhoneLookup.IN_VISIBLE_GROUP, PhoneLookup.PHOTO_ID, PhoneLookup.PHOTO_URI, PhoneLookup.PHOTO_THUMBNAIL_URI, PhoneLookup.CUSTOM_RINGTONE, PhoneLookup.HAS_PHONE_NUMBER, PhoneLookup.SEND_TO_VOICEMAIL, PhoneLookup.NUMBER, PhoneLookup.TYPE, PhoneLookup.LABEL, PhoneLookup.NORMALIZED_NUMBER, }); } public void testGroupsProjection() { assertProjection(Groups.CONTENT_URI, new String[]{ Groups._ID, Groups.ACCOUNT_NAME, Groups.ACCOUNT_TYPE, Groups.DATA_SET, Groups.ACCOUNT_TYPE_AND_DATA_SET, Groups.SOURCE_ID, Groups.DIRTY, Groups.VERSION, Groups.RES_PACKAGE, Groups.TITLE, Groups.TITLE_RES, Groups.GROUP_VISIBLE, Groups.SYSTEM_ID, Groups.DELETED, Groups.NOTES, Groups.SHOULD_SYNC, Groups.FAVORITES, Groups.AUTO_ADD, Groups.GROUP_IS_READ_ONLY, Groups.SYNC1, Groups.SYNC2, Groups.SYNC3, Groups.SYNC4, }); } public void testGroupsSummaryProjection() { assertProjection(Groups.CONTENT_SUMMARY_URI, new String[]{ Groups._ID, Groups.ACCOUNT_NAME, Groups.ACCOUNT_TYPE, Groups.DATA_SET, Groups.ACCOUNT_TYPE_AND_DATA_SET, Groups.SOURCE_ID, Groups.DIRTY, Groups.VERSION, Groups.RES_PACKAGE, Groups.TITLE, Groups.TITLE_RES, Groups.GROUP_VISIBLE, Groups.SYSTEM_ID, Groups.DELETED, Groups.NOTES, Groups.SHOULD_SYNC, Groups.FAVORITES, Groups.AUTO_ADD, Groups.GROUP_IS_READ_ONLY, Groups.SYNC1, Groups.SYNC2, Groups.SYNC3, Groups.SYNC4, Groups.SUMMARY_COUNT, Groups.SUMMARY_WITH_PHONES, Groups.SUMMARY_GROUP_COUNT_PER_ACCOUNT, }); } public void testAggregateExceptionProjection() { assertProjection(AggregationExceptions.CONTENT_URI, new String[]{ AggregationExceptionColumns._ID, AggregationExceptions.TYPE, AggregationExceptions.RAW_CONTACT_ID1, AggregationExceptions.RAW_CONTACT_ID2, }); } public void testSettingsProjection() { assertProjection(Settings.CONTENT_URI, new String[]{ Settings.ACCOUNT_NAME, Settings.ACCOUNT_TYPE, Settings.DATA_SET, Settings.UNGROUPED_VISIBLE, Settings.SHOULD_SYNC, Settings.ANY_UNSYNCED, Settings.UNGROUPED_COUNT, Settings.UNGROUPED_WITH_PHONES, }); } public void testStatusUpdatesProjection() { assertProjection(StatusUpdates.CONTENT_URI, new String[]{ PresenceColumns.RAW_CONTACT_ID, StatusUpdates.DATA_ID, StatusUpdates.IM_ACCOUNT, StatusUpdates.IM_HANDLE, StatusUpdates.PROTOCOL, StatusUpdates.CUSTOM_PROTOCOL, StatusUpdates.PRESENCE, StatusUpdates.CHAT_CAPABILITY, StatusUpdates.STATUS, StatusUpdates.STATUS_TIMESTAMP, StatusUpdates.STATUS_RES_PACKAGE, StatusUpdates.STATUS_ICON, StatusUpdates.STATUS_LABEL, }); } public void testDirectoryProjection() { assertProjection(Directory.CONTENT_URI, new String[]{ Directory._ID, Directory.PACKAGE_NAME, Directory.TYPE_RESOURCE_ID, Directory.DISPLAY_NAME, Directory.DIRECTORY_AUTHORITY, Directory.ACCOUNT_TYPE, Directory.ACCOUNT_NAME, Directory.EXPORT_SUPPORT, Directory.SHORTCUT_SUPPORT, Directory.PHOTO_SUPPORT, }); } public void testRawContactsInsert() { ContentValues values = new ContentValues(); values.put(RawContacts.ACCOUNT_NAME, "a"); values.put(RawContacts.ACCOUNT_TYPE, "b"); values.put(RawContacts.DATA_SET, "ds"); values.put(RawContacts.SOURCE_ID, "c"); values.put(RawContacts.VERSION, 42); values.put(RawContacts.DIRTY, 1); values.put(RawContacts.DELETED, 1); values.put(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_DISABLED); values.put(RawContacts.CUSTOM_RINGTONE, "d"); values.put(RawContacts.SEND_TO_VOICEMAIL, 1); values.put(RawContacts.LAST_TIME_CONTACTED, 12345); values.put(RawContacts.STARRED, 1); values.put(RawContacts.SYNC1, "e"); values.put(RawContacts.SYNC2, "f"); values.put(RawContacts.SYNC3, "g"); values.put(RawContacts.SYNC4, "h"); Uri rowUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rowUri); assertStoredValues(rowUri, values); assertSelection(RawContacts.CONTENT_URI, values, RawContacts._ID, rawContactId); assertNetworkNotified(true); } public void testDataDirectoryWithLookupUri() { ContentValues values = new ContentValues(); long rawContactId = RawContactUtil.createRawContactWithName(mResolver); insertPhoneNumber(rawContactId, "555-GOOG-411"); insertEmail(rawContactId, "[email protected]"); long contactId = queryContactId(rawContactId); String lookupKey = queryLookupKey(contactId); // Complete and valid lookup URI Uri lookupUri = ContactsContract.Contacts.getLookupUri(contactId, lookupKey); Uri dataUri = Uri.withAppendedPath(lookupUri, Contacts.Data.CONTENT_DIRECTORY); assertDataRows(dataUri, values); // Complete but stale lookup URI lookupUri = ContactsContract.Contacts.getLookupUri(contactId + 1, lookupKey); dataUri = Uri.withAppendedPath(lookupUri, Contacts.Data.CONTENT_DIRECTORY); assertDataRows(dataUri, values); // Incomplete lookup URI (lookup key only, no contact ID) dataUri = Uri.withAppendedPath(Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey), Contacts.Data.CONTENT_DIRECTORY); assertDataRows(dataUri, values); } private void assertDataRows(Uri dataUri, ContentValues values) { Cursor cursor = mResolver.query(dataUri, new String[]{ Data.DATA1 }, null, null, Data._ID); assertEquals(3, cursor.getCount()); cursor.moveToFirst(); values.put(Data.DATA1, "John Doe"); assertCursorValues(cursor, values); cursor.moveToNext(); values.put(Data.DATA1, "555-GOOG-411"); assertCursorValues(cursor, values); cursor.moveToNext(); values.put(Data.DATA1, "[email protected]"); assertCursorValues(cursor, values); cursor.close(); } public void testContactEntitiesWithIdBasedUri() { ContentValues values = new ContentValues(); Account account1 = new Account("act1", "actype1"); Account account2 = new Account("act2", "actype2"); long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, account1); insertImHandle(rawContactId1, Im.PROTOCOL_GOOGLE_TALK, null, "gtalk"); insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "gtalk", StatusUpdates.IDLE, "Busy", 90, StatusUpdates.CAPABILITY_HAS_CAMERA, false); long rawContactId2 = RawContactUtil.createRawContact(mResolver, account2); setAggregationException( AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); long contactId = queryContactId(rawContactId1); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri entityUri = Uri.withAppendedPath(contactUri, Contacts.Entity.CONTENT_DIRECTORY); assertEntityRows(entityUri, contactId, rawContactId1, rawContactId2); } public void testContactEntitiesWithLookupUri() { ContentValues values = new ContentValues(); Account account1 = new Account("act1", "actype1"); Account account2 = new Account("act2", "actype2"); long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, account1); insertImHandle(rawContactId1, Im.PROTOCOL_GOOGLE_TALK, null, "gtalk"); insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "gtalk", StatusUpdates.IDLE, "Busy", 90, StatusUpdates.CAPABILITY_HAS_CAMERA, false); long rawContactId2 = RawContactUtil.createRawContact(mResolver, account2); setAggregationException( AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); long contactId = queryContactId(rawContactId1); String lookupKey = queryLookupKey(contactId); // First try with a matching contact ID Uri contactLookupUri = ContactsContract.Contacts.getLookupUri(contactId, lookupKey); Uri entityUri = Uri.withAppendedPath(contactLookupUri, Contacts.Entity.CONTENT_DIRECTORY); assertEntityRows(entityUri, contactId, rawContactId1, rawContactId2); // Now try with a contact ID mismatch contactLookupUri = ContactsContract.Contacts.getLookupUri(contactId + 1, lookupKey); entityUri = Uri.withAppendedPath(contactLookupUri, Contacts.Entity.CONTENT_DIRECTORY); assertEntityRows(entityUri, contactId, rawContactId1, rawContactId2); // Now try without an ID altogether contactLookupUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey); entityUri = Uri.withAppendedPath(contactLookupUri, Contacts.Entity.CONTENT_DIRECTORY); assertEntityRows(entityUri, contactId, rawContactId1, rawContactId2); } private void assertEntityRows(Uri entityUri, long contactId, long rawContactId1, long rawContactId2) { ContentValues values = new ContentValues(); Cursor cursor = mResolver.query(entityUri, null, null, null, Contacts.Entity.RAW_CONTACT_ID + "," + Contacts.Entity.DATA_ID); assertEquals(3, cursor.getCount()); // First row - name cursor.moveToFirst(); values.put(Contacts.Entity.CONTACT_ID, contactId); values.put(Contacts.Entity.RAW_CONTACT_ID, rawContactId1); values.put(Contacts.Entity.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE); values.put(Contacts.Entity.DATA1, "John Doe"); values.put(Contacts.Entity.ACCOUNT_NAME, "act1"); values.put(Contacts.Entity.ACCOUNT_TYPE, "actype1"); values.put(Contacts.Entity.DISPLAY_NAME, "John Doe"); values.put(Contacts.Entity.DISPLAY_NAME_ALTERNATIVE, "Doe, John"); values.put(Contacts.Entity.NAME_RAW_CONTACT_ID, rawContactId1); values.put(Contacts.Entity.CONTACT_CHAT_CAPABILITY, StatusUpdates.CAPABILITY_HAS_CAMERA); values.put(Contacts.Entity.CONTACT_PRESENCE, StatusUpdates.IDLE); values.put(Contacts.Entity.CONTACT_STATUS, "Busy"); values.putNull(Contacts.Entity.PRESENCE); assertCursorValues(cursor, values); // Second row - IM cursor.moveToNext(); values.put(Contacts.Entity.CONTACT_ID, contactId); values.put(Contacts.Entity.RAW_CONTACT_ID, rawContactId1); values.put(Contacts.Entity.MIMETYPE, Im.CONTENT_ITEM_TYPE); values.put(Contacts.Entity.DATA1, "gtalk"); values.put(Contacts.Entity.ACCOUNT_NAME, "act1"); values.put(Contacts.Entity.ACCOUNT_TYPE, "actype1"); values.put(Contacts.Entity.DISPLAY_NAME, "John Doe"); values.put(Contacts.Entity.DISPLAY_NAME_ALTERNATIVE, "Doe, John"); values.put(Contacts.Entity.NAME_RAW_CONTACT_ID, rawContactId1); values.put(Contacts.Entity.CONTACT_CHAT_CAPABILITY, StatusUpdates.CAPABILITY_HAS_CAMERA); values.put(Contacts.Entity.CONTACT_PRESENCE, StatusUpdates.IDLE); values.put(Contacts.Entity.CONTACT_STATUS, "Busy"); values.put(Contacts.Entity.PRESENCE, StatusUpdates.IDLE); assertCursorValues(cursor, values); // Third row - second raw contact, not data cursor.moveToNext(); values.put(Contacts.Entity.CONTACT_ID, contactId); values.put(Contacts.Entity.RAW_CONTACT_ID, rawContactId2); values.putNull(Contacts.Entity.MIMETYPE); values.putNull(Contacts.Entity.DATA_ID); values.putNull(Contacts.Entity.DATA1); values.put(Contacts.Entity.ACCOUNT_NAME, "act2"); values.put(Contacts.Entity.ACCOUNT_TYPE, "actype2"); values.put(Contacts.Entity.DISPLAY_NAME, "John Doe"); values.put(Contacts.Entity.DISPLAY_NAME_ALTERNATIVE, "Doe, John"); values.put(Contacts.Entity.NAME_RAW_CONTACT_ID, rawContactId1); values.put(Contacts.Entity.CONTACT_CHAT_CAPABILITY, StatusUpdates.CAPABILITY_HAS_CAMERA); values.put(Contacts.Entity.CONTACT_PRESENCE, StatusUpdates.IDLE); values.put(Contacts.Entity.CONTACT_STATUS, "Busy"); values.putNull(Contacts.Entity.PRESENCE); assertCursorValues(cursor, values); cursor.close(); } public void testDataInsert() { long rawContactId = RawContactUtil.createRawContactWithName(mResolver, "John", "Doe"); ContentValues values = new ContentValues(); putDataValues(values, rawContactId); Uri dataUri = mResolver.insert(Data.CONTENT_URI, values); long dataId = ContentUris.parseId(dataUri); long contactId = queryContactId(rawContactId); values.put(RawContacts.CONTACT_ID, contactId); assertStoredValues(dataUri, values); assertSelection(Data.CONTENT_URI, values, Data._ID, dataId); // Access the same data through the directory under RawContacts Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); Uri rawContactDataUri = Uri.withAppendedPath(rawContactUri, RawContacts.Data.CONTENT_DIRECTORY); assertSelection(rawContactDataUri, values, Data._ID, dataId); // Access the same data through the directory under Contacts Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri contactDataUri = Uri.withAppendedPath(contactUri, Contacts.Data.CONTENT_DIRECTORY); assertSelection(contactDataUri, values, Data._ID, dataId); assertNetworkNotified(true); } public void testRawContactDataQuery() { Account account1 = new Account("a", "b"); Account account2 = new Account("c", "d"); long rawContactId1 = RawContactUtil.createRawContact(mResolver, account1); Uri dataUri1 = DataUtil.insertStructuredName(mResolver, rawContactId1, "John", "Doe"); long rawContactId2 = RawContactUtil.createRawContact(mResolver, account2); Uri dataUri2 = DataUtil.insertStructuredName(mResolver, rawContactId2, "Jane", "Doe"); Uri uri1 = TestUtil.maybeAddAccountQueryParameters(dataUri1, account1); Uri uri2 = TestUtil.maybeAddAccountQueryParameters(dataUri2, account2); assertStoredValue(uri1, Data._ID, ContentUris.parseId(dataUri1)) ; assertStoredValue(uri2, Data._ID, ContentUris.parseId(dataUri2)) ; } public void testPhonesQuery() { ContentValues values = new ContentValues(); values.put(RawContacts.CUSTOM_RINGTONE, "d"); values.put(RawContacts.SEND_TO_VOICEMAIL, 1); values.put(RawContacts.LAST_TIME_CONTACTED, 12345); values.put(RawContacts.TIMES_CONTACTED, 54321); values.put(RawContacts.STARRED, 1); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); DataUtil.insertStructuredName(mResolver, rawContactId, "Meghan", "Knox"); Uri uri = insertPhoneNumber(rawContactId, "18004664411"); long phoneId = ContentUris.parseId(uri); long contactId = queryContactId(rawContactId); values.clear(); values.put(Data._ID, phoneId); values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(RawContacts.CONTACT_ID, contactId); values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); values.put(Phone.NUMBER, "18004664411"); values.put(Phone.TYPE, Phone.TYPE_HOME); values.putNull(Phone.LABEL); values.put(Contacts.DISPLAY_NAME, "Meghan Knox"); values.put(Contacts.CUSTOM_RINGTONE, "d"); values.put(Contacts.SEND_TO_VOICEMAIL, 1); values.put(Contacts.LAST_TIME_CONTACTED, 12345); values.put(Contacts.TIMES_CONTACTED, 54321); values.put(Contacts.STARRED, 1); assertStoredValues(ContentUris.withAppendedId(Phone.CONTENT_URI, phoneId), values); assertSelection(Phone.CONTENT_URI, values, Data._ID, phoneId); } public void testPhonesWithMergedContacts() { long rawContactId1 = RawContactUtil.createRawContact(mResolver); insertPhoneNumber(rawContactId1, "123456789", true); long rawContactId2 = RawContactUtil.createRawContact(mResolver); insertPhoneNumber(rawContactId2, "123456789", true); setAggregationException(AggregationExceptions.TYPE_KEEP_SEPARATE, rawContactId1, rawContactId2); assertNotAggregated(rawContactId1, rawContactId2); ContentValues values1 = new ContentValues(); values1.put(Contacts.DISPLAY_NAME, "123456789"); values1.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); values1.put(Phone.NUMBER, "123456789"); // There are two phone numbers, so we should get two rows. assertStoredValues(Phone.CONTENT_URI, new ContentValues[] {values1, values1}); // Now set the dedupe flag. But still we should get two rows, because they're two // different contacts. We only dedupe within each contact. final Uri dedupeUri = Phone.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.REMOVE_DUPLICATE_ENTRIES, "true") .build(); assertStoredValues(dedupeUri, new ContentValues[] {values1, values1}); // Now join them into a single contact. setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); assertAggregated(rawContactId1, rawContactId2, "123456789"); // Contact merge won't affect the default result of Phone Uri, where we don't dedupe. assertStoredValues(Phone.CONTENT_URI, new ContentValues[] {values1, values1}); // Now we dedupe them. assertStoredValues(dedupeUri, values1); } public void testPhonesNormalizedNumber() { final long rawContactId = RawContactUtil.createRawContact(mResolver); // Write both a number and a normalized number. Those should be written as-is final ContentValues values = new ContentValues(); values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); values.put(Phone.NUMBER, "1234"); values.put(Phone.NORMALIZED_NUMBER, "5678"); values.put(Phone.TYPE, Phone.TYPE_HOME); final Uri dataUri = mResolver.insert(Data.CONTENT_URI, values); // Check the lookup table. assertEquals(1, getCount(Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, "1234"), null, null)); assertEquals(1, getCount(Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, "5678"), null, null)); // Check the data table. assertStoredValues(dataUri, cv(Phone.NUMBER, "1234", Phone.NORMALIZED_NUMBER, "5678") ); // Replace both in an UPDATE values.clear(); values.put(Phone.NUMBER, "4321"); values.put(Phone.NORMALIZED_NUMBER, "8765"); mResolver.update(dataUri, values, null, null); assertEquals(0, getCount(Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, "1234"), null, null)); assertEquals(1, getCount(Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, "4321"), null, null)); assertEquals(0, getCount(Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, "5678"), null, null)); assertEquals(1, getCount(Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, "8765"), null, null)); assertStoredValues(dataUri, cv(Phone.NUMBER, "4321", Phone.NORMALIZED_NUMBER, "8765") ); // Replace only NUMBER ==> NORMALIZED_NUMBER will be inferred (we test that by making // sure the old manual value can not be found anymore) values.clear(); values.put(Phone.NUMBER, "+1-800-466-5432"); mResolver.update(dataUri, values, null, null); assertEquals( 1, getCount(Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, "+1-800-466-5432"), null, null)); assertEquals(0, getCount(Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, "8765"), null, null)); assertStoredValues(dataUri, cv(Phone.NUMBER, "+1-800-466-5432", Phone.NORMALIZED_NUMBER, "+18004665432") ); // Replace only NORMALIZED_NUMBER ==> call is ignored, things will be unchanged values.clear(); values.put(Phone.NORMALIZED_NUMBER, "8765"); mResolver.update(dataUri, values, null, null); assertEquals( 1, getCount(Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, "+1-800-466-5432"), null, null)); assertEquals(0, getCount(Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, "8765"), null, null)); assertStoredValues(dataUri, cv(Phone.NUMBER, "+1-800-466-5432", Phone.NORMALIZED_NUMBER, "+18004665432") ); // Replace NUMBER with an "invalid" number which can't be normalized. It should clear // NORMALIZED_NUMBER. // 1. Set 999 to NORMALIZED_NUMBER explicitly. values.clear(); values.put(Phone.NUMBER, "888"); values.put(Phone.NORMALIZED_NUMBER, "999"); mResolver.update(dataUri, values, null, null); assertEquals(1, getCount(Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, "999"), null, null)); assertStoredValues(dataUri, cv(Phone.NUMBER, "888", Phone.NORMALIZED_NUMBER, "999") ); // 2. Set an invalid number to NUMBER. values.clear(); values.put(Phone.NUMBER, "1"); mResolver.update(dataUri, values, null, null); assertEquals(0, getCount(Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, "999"), null, null)); assertStoredValues(dataUri, cv(Phone.NUMBER, "1", Phone.NORMALIZED_NUMBER, null) ); } public void testPhonesFilterQuery() { testPhonesFilterQueryInter(Phone.CONTENT_FILTER_URI); } /** * A convenient method for {@link #testPhonesFilterQuery()} and * {@link #testCallablesFilterQuery()}. * * This confirms if both URIs return identical results for phone-only contacts and * appropriately different results for contacts with sip addresses. * * @param baseFilterUri Either {@link Phone#CONTENT_FILTER_URI} or * {@link Callable#CONTENT_FILTER_URI}. */ private void testPhonesFilterQueryInter(Uri baseFilterUri) { assertTrue("Unsupported Uri (" + baseFilterUri + ")", Phone.CONTENT_FILTER_URI.equals(baseFilterUri) || Callable.CONTENT_FILTER_URI.equals(baseFilterUri)); final long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "Hot", "Tamale", TestUtil.ACCOUNT_1); insertPhoneNumber(rawContactId1, "1-800-466-4411"); final long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "Chilled", "Guacamole", TestUtil.ACCOUNT_2); insertPhoneNumber(rawContactId2, "1-800-466-5432"); insertPhoneNumber(rawContactId2, "[email protected]", false, Phone.TYPE_PAGER); insertPhoneNumber(rawContactId2, "[email protected]", false, Phone.TYPE_PAGER); final Uri filterUri1 = Uri.withAppendedPath(baseFilterUri, "tamale"); ContentValues values = new ContentValues(); values.put(Contacts.DISPLAY_NAME, "Hot Tamale"); values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); values.put(Phone.NUMBER, "1-800-466-4411"); values.put(Phone.TYPE, Phone.TYPE_HOME); values.putNull(Phone.LABEL); assertStoredValuesWithProjection(filterUri1, values); final Uri filterUri2 = Uri.withAppendedPath(baseFilterUri, "1-800-GOOG-411"); assertStoredValues(filterUri2, values); final Uri filterUri3 = Uri.withAppendedPath(baseFilterUri, "18004664"); assertStoredValues(filterUri3, values); final Uri filterUri4 = Uri.withAppendedPath(baseFilterUri, "encilada"); assertEquals(0, getCount(filterUri4, null, null)); final Uri filterUri5 = Uri.withAppendedPath(baseFilterUri, "*"); assertEquals(0, getCount(filterUri5, null, null)); ContentValues values1 = new ContentValues(); values1.put(Contacts.DISPLAY_NAME, "Chilled Guacamole"); values1.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); values1.put(Phone.NUMBER, "1-800-466-5432"); values1.put(Phone.TYPE, Phone.TYPE_HOME); values1.putNull(Phone.LABEL); ContentValues values2 = new ContentValues(); values2.put(Contacts.DISPLAY_NAME, "Chilled Guacamole"); values2.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); values2.put(Phone.NUMBER, "[email protected]"); values2.put(Phone.TYPE, Phone.TYPE_PAGER); values2.putNull(Phone.LABEL); ContentValues values3 = new ContentValues(); values3.put(Contacts.DISPLAY_NAME, "Chilled Guacamole"); values3.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); values3.put(Phone.NUMBER, "[email protected]"); values3.put(Phone.TYPE, Phone.TYPE_PAGER); values3.putNull(Phone.LABEL); final Uri filterUri6 = Uri.withAppendedPath(baseFilterUri, "Chilled"); assertStoredValues(filterUri6, new ContentValues[]{values1, values2, values3}); // Insert a SIP address. From here, Phone URI and Callable URI may return different results // than each other. insertSipAddress(rawContactId1, "[email protected]"); insertSipAddress(rawContactId1, "sip:[email protected]"); final Uri filterUri7 = Uri.withAppendedPath(baseFilterUri, "sip_hot"); final Uri filterUri8 = Uri.withAppendedPath(baseFilterUri, "sip_hot_tamale"); if (Callable.CONTENT_FILTER_URI.equals(baseFilterUri)) { ContentValues values4 = new ContentValues(); values4.put(Contacts.DISPLAY_NAME, "Hot Tamale"); values4.put(Data.MIMETYPE, SipAddress.CONTENT_ITEM_TYPE); values4.put(SipAddress.SIP_ADDRESS, "[email protected]"); ContentValues values5 = new ContentValues(); values5.put(Contacts.DISPLAY_NAME, "Hot Tamale"); values5.put(Data.MIMETYPE, SipAddress.CONTENT_ITEM_TYPE); values5.put(SipAddress.SIP_ADDRESS, "sip:[email protected]"); assertStoredValues(filterUri1, new ContentValues[] {values, values4, values5}); assertStoredValues(filterUri7, new ContentValues[] {values4, values5}); assertStoredValues(filterUri8, values4); } else { // Sip address should not affect Phone URI. assertStoredValuesWithProjection(filterUri1, values); assertEquals(0, getCount(filterUri7, null, null)); } // Sanity test. Run tests for "Chilled Guacamole" again and see nothing changes // after the Sip address being inserted. assertStoredValues(filterUri2, values); assertEquals(0, getCount(filterUri4, null, null)); assertEquals(0, getCount(filterUri5, null, null)); assertStoredValues(filterUri6, new ContentValues[] {values1, values2, values3} ); } public void testPhonesFilterSearchParams() { final long rid1 = RawContactUtil.createRawContactWithName(mResolver, "Dad", null); insertPhoneNumber(rid1, "123-456-7890"); final long rid2 = RawContactUtil.createRawContactWithName(mResolver, "Mam", null); insertPhoneNumber(rid2, "323-123-4567"); // By default, "dad" will match both the display name and the phone number. // Because "dad" is "323" after the dialpad conversion, it'll match "Mam" too. assertStoredValues( Phone.CONTENT_FILTER_URI.buildUpon().appendPath("dad").build(), cv(Phone.DISPLAY_NAME, "Dad", Phone.NUMBER, "123-456-7890"), cv(Phone.DISPLAY_NAME, "Mam", Phone.NUMBER, "323-123-4567") ); assertStoredValues( Phone.CONTENT_FILTER_URI.buildUpon().appendPath("dad") .appendQueryParameter(Phone.SEARCH_PHONE_NUMBER_KEY, "0") .build(), cv(Phone.DISPLAY_NAME, "Dad", Phone.NUMBER, "123-456-7890") ); assertStoredValues( Phone.CONTENT_FILTER_URI.buildUpon().appendPath("dad") .appendQueryParameter(Phone.SEARCH_DISPLAY_NAME_KEY, "0") .build(), cv(Phone.DISPLAY_NAME, "Mam", Phone.NUMBER, "323-123-4567") ); assertStoredValues( Phone.CONTENT_FILTER_URI.buildUpon().appendPath("dad") .appendQueryParameter(Phone.SEARCH_DISPLAY_NAME_KEY, "0") .appendQueryParameter(Phone.SEARCH_PHONE_NUMBER_KEY, "0") .build() ); } public void testPhoneLookup() { ContentValues values = new ContentValues(); values.put(RawContacts.CUSTOM_RINGTONE, "d"); values.put(RawContacts.SEND_TO_VOICEMAIL, 1); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); DataUtil.insertStructuredName(mResolver, rawContactId, "Hot", "Tamale"); insertPhoneNumber(rawContactId, "18004664411"); // We'll create two lookup records, 18004664411 and +18004664411, and the below lookup // will match both. Uri lookupUri1 = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, "8004664411"); values.clear(); values.put(PhoneLookup._ID, queryContactId(rawContactId)); values.put(PhoneLookup.DISPLAY_NAME, "Hot Tamale"); values.put(PhoneLookup.NUMBER, "18004664411"); values.put(PhoneLookup.TYPE, Phone.TYPE_HOME); values.putNull(PhoneLookup.LABEL); values.put(PhoneLookup.CUSTOM_RINGTONE, "d"); values.put(PhoneLookup.SEND_TO_VOICEMAIL, 1); assertStoredValues(lookupUri1, null, null, new ContentValues[] {values, values}); // In the context that 8004664411 is a valid number, "4664411" as a // call id should match to both "8004664411" and "+18004664411". Uri lookupUri2 = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, "4664411"); assertEquals(2, getCount(lookupUri2, null, null)); // A wrong area code 799 vs 800 should not be matched lookupUri2 = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, "7994664411"); assertEquals(0, getCount(lookupUri2, null, null)); } public void testPhoneLookupUseCases() { ContentValues values = new ContentValues(); Uri rawContactUri; long rawContactId; Uri lookupUri2; values.put(RawContacts.CUSTOM_RINGTONE, "d"); values.put(RawContacts.SEND_TO_VOICEMAIL, 1); // International format in contacts rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); rawContactId = ContentUris.parseId(rawContactUri); DataUtil.insertStructuredName(mResolver, rawContactId, "Hot", "Tamale"); insertPhoneNumber(rawContactId, "+1-650-861-0000"); values.clear(); // match with international format lookupUri2 = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, "+1 650 861 0000"); assertEquals(1, getCount(lookupUri2, null, null)); // match with national format lookupUri2 = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, "650 861 0000"); assertEquals(1, getCount(lookupUri2, null, null)); // does not match with wrong area code lookupUri2 = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, "649 861 0000"); assertEquals(0, getCount(lookupUri2, null, null)); // does not match with missing digits in mistyped area code lookupUri2 = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, "5 861 0000"); assertEquals(0, getCount(lookupUri2, null, null)); // does not match with missing digit in mistyped area code lookupUri2 = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, "65 861 0000"); assertEquals(0, getCount(lookupUri2, null, null)); // National format in contacts values.clear(); values.put(RawContacts.CUSTOM_RINGTONE, "d"); values.put(RawContacts.SEND_TO_VOICEMAIL, 1); rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); rawContactId = ContentUris.parseId(rawContactUri); DataUtil.insertStructuredName(mResolver, rawContactId, "Hot1", "Tamale"); insertPhoneNumber(rawContactId, "650-861-0001"); values.clear(); // match with international format lookupUri2 = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, "+1 650 861 0001"); assertEquals(2, getCount(lookupUri2, null, null)); // match with national format lookupUri2 = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, "650 861 0001"); assertEquals(2, getCount(lookupUri2, null, null)); // Local format in contacts values.clear(); values.put(RawContacts.CUSTOM_RINGTONE, "d"); values.put(RawContacts.SEND_TO_VOICEMAIL, 1); rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); rawContactId = ContentUris.parseId(rawContactUri); DataUtil.insertStructuredName(mResolver, rawContactId, "Hot2", "Tamale"); insertPhoneNumber(rawContactId, "861-0002"); values.clear(); // match with international format lookupUri2 = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, "+1 650 861 0002"); assertEquals(1, getCount(lookupUri2, null, null)); // match with national format lookupUri2 = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, "650 861 0002"); assertEquals(1, getCount(lookupUri2, null, null)); } public void testIntlPhoneLookupUseCases() { // Checks the logic that relies on phone_number_compare_loose(Gingerbread) as a fallback //for phone number lookups. String fullNumber = "01197297427289"; ContentValues values = new ContentValues(); values.put(RawContacts.CUSTOM_RINGTONE, "d"); values.put(RawContacts.SEND_TO_VOICEMAIL, 1); long rawContactId = ContentUris.parseId(mResolver.insert(RawContacts.CONTENT_URI, values)); DataUtil.insertStructuredName(mResolver, rawContactId, "Senor", "Chang"); insertPhoneNumber(rawContactId, fullNumber); // Full number should definitely match. assertEquals(2, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, fullNumber), null, null)); // Shorter (local) number with 0 prefix should also match. assertEquals(2, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, "097427289"), null, null)); // Number with international (+972) prefix should also match. assertEquals(1, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, "+97297427289"), null, null)); // Same shorter number with dashes should match. assertEquals(2, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, "09-742-7289"), null, null)); // Same shorter number with spaces should match. assertEquals(2, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, "09 742 7289"), null, null)); // Some other number should not match. assertEquals(0, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, "049102395"), null, null)); } public void testPhoneLookupB5252190() { // Test cases from b/5252190 String storedNumber = "796010101"; ContentValues values = new ContentValues(); values.put(RawContacts.CUSTOM_RINGTONE, "d"); values.put(RawContacts.SEND_TO_VOICEMAIL, 1); long rawContactId = ContentUris.parseId(mResolver.insert(RawContacts.CONTENT_URI, values)); DataUtil.insertStructuredName(mResolver, rawContactId, "Senor", "Chang"); insertPhoneNumber(rawContactId, storedNumber); assertEquals(1, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, "0796010101"), null, null)); assertEquals(1, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, "+48796010101"), null, null)); assertEquals(1, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, "48796010101"), null, null)); assertEquals(1, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, "4-879-601-0101"), null, null)); assertEquals(1, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, "4 879 601 0101"), null, null)); } public void testPhoneLookupUseStrictPhoneNumberCompare() { // Test lookup cases when mUseStrictPhoneNumberComparison is true final ContactsProvider2 cp = (ContactsProvider2) getProvider(); final ContactsDatabaseHelper dbHelper = cp.getThreadActiveDatabaseHelperForTest(); // Get and save the original value of mUseStrictPhoneNumberComparison so that we // can restore it when we are done with the test final boolean oldUseStrict = dbHelper.getUseStrictPhoneNumberComparisonForTest(); dbHelper.setUseStrictPhoneNumberComparisonForTest(true); try { String fullNumber = "01197297427289"; ContentValues values = new ContentValues(); values.put(RawContacts.CUSTOM_RINGTONE, "d"); values.put(RawContacts.SEND_TO_VOICEMAIL, 1); long rawContactId = ContentUris.parseId( mResolver.insert(RawContacts.CONTENT_URI, values)); DataUtil.insertStructuredName(mResolver, rawContactId, "Senor", "Chang"); insertPhoneNumber(rawContactId, fullNumber); insertPhoneNumber(rawContactId, "5103337596"); insertPhoneNumber(rawContactId, "+19012345678"); // One match for full number assertEquals(1, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, fullNumber), null, null)); // No matches for extra digit at the front assertEquals(0, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, "55103337596"), null, null)); // No matches for mispelled area code assertEquals(0, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, "5123337596"), null, null)); // One match for matching number with dashes assertEquals(1, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, "510-333-7596"), null, null)); // One match for matching number with international code assertEquals(1, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, "+1-510-333-7596"), null, null)); values.clear(); // No matches for extra 0 in front assertEquals(0, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, "0-510-333-7596"), null, null)); values.clear(); // No matches for different country code assertEquals(0, getCount(Uri.withAppendedPath( PhoneLookup.CONTENT_FILTER_URI, "+819012345678"), null, null)); values.clear(); } finally { // restore the original value of mUseStrictPhoneNumberComparison // upon test completion or failure dbHelper.setUseStrictPhoneNumberComparisonForTest(oldUseStrict); } } public void testPhoneUpdate() { ContentValues values = new ContentValues(); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); DataUtil.insertStructuredName(mResolver, rawContactId, "Hot", "Tamale"); Uri phoneUri = insertPhoneNumber(rawContactId, "18004664411"); Uri lookupUri1 = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, "8004664411"); Uri lookupUri2 = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, "8004664422"); assertEquals(2, getCount(lookupUri1, null, null)); assertEquals(0, getCount(lookupUri2, null, null)); values.clear(); values.put(Phone.NUMBER, "18004664422"); mResolver.update(phoneUri, values, null, null); assertEquals(0, getCount(lookupUri1, null, null)); assertEquals(2, getCount(lookupUri2, null, null)); // Setting number to null will remove the phone lookup record values.clear(); values.putNull(Phone.NUMBER); mResolver.update(phoneUri, values, null, null); assertEquals(0, getCount(lookupUri1, null, null)); assertEquals(0, getCount(lookupUri2, null, null)); // Let's restore that phone lookup record values.clear(); values.put(Phone.NUMBER, "18004664422"); mResolver.update(phoneUri, values, null, null); assertEquals(0, getCount(lookupUri1, null, null)); assertEquals(2, getCount(lookupUri2, null, null)); assertNetworkNotified(true); } /** Tests if {@link Callable#CONTENT_URI} returns both phones and sip addresses. */ public void testCallablesQuery() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "Meghan", "Knox"); long phoneId1 = ContentUris.parseId(insertPhoneNumber(rawContactId1, "18004664411")); long contactId1 = queryContactId(rawContactId1); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "John", "Doe"); long sipAddressId2 = ContentUris.parseId( insertSipAddress(rawContactId2, "[email protected]")); long contactId2 = queryContactId(rawContactId2); ContentValues values1 = new ContentValues(); values1.put(Data._ID, phoneId1); values1.put(Data.RAW_CONTACT_ID, rawContactId1); values1.put(RawContacts.CONTACT_ID, contactId1); values1.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); values1.put(Phone.NUMBER, "18004664411"); values1.put(Phone.TYPE, Phone.TYPE_HOME); values1.putNull(Phone.LABEL); values1.put(Contacts.DISPLAY_NAME, "Meghan Knox"); ContentValues values2 = new ContentValues(); values2.put(Data._ID, sipAddressId2); values2.put(Data.RAW_CONTACT_ID, rawContactId2); values2.put(RawContacts.CONTACT_ID, contactId2); values2.put(Data.MIMETYPE, SipAddress.CONTENT_ITEM_TYPE); values2.put(SipAddress.SIP_ADDRESS, "[email protected]"); values2.put(Contacts.DISPLAY_NAME, "John Doe"); assertEquals(2, getCount(Callable.CONTENT_URI, null, null)); assertStoredValues(Callable.CONTENT_URI, new ContentValues[] { values1, values2 }); } public void testCallablesFilterQuery() { testPhonesFilterQueryInter(Callable.CONTENT_FILTER_URI); } public void testEmailsQuery() { ContentValues values = new ContentValues(); values.put(RawContacts.CUSTOM_RINGTONE, "d"); values.put(RawContacts.SEND_TO_VOICEMAIL, 1); values.put(RawContacts.LAST_TIME_CONTACTED, 12345); values.put(RawContacts.TIMES_CONTACTED, 54321); values.put(RawContacts.STARRED, 1); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); final long rawContactId = ContentUris.parseId(rawContactUri); DataUtil.insertStructuredName(mResolver, rawContactId, "Meghan", "Knox"); final Uri emailUri = insertEmail(rawContactId, "[email protected]"); final long emailId = ContentUris.parseId(emailUri); final long contactId = queryContactId(rawContactId); values.clear(); values.put(Data._ID, emailId); values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(RawContacts.CONTACT_ID, contactId); values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE); values.put(Email.DATA, "[email protected]"); values.put(Email.TYPE, Email.TYPE_HOME); values.putNull(Email.LABEL); values.put(Contacts.DISPLAY_NAME, "Meghan Knox"); values.put(Contacts.CUSTOM_RINGTONE, "d"); values.put(Contacts.SEND_TO_VOICEMAIL, 1); values.put(Contacts.LAST_TIME_CONTACTED, 12345); values.put(Contacts.TIMES_CONTACTED, 54321); values.put(Contacts.STARRED, 1); assertStoredValues(Email.CONTENT_URI, values); assertStoredValues(ContentUris.withAppendedId(Email.CONTENT_URI, emailId), values); assertSelection(Email.CONTENT_URI, values, Data._ID, emailId); // Check if the provider detects duplicated email addresses. final Uri emailUri2 = insertEmail(rawContactId, "[email protected]"); final long emailId2 = ContentUris.parseId(emailUri2); final ContentValues values2 = new ContentValues(values); values2.put(Data._ID, emailId2); final Uri dedupeUri = Email.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.REMOVE_DUPLICATE_ENTRIES, "true") .build(); // URI with ID should return a correct result. assertStoredValues(ContentUris.withAppendedId(Email.CONTENT_URI, emailId), values); assertStoredValues(ContentUris.withAppendedId(dedupeUri, emailId), values); assertStoredValues(ContentUris.withAppendedId(Email.CONTENT_URI, emailId2), values2); assertStoredValues(ContentUris.withAppendedId(dedupeUri, emailId2), values2); assertStoredValues(Email.CONTENT_URI, new ContentValues[] {values, values2}); // If requested to remove duplicates, the query should return just one result, // whose _ID won't be deterministic. values.remove(Data._ID); assertStoredValues(dedupeUri, values); } public void testEmailsLookupQuery() { long rawContactId = RawContactUtil.createRawContactWithName(mResolver, "Hot", "Tamale"); insertEmail(rawContactId, "[email protected]"); Uri filterUri1 = Uri.withAppendedPath(Email.CONTENT_LOOKUP_URI, "[email protected]"); ContentValues values = new ContentValues(); values.put(Contacts.DISPLAY_NAME, "Hot Tamale"); values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE); values.put(Email.DATA, "[email protected]"); values.put(Email.TYPE, Email.TYPE_HOME); values.putNull(Email.LABEL); assertStoredValues(filterUri1, values); Uri filterUri2 = Uri.withAppendedPath(Email.CONTENT_LOOKUP_URI, "Ta<[email protected]>"); assertStoredValues(filterUri2, values); Uri filterUri3 = Uri.withAppendedPath(Email.CONTENT_LOOKUP_URI, "[email protected]"); assertEquals(0, getCount(filterUri3, null, null)); } public void testEmailsFilterQuery() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "Hot", "Tamale", TestUtil.ACCOUNT_1); insertEmail(rawContactId1, "[email protected]"); insertEmail(rawContactId1, "[email protected]"); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "Hot", "Tamale", TestUtil.ACCOUNT_2); insertEmail(rawContactId2, "[email protected]"); Uri filterUri1 = Uri.withAppendedPath(Email.CONTENT_FILTER_URI, "tam"); ContentValues values = new ContentValues(); values.put(Contacts.DISPLAY_NAME, "Hot Tamale"); values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE); values.put(Email.DATA, "[email protected]"); values.put(Email.TYPE, Email.TYPE_HOME); values.putNull(Email.LABEL); assertStoredValuesWithProjection(filterUri1, values); Uri filterUri2 = Uri.withAppendedPath(Email.CONTENT_FILTER_URI, "hot"); assertStoredValuesWithProjection(filterUri2, values); Uri filterUri3 = Uri.withAppendedPath(Email.CONTENT_FILTER_URI, "hot tamale"); assertStoredValuesWithProjection(filterUri3, values); Uri filterUri4 = Uri.withAppendedPath(Email.CONTENT_FILTER_URI, "tamale@acme"); assertStoredValuesWithProjection(filterUri4, values); Uri filterUri5 = Uri.withAppendedPath(Email.CONTENT_FILTER_URI, "encilada"); assertEquals(0, getCount(filterUri5, null, null)); } /** * Tests if ContactsProvider2 returns addresses according to registration order. */ public void testEmailFilterDefaultSortOrder() { long rawContactId1 = RawContactUtil.createRawContact(mResolver); insertEmail(rawContactId1, "[email protected]"); insertEmail(rawContactId1, "[email protected]"); insertEmail(rawContactId1, "[email protected]"); ContentValues v1 = new ContentValues(); v1.put(Email.ADDRESS, "[email protected]"); ContentValues v2 = new ContentValues(); v2.put(Email.ADDRESS, "[email protected]"); ContentValues v3 = new ContentValues(); v3.put(Email.ADDRESS, "[email protected]"); Uri filterUri = Uri.withAppendedPath(Email.CONTENT_FILTER_URI, "address"); assertStoredValuesOrderly(filterUri, new ContentValues[]{v1, v2, v3}); } /** * Tests if ContactsProvider2 returns primary addresses before the other addresses. */ public void testEmailFilterPrimaryAddress() { long rawContactId1 = RawContactUtil.createRawContact(mResolver); insertEmail(rawContactId1, "[email protected]"); insertEmail(rawContactId1, "[email protected]", true); ContentValues v1 = new ContentValues(); v1.put(Email.ADDRESS, "[email protected]"); ContentValues v2 = new ContentValues(); v2.put(Email.ADDRESS, "[email protected]"); Uri filterUri = Uri.withAppendedPath(Email.CONTENT_FILTER_URI, "address"); assertStoredValuesOrderly(filterUri, new ContentValues[] { v2, v1 }); } /** * Tests if ContactsProvider2 has email address associated with a primary account before the * other address. */ public void testEmailFilterPrimaryAccount() { long rawContactId1 = RawContactUtil.createRawContact(mResolver, TestUtil.ACCOUNT_1); insertEmail(rawContactId1, "[email protected]"); long rawContactId2 = RawContactUtil.createRawContact(mResolver, TestUtil.ACCOUNT_2); insertEmail(rawContactId2, "[email protected]"); ContentValues v1 = new ContentValues(); v1.put(Email.ADDRESS, "[email protected]"); ContentValues v2 = new ContentValues(); v2.put(Email.ADDRESS, "[email protected]"); Uri filterUri1 = Email.CONTENT_FILTER_URI.buildUpon().appendPath("acc") .appendQueryParameter(ContactsContract.PRIMARY_ACCOUNT_NAME, TestUtil.ACCOUNT_1.name) .appendQueryParameter(ContactsContract.PRIMARY_ACCOUNT_TYPE, TestUtil.ACCOUNT_1.type) .build(); assertStoredValuesOrderly(filterUri1, new ContentValues[] { v1, v2 }); Uri filterUri2 = Email.CONTENT_FILTER_URI.buildUpon().appendPath("acc") .appendQueryParameter(ContactsContract.PRIMARY_ACCOUNT_NAME, TestUtil.ACCOUNT_2.name) .appendQueryParameter(ContactsContract.PRIMARY_ACCOUNT_TYPE, TestUtil.ACCOUNT_2.type) .build(); assertStoredValuesOrderly(filterUri2, new ContentValues[] { v2, v1 }); // Just with PRIMARY_ACCOUNT_NAME Uri filterUri3 = Email.CONTENT_FILTER_URI.buildUpon().appendPath("acc") .appendQueryParameter(ContactsContract.PRIMARY_ACCOUNT_NAME, TestUtil.ACCOUNT_1.name) .build(); assertStoredValuesOrderly(filterUri3, new ContentValues[]{v1, v2}); Uri filterUri4 = Email.CONTENT_FILTER_URI.buildUpon().appendPath("acc") .appendQueryParameter(ContactsContract.PRIMARY_ACCOUNT_NAME, TestUtil.ACCOUNT_2.name) .build(); assertStoredValuesOrderly(filterUri4, new ContentValues[] { v2, v1 }); } /** * Test emails with the same domain as primary account are ordered first. */ public void testEmailFilterSameDomainAccountOrder() { final Account account = new Account("[email protected]", "not_used"); final long rawContactId = RawContactUtil.createRawContact(mResolver, account); insertEmail(rawContactId, "[email protected]"); insertEmail(rawContactId, "[email protected]"); final ContentValues v1 = cv(Email.ADDRESS, "[email protected]"); final ContentValues v2 = cv(Email.ADDRESS, "[email protected]"); Uri filterUri1 = Email.CONTENT_FILTER_URI.buildUpon().appendPath("acc") .appendQueryParameter(ContactsContract.PRIMARY_ACCOUNT_NAME, account.name) .appendQueryParameter(ContactsContract.PRIMARY_ACCOUNT_TYPE, account.type) .build(); assertStoredValuesOrderly(filterUri1, v2, v1); } /** * Test "default" emails are sorted above emails used last. */ public void testEmailFilterSuperPrimaryOverUsageSort() { final long rawContactId = RawContactUtil.createRawContact(mResolver, TestUtil.ACCOUNT_1); final Uri emailUri1 = insertEmail(rawContactId, "[email protected]"); final Uri emailUri2 = insertEmail(rawContactId, "[email protected]"); insertEmail(rawContactId, "[email protected]", true, true); // Update account1 and account 2 to have higher usage. updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_LONG_TEXT, emailUri1); updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_LONG_TEXT, emailUri1); updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_LONG_TEXT, emailUri2); final ContentValues v1 = cv(Email.ADDRESS, "[email protected]"); final ContentValues v2 = cv(Email.ADDRESS, "[email protected]"); final ContentValues v3 = cv(Email.ADDRESS, "[email protected]"); // Test that account 3 is first even though account 1 and 2 have higher usage. Uri filterUri = Uri.withAppendedPath(Email.CONTENT_FILTER_URI, "acc"); assertStoredValuesOrderly(filterUri, v3, v1, v2); } /** * Test primary emails are sorted below emails used last. * * primary may be set without super primary. Only super primary indicates "default" in the * contact ui. */ public void testEmailFilterUsageOverPrimarySort() { final long rawContactId = RawContactUtil.createRawContact(mResolver, TestUtil.ACCOUNT_1); final Uri emailUri1 = insertEmail(rawContactId, "[email protected]"); final Uri emailUri2 = insertEmail(rawContactId, "[email protected]"); insertEmail(rawContactId, "[email protected]", true); // Update account1 and account 2 to have higher usage. updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_LONG_TEXT, emailUri1); updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_LONG_TEXT, emailUri1); updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_LONG_TEXT, emailUri2); final ContentValues v1 = cv(Email.ADDRESS, "[email protected]"); final ContentValues v2 = cv(Email.ADDRESS, "[email protected]"); final ContentValues v3 = cv(Email.ADDRESS, "[email protected]"); // Test that account 3 is first even though account 1 and 2 have higher usage. Uri filterUri = Uri.withAppendedPath(Email.CONTENT_FILTER_URI, "acc"); assertStoredValuesOrderly(filterUri, v1, v2, v3); } /** Tests {@link DataUsageFeedback} correctly promotes a data row instead of a raw contact. */ public void testEmailFilterSortOrderWithFeedback() { long rawContactId1 = RawContactUtil.createRawContact(mResolver); String address1 = "[email protected]"; insertEmail(rawContactId1, address1); long rawContactId2 = RawContactUtil.createRawContact(mResolver); String address2 = "[email protected]"; insertEmail(rawContactId2, address2); String address3 = "[email protected]"; ContentUris.parseId(insertEmail(rawContactId2, address3)); ContentValues v1 = new ContentValues(); v1.put(Email.ADDRESS, "[email protected]"); ContentValues v2 = new ContentValues(); v2.put(Email.ADDRESS, "[email protected]"); ContentValues v3 = new ContentValues(); v3.put(Email.ADDRESS, "[email protected]"); Uri filterUri1 = Uri.withAppendedPath(Email.CONTENT_FILTER_URI, "address"); Uri filterUri2 = Email.CONTENT_FILTER_URI.buildUpon().appendPath("address") .appendQueryParameter(DataUsageFeedback.USAGE_TYPE, DataUsageFeedback.USAGE_TYPE_CALL) .build(); Uri filterUri3 = Email.CONTENT_FILTER_URI.buildUpon().appendPath("address") .appendQueryParameter(DataUsageFeedback.USAGE_TYPE, DataUsageFeedback.USAGE_TYPE_LONG_TEXT) .build(); Uri filterUri4 = Email.CONTENT_FILTER_URI.buildUpon().appendPath("address") .appendQueryParameter(DataUsageFeedback.USAGE_TYPE, DataUsageFeedback.USAGE_TYPE_SHORT_TEXT) .build(); assertStoredValuesOrderly(filterUri1, new ContentValues[] { v1, v2, v3 }); assertStoredValuesOrderly(filterUri2, new ContentValues[] { v1, v2, v3 }); assertStoredValuesOrderly(filterUri3, new ContentValues[] { v1, v2, v3 }); assertStoredValuesOrderly(filterUri4, new ContentValues[] { v1, v2, v3 }); sendFeedback(address3, DataUsageFeedback.USAGE_TYPE_LONG_TEXT, v3); assertStoredValuesWithProjection(RawContacts.CONTENT_URI, cv(RawContacts._ID, rawContactId1, RawContacts.TIMES_CONTACTED, 0 ), cv(RawContacts._ID, rawContactId2, RawContacts.TIMES_CONTACTED, 1 ) ); // [email protected] should be the first. assertStoredValuesOrderly(filterUri1, new ContentValues[] { v3, v1, v2 }); assertStoredValuesOrderly(filterUri3, new ContentValues[] { v3, v1, v2 }); } /** * Tests {@link DataUsageFeedback} correctly bucketize contacts using each * {@link DataUsageStatColumns#LAST_TIME_USED} */ public void testEmailFilterSortOrderWithOldHistory() { long rawContactId1 = RawContactUtil.createRawContact(mResolver); long dataId1 = ContentUris.parseId(insertEmail(rawContactId1, "[email protected]")); long dataId2 = ContentUris.parseId(insertEmail(rawContactId1, "[email protected]")); long dataId3 = ContentUris.parseId(insertEmail(rawContactId1, "[email protected]")); long dataId4 = ContentUris.parseId(insertEmail(rawContactId1, "[email protected]")); Uri filterUri1 = Uri.withAppendedPath(Email.CONTENT_FILTER_URI, "address"); ContentValues v1 = new ContentValues(); v1.put(Email.ADDRESS, "[email protected]"); ContentValues v2 = new ContentValues(); v2.put(Email.ADDRESS, "[email protected]"); ContentValues v3 = new ContentValues(); v3.put(Email.ADDRESS, "[email protected]"); ContentValues v4 = new ContentValues(); v4.put(Email.ADDRESS, "[email protected]"); final ContactsProvider2 provider = (ContactsProvider2) getProvider(); long nowInMillis = System.currentTimeMillis(); long yesterdayInMillis = (nowInMillis - 24 * 60 * 60 * 1000); long sevenDaysAgoInMillis = (nowInMillis - 7 * 24 * 60 * 60 * 1000); long oneYearAgoInMillis = (nowInMillis - 365L * 24 * 60 * 60 * 1000); // address4 is contacted just once yesterday. provider.updateDataUsageStat(Arrays.asList(dataId4), DataUsageFeedback.USAGE_TYPE_LONG_TEXT, yesterdayInMillis); // address3 is contacted twice 1 week ago. provider.updateDataUsageStat(Arrays.asList(dataId3), DataUsageFeedback.USAGE_TYPE_LONG_TEXT, sevenDaysAgoInMillis); provider.updateDataUsageStat(Arrays.asList(dataId3), DataUsageFeedback.USAGE_TYPE_LONG_TEXT, sevenDaysAgoInMillis); // address2 is contacted three times 1 year ago. provider.updateDataUsageStat(Arrays.asList(dataId2), DataUsageFeedback.USAGE_TYPE_LONG_TEXT, oneYearAgoInMillis); provider.updateDataUsageStat(Arrays.asList(dataId2), DataUsageFeedback.USAGE_TYPE_LONG_TEXT, oneYearAgoInMillis); provider.updateDataUsageStat(Arrays.asList(dataId2), DataUsageFeedback.USAGE_TYPE_LONG_TEXT, oneYearAgoInMillis); // auto-complete should prefer recently contacted methods assertStoredValuesOrderly(filterUri1, new ContentValues[] { v4, v3, v2, v1 }); // Pretend address2 is contacted right now provider.updateDataUsageStat(Arrays.asList(dataId2), DataUsageFeedback.USAGE_TYPE_LONG_TEXT, nowInMillis); // Now address2 is the most recently used address assertStoredValuesOrderly(filterUri1, new ContentValues[] { v2, v4, v3, v1 }); // Pretend address1 is contacted right now provider.updateDataUsageStat(Arrays.asList(dataId1), DataUsageFeedback.USAGE_TYPE_LONG_TEXT, nowInMillis); // address2 is preferred to address1 as address2 is used 4 times in total assertStoredValuesOrderly(filterUri1, new ContentValues[] { v2, v1, v4, v3 }); } public void testPostalsQuery() { long rawContactId = RawContactUtil.createRawContactWithName(mResolver, "Alice", "Nextore"); Uri dataUri = insertPostalAddress(rawContactId, "1600 Amphiteatre Ave, Mountain View"); final long dataId = ContentUris.parseId(dataUri); final long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); values.put(Data._ID, dataId); values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(RawContacts.CONTACT_ID, contactId); values.put(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE); values.put(StructuredPostal.FORMATTED_ADDRESS, "1600 Amphiteatre Ave, Mountain View"); values.put(Contacts.DISPLAY_NAME, "Alice Nextore"); assertStoredValues(StructuredPostal.CONTENT_URI, values); assertStoredValues(ContentUris.withAppendedId(StructuredPostal.CONTENT_URI, dataId), values); assertSelection(StructuredPostal.CONTENT_URI, values, Data._ID, dataId); // Check if the provider detects duplicated addresses. Uri dataUri2 = insertPostalAddress(rawContactId, "1600 Amphiteatre Ave, Mountain View"); final long dataId2 = ContentUris.parseId(dataUri2); final ContentValues values2 = new ContentValues(values); values2.put(Data._ID, dataId2); final Uri dedupeUri = StructuredPostal.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.REMOVE_DUPLICATE_ENTRIES, "true") .build(); // URI with ID should return a correct result. assertStoredValues(ContentUris.withAppendedId(StructuredPostal.CONTENT_URI, dataId), values); assertStoredValues(ContentUris.withAppendedId(dedupeUri, dataId), values); assertStoredValues(ContentUris.withAppendedId(StructuredPostal.CONTENT_URI, dataId2), values2); assertStoredValues(ContentUris.withAppendedId(dedupeUri, dataId2), values2); assertStoredValues(StructuredPostal.CONTENT_URI, new ContentValues[] {values, values2}); // If requested to remove duplicates, the query should return just one result, // whose _ID won't be deterministic. values.remove(Data._ID); assertStoredValues(dedupeUri, values); } public void testDataContentUriInvisibleQuery() { final ContentValues values = new ContentValues(); final long contactId = createContact(values, "John", "Doe", "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_CAMERA | StatusUpdates.CAPABILITY_HAS_VIDEO); final Uri uri = Data.CONTENT_URI.buildUpon(). appendQueryParameter(Data.VISIBLE_CONTACTS_ONLY, "true").build(); assertEquals(4, getCount(uri, null, null)); markInvisible(contactId); assertEquals(0, getCount(uri, null, null)); } public void testContactablesQuery() { final long rawContactId = RawContactUtil.createRawContactWithName(mResolver, "Hot", "Tamale"); insertPhoneNumber(rawContactId, "510-123-5769"); insertEmail(rawContactId, "[email protected]"); final ContentValues cv1 = new ContentValues(); cv1.put(Contacts.DISPLAY_NAME, "Hot Tamale"); cv1.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE); cv1.put(Email.DATA, "[email protected]"); cv1.put(Email.TYPE, Email.TYPE_HOME); cv1.putNull(Email.LABEL); final ContentValues cv2 = new ContentValues(); cv2.put(Contacts.DISPLAY_NAME, "Hot Tamale"); cv2.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); cv2.put(Phone.DATA, "510-123-5769"); cv2.put(Phone.TYPE, Phone.TYPE_HOME); cv2.putNull(Phone.LABEL); final Uri filterUri0 = Uri.withAppendedPath(Contactables.CONTENT_FILTER_URI, ""); assertEquals(0, getCount(filterUri0, null, null)); final Uri filterUri1 = Uri.withAppendedPath(Contactables.CONTENT_FILTER_URI, "tamale"); assertStoredValues(filterUri1, cv1, cv2); final Uri filterUri2 = Uri.withAppendedPath(Contactables.CONTENT_FILTER_URI, "hot"); assertStoredValues(filterUri2, cv1, cv2); final Uri filterUri3 = Uri.withAppendedPath(Contactables.CONTENT_FILTER_URI, "tamale@ac"); assertStoredValues(filterUri3, cv1, cv2); final Uri filterUri4 = Uri.withAppendedPath(Contactables.CONTENT_FILTER_URI, "510"); assertStoredValues(filterUri4, cv1, cv2); final Uri filterUri5 = Uri.withAppendedPath(Contactables.CONTENT_FILTER_URI, "cold"); assertEquals(0, getCount(filterUri5, null, null)); final Uri filterUri6 = Uri.withAppendedPath(Contactables.CONTENT_FILTER_URI, "tamale@google"); assertEquals(0, getCount(filterUri6, null, null)); final Uri filterUri7 = Contactables.CONTENT_URI; assertStoredValues(filterUri7, cv1, cv2); } public void testContactablesMultipleQuery() { final long rawContactId = RawContactUtil.createRawContactWithName(mResolver, "Hot", "Tamale"); insertPhoneNumber(rawContactId, "510-123-5769"); insertEmail(rawContactId, "[email protected]"); insertEmail(rawContactId, "[email protected]"); final long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "Cold", "Tamago"); insertEmail(rawContactId2, "[email protected]"); final long rawContactId3 = RawContactUtil.createRawContactWithName(mResolver, "John", "Doe"); insertPhoneNumber(rawContactId3, "518-354-1111"); insertEmail(rawContactId3, "[email protected]"); final ContentValues cv1 = new ContentValues(); cv1.put(Contacts.DISPLAY_NAME, "Hot Tamale"); cv1.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE); cv1.put(Email.DATA, "[email protected]"); cv1.put(Email.TYPE, Email.TYPE_HOME); cv1.putNull(Email.LABEL); final ContentValues cv2 = new ContentValues(); cv2.put(Contacts.DISPLAY_NAME, "Hot Tamale"); cv2.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); cv2.put(Phone.DATA, "510-123-5769"); cv2.put(Phone.TYPE, Phone.TYPE_HOME); cv2.putNull(Phone.LABEL); final ContentValues cv3 = new ContentValues(); cv3.put(Contacts.DISPLAY_NAME, "Hot Tamale"); cv3.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE); cv3.put(Email.DATA, "[email protected]"); cv3.put(Email.TYPE, Email.TYPE_HOME); cv3.putNull(Email.LABEL); final ContentValues cv4 = new ContentValues(); cv4.put(Contacts.DISPLAY_NAME, "Cold Tamago"); cv4.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE); cv4.put(Email.DATA, "[email protected]"); cv4.put(Email.TYPE, Email.TYPE_HOME); cv4.putNull(Email.LABEL); final ContentValues cv5 = new ContentValues(); cv5.put(Contacts.DISPLAY_NAME, "John Doe"); cv5.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE); cv5.put(Email.DATA, "[email protected]"); cv5.put(Email.TYPE, Email.TYPE_HOME); cv5.putNull(Email.LABEL); final ContentValues cv6 = new ContentValues(); cv6.put(Contacts.DISPLAY_NAME, "John Doe"); cv6.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); cv6.put(Phone.DATA, "518-354-1111"); cv6.put(Phone.TYPE, Phone.TYPE_HOME); cv6.putNull(Phone.LABEL); final Uri filterUri1 = Uri.withAppendedPath(Contactables.CONTENT_FILTER_URI, "tamale"); assertStoredValues(filterUri1, cv1, cv2, cv3); final Uri filterUri2 = Uri.withAppendedPath(Contactables.CONTENT_FILTER_URI, "hot"); assertStoredValues(filterUri2, cv1, cv2, cv3); final Uri filterUri3 = Uri.withAppendedPath(Contactables.CONTENT_FILTER_URI, "tam"); assertStoredValues(filterUri3, cv1, cv2, cv3, cv4); final Uri filterUri4 = Uri.withAppendedPath(Contactables.CONTENT_FILTER_URI, "518"); assertStoredValues(filterUri4, cv5, cv6); final Uri filterUri5 = Uri.withAppendedPath(Contactables.CONTENT_FILTER_URI, "doe"); assertStoredValues(filterUri5, cv5, cv6); final Uri filterUri6 = Uri.withAppendedPath(Contactables.CONTENT_FILTER_URI, "51"); assertStoredValues(filterUri6, cv1, cv2, cv3, cv5, cv6); final Uri filterUri7 = Uri.withAppendedPath(Contactables.CONTENT_FILTER_URI, "tamale@google"); assertEquals(0, getCount(filterUri7, null, null)); final Uri filterUri8 = Contactables.CONTENT_URI; assertStoredValues(filterUri8, cv1, cv2, cv3, cv4, cv5, cv6); // test VISIBLE_CONTACTS_ONLY boolean parameter final Uri filterUri9 = filterUri6.buildUpon().appendQueryParameter( Contactables.VISIBLE_CONTACTS_ONLY, "true").build(); assertStoredValues(filterUri9, cv1, cv2, cv3, cv5, cv6); // mark Hot Tamale as invisible - cv1, cv2, and cv3 should no longer be in the cursor markInvisible(queryContactId(rawContactId)); assertStoredValues(filterUri9, cv5, cv6); } public void testQueryContactData() { ContentValues values = new ContentValues(); long contactId = createContact(values, "John", "Doe", "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_CAMERA | StatusUpdates.CAPABILITY_HAS_VIDEO); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); assertStoredValues(contactUri, values); assertSelection(Contacts.CONTENT_URI, values, Contacts._ID, contactId); } public void testQueryContactWithStatusUpdate() { ContentValues values = new ContentValues(); long contactId = createContact(values, "John", "Doe", "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_CAMERA); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.INVISIBLE); values.put(Contacts.CONTACT_CHAT_CAPABILITY, StatusUpdates.CAPABILITY_HAS_CAMERA); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); assertStoredValuesWithProjection(contactUri, values); assertSelectionWithProjection(Contacts.CONTENT_URI, values, Contacts._ID, contactId); } public void testQueryContactFilterByName() { ContentValues values = new ContentValues(); long rawContactId = createRawContact(values, "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_CAMERA | StatusUpdates.CAPABILITY_HAS_VIDEO | StatusUpdates.CAPABILITY_HAS_VOICE); ContentValues nameValues = new ContentValues(); nameValues.put(StructuredName.GIVEN_NAME, "Stu"); nameValues.put(StructuredName.FAMILY_NAME, "Goulash"); nameValues.put(StructuredName.PHONETIC_FAMILY_NAME, "goo"); nameValues.put(StructuredName.PHONETIC_GIVEN_NAME, "LASH"); Uri nameUri = DataUtil.insertStructuredName(mResolver, rawContactId, nameValues); long contactId = queryContactId(rawContactId); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.INVISIBLE); Uri filterUri1 = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, "goulash"); assertStoredValuesWithProjection(filterUri1, values); assertContactFilter(contactId, "goolash"); assertContactFilter(contactId, "lash"); assertContactFilterNoResult("goolish"); // Phonetic name with given/family reversed should not match assertContactFilterNoResult("lashgoo"); nameValues.clear(); nameValues.put(StructuredName.PHONETIC_FAMILY_NAME, "ga"); nameValues.put(StructuredName.PHONETIC_GIVEN_NAME, "losh"); mResolver.update(nameUri, nameValues, null, null); assertContactFilter(contactId, "galosh"); assertContactFilterNoResult("goolish"); } public void testQueryContactFilterByEmailAddress() { ContentValues values = new ContentValues(); long rawContactId = createRawContact(values, "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_CAMERA | StatusUpdates.CAPABILITY_HAS_VIDEO | StatusUpdates.CAPABILITY_HAS_VOICE); DataUtil.insertStructuredName(mResolver, rawContactId, "James", "Bond"); long contactId = queryContactId(rawContactId); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.INVISIBLE); Uri filterUri1 = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, "[email protected]"); assertStoredValuesWithProjection(filterUri1, values); assertContactFilter(contactId, "goog"); assertContactFilter(contactId, "goog411"); assertContactFilter(contactId, "goog411@"); assertContactFilter(contactId, "goog411@acme"); assertContactFilter(contactId, "[email protected]"); assertContactFilterNoResult("[email protected]"); assertContactFilterNoResult("[email protected]"); assertContactFilterNoResult("goolish"); } public void testQueryContactFilterByPhoneNumber() { ContentValues values = new ContentValues(); long rawContactId = createRawContact(values, "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_CAMERA | StatusUpdates.CAPABILITY_HAS_VIDEO | StatusUpdates.CAPABILITY_HAS_VOICE); DataUtil.insertStructuredName(mResolver, rawContactId, "James", "Bond"); long contactId = queryContactId(rawContactId); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.INVISIBLE); Uri filterUri1 = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, "18004664411"); assertStoredValuesWithProjection(filterUri1, values); assertContactFilter(contactId, "18004664411"); assertContactFilter(contactId, "1800466"); assertContactFilter(contactId, "+18004664411"); assertContactFilter(contactId, "8004664411"); assertContactFilterNoResult("78004664411"); assertContactFilterNoResult("18004664412"); assertContactFilterNoResult("8884664411"); } /** * Checks ContactsProvider2 works well with strequent Uris. The provider should return starred * contacts and frequently used contacts. */ public void testQueryContactStrequent() { ContentValues values1 = new ContentValues(); final String email1 = "[email protected]"; final int timesContacted1 = 0; createContact(values1, "Noah", "Tever", "18004664411", email1, StatusUpdates.OFFLINE, timesContacted1, 0, 0, StatusUpdates.CAPABILITY_HAS_CAMERA | StatusUpdates.CAPABILITY_HAS_VIDEO); final String phoneNumber2 = "18004664412"; ContentValues values2 = new ContentValues(); createContact(values2, "Sam", "Times", phoneNumber2, "[email protected]", StatusUpdates.INVISIBLE, 3, 0, 0, StatusUpdates.CAPABILITY_HAS_CAMERA); ContentValues values3 = new ContentValues(); final String phoneNumber3 = "18004664413"; final int timesContacted3 = 5; createContact(values3, "Lotta", "Calling", phoneNumber3, "[email protected]", StatusUpdates.AWAY, timesContacted3, 0, 0, StatusUpdates.CAPABILITY_HAS_VIDEO); ContentValues values4 = new ContentValues(); final long rawContactId4 = createRawContact(values4, "Fay", "Veritt", null, "[email protected]", StatusUpdates.AVAILABLE, 0, 1, 0, StatusUpdates.CAPABILITY_HAS_VIDEO | StatusUpdates.CAPABILITY_HAS_VOICE); // Starred contacts should be returned. TIMES_CONTACTED should be ignored and only data // usage feedback should be used for "frequently contacted" listing. assertStoredValues(Contacts.CONTENT_STREQUENT_URI, values4); // Send feedback for the 3rd phone number, pretending we called that person via phone. sendFeedback(phoneNumber3, DataUsageFeedback.USAGE_TYPE_CALL, values3); // After the feedback, 3rd contact should be shown after starred one. assertStoredValuesOrderly(Contacts.CONTENT_STREQUENT_URI, new ContentValues[] { values4, values3 }); sendFeedback(email1, DataUsageFeedback.USAGE_TYPE_LONG_TEXT, values1); // Twice. sendFeedback(email1, DataUsageFeedback.USAGE_TYPE_LONG_TEXT, values1); // After the feedback, 1st and 3rd contacts should be shown after starred one. assertStoredValuesOrderly(Contacts.CONTENT_STREQUENT_URI, new ContentValues[] { values4, values1, values3 }); // With phone-only parameter, 1st and 4th contacts shouldn't be returned because: // 1st: feedbacks are only about email, not about phone call. // 4th: it has no phone number though starred. Uri phoneOnlyStrequentUri = Contacts.CONTENT_STREQUENT_URI.buildUpon() .appendQueryParameter(ContactsContract.STREQUENT_PHONE_ONLY, "true") .build(); assertStoredValuesOrderly(phoneOnlyStrequentUri, new ContentValues[] { values3 }); // Now the 4th contact has a phone number. insertPhoneNumber(rawContactId4, "18004664414"); // Phone only strequent should return 4th contact. assertStoredValuesOrderly(phoneOnlyStrequentUri, new ContentValues[] { values4, values3 }); // Send feedback for the 2rd phone number, pretending we send the person a SMS message. sendFeedback(phoneNumber2, DataUsageFeedback.USAGE_TYPE_SHORT_TEXT, values1); // SMS feedback shouldn't affect phone-only results. assertStoredValuesOrderly(phoneOnlyStrequentUri, new ContentValues[] { values4, values3 }); Uri filterUri = Uri.withAppendedPath(Contacts.CONTENT_STREQUENT_FILTER_URI, "fay"); assertStoredValues(filterUri, values4); } public void testQueryContactStrequentFrequentOrder() { // Prepare test data final long rid1 = RawContactUtil.createRawContact(mResolver); final long did1 = ContentUris.parseId(insertPhoneNumber(rid1, "1")); final long did1e = ContentUris.parseId(insertEmail(rid1, "[email protected]")); final long rid2 = RawContactUtil.createRawContact(mResolver); final long did2 = ContentUris.parseId(insertPhoneNumber(rid2, "2")); final long rid3 = RawContactUtil.createRawContact(mResolver); final long did3 = ContentUris.parseId(insertPhoneNumber(rid3, "3")); final long rid4 = RawContactUtil.createRawContact(mResolver); final long did4 = ContentUris.parseId(insertPhoneNumber(rid4, "4")); final long rid5 = RawContactUtil.createRawContact(mResolver); final long did5 = ContentUris.parseId(insertPhoneNumber(rid5, "5")); final long rid6 = RawContactUtil.createRawContact(mResolver); final long did6 = ContentUris.parseId(insertPhoneNumber(rid6, "6")); final long cid1 = queryContactId(rid1); final long cid2 = queryContactId(rid2); final long cid3 = queryContactId(rid3); final long cid4 = queryContactId(rid4); final long cid5 = queryContactId(rid5); final long cid6 = queryContactId(rid6); // Make sure they aren't aggregated. EvenMoreAsserts.assertUnique(cid1, cid2, cid3, cid4, cid5, cid6); // Prepare the clock sMockClock.install(); // We check the timestamp in SQL, which doesn't know about the MockClock. So we need to // use the actual (roughly) time. final long nowInMillis = System.currentTimeMillis(); final long yesterdayInMillis = (nowInMillis - 24 * 60 * 60 * 1000); final long sevenDaysAgoInMillis = (nowInMillis - 7 * 24 * 60 * 60 * 1000); final long oneYearAgoInMillis = (nowInMillis - 365L * 24 * 60 * 60 * 1000); // A year ago... sMockClock.setCurrentTimeMillis(oneYearAgoInMillis); updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_CALL, did1, did2); updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_CALL, did1); // 7 days ago... sMockClock.setCurrentTimeMillis(sevenDaysAgoInMillis); updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_CALL, did3, did4); updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_CALL, did3); // Yesterday... sMockClock.setCurrentTimeMillis(yesterdayInMillis); updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_CALL, did5, did6); updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_CALL, did5); // Contact cid1 again, but it's an email, not a phone call. updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_LONG_TEXT, did1e); // Check the order -- The regular frequent, which is contact based. // Note because we contacted cid1 yesterday, it's been contacted 3 times, so it comes // first. assertStoredValuesOrderly(Contacts.CONTENT_STREQUENT_URI, cv(Contacts._ID, cid1), cv(Contacts._ID, cid5), cv(Contacts._ID, cid6), cv(Contacts._ID, cid3), cv(Contacts._ID, cid4), cv(Contacts._ID, cid2)); // Check the order -- phone only frequent, which is data based. // Note this is based on data, and only looks at phone numbers, so the order is different // now. assertStoredValuesOrderly(Contacts.CONTENT_STREQUENT_URI.buildUpon() .appendQueryParameter(ContactsContract.STREQUENT_PHONE_ONLY, "1").build(), cv(Data._ID, did5), cv(Data._ID, did6), cv(Data._ID, did3), cv(Data._ID, did4), cv(Data._ID, did1), cv(Data._ID, did2)); } /** * Checks ContactsProvider2 works well with frequent Uri. The provider should return frequently * contacted person ordered by number of times contacted. */ public void testQueryContactFrequent() { ContentValues values1 = new ContentValues(); final String email1 = "[email protected]"; createContact(values1, "Noah", "Tever", "18004664411", email1, StatusUpdates.OFFLINE, 0, 0, 0, 0); ContentValues values2 = new ContentValues(); final String email2 = "[email protected]"; createContact(values2, "Sam", "Times", "18004664412", email2, StatusUpdates.INVISIBLE, 0, 0, 0, 0); ContentValues values3 = new ContentValues(); final String phoneNumber3 = "18004664413"; final long contactId3 = createContact(values3, "Lotta", "Calling", phoneNumber3, "[email protected]", StatusUpdates.AWAY, 0, 1, 0, 0); ContentValues values4 = new ContentValues(); createContact(values4, "Fay", "Veritt", "18004664414", "[email protected]", StatusUpdates.AVAILABLE, 0, 1, 0, 0); sendFeedback(email1, DataUsageFeedback.USAGE_TYPE_LONG_TEXT, values1); assertStoredValues(Contacts.CONTENT_FREQUENT_URI, values1); // Pretend email was sent to the address twice. sendFeedback(email2, DataUsageFeedback.USAGE_TYPE_LONG_TEXT, values2); sendFeedback(email2, DataUsageFeedback.USAGE_TYPE_LONG_TEXT, values2); assertStoredValues(Contacts.CONTENT_FREQUENT_URI, new ContentValues[] {values2, values1}); // Three times sendFeedback(phoneNumber3, DataUsageFeedback.USAGE_TYPE_CALL, values3); sendFeedback(phoneNumber3, DataUsageFeedback.USAGE_TYPE_CALL, values3); sendFeedback(phoneNumber3, DataUsageFeedback.USAGE_TYPE_CALL, values3); assertStoredValues(Contacts.CONTENT_FREQUENT_URI, new ContentValues[] {values3, values2, values1}); // Test it works with selection/selectionArgs assertStoredValues(Contacts.CONTENT_FREQUENT_URI, Contacts.STARRED + "=?", new String[] {"0"}, new ContentValues[] {values2, values1}); assertStoredValues(Contacts.CONTENT_FREQUENT_URI, Contacts.STARRED + "=?", new String[] {"1"}, new ContentValues[] {values3}); values3.put(Contacts.STARRED, 0); assertEquals(1, mResolver.update(Uri.withAppendedPath(Contacts.CONTENT_URI, String.valueOf(contactId3)), values3, null, null)); assertStoredValues(Contacts.CONTENT_FREQUENT_URI, Contacts.STARRED + "=?", new String[] {"0"}, new ContentValues[] {values3, values2, values1}); assertStoredValues(Contacts.CONTENT_FREQUENT_URI, Contacts.STARRED + "=?", new String[] {"1"}, new ContentValues[] {}); } public void testQueryContactFrequentExcludingInvisible() { ContentValues values1 = new ContentValues(); final String email1 = "[email protected]"; final long cid1 = createContact(values1, "Noah", "Tever", "18004664411", email1, StatusUpdates.OFFLINE, 0, 0, 0, 0); ContentValues values2 = new ContentValues(); final String email2 = "[email protected]"; final long cid2 = createContact(values2, "Sam", "Times", "18004664412", email2, StatusUpdates.INVISIBLE, 0, 0, 0, 0); sendFeedback(email1, DataUsageFeedback.USAGE_TYPE_LONG_TEXT, values1); sendFeedback(email2, DataUsageFeedback.USAGE_TYPE_LONG_TEXT, values2); // First, we have two contacts in frequent. assertStoredValues(Contacts.CONTENT_FREQUENT_URI, new ContentValues[] {values2, values1}); // Contact 2 goes invisible. markInvisible(cid2); // Now we have only 1 frequent. assertStoredValues(Contacts.CONTENT_FREQUENT_URI, new ContentValues[] {values1}); } public void testQueryDataUsageStat() { ContentValues values1 = new ContentValues(); final String email1 = "[email protected]"; final long cid1 = createContact(values1, "Noah", "Tever", "18004664411", email1, StatusUpdates.OFFLINE, 0, 0, 0, 0); sMockClock.install(); sMockClock.setCurrentTimeMillis(100); sendFeedback(email1, DataUsageFeedback.USAGE_TYPE_LONG_TEXT, values1); assertDataUsageCursorContains(Data.CONTENT_URI, "[email protected]", 1, 100); sMockClock.setCurrentTimeMillis(111); sendFeedback(email1, DataUsageFeedback.USAGE_TYPE_LONG_TEXT, values1); assertDataUsageCursorContains(Data.CONTENT_URI, "[email protected]", 2, 111); sMockClock.setCurrentTimeMillis(123); sendFeedback(email1, DataUsageFeedback.USAGE_TYPE_SHORT_TEXT, values1); assertDataUsageCursorContains(Data.CONTENT_URI, "[email protected]", 3, 123); final Uri dataUriWithUsageTypeLongText = Data.CONTENT_URI.buildUpon().appendQueryParameter( DataUsageFeedback.USAGE_TYPE, DataUsageFeedback.USAGE_TYPE_LONG_TEXT).build(); assertDataUsageCursorContains(dataUriWithUsageTypeLongText, "[email protected]", 2, 111); sMockClock.setCurrentTimeMillis(200); sendFeedback(email1, DataUsageFeedback.USAGE_TYPE_CALL, values1); sendFeedback(email1, DataUsageFeedback.USAGE_TYPE_CALL, values1); sendFeedback(email1, DataUsageFeedback.USAGE_TYPE_CALL, values1); assertDataUsageCursorContains(Data.CONTENT_URI, "[email protected]", 6, 200); final Uri dataUriWithUsageTypeCall = Data.CONTENT_URI.buildUpon().appendQueryParameter( DataUsageFeedback.USAGE_TYPE, DataUsageFeedback.USAGE_TYPE_CALL).build(); assertDataUsageCursorContains(dataUriWithUsageTypeCall, "[email protected]", 3, 200); } public void testQueryContactGroup() { long groupId = createGroup(null, "testGroup", "Test Group"); ContentValues values1 = new ContentValues(); createContact(values1, "Best", "West", "18004664411", "[email protected]", StatusUpdates.OFFLINE, 0, 0, groupId, StatusUpdates.CAPABILITY_HAS_CAMERA); ContentValues values2 = new ContentValues(); createContact(values2, "Rest", "East", "18004664422", "[email protected]", StatusUpdates.AVAILABLE, 0, 0, 0, StatusUpdates.CAPABILITY_HAS_VOICE); Uri filterUri1 = Uri.withAppendedPath(Contacts.CONTENT_GROUP_URI, "Test Group"); Cursor c = mResolver.query(filterUri1, null, null, null, Contacts._ID); assertEquals(1, c.getCount()); c.moveToFirst(); assertCursorValues(c, values1); c.close(); Uri filterUri2 = Uri.withAppendedPath(Contacts.CONTENT_GROUP_URI, "Test Group"); c = mResolver.query(filterUri2, null, Contacts.DISPLAY_NAME + "=?", new String[] { "Best West" }, Contacts._ID); assertEquals(1, c.getCount()); c.close(); Uri filterUri3 = Uri.withAppendedPath(Contacts.CONTENT_GROUP_URI, "Next Group"); c = mResolver.query(filterUri3, null, null, null, Contacts._ID); assertEquals(0, c.getCount()); c.close(); } private void expectSecurityException(String failureMessage, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { Cursor c = null; try { c = mResolver.query(uri, projection, selection, selectionArgs, sortOrder); fail(failureMessage); } catch (SecurityException expected) { // The security exception is expected to occur because we're missing a permission. } finally { if (c != null) { c.close(); } } } public void testQueryProfileRequiresReadPermission() { mActor.removePermissions("android.permission.READ_PROFILE"); createBasicProfileContact(new ContentValues()); // Case 1: Retrieving profile contact. expectSecurityException( "Querying for the profile without READ_PROFILE access should fail.", Profile.CONTENT_URI, null, null, null, Contacts._ID); // Case 2: Retrieving profile data. expectSecurityException( "Querying for the profile data without READ_PROFILE access should fail.", Profile.CONTENT_URI.buildUpon().appendPath("data").build(), null, null, null, Contacts._ID); // Case 3: Retrieving profile entities. expectSecurityException( "Querying for the profile entities without READ_PROFILE access should fail.", Profile.CONTENT_URI.buildUpon() .appendPath("entities").build(), null, null, null, Contacts._ID); } public void testQueryProfileByContactIdRequiresReadPermission() { long profileRawContactId = createBasicProfileContact(new ContentValues()); long profileContactId = queryContactId(profileRawContactId); mActor.removePermissions("android.permission.READ_PROFILE"); // A query for the profile contact by ID should fail. expectSecurityException( "Querying for the profile by contact ID without READ_PROFILE access should fail.", ContentUris.withAppendedId(Contacts.CONTENT_URI, profileContactId), null, null, null, Contacts._ID); } public void testQueryProfileByRawContactIdRequiresReadPermission() { long profileRawContactId = createBasicProfileContact(new ContentValues()); // Remove profile read permission and attempt to retrieve the raw contact. mActor.removePermissions("android.permission.READ_PROFILE"); expectSecurityException( "Querying for the raw contact profile without READ_PROFILE access should fail.", ContentUris.withAppendedId(RawContacts.CONTENT_URI, profileRawContactId), null, null, null, RawContacts._ID); } public void testQueryProfileRawContactRequiresReadPermission() { long profileRawContactId = createBasicProfileContact(new ContentValues()); // Remove profile read permission and attempt to retrieve the profile's raw contact data. mActor.removePermissions("android.permission.READ_PROFILE"); // Case 1: Retrieve the overall raw contact set for the profile. expectSecurityException( "Querying for the raw contact profile without READ_PROFILE access should fail.", Profile.CONTENT_RAW_CONTACTS_URI, null, null, null, null); // Case 2: Retrieve the raw contact profile data for the inserted raw contact ID. expectSecurityException( "Querying for the raw profile data without READ_PROFILE access should fail.", ContentUris.withAppendedId( Profile.CONTENT_RAW_CONTACTS_URI, profileRawContactId).buildUpon() .appendPath("data").build(), null, null, null, null); // Case 3: Retrieve the raw contact profile entity for the inserted raw contact ID. expectSecurityException( "Querying for the raw profile entities without READ_PROFILE access should fail.", ContentUris.withAppendedId( Profile.CONTENT_RAW_CONTACTS_URI, profileRawContactId).buildUpon() .appendPath("entity").build(), null, null, null, null); } public void testQueryProfileDataByDataIdRequiresReadPermission() { createBasicProfileContact(new ContentValues()); Cursor c = mResolver.query(Profile.CONTENT_URI.buildUpon().appendPath("data").build(), new String[]{Data._ID, Data.MIMETYPE}, null, null, null); assertEquals(4, c.getCount()); // Photo, phone, email, name. c.moveToFirst(); long profileDataId = c.getLong(0); c.close(); // Remove profile read permission and attempt to retrieve the data mActor.removePermissions("android.permission.READ_PROFILE"); expectSecurityException( "Querying for the data in the profile without READ_PROFILE access should fail.", ContentUris.withAppendedId(Data.CONTENT_URI, profileDataId), null, null, null, null); } public void testQueryProfileDataRequiresReadPermission() { createBasicProfileContact(new ContentValues()); // Remove profile read permission and attempt to retrieve all profile data. mActor.removePermissions("android.permission.READ_PROFILE"); expectSecurityException( "Querying for the data in the profile without READ_PROFILE access should fail.", Profile.CONTENT_URI.buildUpon().appendPath("data").build(), null, null, null, null); } public void testInsertProfileRequiresWritePermission() { mActor.removePermissions("android.permission.WRITE_PROFILE"); // Creating a non-profile contact should be fine. createBasicNonProfileContact(new ContentValues()); // Creating a profile contact should throw an exception. try { createBasicProfileContact(new ContentValues()); fail("Creating a profile contact should fail without WRITE_PROFILE access."); } catch (SecurityException expected) { } } public void testInsertProfileDataRequiresWritePermission() { long profileRawContactId = createBasicProfileContact(new ContentValues()); mActor.removePermissions("android.permission.WRITE_PROFILE"); try { insertEmail(profileRawContactId, "[email protected]", false); fail("Inserting data into a profile contact should fail without WRITE_PROFILE access."); } catch (SecurityException expected) { } } public void testUpdateDataDoesNotRequireProfilePermission() { mActor.removePermissions("android.permission.READ_PROFILE"); mActor.removePermissions("android.permission.WRITE_PROFILE"); // Create a non-profile contact. long rawContactId = RawContactUtil.createRawContactWithName(mResolver, "Domo", "Arigato"); long dataId = getStoredLongValue(Data.CONTENT_URI, Data.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + "=?", new String[]{String.valueOf(rawContactId), StructuredName.CONTENT_ITEM_TYPE}, Data._ID); // Updates its name using a selection. ContentValues values = new ContentValues(); values.put(StructuredName.GIVEN_NAME, "Bob"); values.put(StructuredName.FAMILY_NAME, "Blob"); mResolver.update(Data.CONTENT_URI, values, Data._ID + "=?", new String[]{String.valueOf(dataId)}); // Check that the update went through. assertStoredValues(ContentUris.withAppendedId(Data.CONTENT_URI, dataId), values); } public void testQueryContactThenProfile() { ContentValues profileValues = new ContentValues(); long profileRawContactId = createBasicProfileContact(profileValues); long profileContactId = queryContactId(profileRawContactId); ContentValues nonProfileValues = new ContentValues(); long nonProfileRawContactId = createBasicNonProfileContact(nonProfileValues); long nonProfileContactId = queryContactId(nonProfileRawContactId); assertStoredValues(Contacts.CONTENT_URI, nonProfileValues); assertSelection(Contacts.CONTENT_URI, nonProfileValues, Contacts._ID, nonProfileContactId); assertStoredValues(Profile.CONTENT_URI, profileValues); } public void testQueryContactExcludeProfile() { // Create a profile contact (it should not be returned by the general contact URI). createBasicProfileContact(new ContentValues()); // Create a non-profile contact - this should be returned. ContentValues nonProfileValues = new ContentValues(); createBasicNonProfileContact(nonProfileValues); assertStoredValues(Contacts.CONTENT_URI, new ContentValues[] {nonProfileValues}); } public void testQueryProfile() { ContentValues profileValues = new ContentValues(); createBasicProfileContact(profileValues); assertStoredValues(Profile.CONTENT_URI, profileValues); } private ContentValues[] getExpectedProfileDataValues() { // Expected photo data values (only field is the photo BLOB, which we can't check). ContentValues photoRow = new ContentValues(); photoRow.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); // Expected phone data values. ContentValues phoneRow = new ContentValues(); phoneRow.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); phoneRow.put(Phone.NUMBER, "18005554411"); // Expected email data values. ContentValues emailRow = new ContentValues(); emailRow.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE); emailRow.put(Email.ADDRESS, "[email protected]"); // Expected name data values. ContentValues nameRow = new ContentValues(); nameRow.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE); nameRow.put(StructuredName.DISPLAY_NAME, "Mia Prophyl"); nameRow.put(StructuredName.GIVEN_NAME, "Mia"); nameRow.put(StructuredName.FAMILY_NAME, "Prophyl"); return new ContentValues[]{photoRow, phoneRow, emailRow, nameRow}; } public void testQueryProfileData() { createBasicProfileContact(new ContentValues()); assertStoredValues(Profile.CONTENT_URI.buildUpon().appendPath("data").build(), getExpectedProfileDataValues()); } public void testQueryProfileEntities() { createBasicProfileContact(new ContentValues()); assertStoredValues(Profile.CONTENT_URI.buildUpon().appendPath("entities").build(), getExpectedProfileDataValues()); } public void testQueryRawProfile() { ContentValues profileValues = new ContentValues(); createBasicProfileContact(profileValues); // The raw contact view doesn't include the photo ID. profileValues.remove(Contacts.PHOTO_ID); assertStoredValues(Profile.CONTENT_RAW_CONTACTS_URI, profileValues); } public void testQueryRawProfileById() { ContentValues profileValues = new ContentValues(); long profileRawContactId = createBasicProfileContact(profileValues); // The raw contact view doesn't include the photo ID. profileValues.remove(Contacts.PHOTO_ID); assertStoredValues(ContentUris.withAppendedId( Profile.CONTENT_RAW_CONTACTS_URI, profileRawContactId), profileValues); } public void testQueryRawProfileData() { long profileRawContactId = createBasicProfileContact(new ContentValues()); assertStoredValues(ContentUris.withAppendedId( Profile.CONTENT_RAW_CONTACTS_URI, profileRawContactId).buildUpon() .appendPath("data").build(), getExpectedProfileDataValues()); } public void testQueryRawProfileEntity() { long profileRawContactId = createBasicProfileContact(new ContentValues()); assertStoredValues(ContentUris.withAppendedId( Profile.CONTENT_RAW_CONTACTS_URI, profileRawContactId).buildUpon() .appendPath("entity").build(), getExpectedProfileDataValues()); } public void testQueryDataForProfile() { createBasicProfileContact(new ContentValues()); assertStoredValues(Profile.CONTENT_URI.buildUpon().appendPath("data").build(), getExpectedProfileDataValues()); } public void testUpdateProfileRawContact() { createBasicProfileContact(new ContentValues()); ContentValues updatedValues = new ContentValues(); updatedValues.put(RawContacts.SEND_TO_VOICEMAIL, 0); updatedValues.put(RawContacts.CUSTOM_RINGTONE, "rachmaninoff3"); updatedValues.put(RawContacts.STARRED, 1); mResolver.update(Profile.CONTENT_RAW_CONTACTS_URI, updatedValues, null, null); assertStoredValues(Profile.CONTENT_RAW_CONTACTS_URI, updatedValues); } public void testInsertProfileWithDataSetTriggersAccountCreation() { // Check that we have no profile raw contacts. assertStoredValues(Profile.CONTENT_RAW_CONTACTS_URI, new ContentValues[]{}); // Insert a profile record with a new data set. Account account = new Account("a", "b"); String dataSet = "c"; Uri profileUri = TestUtil.maybeAddAccountQueryParameters(Profile.CONTENT_RAW_CONTACTS_URI, account) .buildUpon().appendQueryParameter(RawContacts.DATA_SET, dataSet).build(); ContentValues values = new ContentValues(); long rawContactId = ContentUris.parseId(mResolver.insert(profileUri, values)); values.put(RawContacts._ID, rawContactId); // Check that querying for the profile gets the created raw contact. assertStoredValues(Profile.CONTENT_RAW_CONTACTS_URI, values); } public void testLoadProfilePhoto() throws IOException { long rawContactId = createBasicProfileContact(new ContentValues()); insertPhoto(rawContactId, R.drawable.earth_normal); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.THUMBNAIL), Contacts.openContactPhotoInputStream(mResolver, Profile.CONTENT_URI, false)); } public void testLoadProfileDisplayPhoto() throws IOException { long rawContactId = createBasicProfileContact(new ContentValues()); insertPhoto(rawContactId, R.drawable.earth_normal); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO), Contacts.openContactPhotoInputStream(mResolver, Profile.CONTENT_URI, true)); } public void testPhonesWithStatusUpdate() { ContentValues values = new ContentValues(); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); DataUtil.insertStructuredName(mResolver, rawContactId, "John", "Doe"); Uri photoUri = insertPhoto(rawContactId); long photoId = ContentUris.parseId(photoUri); insertPhoneNumber(rawContactId, "18004664411"); insertPhoneNumber(rawContactId, "18004664412"); insertEmail(rawContactId, "[email protected]"); insertEmail(rawContactId, "[email protected]"); insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.INVISIBLE, "Bad", StatusUpdates.CAPABILITY_HAS_CAMERA); insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.AVAILABLE, "Good", StatusUpdates.CAPABILITY_HAS_CAMERA | StatusUpdates.CAPABILITY_HAS_VOICE); long contactId = queryContactId(rawContactId); Uri uri = Data.CONTENT_URI; Cursor c = mResolver.query(uri, null, RawContacts.CONTACT_ID + "=" + contactId + " AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'", null, Phone.NUMBER); assertEquals(2, c.getCount()); c.moveToFirst(); values.clear(); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.AVAILABLE); values.put(Contacts.CONTACT_STATUS, "Bad"); values.put(Contacts.DISPLAY_NAME, "John Doe"); values.put(Phone.NUMBER, "18004664411"); values.putNull(Phone.LABEL); values.put(RawContacts.CONTACT_ID, contactId); assertCursorValues(c, values); c.moveToNext(); values.clear(); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.AVAILABLE); values.put(Contacts.CONTACT_STATUS, "Bad"); values.put(Contacts.DISPLAY_NAME, "John Doe"); values.put(Phone.NUMBER, "18004664412"); values.putNull(Phone.LABEL); values.put(RawContacts.CONTACT_ID, contactId); assertCursorValues(c, values); c.close(); } public void testGroupQuery() { Account account1 = new Account("a", "b"); Account account2 = new Account("c", "d"); long groupId1 = createGroup(account1, "e", "f"); long groupId2 = createGroup(account2, "g", "h"); Uri uri1 = TestUtil.maybeAddAccountQueryParameters(Groups.CONTENT_URI, account1); Uri uri2 = TestUtil.maybeAddAccountQueryParameters(Groups.CONTENT_URI, account2); assertEquals(1, getCount(uri1, null, null)); assertEquals(1, getCount(uri2, null, null)); assertStoredValue(uri1, Groups._ID + "=" + groupId1, null, Groups._ID, groupId1) ; assertStoredValue(uri2, Groups._ID + "=" + groupId2, null, Groups._ID, groupId2) ; } public void testGroupInsert() { ContentValues values = new ContentValues(); values.put(Groups.ACCOUNT_NAME, "a"); values.put(Groups.ACCOUNT_TYPE, "b"); values.put(Groups.DATA_SET, "ds"); values.put(Groups.SOURCE_ID, "c"); values.put(Groups.VERSION, 42); values.put(Groups.GROUP_VISIBLE, 1); values.put(Groups.TITLE, "d"); values.put(Groups.TITLE_RES, 1234); values.put(Groups.NOTES, "e"); values.put(Groups.RES_PACKAGE, "f"); values.put(Groups.SYSTEM_ID, "g"); values.put(Groups.DELETED, 1); values.put(Groups.SYNC1, "h"); values.put(Groups.SYNC2, "i"); values.put(Groups.SYNC3, "j"); values.put(Groups.SYNC4, "k"); Uri rowUri = mResolver.insert(Groups.CONTENT_URI, values); values.put(Groups.DIRTY, 1); assertStoredValues(rowUri, values); } public void testGroupCreationAfterMembershipInsert() { long rawContactId1 = RawContactUtil.createRawContact(mResolver, mAccount); Uri groupMembershipUri = insertGroupMembership(rawContactId1, "gsid1"); long groupId = assertSingleGroup(NO_LONG, mAccount, "gsid1", null); assertSingleGroupMembership(ContentUris.parseId(groupMembershipUri), rawContactId1, groupId, "gsid1"); } public void testGroupReuseAfterMembershipInsert() { long rawContactId1 = RawContactUtil.createRawContact(mResolver, mAccount); long groupId1 = createGroup(mAccount, "gsid1", "title1"); Uri groupMembershipUri = insertGroupMembership(rawContactId1, "gsid1"); assertSingleGroup(groupId1, mAccount, "gsid1", "title1"); assertSingleGroupMembership(ContentUris.parseId(groupMembershipUri), rawContactId1, groupId1, "gsid1"); } public void testGroupInsertFailureOnGroupIdConflict() { long rawContactId1 = RawContactUtil.createRawContact(mResolver, mAccount); long groupId1 = createGroup(mAccount, "gsid1", "title1"); ContentValues values = new ContentValues(); values.put(GroupMembership.RAW_CONTACT_ID, rawContactId1); values.put(GroupMembership.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE); values.put(GroupMembership.GROUP_SOURCE_ID, "gsid1"); values.put(GroupMembership.GROUP_ROW_ID, groupId1); try { mResolver.insert(Data.CONTENT_URI, values); fail("the insert was expected to fail, but it succeeded"); } catch (IllegalArgumentException e) { // this was expected } } public void testGroupDelete_byAccountSelection() { final Account account1 = new Account("accountName1", "accountType1"); final Account account2 = new Account("accountName2", "accountType2"); final long groupId1 = createGroup(account1, "sourceId1", "title1"); final long groupId2 = createGroup(account2, "sourceId2", "title2"); final long groupId3 = createGroup(account2, "sourceId3", "title3"); final int numDeleted = mResolver.delete(Groups.CONTENT_URI, Groups.ACCOUNT_NAME + "=? AND " + Groups.ACCOUNT_TYPE + "=?", new String[]{account2.name, account2.type}); assertEquals(2, numDeleted); ContentValues v1 = new ContentValues(); v1.put(Groups._ID, groupId1); v1.put(Groups.DELETED, 0); ContentValues v2 = new ContentValues(); v2.put(Groups._ID, groupId2); v2.put(Groups.DELETED, 1); ContentValues v3 = new ContentValues(); v3.put(Groups._ID, groupId3); v3.put(Groups.DELETED, 1); assertStoredValues(Groups.CONTENT_URI, new ContentValues[] { v1, v2, v3 }); } public void testGroupDelete_byAccountParam() { final Account account1 = new Account("accountName1", "accountType1"); final Account account2 = new Account("accountName2", "accountType2"); final long groupId1 = createGroup(account1, "sourceId1", "title1"); final long groupId2 = createGroup(account2, "sourceId2", "title2"); final long groupId3 = createGroup(account2, "sourceId3", "title3"); final int numDeleted = mResolver.delete( Groups.CONTENT_URI.buildUpon() .appendQueryParameter(Groups.ACCOUNT_NAME, account2.name) .appendQueryParameter(Groups.ACCOUNT_TYPE, account2.type) .build(), null, null); assertEquals(2, numDeleted); ContentValues v1 = new ContentValues(); v1.put(Groups._ID, groupId1); v1.put(Groups.DELETED, 0); ContentValues v2 = new ContentValues(); v2.put(Groups._ID, groupId2); v2.put(Groups.DELETED, 1); ContentValues v3 = new ContentValues(); v3.put(Groups._ID, groupId3); v3.put(Groups.DELETED, 1); assertStoredValues(Groups.CONTENT_URI, new ContentValues[] { v1, v2, v3 }); } public void testGroupSummaryQuery() { final Account account1 = new Account("accountName1", "accountType1"); final Account account2 = new Account("accountName2", "accountType2"); final long groupId1 = createGroup(account1, "sourceId1", "title1"); final long groupId2 = createGroup(account2, "sourceId2", "title2"); final long groupId3 = createGroup(account2, "sourceId3", "title3"); // Prepare raw contact id not used at all, to test group summary uri won't be confused // with it. final long rawContactId0 = RawContactUtil.createRawContactWithName(mResolver, "firstName0", "lastName0"); final long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "firstName1", "lastName1"); insertEmail(rawContactId1, "[email protected]"); insertGroupMembership(rawContactId1, groupId1); final long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "firstName2", "lastName2"); insertEmail(rawContactId2, "[email protected]"); insertPhoneNumber(rawContactId2, "222-222-2222"); insertGroupMembership(rawContactId2, groupId1); ContentValues v1 = new ContentValues(); v1.put(Groups._ID, groupId1); v1.put(Groups.TITLE, "title1"); v1.put(Groups.SOURCE_ID, "sourceId1"); v1.put(Groups.ACCOUNT_NAME, account1.name); v1.put(Groups.ACCOUNT_TYPE, account1.type); v1.put(Groups.SUMMARY_COUNT, 2); v1.put(Groups.SUMMARY_WITH_PHONES, 1); ContentValues v2 = new ContentValues(); v2.put(Groups._ID, groupId2); v2.put(Groups.TITLE, "title2"); v2.put(Groups.SOURCE_ID, "sourceId2"); v2.put(Groups.ACCOUNT_NAME, account2.name); v2.put(Groups.ACCOUNT_TYPE, account2.type); v2.put(Groups.SUMMARY_COUNT, 0); v2.put(Groups.SUMMARY_WITH_PHONES, 0); ContentValues v3 = new ContentValues(); v3.put(Groups._ID, groupId3); v3.put(Groups.TITLE, "title3"); v3.put(Groups.SOURCE_ID, "sourceId3"); v3.put(Groups.ACCOUNT_NAME, account2.name); v3.put(Groups.ACCOUNT_TYPE, account2.type); v3.put(Groups.SUMMARY_COUNT, 0); v3.put(Groups.SUMMARY_WITH_PHONES, 0); assertStoredValues(Groups.CONTENT_SUMMARY_URI, new ContentValues[] { v1, v2, v3 }); // Now rawContactId1 has two phone numbers. insertPhoneNumber(rawContactId1, "111-111-1111"); insertPhoneNumber(rawContactId1, "111-111-1112"); // Result should reflect it correctly (don't count phone numbers but raw contacts) v1.put(Groups.SUMMARY_WITH_PHONES, v1.getAsInteger(Groups.SUMMARY_WITH_PHONES) + 1); assertStoredValues(Groups.CONTENT_SUMMARY_URI, new ContentValues[] { v1, v2, v3 }); // Introduce new raw contact, pretending the user added another info. final long rawContactId3 = RawContactUtil.createRawContactWithName(mResolver, "firstName3", "lastName3"); insertEmail(rawContactId3, "[email protected]"); insertPhoneNumber(rawContactId3, "333-333-3333"); insertGroupMembership(rawContactId3, groupId2); v2.put(Groups.SUMMARY_COUNT, v2.getAsInteger(Groups.SUMMARY_COUNT) + 1); v2.put(Groups.SUMMARY_WITH_PHONES, v2.getAsInteger(Groups.SUMMARY_WITH_PHONES) + 1); assertStoredValues(Groups.CONTENT_SUMMARY_URI, new ContentValues[] { v1, v2, v3 }); final Uri uri = Groups.CONTENT_SUMMARY_URI; // TODO Once SUMMARY_GROUP_COUNT_PER_ACCOUNT is supported remove all the if(false). if (false) { v1.put(Groups.SUMMARY_GROUP_COUNT_PER_ACCOUNT, 1); v2.put(Groups.SUMMARY_GROUP_COUNT_PER_ACCOUNT, 2); v3.put(Groups.SUMMARY_GROUP_COUNT_PER_ACCOUNT, 2); } else { v1.put(Groups.SUMMARY_GROUP_COUNT_PER_ACCOUNT, 0); v2.put(Groups.SUMMARY_GROUP_COUNT_PER_ACCOUNT, 0); v3.put(Groups.SUMMARY_GROUP_COUNT_PER_ACCOUNT, 0); } assertStoredValues(uri, new ContentValues[] { v1, v2, v3 }); // Introduce another group in account1, testing SUMMARY_GROUP_COUNT_PER_ACCOUNT correctly // reflects the change. final long groupId4 = createGroup(account1, "sourceId4", "title4"); if (false) { v1.put(Groups.SUMMARY_GROUP_COUNT_PER_ACCOUNT, v1.getAsInteger(Groups.SUMMARY_GROUP_COUNT_PER_ACCOUNT) + 1); } else { v1.put(Groups.SUMMARY_GROUP_COUNT_PER_ACCOUNT, 0); } ContentValues v4 = new ContentValues(); v4.put(Groups._ID, groupId4); v4.put(Groups.TITLE, "title4"); v4.put(Groups.SOURCE_ID, "sourceId4"); v4.put(Groups.ACCOUNT_NAME, account1.name); v4.put(Groups.ACCOUNT_TYPE, account1.type); v4.put(Groups.SUMMARY_COUNT, 0); v4.put(Groups.SUMMARY_WITH_PHONES, 0); if (false) { v4.put(Groups.SUMMARY_GROUP_COUNT_PER_ACCOUNT, v1.getAsInteger(Groups.SUMMARY_GROUP_COUNT_PER_ACCOUNT)); } else { v4.put(Groups.SUMMARY_GROUP_COUNT_PER_ACCOUNT, 0); } assertStoredValues(uri, new ContentValues[] { v1, v2, v3, v4 }); // We change the tables dynamically according to the requested projection. // Make sure the SUMMARY_COUNT column exists v1.clear(); v1.put(Groups.SUMMARY_COUNT, 2); v2.clear(); v2.put(Groups.SUMMARY_COUNT, 1); v3.clear(); v3.put(Groups.SUMMARY_COUNT, 0); v4.clear(); v4.put(Groups.SUMMARY_COUNT, 0); assertStoredValuesWithProjection(uri, new ContentValues[] { v1, v2, v3, v4 }); } public void testSettingsQuery() { Account account1 = new Account("a", "b"); Account account2 = new Account("c", "d"); AccountWithDataSet account3 = new AccountWithDataSet("e", "f", "plus"); createSettings(account1, "0", "0"); createSettings(account2, "1", "1"); createSettings(account3, "1", "0"); Uri uri1 = TestUtil.maybeAddAccountQueryParameters(Settings.CONTENT_URI, account1); Uri uri2 = TestUtil.maybeAddAccountQueryParameters(Settings.CONTENT_URI, account2); Uri uri3 = Settings.CONTENT_URI.buildUpon() .appendQueryParameter(RawContacts.ACCOUNT_NAME, account3.getAccountName()) .appendQueryParameter(RawContacts.ACCOUNT_TYPE, account3.getAccountType()) .appendQueryParameter(RawContacts.DATA_SET, account3.getDataSet()) .build(); assertEquals(1, getCount(uri1, null, null)); assertEquals(1, getCount(uri2, null, null)); assertEquals(1, getCount(uri3, null, null)); assertStoredValue(uri1, Settings.SHOULD_SYNC, "0") ; assertStoredValue(uri1, Settings.UNGROUPED_VISIBLE, "0"); assertStoredValue(uri2, Settings.SHOULD_SYNC, "1") ; assertStoredValue(uri2, Settings.UNGROUPED_VISIBLE, "1"); assertStoredValue(uri3, Settings.SHOULD_SYNC, "1"); assertStoredValue(uri3, Settings.UNGROUPED_VISIBLE, "0"); } public void testSettingsInsertionPreventsDuplicates() { Account account1 = new Account("a", "b"); AccountWithDataSet account2 = new AccountWithDataSet("c", "d", "plus"); createSettings(account1, "0", "0"); createSettings(account2, "1", "1"); // Now try creating the settings rows again. It should update the existing settings rows. createSettings(account1, "1", "0"); assertStoredValue(Settings.CONTENT_URI, Settings.ACCOUNT_NAME + "=? AND " + Settings.ACCOUNT_TYPE + "=?", new String[] {"a", "b"}, Settings.SHOULD_SYNC, "1"); createSettings(account2, "0", "1"); assertStoredValue(Settings.CONTENT_URI, Settings.ACCOUNT_NAME + "=? AND " + Settings.ACCOUNT_TYPE + "=? AND " + Settings.DATA_SET + "=?", new String[] {"c", "d", "plus"}, Settings.SHOULD_SYNC, "0"); } public void testDisplayNameParsingWhenPartsUnspecified() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = new ContentValues(); values.put(StructuredName.DISPLAY_NAME, "Mr.John Kevin von Smith, Jr."); DataUtil.insertStructuredName(mResolver, rawContactId, values); assertStructuredName(rawContactId, "Mr.", "John", "Kevin", "von Smith", "Jr."); } public void testDisplayNameParsingWhenPartsAreNull() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = new ContentValues(); values.put(StructuredName.DISPLAY_NAME, "Mr.John Kevin von Smith, Jr."); values.putNull(StructuredName.GIVEN_NAME); values.putNull(StructuredName.FAMILY_NAME); DataUtil.insertStructuredName(mResolver, rawContactId, values); assertStructuredName(rawContactId, "Mr.", "John", "Kevin", "von Smith", "Jr."); } public void testDisplayNameParsingWhenPartsSpecified() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = new ContentValues(); values.put(StructuredName.DISPLAY_NAME, "Mr.John Kevin von Smith, Jr."); values.put(StructuredName.FAMILY_NAME, "Johnson"); DataUtil.insertStructuredName(mResolver, rawContactId, values); assertStructuredName(rawContactId, null, null, null, "Johnson", null); } public void testContactWithoutPhoneticName() { ContactLocaleUtils.setLocale(Locale.ENGLISH); final long rawContactId = RawContactUtil.createRawContact(mResolver, null); ContentValues values = new ContentValues(); values.put(StructuredName.PREFIX, "Mr"); values.put(StructuredName.GIVEN_NAME, "John"); values.put(StructuredName.MIDDLE_NAME, "K."); values.put(StructuredName.FAMILY_NAME, "Doe"); values.put(StructuredName.SUFFIX, "Jr."); Uri dataUri = DataUtil.insertStructuredName(mResolver, rawContactId, values); values.clear(); values.put(RawContacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(RawContacts.DISPLAY_NAME_PRIMARY, "Mr John K. Doe, Jr."); values.put(RawContacts.DISPLAY_NAME_ALTERNATIVE, "Mr Doe, John K., Jr."); values.putNull(RawContacts.PHONETIC_NAME); values.put(RawContacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(RawContacts.SORT_KEY_PRIMARY, "John K. Doe, Jr."); values.put(RawContactsColumns.PHONEBOOK_LABEL_PRIMARY, "J"); values.put(RawContacts.SORT_KEY_ALTERNATIVE, "Doe, John K., Jr."); values.put(RawContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "D"); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); assertStoredValues(rawContactUri, values); values.clear(); values.put(Contacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(Contacts.DISPLAY_NAME_PRIMARY, "Mr John K. Doe, Jr."); values.put(Contacts.DISPLAY_NAME_ALTERNATIVE, "Mr Doe, John K., Jr."); values.putNull(Contacts.PHONETIC_NAME); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(Contacts.SORT_KEY_PRIMARY, "John K. Doe, Jr."); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "J"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "Doe, John K., Jr."); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "D"); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId)); assertStoredValues(contactUri, values); // The same values should be available through a join with Data assertStoredValues(dataUri, values); } public void testContactWithChineseName() { if (!hasChineseCollator()) { return; } ContactLocaleUtils.setLocale(Locale.SIMPLIFIED_CHINESE); long rawContactId = RawContactUtil.createRawContact(mResolver, null); ContentValues values = new ContentValues(); // "DUAN \u6BB5 XIAO \u5C0F TAO \u6D9B" values.put(StructuredName.DISPLAY_NAME, "\u6BB5\u5C0F\u6D9B"); Uri dataUri = DataUtil.insertStructuredName(mResolver, rawContactId, values); values.clear(); values.put(RawContacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(RawContacts.DISPLAY_NAME_PRIMARY, "\u6BB5\u5C0F\u6D9B"); values.put(RawContacts.DISPLAY_NAME_ALTERNATIVE, "\u6BB5\u5C0F\u6D9B"); values.putNull(RawContacts.PHONETIC_NAME); values.put(RawContacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(RawContacts.SORT_KEY_PRIMARY, "\u6BB5\u5C0F\u6D9B"); values.put(RawContactsColumns.PHONEBOOK_LABEL_PRIMARY, "D"); values.put(RawContacts.SORT_KEY_ALTERNATIVE, "\u6BB5\u5C0F\u6D9B"); values.put(RawContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "D"); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); assertStoredValues(rawContactUri, values); values.clear(); values.put(Contacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(Contacts.DISPLAY_NAME_PRIMARY, "\u6BB5\u5C0F\u6D9B"); values.put(Contacts.DISPLAY_NAME_ALTERNATIVE, "\u6BB5\u5C0F\u6D9B"); values.putNull(Contacts.PHONETIC_NAME); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(Contacts.SORT_KEY_PRIMARY, "\u6BB5\u5C0F\u6D9B"); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "D"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "\u6BB5\u5C0F\u6D9B"); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "D"); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId)); assertStoredValues(contactUri, values); // The same values should be available through a join with Data assertStoredValues(dataUri, values); } public void testJapaneseNameContactInEnglishLocale() { // Need Japanese locale data for transliteration if (!hasJapaneseCollator()) { return; } ContactLocaleUtils.setLocale(Locale.US); - long rawContactId = createRawContact(null); + long rawContactId = RawContactUtil.createRawContact(null); ContentValues values = new ContentValues(); values.put(StructuredName.GIVEN_NAME, "\u7A7A\u6D77"); values.put(StructuredName.PHONETIC_GIVEN_NAME, "\u304B\u3044\u304F\u3046"); - insertStructuredName(rawContactId, values); + DataUtil.insertStructuredName(mResolver, rawContactId, values); long contactId = queryContactId(rawContactId); // en_US should behave same as ja_JP (match on Hiragana and Romaji // but not Pinyin) assertContactFilter(contactId, "\u304B\u3044\u304F\u3046"); assertContactFilter(contactId, "kaiku"); assertContactFilterNoResult("kong"); } public void testContactWithJapaneseName() { if (!hasJapaneseCollator()) { return; } ContactLocaleUtils.setLocale(Locale.JAPAN); long rawContactId = RawContactUtil.createRawContact(mResolver, null); ContentValues values = new ContentValues(); values.put(StructuredName.GIVEN_NAME, "\u7A7A\u6D77"); values.put(StructuredName.PHONETIC_GIVEN_NAME, "\u304B\u3044\u304F\u3046"); Uri dataUri = DataUtil.insertStructuredName(mResolver, rawContactId, values); values.clear(); values.put(RawContacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(RawContacts.DISPLAY_NAME_PRIMARY, "\u7A7A\u6D77"); values.put(RawContacts.DISPLAY_NAME_ALTERNATIVE, "\u7A7A\u6D77"); values.put(RawContacts.PHONETIC_NAME, "\u304B\u3044\u304F\u3046"); values.put(RawContacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.JAPANESE); values.put(RawContacts.SORT_KEY_PRIMARY, "\u304B\u3044\u304F\u3046"); values.put(RawContacts.SORT_KEY_ALTERNATIVE, "\u304B\u3044\u304F\u3046"); values.put(RawContactsColumns.PHONEBOOK_LABEL_PRIMARY, "\u304B"); values.put(RawContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "\u304B"); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); assertStoredValues(rawContactUri, values); values.clear(); values.put(Contacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(Contacts.DISPLAY_NAME_PRIMARY, "\u7A7A\u6D77"); values.put(Contacts.DISPLAY_NAME_ALTERNATIVE, "\u7A7A\u6D77"); values.put(Contacts.PHONETIC_NAME, "\u304B\u3044\u304F\u3046"); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.JAPANESE); values.put(Contacts.SORT_KEY_PRIMARY, "\u304B\u3044\u304F\u3046"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "\u304B\u3044\u304F\u3046"); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "\u304B"); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "\u304B"); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId)); assertStoredValues(contactUri, values); // The same values should be available through a join with Data assertStoredValues(dataUri, values); long contactId = queryContactId(rawContactId); // ja_JP should match on Hiragana and Romaji but not Pinyin assertContactFilter(contactId, "\u304B\u3044\u304F\u3046"); assertContactFilter(contactId, "kaiku"); assertContactFilterNoResult("kong"); } public void testDisplayNameUpdate() { long rawContactId1 = RawContactUtil.createRawContact(mResolver); insertEmail(rawContactId1, "[email protected]", true); long rawContactId2 = RawContactUtil.createRawContact(mResolver); insertPhoneNumber(rawContactId2, "123456789", true); setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); assertAggregated(rawContactId1, rawContactId2, "123456789"); DataUtil.insertStructuredName(mResolver, rawContactId2, "Potato", "Head"); assertAggregated(rawContactId1, rawContactId2, "Potato Head"); assertNetworkNotified(true); } public void testDisplayNameFromData() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); assertStoredValue(uri, Contacts.DISPLAY_NAME, null); insertEmail(rawContactId, "[email protected]"); assertStoredValue(uri, Contacts.DISPLAY_NAME, "[email protected]"); insertEmail(rawContactId, "[email protected]", true); assertStoredValue(uri, Contacts.DISPLAY_NAME, "[email protected]"); insertPhoneNumber(rawContactId, "1-800-466-4411"); assertStoredValue(uri, Contacts.DISPLAY_NAME, "1-800-466-4411"); // If there are title and company, the company is display name. values.clear(); values.put(Organization.COMPANY, "Monsters Inc"); Uri organizationUri = insertOrganization(rawContactId, values); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Monsters Inc"); // If there is nickname, that is display name. insertNickname(rawContactId, "Sully"); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Sully"); // If there is structured name, that is display name. values.clear(); values.put(StructuredName.GIVEN_NAME, "James"); values.put(StructuredName.MIDDLE_NAME, "P."); values.put(StructuredName.FAMILY_NAME, "Sullivan"); DataUtil.insertStructuredName(mResolver, rawContactId, values); assertStoredValue(uri, Contacts.DISPLAY_NAME, "James P. Sullivan"); } public void testDisplayNameFromOrganizationWithoutPhoneticName() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); // If there is title without company, the title is display name. values.clear(); values.put(Organization.TITLE, "Protagonist"); Uri organizationUri = insertOrganization(rawContactId, values); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Protagonist"); // If there are title and company, the company is display name. values.clear(); values.put(Organization.COMPANY, "Monsters Inc"); mResolver.update(organizationUri, values, null, null); values.clear(); values.put(Contacts.DISPLAY_NAME, "Monsters Inc"); values.putNull(Contacts.PHONETIC_NAME); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(Contacts.SORT_KEY_PRIMARY, "Monsters Inc"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "Monsters Inc"); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "M"); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "M"); assertStoredValues(uri, values); } public void testDisplayNameFromOrganizationWithJapanesePhoneticName() { if (!hasJapaneseCollator()) { return; } ContactLocaleUtils.setLocale(Locale.JAPAN); long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); // If there is title without company, the title is display name. values.clear(); values.put(Organization.COMPANY, "DoCoMo"); values.put(Organization.PHONETIC_NAME, "\u30C9\u30B3\u30E2"); Uri organizationUri = insertOrganization(rawContactId, values); values.clear(); values.put(Contacts.DISPLAY_NAME, "DoCoMo"); values.put(Contacts.PHONETIC_NAME, "\u30C9\u30B3\u30E2"); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.JAPANESE); values.put(Contacts.SORT_KEY_PRIMARY, "\u30C9\u30B3\u30E2"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "\u30C9\u30B3\u30E2"); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "\u305F"); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "\u305F"); assertStoredValues(uri, values); } public void testDisplayNameFromOrganizationWithChineseName() { if (!hasChineseCollator()) { return; } ContactLocaleUtils.setLocale(Locale.SIMPLIFIED_CHINESE); long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); // If there is title without company, the title is display name. values.clear(); values.put(Organization.COMPANY, "\u4E2D\u56FD\u7535\u4FE1"); Uri organizationUri = insertOrganization(rawContactId, values); values.clear(); values.put(Contacts.DISPLAY_NAME, "\u4E2D\u56FD\u7535\u4FE1"); values.putNull(Contacts.PHONETIC_NAME); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(Contacts.SORT_KEY_PRIMARY, "\u4E2D\u56FD\u7535\u4FE1"); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "Z"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "\u4E2D\u56FD\u7535\u4FE1"); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "Z"); assertStoredValues(uri, values); } public void testLookupByOrganization() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); values.clear(); values.put(Organization.COMPANY, "acmecorp"); values.put(Organization.TITLE, "president"); Uri organizationUri = insertOrganization(rawContactId, values); assertContactFilter(contactId, "acmecorp"); assertContactFilter(contactId, "president"); values.clear(); values.put(Organization.DEPARTMENT, "software"); mResolver.update(organizationUri, values, null, null); assertContactFilter(contactId, "acmecorp"); assertContactFilter(contactId, "president"); values.clear(); values.put(Organization.COMPANY, "incredibles"); mResolver.update(organizationUri, values, null, null); assertContactFilter(contactId, "incredibles"); assertContactFilter(contactId, "president"); values.clear(); values.put(Organization.TITLE, "director"); mResolver.update(organizationUri, values, null, null); assertContactFilter(contactId, "incredibles"); assertContactFilter(contactId, "director"); values.clear(); values.put(Organization.COMPANY, "monsters"); values.put(Organization.TITLE, "scarer"); mResolver.update(organizationUri, values, null, null); assertContactFilter(contactId, "monsters"); assertContactFilter(contactId, "scarer"); } private void assertContactFilter(long contactId, String filter) { Uri filterUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode(filter)); assertStoredValue(filterUri, Contacts._ID, contactId); } private void assertContactFilterNoResult(String filter) { Uri filterUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode(filter)); assertEquals(0, getCount(filterUri, null, null)); } public void testSearchSnippetOrganization() throws Exception { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); // Some random data element insertEmail(rawContactId, "[email protected]"); ContentValues values = new ContentValues(); values.clear(); values.put(Organization.COMPANY, "acmecorp"); values.put(Organization.TITLE, "engineer"); Uri organizationUri = insertOrganization(rawContactId, values); // Add another matching organization values.put(Organization.COMPANY, "acmeinc"); insertOrganization(rawContactId, values); // Add another non-matching organization values.put(Organization.COMPANY, "corpacme"); insertOrganization(rawContactId, values); // And another data element insertEmail(rawContactId, "[email protected]", true, Email.TYPE_CUSTOM, "Custom"); Uri filterUri = buildFilterUri("acme", true); values.clear(); values.put(Contacts._ID, contactId); values.put(SearchSnippetColumns.SNIPPET, "engineer, [acmecorp]"); assertStoredValues(filterUri, values); } public void testSearchSnippetEmail() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); DataUtil.insertStructuredName(mResolver, rawContactId, "John", "Doe"); Uri dataUri = insertEmail(rawContactId, "[email protected]", true, Email.TYPE_CUSTOM, "Custom"); Uri filterUri = buildFilterUri("acme", true); values.clear(); values.put(Contacts._ID, contactId); values.put(SearchSnippetColumns.SNIPPET, "[[email protected]]"); assertStoredValues(filterUri, values); } public void testCountPhoneNumberDigits() { assertEquals(10, ContactsProvider2.countPhoneNumberDigits("86 (0) 5-55-12-34")); assertEquals(10, ContactsProvider2.countPhoneNumberDigits("860 555-1234")); assertEquals(3, ContactsProvider2.countPhoneNumberDigits("860")); assertEquals(10, ContactsProvider2.countPhoneNumberDigits("8605551234")); assertEquals(6, ContactsProvider2.countPhoneNumberDigits("860555")); assertEquals(6, ContactsProvider2.countPhoneNumberDigits("860 555")); assertEquals(6, ContactsProvider2.countPhoneNumberDigits("860-555")); assertEquals(12, ContactsProvider2.countPhoneNumberDigits("+441234098765")); assertEquals(0, ContactsProvider2.countPhoneNumberDigits("44+1234098765")); assertEquals(0, ContactsProvider2.countPhoneNumberDigits("+441234098foo")); } public void testSearchSnippetPhone() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); DataUtil.insertStructuredName(mResolver, rawContactId, "Cave", "Johnson"); insertPhoneNumber(rawContactId, "(860) 555-1234"); values.clear(); values.put(Contacts._ID, contactId); values.put(SearchSnippetColumns.SNIPPET, "[(860) 555-1234]"); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("86 (0) 5-55-12-34")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("860 555-1234")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("860")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("8605551234")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("860555")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("860 555")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("860-555")), values); } private Uri buildFilterUri(String query, boolean deferredSnippeting) { Uri.Builder builder = Contacts.CONTENT_FILTER_URI.buildUpon() .appendPath(Uri.encode(query)); if (deferredSnippeting) { builder.appendQueryParameter(ContactsContract.DEFERRED_SNIPPETING, "1"); } return builder.build(); } public void testSearchSnippetNickname() throws Exception { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); Uri dataUri = insertNickname(rawContactId, "Incredible"); Uri filterUri = buildFilterUri("inc", true); values.clear(); values.put(Contacts._ID, contactId); values.put(SearchSnippetColumns.SNIPPET, "[Incredible]"); assertStoredValues(filterUri, values); } public void testSearchSnippetEmptyForNameInDisplayName() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); DataUtil.insertStructuredName(mResolver, rawContactId, "Cave", "Johnson"); insertEmail(rawContactId, "[email protected]", true); ContentValues emptySnippet = new ContentValues(); emptySnippet.clear(); emptySnippet.put(Contacts._ID, contactId); emptySnippet.put(SearchSnippetColumns.SNIPPET, (String) null); assertStoredValues(buildFilterUri("cave", true), emptySnippet); assertStoredValues(buildFilterUri("john", true), emptySnippet); } public void testSearchSnippetEmptyForNicknameInDisplayName() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); insertNickname(rawContactId, "Caveman"); insertEmail(rawContactId, "[email protected]", true); ContentValues emptySnippet = new ContentValues(); emptySnippet.clear(); emptySnippet.put(Contacts._ID, contactId); emptySnippet.put(SearchSnippetColumns.SNIPPET, (String) null); assertStoredValues(buildFilterUri("cave", true), emptySnippet); } public void testSearchSnippetEmptyForCompanyInDisplayName() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues company = new ContentValues(); company.clear(); company.put(Organization.COMPANY, "Aperture Science"); company.put(Organization.TITLE, "President"); insertOrganization(rawContactId, company); insertEmail(rawContactId, "[email protected]", true); ContentValues emptySnippet = new ContentValues(); emptySnippet.clear(); emptySnippet.put(Contacts._ID, contactId); emptySnippet.put(SearchSnippetColumns.SNIPPET, (String) null); assertStoredValues(buildFilterUri("aperture", true), emptySnippet); } public void testSearchSnippetEmptyForPhoneInDisplayName() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); insertPhoneNumber(rawContactId, "860-555-1234"); insertEmail(rawContactId, "[email protected]", true); ContentValues emptySnippet = new ContentValues(); emptySnippet.clear(); emptySnippet.put(Contacts._ID, contactId); emptySnippet.put(SearchSnippetColumns.SNIPPET, (String) null); assertStoredValues(buildFilterUri("860", true), emptySnippet); } public void testSearchSnippetEmptyForEmailInDisplayName() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); insertEmail(rawContactId, "[email protected]", true); insertNote(rawContactId, "Cave Johnson is president of Aperture Science"); ContentValues emptySnippet = new ContentValues(); emptySnippet.clear(); emptySnippet.put(Contacts._ID, contactId); emptySnippet.put(SearchSnippetColumns.SNIPPET, (String) null); assertStoredValues(buildFilterUri("cave", true), emptySnippet); } public void testDisplayNameUpdateFromStructuredNameUpdate() { long rawContactId = RawContactUtil.createRawContact(mResolver); Uri nameUri = DataUtil.insertStructuredName(mResolver, rawContactId, "Slinky", "Dog"); long contactId = queryContactId(rawContactId); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Slinky Dog"); ContentValues values = new ContentValues(); values.putNull(StructuredName.FAMILY_NAME); mResolver.update(nameUri, values, null, null); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Slinky"); values.putNull(StructuredName.GIVEN_NAME); mResolver.update(nameUri, values, null, null); assertStoredValue(uri, Contacts.DISPLAY_NAME, null); values.put(StructuredName.FAMILY_NAME, "Dog"); mResolver.update(nameUri, values, null, null); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Dog"); } public void testInsertDataWithContentProviderOperations() throws Exception { ContentProviderOperation cpo1 = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI) .withValues(new ContentValues()) .build(); ContentProviderOperation cpo2 = ContentProviderOperation.newInsert(Data.CONTENT_URI) .withValueBackReference(Data.RAW_CONTACT_ID, 0) .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE) .withValue(StructuredName.GIVEN_NAME, "John") .withValue(StructuredName.FAMILY_NAME, "Doe") .build(); ContentProviderResult[] results = mResolver.applyBatch(ContactsContract.AUTHORITY, Lists.newArrayList(cpo1, cpo2)); long contactId = queryContactId(ContentUris.parseId(results[0].uri)); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); assertStoredValue(uri, Contacts.DISPLAY_NAME, "John Doe"); } public void testSendToVoicemailDefault() { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); Cursor c = queryContact(contactId); assertTrue(c.moveToNext()); int sendToVoicemail = c.getInt(c.getColumnIndex(Contacts.SEND_TO_VOICEMAIL)); assertEquals(0, sendToVoicemail); c.close(); } public void testSetSendToVoicemailAndRingtone() { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); updateSendToVoicemailAndRingtone(contactId, true, "foo"); assertSendToVoicemailAndRingtone(contactId, true, "foo"); assertNetworkNotified(false); updateSendToVoicemailAndRingtoneWithSelection(contactId, false, "bar"); assertSendToVoicemailAndRingtone(contactId, false, "bar"); assertNetworkNotified(false); } public void testSendToVoicemailAndRingtoneAfterAggregation() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "a", "b"); long contactId1 = queryContactId(rawContactId1); updateSendToVoicemailAndRingtone(contactId1, true, "foo"); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "c", "d"); long contactId2 = queryContactId(rawContactId2); updateSendToVoicemailAndRingtone(contactId2, true, "bar"); // Aggregate them setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); // Both contacts had "send to VM", the contact now has the same value assertSendToVoicemailAndRingtone(contactId1, true, "foo,bar"); // Either foo or bar } public void testDoNotSendToVoicemailAfterAggregation() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "e", "f"); long contactId1 = queryContactId(rawContactId1); updateSendToVoicemailAndRingtone(contactId1, true, null); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "g", "h"); long contactId2 = queryContactId(rawContactId2); updateSendToVoicemailAndRingtone(contactId2, false, null); // Aggregate them setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); // Since one of the contacts had "don't send to VM" that setting wins for the aggregate assertSendToVoicemailAndRingtone(queryContactId(rawContactId1), false, null); } public void testSetSendToVoicemailAndRingtonePreservedAfterJoinAndSplit() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "i", "j"); long contactId1 = queryContactId(rawContactId1); updateSendToVoicemailAndRingtone(contactId1, true, "foo"); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "k", "l"); long contactId2 = queryContactId(rawContactId2); updateSendToVoicemailAndRingtone(contactId2, false, "bar"); // Aggregate them setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); // Split them setAggregationException(AggregationExceptions.TYPE_KEEP_SEPARATE, rawContactId1, rawContactId2); assertSendToVoicemailAndRingtone(queryContactId(rawContactId1), true, "foo"); assertSendToVoicemailAndRingtone(queryContactId(rawContactId2), false, "bar"); } public void testStatusUpdateInsert() { long rawContactId = RawContactUtil.createRawContact(mResolver); Uri imUri = insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); long dataId = ContentUris.parseId(imUri); ContentValues values = new ContentValues(); values.put(StatusUpdates.DATA_ID, dataId); values.put(StatusUpdates.PROTOCOL, Im.PROTOCOL_AIM); values.putNull(StatusUpdates.CUSTOM_PROTOCOL); values.put(StatusUpdates.IM_HANDLE, "aim"); values.put(StatusUpdates.PRESENCE, StatusUpdates.INVISIBLE); values.put(StatusUpdates.STATUS, "Hiding"); values.put(StatusUpdates.STATUS_TIMESTAMP, 100); values.put(StatusUpdates.STATUS_RES_PACKAGE, "a.b.c"); values.put(StatusUpdates.STATUS_ICON, 1234); values.put(StatusUpdates.STATUS_LABEL, 2345); Uri resultUri = mResolver.insert(StatusUpdates.CONTENT_URI, values); assertStoredValues(resultUri, values); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); values.clear(); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.INVISIBLE); values.put(Contacts.CONTACT_STATUS, "Hiding"); values.put(Contacts.CONTACT_STATUS_TIMESTAMP, 100); values.put(Contacts.CONTACT_STATUS_RES_PACKAGE, "a.b.c"); values.put(Contacts.CONTACT_STATUS_ICON, 1234); values.put(Contacts.CONTACT_STATUS_LABEL, 2345); assertStoredValues(contactUri, values); values.clear(); values.put(StatusUpdates.DATA_ID, dataId); values.put(StatusUpdates.STATUS, "Cloaked"); values.put(StatusUpdates.STATUS_TIMESTAMP, 200); values.put(StatusUpdates.STATUS_RES_PACKAGE, "d.e.f"); values.put(StatusUpdates.STATUS_ICON, 4321); values.put(StatusUpdates.STATUS_LABEL, 5432); mResolver.insert(StatusUpdates.CONTENT_URI, values); values.clear(); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.INVISIBLE); values.put(Contacts.CONTACT_STATUS, "Cloaked"); values.put(Contacts.CONTACT_STATUS_TIMESTAMP, 200); values.put(Contacts.CONTACT_STATUS_RES_PACKAGE, "d.e.f"); values.put(Contacts.CONTACT_STATUS_ICON, 4321); values.put(Contacts.CONTACT_STATUS_LABEL, 5432); assertStoredValues(contactUri, values); } public void testStatusUpdateInferAttribution() { long rawContactId = RawContactUtil.createRawContact(mResolver); Uri imUri = insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); long dataId = ContentUris.parseId(imUri); ContentValues values = new ContentValues(); values.put(StatusUpdates.DATA_ID, dataId); values.put(StatusUpdates.PROTOCOL, Im.PROTOCOL_AIM); values.put(StatusUpdates.IM_HANDLE, "aim"); values.put(StatusUpdates.STATUS, "Hiding"); Uri resultUri = mResolver.insert(StatusUpdates.CONTENT_URI, values); values.clear(); values.put(StatusUpdates.DATA_ID, dataId); values.put(StatusUpdates.STATUS_LABEL, com.android.internal.R.string.imProtocolAim); values.put(StatusUpdates.STATUS, "Hiding"); assertStoredValues(resultUri, values); } public void testStatusUpdateMatchingImOrEmail() { long rawContactId = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); insertImHandle(rawContactId, Im.PROTOCOL_CUSTOM, "my_im_proto", "my_im"); insertEmail(rawContactId, "[email protected]"); // Match on IM (standard) insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", StatusUpdates.AVAILABLE, "Available", StatusUpdates.CAPABILITY_HAS_CAMERA); // Match on IM (custom) insertStatusUpdate(Im.PROTOCOL_CUSTOM, "my_im_proto", "my_im", StatusUpdates.IDLE, "Idle", StatusUpdates.CAPABILITY_HAS_CAMERA | StatusUpdates.CAPABILITY_HAS_VIDEO); // Match on Email insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.AWAY, "Away", StatusUpdates.CAPABILITY_HAS_VOICE); // No match insertStatusUpdate(Im.PROTOCOL_ICQ, null, "12345", StatusUpdates.DO_NOT_DISTURB, "Go away", StatusUpdates.CAPABILITY_HAS_CAMERA); Cursor c = mResolver.query(StatusUpdates.CONTENT_URI, new String[] { StatusUpdates.DATA_ID, StatusUpdates.PROTOCOL, StatusUpdates.CUSTOM_PROTOCOL, StatusUpdates.PRESENCE, StatusUpdates.STATUS}, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId, null, StatusUpdates.DATA_ID); assertTrue(c.moveToNext()); assertStatusUpdate(c, Im.PROTOCOL_AIM, null, StatusUpdates.AVAILABLE, "Available"); assertTrue(c.moveToNext()); assertStatusUpdate(c, Im.PROTOCOL_CUSTOM, "my_im_proto", StatusUpdates.IDLE, "Idle"); assertTrue(c.moveToNext()); assertStatusUpdate(c, Im.PROTOCOL_GOOGLE_TALK, null, StatusUpdates.AWAY, "Away"); assertFalse(c.moveToNext()); c.close(); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); ContentValues values = new ContentValues(); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.AVAILABLE); values.put(Contacts.CONTACT_STATUS, "Available"); assertStoredValuesWithProjection(contactUri, values); } public void testStatusUpdateUpdateAndDelete() { long rawContactId = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); ContentValues values = new ContentValues(); values.putNull(Contacts.CONTACT_PRESENCE); values.putNull(Contacts.CONTACT_STATUS); assertStoredValuesWithProjection(contactUri, values); insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", StatusUpdates.AWAY, "BUSY", StatusUpdates.CAPABILITY_HAS_CAMERA); insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", StatusUpdates.DO_NOT_DISTURB, "GO AWAY", StatusUpdates.CAPABILITY_HAS_CAMERA); Uri statusUri = insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", StatusUpdates.AVAILABLE, "Available", StatusUpdates.CAPABILITY_HAS_CAMERA); long statusId = ContentUris.parseId(statusUri); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.AVAILABLE); values.put(Contacts.CONTACT_STATUS, "Available"); assertStoredValuesWithProjection(contactUri, values); // update status_updates table to set new values for // status_updates.status // status_updates.status_ts // presence long updatedTs = 200; String testUpdate = "test_update"; String selection = StatusUpdates.DATA_ID + "=" + statusId; values.clear(); values.put(StatusUpdates.STATUS_TIMESTAMP, updatedTs); values.put(StatusUpdates.STATUS, testUpdate); values.put(StatusUpdates.PRESENCE, "presence_test"); mResolver.update(StatusUpdates.CONTENT_URI, values, StatusUpdates.DATA_ID + "=" + statusId, null); assertStoredValuesWithProjection(StatusUpdates.CONTENT_URI, values); // update status_updates table to set new values for columns in status_updates table ONLY // i.e., no rows in presence table are to be updated. updatedTs = 300; testUpdate = "test_update_new"; selection = StatusUpdates.DATA_ID + "=" + statusId; values.clear(); values.put(StatusUpdates.STATUS_TIMESTAMP, updatedTs); values.put(StatusUpdates.STATUS, testUpdate); mResolver.update(StatusUpdates.CONTENT_URI, values, StatusUpdates.DATA_ID + "=" + statusId, null); // make sure the presence column value is still the old value values.put(StatusUpdates.PRESENCE, "presence_test"); assertStoredValuesWithProjection(StatusUpdates.CONTENT_URI, values); // update status_updates table to set new values for columns in presence table ONLY // i.e., no rows in status_updates table are to be updated. selection = StatusUpdates.DATA_ID + "=" + statusId; values.clear(); values.put(StatusUpdates.PRESENCE, "presence_test_new"); mResolver.update(StatusUpdates.CONTENT_URI, values, StatusUpdates.DATA_ID + "=" + statusId, null); // make sure the status_updates table is not updated values.put(StatusUpdates.STATUS_TIMESTAMP, updatedTs); values.put(StatusUpdates.STATUS, testUpdate); assertStoredValuesWithProjection(StatusUpdates.CONTENT_URI, values); // effect "delete status_updates" operation and expect the following // data deleted from status_updates table // presence set to null mResolver.delete(StatusUpdates.CONTENT_URI, StatusUpdates.DATA_ID + "=" + statusId, null); values.clear(); values.putNull(Contacts.CONTACT_PRESENCE); assertStoredValuesWithProjection(contactUri, values); } public void testStatusUpdateUpdateToNull() { long rawContactId = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); ContentValues values = new ContentValues(); Uri statusUri = insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", StatusUpdates.AVAILABLE, "Available", StatusUpdates.CAPABILITY_HAS_CAMERA); long statusId = ContentUris.parseId(statusUri); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.AVAILABLE); values.put(Contacts.CONTACT_STATUS, "Available"); assertStoredValuesWithProjection(contactUri, values); values.clear(); values.putNull(StatusUpdates.PRESENCE); mResolver.update(StatusUpdates.CONTENT_URI, values, StatusUpdates.DATA_ID + "=" + statusId, null); values.clear(); values.putNull(Contacts.CONTACT_PRESENCE); values.put(Contacts.CONTACT_STATUS, "Available"); assertStoredValuesWithProjection(contactUri, values); } public void testStatusUpdateWithTimestamp() { long rawContactId = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); insertImHandle(rawContactId, Im.PROTOCOL_GOOGLE_TALK, null, "gtalk"); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", 0, "Offline", 80, StatusUpdates.CAPABILITY_HAS_CAMERA, false); insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", 0, "Available", 100, StatusUpdates.CAPABILITY_HAS_CAMERA, false); insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "gtalk", 0, "Busy", 90, StatusUpdates.CAPABILITY_HAS_CAMERA, false); // Should return the latest status ContentValues values = new ContentValues(); values.put(Contacts.CONTACT_STATUS_TIMESTAMP, 100); values.put(Contacts.CONTACT_STATUS, "Available"); assertStoredValuesWithProjection(contactUri, values); } private void assertStatusUpdate(Cursor c, int protocol, String customProtocol, int presence, String status) { ContentValues values = new ContentValues(); values.put(StatusUpdates.PROTOCOL, protocol); values.put(StatusUpdates.CUSTOM_PROTOCOL, customProtocol); values.put(StatusUpdates.PRESENCE, presence); values.put(StatusUpdates.STATUS, status); assertCursorValues(c, values); } // Stream item query test cases. public void testQueryStreamItemsByRawContactId() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); ContentValues values = buildGenericStreamItemValues(); insertStreamItem(rawContactId, values, mAccount); assertStoredValues( Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), values); } public void testQueryStreamItemsByContactId() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = buildGenericStreamItemValues(); insertStreamItem(rawContactId, values, null); assertStoredValues( Uri.withAppendedPath( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.StreamItems.CONTENT_DIRECTORY), values); } public void testQueryStreamItemsByLookupKey() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); String lookupKey = queryLookupKey(contactId); ContentValues values = buildGenericStreamItemValues(); insertStreamItem(rawContactId, values, null); assertStoredValues( Uri.withAppendedPath( Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey), Contacts.StreamItems.CONTENT_DIRECTORY), values); } public void testQueryStreamItemsByLookupKeyAndContactId() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); String lookupKey = queryLookupKey(contactId); ContentValues values = buildGenericStreamItemValues(); insertStreamItem(rawContactId, values, null); assertStoredValues( Uri.withAppendedPath( ContentUris.withAppendedId( Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey), contactId), Contacts.StreamItems.CONTENT_DIRECTORY), values); } public void testQueryStreamItems() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); insertStreamItem(rawContactId, values, null); assertStoredValues(StreamItems.CONTENT_URI, values); } public void testQueryStreamItemsWithSelection() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues firstValues = buildGenericStreamItemValues(); insertStreamItem(rawContactId, firstValues, null); ContentValues secondValues = buildGenericStreamItemValues(); secondValues.put(StreamItems.TEXT, "Goodbye world"); insertStreamItem(rawContactId, secondValues, null); // Select only the first stream item. assertStoredValues(StreamItems.CONTENT_URI, StreamItems.TEXT + "=?", new String[]{"Hello world"}, firstValues); // Select only the second stream item. assertStoredValues(StreamItems.CONTENT_URI, StreamItems.TEXT + "=?", new String[]{"Goodbye world"}, secondValues); } public void testQueryStreamItemById() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues firstValues = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, firstValues, null); long firstStreamItemId = ContentUris.parseId(resultUri); ContentValues secondValues = buildGenericStreamItemValues(); secondValues.put(StreamItems.TEXT, "Goodbye world"); resultUri = insertStreamItem(rawContactId, secondValues, null); long secondStreamItemId = ContentUris.parseId(resultUri); // Select only the first stream item. assertStoredValues(ContentUris.withAppendedId(StreamItems.CONTENT_URI, firstStreamItemId), firstValues); // Select only the second stream item. assertStoredValues(ContentUris.withAppendedId(StreamItems.CONTENT_URI, secondStreamItemId), secondValues); } // Stream item photo insertion + query test cases. public void testQueryStreamItemPhotoWithSelection() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, values, null); long streamItemId = ContentUris.parseId(resultUri); ContentValues photo1Values = buildGenericStreamItemPhotoValues(1); insertStreamItemPhoto(streamItemId, photo1Values, null); photo1Values.remove(StreamItemPhotos.PHOTO); // Removed during processing. ContentValues photo2Values = buildGenericStreamItemPhotoValues(2); insertStreamItemPhoto(streamItemId, photo2Values, null); // Select only the first photo. assertStoredValues(StreamItems.CONTENT_PHOTO_URI, StreamItemPhotos.SORT_INDEX + "=?", new String[]{"1"}, photo1Values); } public void testQueryStreamItemPhotoByStreamItemId() { long rawContactId = RawContactUtil.createRawContact(mResolver); // Insert a first stream item. ContentValues firstValues = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, firstValues, null); long firstStreamItemId = ContentUris.parseId(resultUri); // Insert a second stream item. ContentValues secondValues = buildGenericStreamItemValues(); resultUri = insertStreamItem(rawContactId, secondValues, null); long secondStreamItemId = ContentUris.parseId(resultUri); // Add a photo to the first stream item. ContentValues photo1Values = buildGenericStreamItemPhotoValues(1); insertStreamItemPhoto(firstStreamItemId, photo1Values, null); photo1Values.remove(StreamItemPhotos.PHOTO); // Removed during processing. // Add a photo to the second stream item. ContentValues photo2Values = buildGenericStreamItemPhotoValues(1); photo2Values.put(StreamItemPhotos.PHOTO, loadPhotoFromResource( R.drawable.nebula, PhotoSize.ORIGINAL)); insertStreamItemPhoto(secondStreamItemId, photo2Values, null); photo2Values.remove(StreamItemPhotos.PHOTO); // Removed during processing. // Select only the photos from the second stream item. assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, secondStreamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), photo2Values); } public void testQueryStreamItemPhotoByStreamItemPhotoId() { long rawContactId = RawContactUtil.createRawContact(mResolver); // Insert a first stream item. ContentValues firstValues = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, firstValues, null); long firstStreamItemId = ContentUris.parseId(resultUri); // Insert a second stream item. ContentValues secondValues = buildGenericStreamItemValues(); resultUri = insertStreamItem(rawContactId, secondValues, null); long secondStreamItemId = ContentUris.parseId(resultUri); // Add a photo to the first stream item. ContentValues photo1Values = buildGenericStreamItemPhotoValues(1); resultUri = insertStreamItemPhoto(firstStreamItemId, photo1Values, null); long firstPhotoId = ContentUris.parseId(resultUri); photo1Values.remove(StreamItemPhotos.PHOTO); // Removed during processing. // Add a photo to the second stream item. ContentValues photo2Values = buildGenericStreamItemPhotoValues(1); photo2Values.put(StreamItemPhotos.PHOTO, loadPhotoFromResource( R.drawable.galaxy, PhotoSize.ORIGINAL)); resultUri = insertStreamItemPhoto(secondStreamItemId, photo2Values, null); long secondPhotoId = ContentUris.parseId(resultUri); photo2Values.remove(StreamItemPhotos.PHOTO); // Removed during processing. // Select the first photo. assertStoredValues(ContentUris.withAppendedId( Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, firstStreamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), firstPhotoId), photo1Values); // Select the second photo. assertStoredValues(ContentUris.withAppendedId( Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, secondStreamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), secondPhotoId), photo2Values); } // Stream item insertion test cases. public void testInsertStreamItemInProfileRequiresWriteProfileAccess() { long profileRawContactId = createBasicProfileContact(new ContentValues()); // With our (default) write profile permission, we should be able to insert a stream item. ContentValues values = buildGenericStreamItemValues(); insertStreamItem(profileRawContactId, values, null); // Now take away write profile permission. mActor.removePermissions("android.permission.WRITE_PROFILE"); // Try inserting another stream item. try { insertStreamItem(profileRawContactId, values, null); fail("Should require WRITE_PROFILE access to insert a stream item in the profile."); } catch (SecurityException expected) { // Trying to insert a stream item in the profile without WRITE_PROFILE permission // should fail. } } public void testInsertStreamItemWithContentValues() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); values.put(StreamItems.RAW_CONTACT_ID, rawContactId); mResolver.insert(StreamItems.CONTENT_URI, values); assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), values); } public void testInsertStreamItemOverLimit() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); values.put(StreamItems.RAW_CONTACT_ID, rawContactId); List<Long> streamItemIds = Lists.newArrayList(); // Insert MAX + 1 stream items. long baseTime = System.currentTimeMillis(); for (int i = 0; i < 6; i++) { values.put(StreamItems.TIMESTAMP, baseTime + i); Uri resultUri = mResolver.insert(StreamItems.CONTENT_URI, values); streamItemIds.add(ContentUris.parseId(resultUri)); } Long doomedStreamItemId = streamItemIds.get(0); // There should only be MAX items. The oldest one should have been cleaned up. Cursor c = mResolver.query( Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), new String[]{StreamItems._ID}, null, null, null); try { while(c.moveToNext()) { long streamItemId = c.getLong(0); streamItemIds.remove(streamItemId); } } finally { c.close(); } assertEquals(1, streamItemIds.size()); assertEquals(doomedStreamItemId, streamItemIds.get(0)); } public void testInsertStreamItemOlderThanOldestInLimit() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); values.put(StreamItems.RAW_CONTACT_ID, rawContactId); // Insert MAX stream items. long baseTime = System.currentTimeMillis(); for (int i = 0; i < 5; i++) { values.put(StreamItems.TIMESTAMP, baseTime + i); Uri resultUri = mResolver.insert(StreamItems.CONTENT_URI, values); assertNotSame("Expected non-0 stream item ID to be inserted", 0L, ContentUris.parseId(resultUri)); } // Now try to insert a stream item that's older. It should be deleted immediately // and return an ID of 0. values.put(StreamItems.TIMESTAMP, baseTime - 1); Uri resultUri = mResolver.insert(StreamItems.CONTENT_URI, values); assertEquals(0L, ContentUris.parseId(resultUri)); } // Stream item photo insertion test cases. public void testInsertStreamItemsAndPhotosInBatch() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues streamItemValues = buildGenericStreamItemValues(); ContentValues streamItemPhotoValues = buildGenericStreamItemPhotoValues(0); ArrayList<ContentProviderOperation> ops = Lists.newArrayList(); ops.add(ContentProviderOperation.newInsert( Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY)) .withValues(streamItemValues).build()); for (int i = 0; i < 5; i++) { streamItemPhotoValues.put(StreamItemPhotos.SORT_INDEX, i); ops.add(ContentProviderOperation.newInsert(StreamItems.CONTENT_PHOTO_URI) .withValues(streamItemPhotoValues) .withValueBackReference(StreamItemPhotos.STREAM_ITEM_ID, 0) .build()); } mResolver.applyBatch(ContactsContract.AUTHORITY, ops); // Check that all five photos were inserted under the raw contact. Cursor c = mResolver.query(StreamItems.CONTENT_URI, new String[]{StreamItems._ID}, StreamItems.RAW_CONTACT_ID + "=?", new String[]{String.valueOf(rawContactId)}, null); long streamItemId = 0; try { assertEquals(1, c.getCount()); c.moveToFirst(); streamItemId = c.getLong(0); } finally { c.close(); } c = mResolver.query(Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), new String[]{StreamItemPhotos._ID, StreamItemPhotos.PHOTO_URI}, null, null, null); try { assertEquals(5, c.getCount()); byte[] expectedPhotoBytes = loadPhotoFromResource( R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO); while (c.moveToNext()) { String photoUri = c.getString(1); EvenMoreAsserts.assertImageRawData(getContext(), expectedPhotoBytes, mResolver.openInputStream(Uri.parse(photoUri))); } } finally { c.close(); } } // Stream item update test cases. public void testUpdateStreamItemById() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, values, null); long streamItemId = ContentUris.parseId(resultUri); values.put(StreamItems.TEXT, "Goodbye world"); mResolver.update(ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), values, null, null); assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), values); } public void testUpdateStreamItemWithContentValues() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, values, null); long streamItemId = ContentUris.parseId(resultUri); values.put(StreamItems._ID, streamItemId); values.put(StreamItems.TEXT, "Goodbye world"); mResolver.update(StreamItems.CONTENT_URI, values, null, null); assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), values); } // Stream item photo update test cases. public void testUpdateStreamItemPhotoById() throws IOException { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, values, null); long streamItemId = ContentUris.parseId(resultUri); ContentValues photoValues = buildGenericStreamItemPhotoValues(1); resultUri = insertStreamItemPhoto(streamItemId, photoValues, null); long streamItemPhotoId = ContentUris.parseId(resultUri); photoValues.put(StreamItemPhotos.PHOTO, loadPhotoFromResource( R.drawable.nebula, PhotoSize.ORIGINAL)); Uri photoUri = ContentUris.withAppendedId( Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), streamItemPhotoId); mResolver.update(photoUri, photoValues, null, null); photoValues.remove(StreamItemPhotos.PHOTO); // Removed during processing. assertStoredValues(photoUri, photoValues); // Check that the photo stored is the expected one. String displayPhotoUri = getStoredValue(photoUri, StreamItemPhotos.PHOTO_URI); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.nebula, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(Uri.parse(displayPhotoUri))); } public void testUpdateStreamItemPhotoWithContentValues() throws IOException { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, values, null); long streamItemId = ContentUris.parseId(resultUri); ContentValues photoValues = buildGenericStreamItemPhotoValues(1); resultUri = insertStreamItemPhoto(streamItemId, photoValues, null); long streamItemPhotoId = ContentUris.parseId(resultUri); photoValues.put(StreamItemPhotos._ID, streamItemPhotoId); photoValues.put(StreamItemPhotos.PHOTO, loadPhotoFromResource( R.drawable.nebula, PhotoSize.ORIGINAL)); Uri photoUri = Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY); mResolver.update(photoUri, photoValues, null, null); photoValues.remove(StreamItemPhotos.PHOTO); // Removed during processing. assertStoredValues(photoUri, photoValues); // Check that the photo stored is the expected one. String displayPhotoUri = getStoredValue(photoUri, StreamItemPhotos.PHOTO_URI); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.nebula, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(Uri.parse(displayPhotoUri))); } // Stream item deletion test cases. public void testDeleteStreamItemById() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues firstValues = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, firstValues, null); long firstStreamItemId = ContentUris.parseId(resultUri); ContentValues secondValues = buildGenericStreamItemValues(); secondValues.put(StreamItems.TEXT, "Goodbye world"); insertStreamItem(rawContactId, secondValues, null); // Delete the first stream item. mResolver.delete(ContentUris.withAppendedId(StreamItems.CONTENT_URI, firstStreamItemId), null, null); // Check that only the second item remains. assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), secondValues); } public void testDeleteStreamItemWithSelection() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues firstValues = buildGenericStreamItemValues(); insertStreamItem(rawContactId, firstValues, null); ContentValues secondValues = buildGenericStreamItemValues(); secondValues.put(StreamItems.TEXT, "Goodbye world"); insertStreamItem(rawContactId, secondValues, null); // Delete the first stream item with a custom selection. mResolver.delete(StreamItems.CONTENT_URI, StreamItems.TEXT + "=?", new String[]{"Hello world"}); // Check that only the second item remains. assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), secondValues); } // Stream item photo deletion test cases. public void testDeleteStreamItemPhotoById() { long rawContactId = RawContactUtil.createRawContact(mResolver); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); long streamItemPhotoId = ContentUris.parseId( insertStreamItemPhoto(streamItemId, buildGenericStreamItemPhotoValues(0), null)); mResolver.delete( ContentUris.withAppendedId( Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), streamItemPhotoId), null, null); Cursor c = mResolver.query(StreamItems.CONTENT_PHOTO_URI, new String[]{StreamItemPhotos._ID}, StreamItemPhotos.STREAM_ITEM_ID + "=?", new String[]{String.valueOf(streamItemId)}, null); try { assertEquals("Expected photo to be deleted.", 0, c.getCount()); } finally { c.close(); } } public void testDeleteStreamItemPhotoWithSelection() { long rawContactId = RawContactUtil.createRawContact(mResolver); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); ContentValues firstPhotoValues = buildGenericStreamItemPhotoValues(0); ContentValues secondPhotoValues = buildGenericStreamItemPhotoValues(1); insertStreamItemPhoto(streamItemId, firstPhotoValues, null); firstPhotoValues.remove(StreamItemPhotos.PHOTO); // Removed while processing. insertStreamItemPhoto(streamItemId, secondPhotoValues, null); Uri photoUri = Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY); mResolver.delete(photoUri, StreamItemPhotos.SORT_INDEX + "=1", null); assertStoredValues(photoUri, firstPhotoValues); } public void testDeleteStreamItemsWhenRawContactDeleted() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri streamItemUri = insertStreamItem(rawContactId, buildGenericStreamItemValues(), mAccount); Uri streamItemPhotoUri = insertStreamItemPhoto(ContentUris.parseId(streamItemUri), buildGenericStreamItemPhotoValues(0), mAccount); mResolver.delete(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), null, null); ContentValues[] emptyValues = new ContentValues[0]; // The stream item and its photo should be gone. assertStoredValues(streamItemUri, emptyValues); assertStoredValues(streamItemPhotoUri, emptyValues); } public void testQueryStreamItemLimit() { ContentValues values = new ContentValues(); values.put(StreamItems.MAX_ITEMS, 5); assertStoredValues(StreamItems.CONTENT_LIMIT_URI, values); } // Tests for inserting or updating stream items as a side-effect of making status updates // (forward-compatibility of status updates into the new social stream API). public void testStreamItemInsertedOnStatusUpdate() { // This method of creating a raw contact automatically inserts a status update with // the status message "hacking". ContentValues values = new ContentValues(); long rawContactId = createRawContact(values, "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_CAMERA | StatusUpdates.CAPABILITY_HAS_VIDEO | StatusUpdates.CAPABILITY_HAS_VOICE); ContentValues expectedValues = new ContentValues(); expectedValues.put(StreamItems.RAW_CONTACT_ID, rawContactId); expectedValues.put(StreamItems.TEXT, "hacking"); assertStoredValues(RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.StreamItems.CONTENT_DIRECTORY).build(), expectedValues); } public void testStreamItemInsertedOnStatusUpdate_HtmlQuoting() { // This method of creating a raw contact automatically inserts a status update with // the status message "hacking". ContentValues values = new ContentValues(); long rawContactId = createRawContact(values, "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_VOICE); // Insert a new status update for the raw contact. insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.INVISIBLE, "& <b> test &#39;", StatusUpdates.CAPABILITY_HAS_VOICE); ContentValues expectedValues = new ContentValues(); expectedValues.put(StreamItems.RAW_CONTACT_ID, rawContactId); expectedValues.put(StreamItems.TEXT, "&amp; &lt;b&gt; test &amp;#39;"); assertStoredValues(RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.StreamItems.CONTENT_DIRECTORY).build(), expectedValues); } public void testStreamItemUpdatedOnSecondStatusUpdate() { // This method of creating a raw contact automatically inserts a status update with // the status message "hacking". ContentValues values = new ContentValues(); int chatMode = StatusUpdates.CAPABILITY_HAS_CAMERA | StatusUpdates.CAPABILITY_HAS_VIDEO | StatusUpdates.CAPABILITY_HAS_VOICE; long rawContactId = createRawContact(values, "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, chatMode); // Insert a new status update for the raw contact. insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.INVISIBLE, "finished hacking", chatMode); ContentValues expectedValues = new ContentValues(); expectedValues.put(StreamItems.RAW_CONTACT_ID, rawContactId); expectedValues.put(StreamItems.TEXT, "finished hacking"); assertStoredValues(RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.StreamItems.CONTENT_DIRECTORY).build(), expectedValues); } public void testStreamItemReadRequiresReadSocialStreamPermission() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); String lookupKey = queryLookupKey(contactId); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); mActor.removePermissions("android.permission.READ_SOCIAL_STREAM"); // Try selecting the stream item in various ways. expectSecurityException( "Querying stream items by contact ID requires social stream read permission", Uri.withAppendedPath( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.StreamItems.CONTENT_DIRECTORY), null, null, null, null); expectSecurityException( "Querying stream items by lookup key requires social stream read permission", Contacts.CONTENT_LOOKUP_URI.buildUpon().appendPath(lookupKey) .appendPath(Contacts.StreamItems.CONTENT_DIRECTORY).build(), null, null, null, null); expectSecurityException( "Querying stream items by lookup key and ID requires social stream read permission", Uri.withAppendedPath(Contacts.getLookupUri(contactId, lookupKey), Contacts.StreamItems.CONTENT_DIRECTORY), null, null, null, null); expectSecurityException( "Querying stream items by raw contact ID requires social stream read permission", Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), null, null, null, null); expectSecurityException( "Querying stream items by raw contact ID and stream item ID requires social " + "stream read permission", ContentUris.withAppendedId( Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), streamItemId), null, null, null, null); expectSecurityException( "Querying all stream items requires social stream read permission", StreamItems.CONTENT_URI, null, null, null, null); expectSecurityException( "Querying stream item by ID requires social stream read permission", ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), null, null, null, null); } public void testStreamItemPhotoReadRequiresReadSocialStreamPermission() { long rawContactId = RawContactUtil.createRawContact(mResolver); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); long streamItemPhotoId = ContentUris.parseId( insertStreamItemPhoto(streamItemId, buildGenericStreamItemPhotoValues(0), null)); mActor.removePermissions("android.permission.READ_SOCIAL_STREAM"); // Try selecting the stream item photo in various ways. expectSecurityException( "Querying all stream item photos requires social stream read permission", StreamItems.CONTENT_URI.buildUpon() .appendPath(StreamItems.StreamItemPhotos.CONTENT_DIRECTORY).build(), null, null, null, null); expectSecurityException( "Querying all stream item photos requires social stream read permission", StreamItems.CONTENT_URI.buildUpon() .appendPath(String.valueOf(streamItemId)) .appendPath(StreamItems.StreamItemPhotos.CONTENT_DIRECTORY) .appendPath(String.valueOf(streamItemPhotoId)).build(), null, null, null, null); } public void testStreamItemModificationRequiresWriteSocialStreamPermission() { long rawContactId = RawContactUtil.createRawContact(mResolver); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); mActor.removePermissions("android.permission.WRITE_SOCIAL_STREAM"); try { insertStreamItem(rawContactId, buildGenericStreamItemValues(), null); fail("Should not be able to insert to stream without write social stream permission"); } catch (SecurityException expected) { } try { ContentValues values = new ContentValues(); values.put(StreamItems.TEXT, "Goodbye world"); mResolver.update(ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), values, null, null); fail("Should not be able to update stream without write social stream permission"); } catch (SecurityException expected) { } try { mResolver.delete(ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), null, null); fail("Should not be able to delete from stream without write social stream permission"); } catch (SecurityException expected) { } } public void testStreamItemPhotoModificationRequiresWriteSocialStreamPermission() { long rawContactId = RawContactUtil.createRawContact(mResolver); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); long streamItemPhotoId = ContentUris.parseId( insertStreamItemPhoto(streamItemId, buildGenericStreamItemPhotoValues(0), null)); mActor.removePermissions("android.permission.WRITE_SOCIAL_STREAM"); Uri photoUri = StreamItems.CONTENT_URI.buildUpon() .appendPath(String.valueOf(streamItemId)) .appendPath(StreamItems.StreamItemPhotos.CONTENT_DIRECTORY) .appendPath(String.valueOf(streamItemPhotoId)).build(); try { insertStreamItemPhoto(streamItemId, buildGenericStreamItemPhotoValues(1), null); fail("Should not be able to insert photos without write social stream permission"); } catch (SecurityException expected) { } try { ContentValues values = new ContentValues(); values.put(StreamItemPhotos.PHOTO, loadPhotoFromResource(R.drawable.galaxy, PhotoSize.ORIGINAL)); mResolver.update(photoUri, values, null, null); fail("Should not be able to update photos without write social stream permission"); } catch (SecurityException expected) { } try { mResolver.delete(photoUri, null, null); fail("Should not be able to delete photos without write social stream permission"); } catch (SecurityException expected) { } } public void testStatusUpdateDoesNotRequireReadOrWriteSocialStreamPermission() { int protocol1 = Im.PROTOCOL_GOOGLE_TALK; String handle1 = "[email protected]"; long rawContactId = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId, protocol1, null, handle1); mActor.removePermissions("android.permission.READ_SOCIAL_STREAM"); mActor.removePermissions("android.permission.WRITE_SOCIAL_STREAM"); insertStatusUpdate(protocol1, null, handle1, StatusUpdates.AVAILABLE, "Green", StatusUpdates.CAPABILITY_HAS_CAMERA); mActor.addPermissions("android.permission.READ_SOCIAL_STREAM"); ContentValues expectedValues = new ContentValues(); expectedValues.put(StreamItems.TEXT, "Green"); assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), expectedValues); } private ContentValues buildGenericStreamItemValues() { ContentValues values = new ContentValues(); values.put(StreamItems.TEXT, "Hello world"); values.put(StreamItems.TIMESTAMP, System.currentTimeMillis()); values.put(StreamItems.COMMENTS, "Reshared by 123 others"); return values; } private ContentValues buildGenericStreamItemPhotoValues(int sortIndex) { ContentValues values = new ContentValues(); values.put(StreamItemPhotos.SORT_INDEX, sortIndex); values.put(StreamItemPhotos.PHOTO, loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.ORIGINAL)); return values; } public void testSingleStatusUpdateRowPerContact() { int protocol1 = Im.PROTOCOL_GOOGLE_TALK; String handle1 = "[email protected]"; long rawContactId1 = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId1, protocol1, null, handle1); insertStatusUpdate(protocol1, null, handle1, StatusUpdates.AVAILABLE, "Green", StatusUpdates.CAPABILITY_HAS_CAMERA); insertStatusUpdate(protocol1, null, handle1, StatusUpdates.AWAY, "Yellow", StatusUpdates.CAPABILITY_HAS_CAMERA); insertStatusUpdate(protocol1, null, handle1, StatusUpdates.INVISIBLE, "Red", StatusUpdates.CAPABILITY_HAS_CAMERA); Cursor c = queryContact(queryContactId(rawContactId1), new String[] {Contacts.CONTACT_PRESENCE, Contacts.CONTACT_STATUS}); assertEquals(1, c.getCount()); c.moveToFirst(); assertEquals(StatusUpdates.INVISIBLE, c.getInt(0)); assertEquals("Red", c.getString(1)); c.close(); } private void updateSendToVoicemailAndRingtone(long contactId, boolean sendToVoicemail, String ringtone) { ContentValues values = new ContentValues(); values.put(Contacts.SEND_TO_VOICEMAIL, sendToVoicemail); if (ringtone != null) { values.put(Contacts.CUSTOM_RINGTONE, ringtone); } final Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); int count = mResolver.update(uri, values, null, null); assertEquals(1, count); } private void updateSendToVoicemailAndRingtoneWithSelection(long contactId, boolean sendToVoicemail, String ringtone) { ContentValues values = new ContentValues(); values.put(Contacts.SEND_TO_VOICEMAIL, sendToVoicemail); if (ringtone != null) { values.put(Contacts.CUSTOM_RINGTONE, ringtone); } int count = mResolver.update(Contacts.CONTENT_URI, values, Contacts._ID + "=" + contactId, null); assertEquals(1, count); } private void assertSendToVoicemailAndRingtone(long contactId, boolean expectedSendToVoicemail, String expectedRingtone) { Cursor c = queryContact(contactId); assertTrue(c.moveToNext()); int sendToVoicemail = c.getInt(c.getColumnIndex(Contacts.SEND_TO_VOICEMAIL)); assertEquals(expectedSendToVoicemail ? 1 : 0, sendToVoicemail); String ringtone = c.getString(c.getColumnIndex(Contacts.CUSTOM_RINGTONE)); if (expectedRingtone == null) { assertNull(ringtone); } else { assertTrue(ArrayUtils.contains(expectedRingtone.split(","), ringtone)); } c.close(); } public void testContactVisibilityUpdateOnMembershipChange() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); assertVisibility(rawContactId, "0"); long visibleGroupId = createGroup(mAccount, "123", "Visible", 1); long invisibleGroupId = createGroup(mAccount, "567", "Invisible", 0); Uri membership1 = insertGroupMembership(rawContactId, visibleGroupId); assertVisibility(rawContactId, "1"); Uri membership2 = insertGroupMembership(rawContactId, invisibleGroupId); assertVisibility(rawContactId, "1"); mResolver.delete(membership1, null, null); assertVisibility(rawContactId, "0"); ContentValues values = new ContentValues(); values.put(GroupMembership.GROUP_ROW_ID, visibleGroupId); mResolver.update(membership2, values, null, null); assertVisibility(rawContactId, "1"); } private void assertVisibility(long rawContactId, String expectedValue) { assertStoredValue(Contacts.CONTENT_URI, Contacts._ID + "=" + queryContactId(rawContactId), null, Contacts.IN_VISIBLE_GROUP, expectedValue); } public void testSupplyingBothValuesAndParameters() throws Exception { Account account = new Account("account 1", "type%/:1"); Uri uri = ContactsContract.Groups.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.Groups.ACCOUNT_NAME, account.name) .appendQueryParameter(ContactsContract.Groups.ACCOUNT_TYPE, account.type) .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true") .build(); ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(uri); builder.withValue(ContactsContract.Groups.ACCOUNT_TYPE, account.type); builder.withValue(ContactsContract.Groups.ACCOUNT_NAME, account.name); builder.withValue(ContactsContract.Groups.SYSTEM_ID, "some id"); builder.withValue(ContactsContract.Groups.TITLE, "some name"); builder.withValue(ContactsContract.Groups.GROUP_VISIBLE, 1); mResolver.applyBatch(ContactsContract.AUTHORITY, Lists.newArrayList(builder.build())); builder = ContentProviderOperation.newInsert(uri); builder.withValue(ContactsContract.Groups.ACCOUNT_TYPE, account.type + "diff"); builder.withValue(ContactsContract.Groups.ACCOUNT_NAME, account.name); builder.withValue(ContactsContract.Groups.SYSTEM_ID, "some other id"); builder.withValue(ContactsContract.Groups.TITLE, "some other name"); builder.withValue(ContactsContract.Groups.GROUP_VISIBLE, 1); try { mResolver.applyBatch(ContactsContract.AUTHORITY, Lists.newArrayList(builder.build())); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException ex) { // Expected } } public void testContentEntityIterator() { // create multiple contacts and check that the selected ones are returned long id; long groupId1 = createGroup(mAccount, "gsid1", "title1"); long groupId2 = createGroup(mAccount, "gsid2", "title2"); id = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "c0"); insertGroupMembership(id, "gsid1"); insertEmail(id, "[email protected]"); insertPhoneNumber(id, "5551212c0"); long c1 = id = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "c1"); Uri id_1_0 = insertGroupMembership(id, "gsid1"); Uri id_1_1 = insertGroupMembership(id, "gsid2"); Uri id_1_2 = insertEmail(id, "[email protected]"); Uri id_1_3 = insertPhoneNumber(id, "5551212c1"); long c2 = id = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "c2"); Uri id_2_0 = insertGroupMembership(id, "gsid1"); Uri id_2_1 = insertEmail(id, "[email protected]"); Uri id_2_2 = insertPhoneNumber(id, "5551212c2"); long c3 = id = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "c3"); Uri id_3_0 = insertGroupMembership(id, groupId2); Uri id_3_1 = insertEmail(id, "[email protected]"); Uri id_3_2 = insertPhoneNumber(id, "5551212c3"); EntityIterator iterator = RawContacts.newEntityIterator(mResolver.query( TestUtil.maybeAddAccountQueryParameters(RawContactsEntity.CONTENT_URI, mAccount), null, RawContacts.SOURCE_ID + " in ('c1', 'c2', 'c3')", null, null)); Entity entity; ContentValues[] subValues; entity = iterator.next(); assertEquals(c1, (long) entity.getEntityValues().getAsLong(RawContacts._ID)); subValues = asSortedContentValuesArray(entity.getSubValues()); assertEquals(4, subValues.length); assertDataRow(subValues[0], GroupMembership.CONTENT_ITEM_TYPE, Data._ID, id_1_0, GroupMembership.GROUP_ROW_ID, groupId1, GroupMembership.GROUP_SOURCE_ID, "gsid1"); assertDataRow(subValues[1], GroupMembership.CONTENT_ITEM_TYPE, Data._ID, id_1_1, GroupMembership.GROUP_ROW_ID, groupId2, GroupMembership.GROUP_SOURCE_ID, "gsid2"); assertDataRow(subValues[2], Email.CONTENT_ITEM_TYPE, Data._ID, id_1_2, Email.DATA, "[email protected]"); assertDataRow(subValues[3], Phone.CONTENT_ITEM_TYPE, Data._ID, id_1_3, Email.DATA, "5551212c1"); entity = iterator.next(); assertEquals(c2, (long) entity.getEntityValues().getAsLong(RawContacts._ID)); subValues = asSortedContentValuesArray(entity.getSubValues()); assertEquals(3, subValues.length); assertDataRow(subValues[0], GroupMembership.CONTENT_ITEM_TYPE, Data._ID, id_2_0, GroupMembership.GROUP_ROW_ID, groupId1, GroupMembership.GROUP_SOURCE_ID, "gsid1"); assertDataRow(subValues[1], Email.CONTENT_ITEM_TYPE, Data._ID, id_2_1, Email.DATA, "[email protected]"); assertDataRow(subValues[2], Phone.CONTENT_ITEM_TYPE, Data._ID, id_2_2, Email.DATA, "5551212c2"); entity = iterator.next(); assertEquals(c3, (long) entity.getEntityValues().getAsLong(RawContacts._ID)); subValues = asSortedContentValuesArray(entity.getSubValues()); assertEquals(3, subValues.length); assertDataRow(subValues[0], GroupMembership.CONTENT_ITEM_TYPE, Data._ID, id_3_0, GroupMembership.GROUP_ROW_ID, groupId2, GroupMembership.GROUP_SOURCE_ID, "gsid2"); assertDataRow(subValues[1], Email.CONTENT_ITEM_TYPE, Data._ID, id_3_1, Email.DATA, "[email protected]"); assertDataRow(subValues[2], Phone.CONTENT_ITEM_TYPE, Data._ID, id_3_2, Email.DATA, "5551212c3"); assertFalse(iterator.hasNext()); iterator.close(); } public void testDataCreateUpdateDeleteByMimeType() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = new ContentValues(); values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, "testmimetype"); values.put(Data.RES_PACKAGE, "oldpackage"); values.put(Data.IS_PRIMARY, 1); values.put(Data.IS_SUPER_PRIMARY, 1); values.put(Data.DATA1, "old1"); values.put(Data.DATA2, "old2"); values.put(Data.DATA3, "old3"); values.put(Data.DATA4, "old4"); values.put(Data.DATA5, "old5"); values.put(Data.DATA6, "old6"); values.put(Data.DATA7, "old7"); values.put(Data.DATA8, "old8"); values.put(Data.DATA9, "old9"); values.put(Data.DATA10, "old10"); values.put(Data.DATA11, "old11"); values.put(Data.DATA12, "old12"); values.put(Data.DATA13, "old13"); values.put(Data.DATA14, "old14"); values.put(Data.DATA15, "old15"); Uri uri = mResolver.insert(Data.CONTENT_URI, values); assertStoredValues(uri, values); assertNetworkNotified(true); values.clear(); values.put(Data.RES_PACKAGE, "newpackage"); values.put(Data.IS_PRIMARY, 0); values.put(Data.IS_SUPER_PRIMARY, 0); values.put(Data.DATA1, "new1"); values.put(Data.DATA2, "new2"); values.put(Data.DATA3, "new3"); values.put(Data.DATA4, "new4"); values.put(Data.DATA5, "new5"); values.put(Data.DATA6, "new6"); values.put(Data.DATA7, "new7"); values.put(Data.DATA8, "new8"); values.put(Data.DATA9, "new9"); values.put(Data.DATA10, "new10"); values.put(Data.DATA11, "new11"); values.put(Data.DATA12, "new12"); values.put(Data.DATA13, "new13"); values.put(Data.DATA14, "new14"); values.put(Data.DATA15, "new15"); mResolver.update(Data.CONTENT_URI, values, Data.RAW_CONTACT_ID + "=" + rawContactId + " AND " + Data.MIMETYPE + "='testmimetype'", null); assertNetworkNotified(true); assertStoredValues(uri, values); int count = mResolver.delete(Data.CONTENT_URI, Data.RAW_CONTACT_ID + "=" + rawContactId + " AND " + Data.MIMETYPE + "='testmimetype'", null); assertEquals(1, count); assertEquals(0, getCount(Data.CONTENT_URI, Data.RAW_CONTACT_ID + "=" + rawContactId + " AND " + Data.MIMETYPE + "='testmimetype'", null)); assertNetworkNotified(true); } public void testRawContactQuery() { Account account1 = new Account("a", "b"); Account account2 = new Account("c", "d"); long rawContactId1 = RawContactUtil.createRawContact(mResolver, account1); long rawContactId2 = RawContactUtil.createRawContact(mResolver, account2); Uri uri1 = TestUtil.maybeAddAccountQueryParameters(RawContacts.CONTENT_URI, account1); Uri uri2 = TestUtil.maybeAddAccountQueryParameters(RawContacts.CONTENT_URI, account2); assertEquals(1, getCount(uri1, null, null)); assertEquals(1, getCount(uri2, null, null)); assertStoredValue(uri1, RawContacts._ID, rawContactId1) ; assertStoredValue(uri2, RawContacts._ID, rawContactId2) ; Uri rowUri1 = ContentUris.withAppendedId(uri1, rawContactId1); Uri rowUri2 = ContentUris.withAppendedId(uri2, rawContactId2); assertStoredValue(rowUri1, RawContacts._ID, rawContactId1) ; assertStoredValue(rowUri2, RawContacts._ID, rawContactId2) ; } public void testRawContactDeletion() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); insertImHandle(rawContactId, Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]"); insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.AVAILABLE, null, StatusUpdates.CAPABILITY_HAS_CAMERA); long contactId = queryContactId(rawContactId); assertEquals(1, getCount(Uri.withAppendedPath(uri, RawContacts.Data.CONTENT_DIRECTORY), null, null)); assertEquals(1, getCount(StatusUpdates.CONTENT_URI, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId, null)); mResolver.delete(uri, null, null); assertStoredValue(uri, RawContacts.DELETED, "1"); assertNetworkNotified(true); Uri permanentDeletionUri = setCallerIsSyncAdapter(uri, mAccount); mResolver.delete(permanentDeletionUri, null, null); assertEquals(0, getCount(uri, null, null)); assertEquals(0, getCount(Uri.withAppendedPath(uri, RawContacts.Data.CONTENT_DIRECTORY), null, null)); assertEquals(0, getCount(StatusUpdates.CONTENT_URI, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId, null)); assertEquals(0, getCount(Contacts.CONTENT_URI, Contacts._ID + "=" + contactId, null)); assertNetworkNotified(false); } public void testRawContactDeletionKeepingAggregateContact() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, mAccount); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, mAccount); setAggregationException( AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); long contactId = queryContactId(rawContactId1); Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId1); Uri permanentDeletionUri = setCallerIsSyncAdapter(uri, mAccount); mResolver.delete(permanentDeletionUri, null, null); assertEquals(0, getCount(uri, null, null)); assertEquals(1, getCount(Contacts.CONTENT_URI, Contacts._ID + "=" + contactId, null)); } public void testRawContactDeletion_byAccountParam() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); insertImHandle(rawContactId, Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]"); insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.AVAILABLE, null, StatusUpdates.CAPABILITY_HAS_CAMERA); assertEquals(1, getCount(Uri.withAppendedPath(uri, RawContacts.Data.CONTENT_DIRECTORY), null, null)); assertEquals(1, getCount(StatusUpdates.CONTENT_URI, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId, null)); // Do not delete if we are deleting with wrong account. Uri deleteWithWrongAccountUri = RawContacts.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, mAccountTwo.name) .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, mAccountTwo.type) .build(); int numDeleted = mResolver.delete(deleteWithWrongAccountUri, null, null); assertEquals(0, numDeleted); assertStoredValue(uri, RawContacts.DELETED, "0"); // Delete if we are deleting with correct account. Uri deleteWithCorrectAccountUri = RawContacts.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, mAccount.name) .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, mAccount.type) .build(); numDeleted = mResolver.delete(deleteWithCorrectAccountUri, null, null); assertEquals(1, numDeleted); assertStoredValue(uri, RawContacts.DELETED, "1"); } public void testRawContactDeletion_byAccountSelection() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); // Do not delete if we are deleting with wrong account. int numDeleted = mResolver.delete(RawContacts.CONTENT_URI, RawContacts.ACCOUNT_NAME + "=? AND " + RawContacts.ACCOUNT_TYPE + "=?", new String[] {mAccountTwo.name, mAccountTwo.type}); assertEquals(0, numDeleted); assertStoredValue(uri, RawContacts.DELETED, "0"); // Delete if we are deleting with correct account. numDeleted = mResolver.delete(RawContacts.CONTENT_URI, RawContacts.ACCOUNT_NAME + "=? AND " + RawContacts.ACCOUNT_TYPE + "=?", new String[] {mAccount.name, mAccount.type}); assertEquals(1, numDeleted); assertStoredValue(uri, RawContacts.DELETED, "1"); } /** * Test for {@link ContactsProvider2#stringToAccounts} and * {@link ContactsProvider2#accountsToString}. */ public void testAccountsToString() { final Set<Account> EXPECTED_0 = Sets.newHashSet(); final Set<Account> EXPECTED_1 = Sets.newHashSet(TestUtil.ACCOUNT_1); final Set<Account> EXPECTED_2 = Sets.newHashSet(TestUtil.ACCOUNT_2); final Set<Account> EXPECTED_1_2 = Sets.newHashSet(TestUtil.ACCOUNT_1, TestUtil.ACCOUNT_2); final Set<Account> ACTUAL_0 = Sets.newHashSet(); final Set<Account> ACTUAL_1 = Sets.newHashSet(TestUtil.ACCOUNT_1); final Set<Account> ACTUAL_2 = Sets.newHashSet(TestUtil.ACCOUNT_2); final Set<Account> ACTUAL_1_2 = Sets.newHashSet(TestUtil.ACCOUNT_2, TestUtil.ACCOUNT_1); assertTrue(EXPECTED_0.equals(accountsToStringToAccounts(ACTUAL_0))); assertFalse(EXPECTED_0.equals(accountsToStringToAccounts(ACTUAL_1))); assertFalse(EXPECTED_0.equals(accountsToStringToAccounts(ACTUAL_2))); assertFalse(EXPECTED_0.equals(accountsToStringToAccounts(ACTUAL_1_2))); assertFalse(EXPECTED_1.equals(accountsToStringToAccounts(ACTUAL_0))); assertTrue(EXPECTED_1.equals(accountsToStringToAccounts(ACTUAL_1))); assertFalse(EXPECTED_1.equals(accountsToStringToAccounts(ACTUAL_2))); assertFalse(EXPECTED_1.equals(accountsToStringToAccounts(ACTUAL_1_2))); assertFalse(EXPECTED_2.equals(accountsToStringToAccounts(ACTUAL_0))); assertFalse(EXPECTED_2.equals(accountsToStringToAccounts(ACTUAL_1))); assertTrue(EXPECTED_2.equals(accountsToStringToAccounts(ACTUAL_2))); assertFalse(EXPECTED_2.equals(accountsToStringToAccounts(ACTUAL_1_2))); assertFalse(EXPECTED_1_2.equals(accountsToStringToAccounts(ACTUAL_0))); assertFalse(EXPECTED_1_2.equals(accountsToStringToAccounts(ACTUAL_1))); assertFalse(EXPECTED_1_2.equals(accountsToStringToAccounts(ACTUAL_2))); assertTrue(EXPECTED_1_2.equals(accountsToStringToAccounts(ACTUAL_1_2))); try { ContactsProvider2.stringToAccounts("x"); fail("Didn't throw for malformed input"); } catch (IllegalArgumentException expected) { } } private static final Set<Account> accountsToStringToAccounts(Set<Account> accounts) { return ContactsProvider2.stringToAccounts(ContactsProvider2.accountsToString(accounts)); } /** * Test for {@link ContactsProvider2#haveAccountsChanged} and * {@link ContactsProvider2#saveAccounts}. */ public void testHaveAccountsChanged() { final ContactsProvider2 cp = (ContactsProvider2) getProvider(); final Account[] ACCOUNTS_0 = new Account[] {}; final Account[] ACCOUNTS_1 = new Account[] {TestUtil.ACCOUNT_1}; final Account[] ACCOUNTS_2 = new Account[] {TestUtil.ACCOUNT_2}; final Account[] ACCOUNTS_1_2 = new Account[] {TestUtil.ACCOUNT_1, TestUtil.ACCOUNT_2}; final Account[] ACCOUNTS_2_1 = new Account[] {TestUtil.ACCOUNT_2, TestUtil.ACCOUNT_1}; // Add ACCOUNT_1 assertTrue(cp.haveAccountsChanged(ACCOUNTS_1)); cp.saveAccounts(ACCOUNTS_1); assertFalse(cp.haveAccountsChanged(ACCOUNTS_1)); // Add ACCOUNT_2 assertTrue(cp.haveAccountsChanged(ACCOUNTS_1_2)); // (try with reverse order) assertTrue(cp.haveAccountsChanged(ACCOUNTS_2_1)); cp.saveAccounts(ACCOUNTS_1_2); assertFalse(cp.haveAccountsChanged(ACCOUNTS_1_2)); // (try with reverse order) assertFalse(cp.haveAccountsChanged(ACCOUNTS_2_1)); // Remove ACCOUNT_1 assertTrue(cp.haveAccountsChanged(ACCOUNTS_2)); cp.saveAccounts(ACCOUNTS_2); assertFalse(cp.haveAccountsChanged(ACCOUNTS_2)); // Remove ACCOUNT_2 assertTrue(cp.haveAccountsChanged(ACCOUNTS_0)); cp.saveAccounts(ACCOUNTS_0); assertFalse(cp.haveAccountsChanged(ACCOUNTS_0)); // Test with malformed DB property. final ContactsDatabaseHelper dbHelper = cp.getThreadActiveDatabaseHelperForTest(); dbHelper.setProperty(DbProperties.KNOWN_ACCOUNTS, "x"); // With malformed property the method always return true. assertTrue(cp.haveAccountsChanged(ACCOUNTS_0)); assertTrue(cp.haveAccountsChanged(ACCOUNTS_1)); } public void testAccountsUpdated() { // This is to ensure we do not delete contacts with null, null (account name, type) // accidentally. long rawContactId3 = RawContactUtil.createRawContactWithName(mResolver, "James", "Sullivan"); insertPhoneNumber(rawContactId3, "5234567890"); Uri rawContact3 = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId3); assertEquals(1, getCount(RawContacts.CONTENT_URI, null, null)); ContactsProvider2 cp = (ContactsProvider2) getProvider(); mActor.setAccounts(new Account[]{mAccount, mAccountTwo}); cp.onAccountsUpdated(new Account[]{mAccount, mAccountTwo}); assertEquals(1, getCount(RawContacts.CONTENT_URI, null, null)); assertStoredValue(rawContact3, RawContacts.ACCOUNT_NAME, null); assertStoredValue(rawContact3, RawContacts.ACCOUNT_TYPE, null); long rawContactId1 = RawContactUtil.createRawContact(mResolver, mAccount); insertEmail(rawContactId1, "[email protected]"); long rawContactId2 = RawContactUtil.createRawContact(mResolver, mAccountTwo); insertEmail(rawContactId2, "[email protected]"); insertImHandle(rawContactId2, Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]"); insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.AVAILABLE, null, StatusUpdates.CAPABILITY_HAS_CAMERA); mActor.setAccounts(new Account[]{mAccount}); cp.onAccountsUpdated(new Account[]{mAccount}); assertEquals(2, getCount(RawContacts.CONTENT_URI, null, null)); assertEquals(0, getCount(StatusUpdates.CONTENT_URI, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId2, null)); } public void testAccountDeletion() { Account readOnlyAccount = new Account("act", READ_ONLY_ACCOUNT_TYPE); ContactsProvider2 cp = (ContactsProvider2) getProvider(); mActor.setAccounts(new Account[]{readOnlyAccount, mAccount}); cp.onAccountsUpdated(new Account[]{readOnlyAccount, mAccount}); long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "John", "Doe", readOnlyAccount); Uri photoUri1 = insertPhoto(rawContactId1); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "john", "doe", mAccount); Uri photoUri2 = insertPhoto(rawContactId2); storeValue(photoUri2, Photo.IS_SUPER_PRIMARY, "1"); assertAggregated(rawContactId1, rawContactId2); long contactId = queryContactId(rawContactId1); // The display name should come from the writable account assertStoredValue(Uri.withAppendedPath( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.Data.CONTENT_DIRECTORY), Contacts.DISPLAY_NAME, "john doe"); // The photo should be the one we marked as super-primary assertStoredValue(Contacts.CONTENT_URI, contactId, Contacts.PHOTO_ID, ContentUris.parseId(photoUri2)); mActor.setAccounts(new Account[]{readOnlyAccount}); // Remove the writable account cp.onAccountsUpdated(new Account[]{readOnlyAccount}); // The display name should come from the remaining account assertStoredValue(Uri.withAppendedPath( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.Data.CONTENT_DIRECTORY), Contacts.DISPLAY_NAME, "John Doe"); // The photo should be the remaining one assertStoredValue(Contacts.CONTENT_URI, contactId, Contacts.PHOTO_ID, ContentUris.parseId(photoUri1)); } public void testStreamItemsCleanedUpOnAccountRemoval() { Account doomedAccount = new Account("doom", "doom"); Account safeAccount = mAccount; ContactsProvider2 cp = (ContactsProvider2) getProvider(); mActor.setAccounts(new Account[]{doomedAccount, safeAccount}); cp.onAccountsUpdated(new Account[]{doomedAccount, safeAccount}); // Create a doomed raw contact, stream item, and photo. long doomedRawContactId = RawContactUtil.createRawContactWithName(mResolver, doomedAccount); Uri doomedStreamItemUri = insertStreamItem(doomedRawContactId, buildGenericStreamItemValues(), doomedAccount); long doomedStreamItemId = ContentUris.parseId(doomedStreamItemUri); Uri doomedStreamItemPhotoUri = insertStreamItemPhoto( doomedStreamItemId, buildGenericStreamItemPhotoValues(0), doomedAccount); // Create a safe raw contact, stream item, and photo. long safeRawContactId = RawContactUtil.createRawContactWithName(mResolver, safeAccount); Uri safeStreamItemUri = insertStreamItem(safeRawContactId, buildGenericStreamItemValues(), safeAccount); long safeStreamItemId = ContentUris.parseId(safeStreamItemUri); Uri safeStreamItemPhotoUri = insertStreamItemPhoto( safeStreamItemId, buildGenericStreamItemPhotoValues(0), safeAccount); long safeStreamItemPhotoId = ContentUris.parseId(safeStreamItemPhotoUri); // Remove the doomed account. mActor.setAccounts(new Account[]{safeAccount}); cp.onAccountsUpdated(new Account[]{safeAccount}); // Check that the doomed stuff has all been nuked. ContentValues[] noValues = new ContentValues[0]; assertStoredValues(ContentUris.withAppendedId(RawContacts.CONTENT_URI, doomedRawContactId), noValues); assertStoredValues(doomedStreamItemUri, noValues); assertStoredValues(doomedStreamItemPhotoUri, noValues); // Check that the safe stuff lives on. assertStoredValue(RawContacts.CONTENT_URI, safeRawContactId, RawContacts._ID, safeRawContactId); assertStoredValue(safeStreamItemUri, StreamItems._ID, safeStreamItemId); assertStoredValue(safeStreamItemPhotoUri, StreamItemPhotos._ID, safeStreamItemPhotoId); } public void testContactDeletion() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "John", "Doe", TestUtil.ACCOUNT_1); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "John", "Doe", TestUtil.ACCOUNT_2); long contactId = queryContactId(rawContactId1); mResolver.delete(ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), null, null); assertStoredValue(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId1), RawContacts.DELETED, "1"); assertStoredValue(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId2), RawContacts.DELETED, "1"); } public void testMarkAsDirtyParameter() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); Uri uri = DataUtil.insertStructuredName(mResolver, rawContactId, "John", "Doe"); clearDirty(rawContactUri); Uri updateUri = setCallerIsSyncAdapter(uri, mAccount); ContentValues values = new ContentValues(); values.put(StructuredName.FAMILY_NAME, "Dough"); mResolver.update(updateUri, values, null, null); assertStoredValue(uri, StructuredName.FAMILY_NAME, "Dough"); assertDirty(rawContactUri, false); assertNetworkNotified(false); } public void testRawContactDirtyAndVersion() { final long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, rawContactId); assertDirty(uri, false); long version = getVersion(uri); ContentValues values = new ContentValues(); values.put(ContactsContract.RawContacts.DIRTY, 0); values.put(ContactsContract.RawContacts.SEND_TO_VOICEMAIL, 1); values.put(ContactsContract.RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_IMMEDIATE); values.put(ContactsContract.RawContacts.STARRED, 1); assertEquals(1, mResolver.update(uri, values, null, null)); assertEquals(version, getVersion(uri)); assertDirty(uri, false); assertNetworkNotified(false); Uri emailUri = insertEmail(rawContactId, "[email protected]"); assertDirty(uri, true); assertNetworkNotified(true); ++version; assertEquals(version, getVersion(uri)); clearDirty(uri); values = new ContentValues(); values.put(Email.DATA, "[email protected]"); mResolver.update(emailUri, values, null, null); assertDirty(uri, true); assertNetworkNotified(true); ++version; assertEquals(version, getVersion(uri)); clearDirty(uri); mResolver.delete(emailUri, null, null); assertDirty(uri, true); assertNetworkNotified(true); ++version; assertEquals(version, getVersion(uri)); } public void testRawContactClearDirty() { final long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, rawContactId); long version = getVersion(uri); insertEmail(rawContactId, "[email protected]"); assertDirty(uri, true); version++; assertEquals(version, getVersion(uri)); clearDirty(uri); assertDirty(uri, false); assertEquals(version, getVersion(uri)); } public void testRawContactDeletionSetsDirty() { final long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, rawContactId); long version = getVersion(uri); clearDirty(uri); assertDirty(uri, false); mResolver.delete(uri, null, null); assertStoredValue(uri, RawContacts.DELETED, "1"); assertDirty(uri, true); assertNetworkNotified(true); version++; assertEquals(version, getVersion(uri)); } public void testDeleteContactWithoutName() { Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, new ContentValues()); long rawContactId = ContentUris.parseId(rawContactUri); Uri phoneUri = insertPhoneNumber(rawContactId, "555-123-45678", true); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri lookupUri = Contacts.getLookupUri(mResolver, contactUri); int numDeleted = mResolver.delete(lookupUri, null, null); assertEquals(1, numDeleted); } public void testDeleteContactWithoutAnyData() { Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, new ContentValues()); long rawContactId = ContentUris.parseId(rawContactUri); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri lookupUri = Contacts.getLookupUri(mResolver, contactUri); int numDeleted = mResolver.delete(lookupUri, null, null); assertEquals(1, numDeleted); } public void testDeleteContactWithEscapedUri() { ContentValues values = new ContentValues(); values.put(RawContacts.SOURCE_ID, "!@#$%^&*()_+=-/.,<>?;'\":[]}{\\|`~"); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri lookupUri = Contacts.getLookupUri(mResolver, contactUri); assertEquals(1, mResolver.delete(lookupUri, null, null)); } public void testQueryContactWithEscapedUri() { ContentValues values = new ContentValues(); values.put(RawContacts.SOURCE_ID, "!@#$%^&*()_+=-/.,<>?;'\":[]}{\\|`~"); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri lookupUri = Contacts.getLookupUri(mResolver, contactUri); Cursor c = mResolver.query(lookupUri, null, null, null, ""); assertEquals(1, c.getCount()); c.close(); } public void testGetPhotoUri() { ContentValues values = new ContentValues(); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); DataUtil.insertStructuredName(mResolver, rawContactId, "John", "Doe"); long dataId = ContentUris.parseId(insertPhoto(rawContactId, R.drawable.earth_normal)); long photoFileId = getStoredLongValue(Data.CONTENT_URI, Data._ID + "=?", new String[]{String.valueOf(dataId)}, Photo.PHOTO_FILE_ID); String photoUri = ContentUris.withAppendedId(DisplayPhoto.CONTENT_URI, photoFileId) .toString(); assertStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId)), Contacts.PHOTO_URI, photoUri); } public void testGetPhotoViaLookupUri() throws IOException { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri lookupUri = Contacts.getLookupUri(mResolver, contactUri); String lookupKey = lookupUri.getPathSegments().get(2); insertPhoto(rawContactId, R.drawable.earth_small); byte[] thumbnail = loadPhotoFromResource(R.drawable.earth_small, PhotoSize.THUMBNAIL); // Two forms of lookup key URIs should be valid - one with the contact ID, one without. Uri photoLookupUriWithId = Uri.withAppendedPath(lookupUri, "photo"); Uri photoLookupUriWithoutId = Contacts.CONTENT_LOOKUP_URI.buildUpon() .appendPath(lookupKey).appendPath("photo").build(); // Try retrieving as a data record. ContentValues values = new ContentValues(); values.put(Photo.PHOTO, thumbnail); assertStoredValues(photoLookupUriWithId, values); assertStoredValues(photoLookupUriWithoutId, values); // Try opening as an input stream. EvenMoreAsserts.assertImageRawData(getContext(), thumbnail, mResolver.openInputStream(photoLookupUriWithId)); EvenMoreAsserts.assertImageRawData(getContext(), thumbnail, mResolver.openInputStream(photoLookupUriWithoutId)); } public void testInputStreamForPhoto() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); insertPhoto(rawContactId); Uri photoUri = Uri.parse(getStoredValue(contactUri, Contacts.PHOTO_URI)); Uri photoThumbnailUri = Uri.parse(getStoredValue(contactUri, Contacts.PHOTO_THUMBNAIL_URI)); // Check the thumbnail. EvenMoreAsserts.assertImageRawData(getContext(), loadTestPhoto(PhotoSize.THUMBNAIL), mResolver.openInputStream(photoThumbnailUri)); // Then check the display photo. Note because we only inserted a small photo, but not a // display photo, this returns the thumbnail image itself, which was compressed at // the thumnail compression rate, which is why we compare to // loadTestPhoto(PhotoSize.THUMBNAIL) rather than loadTestPhoto(PhotoSize.DISPLAY_PHOTO) // here. // (In other words, loadTestPhoto(PhotoSize.DISPLAY_PHOTO) returns the same photo as // loadTestPhoto(PhotoSize.THUMBNAIL), except it's compressed at a lower compression rate.) EvenMoreAsserts.assertImageRawData(getContext(), loadTestPhoto(PhotoSize.THUMBNAIL), mResolver.openInputStream(photoUri)); } public void testSuperPrimaryPhoto() { long rawContactId1 = RawContactUtil.createRawContact(mResolver, new Account("a", "a")); Uri photoUri1 = insertPhoto(rawContactId1, R.drawable.earth_normal); long photoId1 = ContentUris.parseId(photoUri1); long rawContactId2 = RawContactUtil.createRawContact(mResolver, new Account("b", "b")); Uri photoUri2 = insertPhoto(rawContactId2, R.drawable.earth_normal); long photoId2 = ContentUris.parseId(photoUri2); setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId1)); long photoFileId1 = getStoredLongValue(Data.CONTENT_URI, Data._ID + "=?", new String[]{String.valueOf(photoId1)}, Photo.PHOTO_FILE_ID); String photoUri = ContentUris.withAppendedId(DisplayPhoto.CONTENT_URI, photoFileId1) .toString(); assertStoredValue(contactUri, Contacts.PHOTO_ID, photoId1); assertStoredValue(contactUri, Contacts.PHOTO_URI, photoUri); setAggregationException(AggregationExceptions.TYPE_KEEP_SEPARATE, rawContactId1, rawContactId2); ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 1); mResolver.update(photoUri2, values, null, null); setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId1)); assertStoredValue(contactUri, Contacts.PHOTO_ID, photoId2); mResolver.update(photoUri1, values, null, null); assertStoredValue(contactUri, Contacts.PHOTO_ID, photoId1); } public void testUpdatePhoto() { ContentValues values = new ContentValues(); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); DataUtil.insertStructuredName(mResolver, rawContactId, "John", "Doe"); Uri twigUri = Uri.withAppendedPath(ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId)), Contacts.Photo.CONTENT_DIRECTORY); values.clear(); values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); values.putNull(Photo.PHOTO); Uri dataUri = mResolver.insert(Data.CONTENT_URI, values); long photoId = ContentUris.parseId(dataUri); assertEquals(0, getCount(twigUri, null, null)); values.clear(); values.put(Photo.PHOTO, loadTestPhoto()); mResolver.update(dataUri, values, null, null); assertNetworkNotified(true); long twigId = getStoredLongValue(twigUri, Data._ID); assertEquals(photoId, twigId); } public void testUpdateRawContactDataPhoto() { // setup a contact with a null photo ContentValues values = new ContentValues(); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); // setup a photo values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); values.putNull(Photo.PHOTO); // try to do an update before insert should return count == 0 Uri dataUri = Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.Data.CONTENT_DIRECTORY); assertEquals(0, mResolver.update(dataUri, values, Data.MIMETYPE + "=?", new String[] {Photo.CONTENT_ITEM_TYPE})); mResolver.insert(Data.CONTENT_URI, values); // save a photo to the db values.clear(); values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); values.put(Photo.PHOTO, loadTestPhoto()); assertEquals(1, mResolver.update(dataUri, values, Data.MIMETYPE + "=?", new String[] {Photo.CONTENT_ITEM_TYPE})); // verify the photo Cursor storedPhoto = mResolver.query(dataUri, new String[] {Photo.PHOTO}, Data.MIMETYPE + "=?", new String[] {Photo.CONTENT_ITEM_TYPE}, null); storedPhoto.moveToFirst(); MoreAsserts.assertEquals(loadTestPhoto(PhotoSize.THUMBNAIL), storedPhoto.getBlob(0)); storedPhoto.close(); } public void testOpenDisplayPhotoForContactId() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); insertPhoto(rawContactId, R.drawable.earth_normal); Uri photoUri = Contacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(contactId)) .appendPath(Contacts.Photo.DISPLAY_PHOTO).build(); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(photoUri)); } public void testOpenDisplayPhotoForContactLookupKey() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); String lookupKey = queryLookupKey(contactId); insertPhoto(rawContactId, R.drawable.earth_normal); Uri photoUri = Contacts.CONTENT_LOOKUP_URI.buildUpon() .appendPath(lookupKey) .appendPath(Contacts.Photo.DISPLAY_PHOTO).build(); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(photoUri)); } public void testOpenDisplayPhotoForContactLookupKeyAndId() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); String lookupKey = queryLookupKey(contactId); insertPhoto(rawContactId, R.drawable.earth_normal); Uri photoUri = Contacts.CONTENT_LOOKUP_URI.buildUpon() .appendPath(lookupKey) .appendPath(String.valueOf(contactId)) .appendPath(Contacts.Photo.DISPLAY_PHOTO).build(); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(photoUri)); } public void testOpenDisplayPhotoForRawContactId() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); insertPhoto(rawContactId, R.drawable.earth_normal); Uri photoUri = RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.DisplayPhoto.CONTENT_DIRECTORY).build(); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(photoUri)); } public void testOpenDisplayPhotoByPhotoUri() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); insertPhoto(rawContactId, R.drawable.earth_normal); // Get the photo URI out and check the content. String photoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(Uri.parse(photoUri))); } public void testPhotoUriForDisplayPhoto() { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); // Photo being inserted is larger than a thumbnail, so it will be stored as a file. long dataId = ContentUris.parseId(insertPhoto(rawContactId, R.drawable.earth_normal)); String photoFileId = getStoredValue(ContentUris.withAppendedId(Data.CONTENT_URI, dataId), Photo.PHOTO_FILE_ID); String photoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); // Check that the photo URI differs from the thumbnail. String thumbnailUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_THUMBNAIL_URI); assertFalse(photoUri.equals(thumbnailUri)); // URI should be of the form display_photo/ID assertEquals(Uri.withAppendedPath(DisplayPhoto.CONTENT_URI, photoFileId).toString(), photoUri); } public void testPhotoUriForThumbnailPhoto() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); // Photo being inserted is a thumbnail, so it will only be stored in a BLOB. The photo URI // will fall back to the thumbnail URI. insertPhoto(rawContactId, R.drawable.earth_small); String photoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); // Check that the photo URI is equal to the thumbnail URI. String thumbnailUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_THUMBNAIL_URI); assertEquals(photoUri, thumbnailUri); // URI should be of the form contacts/ID/photo assertEquals(Uri.withAppendedPath( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.Photo.CONTENT_DIRECTORY).toString(), photoUri); // Loading the photo URI content should get the thumbnail. EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_small, PhotoSize.THUMBNAIL), mResolver.openInputStream(Uri.parse(photoUri))); } public void testWriteNewPhotoToAssetFile() throws Exception { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); // Load in a huge photo. final byte[] originalPhoto = loadPhotoFromResource( R.drawable.earth_huge, PhotoSize.ORIGINAL); // Write it out. final Uri writeablePhotoUri = RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.DisplayPhoto.CONTENT_DIRECTORY).build(); writePhotoAsync(writeablePhotoUri, originalPhoto); // Check that the display photo and thumbnail have been set. String photoUri = null; for (int i = 0; i < 10 && photoUri == null; i++) { // Wait a tick for the photo processing to occur. Thread.sleep(100); photoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); } assertFalse(TextUtils.isEmpty(photoUri)); String thumbnailUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_THUMBNAIL_URI); assertFalse(TextUtils.isEmpty(thumbnailUri)); assertNotSame(photoUri, thumbnailUri); // Check the content of the display photo and thumbnail. EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(Uri.parse(photoUri))); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.THUMBNAIL), mResolver.openInputStream(Uri.parse(thumbnailUri))); } public void testWriteUpdatedPhotoToAssetFile() throws Exception { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); // Insert a large photo first. insertPhoto(rawContactId, R.drawable.earth_large); String largeEarthPhotoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); // Load in a huge photo. byte[] originalPhoto = loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.ORIGINAL); // Write it out. Uri writeablePhotoUri = RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.DisplayPhoto.CONTENT_DIRECTORY).build(); writePhotoAsync(writeablePhotoUri, originalPhoto); // Allow a second for processing to occur. Thread.sleep(1000); // Check that the display photo URI has been modified. String hugeEarthPhotoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); assertFalse(hugeEarthPhotoUri.equals(largeEarthPhotoUri)); // Check the content of the display photo and thumbnail. String hugeEarthThumbnailUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_THUMBNAIL_URI); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(Uri.parse(hugeEarthPhotoUri))); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.THUMBNAIL), mResolver.openInputStream(Uri.parse(hugeEarthThumbnailUri))); } private void writePhotoAsync(final Uri uri, final byte[] photoBytes) throws Exception { AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() { @Override protected Object doInBackground(Object... params) { OutputStream os; try { os = mResolver.openOutputStream(uri, "rw"); os.write(photoBytes); os.close(); return null; } catch (IOException ioe) { throw new RuntimeException(ioe); } } }; task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null).get(); } public void testPhotoDimensionLimits() { ContentValues values = new ContentValues(); values.put(DisplayPhoto.DISPLAY_MAX_DIM, 256); values.put(DisplayPhoto.THUMBNAIL_MAX_DIM, 96); assertStoredValues(DisplayPhoto.CONTENT_MAX_DIMENSIONS_URI, values); } public void testPhotoStoreCleanup() throws IOException { SynchronousContactsProvider2 provider = (SynchronousContactsProvider2) mActor.provider; PhotoStore photoStore = provider.getPhotoStore(); // Trigger an initial cleanup so another one won't happen while we're running this test. provider.cleanupPhotoStore(); // Insert a couple of contacts with photos. long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver); long contactId1 = queryContactId(rawContactId1); long dataId1 = ContentUris.parseId(insertPhoto(rawContactId1, R.drawable.earth_normal)); long photoFileId1 = getStoredLongValue(ContentUris.withAppendedId(Data.CONTENT_URI, dataId1), Photo.PHOTO_FILE_ID); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver); long contactId2 = queryContactId(rawContactId2); long dataId2 = ContentUris.parseId(insertPhoto(rawContactId2, R.drawable.earth_normal)); long photoFileId2 = getStoredLongValue(ContentUris.withAppendedId(Data.CONTENT_URI, dataId2), Photo.PHOTO_FILE_ID); // Update the second raw contact with a different photo. ContentValues values = new ContentValues(); values.put(Data.RAW_CONTACT_ID, rawContactId2); values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); values.put(Photo.PHOTO, loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.ORIGINAL)); assertEquals(1, mResolver.update(Data.CONTENT_URI, values, Data._ID + "=?", new String[]{String.valueOf(dataId2)})); long replacementPhotoFileId = getStoredLongValue(ContentUris.withAppendedId(Data.CONTENT_URI, dataId2), Photo.PHOTO_FILE_ID); // Insert a third raw contact that has a bogus photo file ID. long bogusFileId = 1234567; long rawContactId3 = RawContactUtil.createRawContactWithName(mResolver); long contactId3 = queryContactId(rawContactId3); values.clear(); values.put(Data.RAW_CONTACT_ID, rawContactId3); values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); values.put(Photo.PHOTO, loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.THUMBNAIL)); values.put(Photo.PHOTO_FILE_ID, bogusFileId); values.put(DataRowHandlerForPhoto.SKIP_PROCESSING_KEY, true); mResolver.insert(Data.CONTENT_URI, values); // Insert a fourth raw contact with a stream item that has a photo, then remove that photo // from the photo store. Account socialAccount = new Account("social", "social"); long rawContactId4 = RawContactUtil.createRawContactWithName(mResolver, socialAccount); Uri streamItemUri = insertStreamItem(rawContactId4, buildGenericStreamItemValues(), socialAccount); long streamItemId = ContentUris.parseId(streamItemUri); Uri streamItemPhotoUri = insertStreamItemPhoto( streamItemId, buildGenericStreamItemPhotoValues(0), socialAccount); long streamItemPhotoFileId = getStoredLongValue(streamItemPhotoUri, StreamItemPhotos.PHOTO_FILE_ID); photoStore.remove(streamItemPhotoFileId); // Also insert a bogus photo that nobody is using. long bogusPhotoId = photoStore.insert(new PhotoProcessor(loadPhotoFromResource( R.drawable.earth_huge, PhotoSize.ORIGINAL), 256, 96)); // Manually trigger another cleanup in the provider. provider.cleanupPhotoStore(); // The following things should have happened. // 1. Raw contact 1 and its photo remain unaffected. assertEquals(photoFileId1, (long) getStoredLongValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId1), Contacts.PHOTO_FILE_ID)); // 2. Raw contact 2 retains its new photo. The old one is deleted from the photo store. assertEquals(replacementPhotoFileId, (long) getStoredLongValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId2), Contacts.PHOTO_FILE_ID)); assertNull(photoStore.get(photoFileId2)); // 3. Raw contact 3 should have its photo file reference cleared. assertNull(getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId3), Contacts.PHOTO_FILE_ID)); // 4. The bogus photo that nobody was using should be cleared from the photo store. assertNull(photoStore.get(bogusPhotoId)); // 5. The bogus stream item photo should be cleared from the stream item. assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), new ContentValues[0]); } public void testPhotoStoreCleanupForProfile() { SynchronousContactsProvider2 provider = (SynchronousContactsProvider2) mActor.provider; PhotoStore profilePhotoStore = provider.getProfilePhotoStore(); // Trigger an initial cleanup so another one won't happen while we're running this test. provider.switchToProfileModeForTest(); provider.cleanupPhotoStore(); // Create the profile contact and add a photo. Account socialAccount = new Account("social", "social"); ContentValues values = new ContentValues(); values.put(RawContacts.ACCOUNT_NAME, socialAccount.name); values.put(RawContacts.ACCOUNT_TYPE, socialAccount.type); long profileRawContactId = createBasicProfileContact(values); long profileContactId = queryContactId(profileRawContactId); long dataId = ContentUris.parseId( insertPhoto(profileRawContactId, R.drawable.earth_normal)); long profilePhotoFileId = getStoredLongValue(ContentUris.withAppendedId(Data.CONTENT_URI, dataId), Photo.PHOTO_FILE_ID); // Also add a stream item with a photo. Uri streamItemUri = insertStreamItem(profileRawContactId, buildGenericStreamItemValues(), socialAccount); long streamItemId = ContentUris.parseId(streamItemUri); Uri streamItemPhotoUri = insertStreamItemPhoto( streamItemId, buildGenericStreamItemPhotoValues(0), socialAccount); long streamItemPhotoFileId = getStoredLongValue(streamItemPhotoUri, StreamItemPhotos.PHOTO_FILE_ID); // Remove the stream item photo and the profile photo. profilePhotoStore.remove(profilePhotoFileId); profilePhotoStore.remove(streamItemPhotoFileId); // Manually trigger another cleanup in the provider. provider.switchToProfileModeForTest(); provider.cleanupPhotoStore(); // The following things should have happened. // The stream item photo should have been removed. assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), new ContentValues[0]); // The profile photo should have been cleared. assertNull(getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, profileContactId), Contacts.PHOTO_FILE_ID)); } public void testOverwritePhotoWithThumbnail() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); // Write a regular-size photo. long dataId = ContentUris.parseId(insertPhoto(rawContactId, R.drawable.earth_normal)); Long photoFileId = getStoredLongValue(contactUri, Contacts.PHOTO_FILE_ID); assertTrue(photoFileId != null && photoFileId > 0); // Now overwrite the photo with a thumbnail-sized photo. ContentValues update = new ContentValues(); update.put(Photo.PHOTO, loadPhotoFromResource(R.drawable.earth_small, PhotoSize.ORIGINAL)); mResolver.update(ContentUris.withAppendedId(Data.CONTENT_URI, dataId), update, null, null); // Photo file ID should have been nulled out, and the photo URI should be the same as the // thumbnail URI. assertNull(getStoredValue(contactUri, Contacts.PHOTO_FILE_ID)); String photoUri = getStoredValue(contactUri, Contacts.PHOTO_URI); String thumbnailUri = getStoredValue(contactUri, Contacts.PHOTO_THUMBNAIL_URI); assertEquals(photoUri, thumbnailUri); // Retrieving the photo URI should get the thumbnail content. EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_small, PhotoSize.THUMBNAIL), mResolver.openInputStream(Uri.parse(photoUri))); } public void testUpdateRawContactSetStarred() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver); Uri rawContactUri1 = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId1); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver); Uri rawContactUri2 = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId2); setAggregationException( AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); long contactId = queryContactId(rawContactId1); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); assertStoredValue(contactUri, Contacts.STARRED, "0"); ContentValues values = new ContentValues(); values.put(RawContacts.STARRED, "1"); mResolver.update(rawContactUri1, values, null, null); assertStoredValue(rawContactUri1, RawContacts.STARRED, "1"); assertStoredValue(rawContactUri2, RawContacts.STARRED, "0"); assertStoredValue(contactUri, Contacts.STARRED, "1"); values.put(RawContacts.STARRED, "0"); mResolver.update(rawContactUri1, values, null, null); assertStoredValue(rawContactUri1, RawContacts.STARRED, "0"); assertStoredValue(rawContactUri2, RawContacts.STARRED, "0"); assertStoredValue(contactUri, Contacts.STARRED, "0"); values.put(Contacts.STARRED, "1"); mResolver.update(contactUri, values, null, null); assertStoredValue(rawContactUri1, RawContacts.STARRED, "1"); assertStoredValue(rawContactUri2, RawContacts.STARRED, "1"); assertStoredValue(contactUri, Contacts.STARRED, "1"); } public void testSetAndClearSuperPrimaryEmail() { long rawContactId1 = RawContactUtil.createRawContact(mResolver, new Account("a", "a")); Uri mailUri11 = insertEmail(rawContactId1, "[email protected]"); Uri mailUri12 = insertEmail(rawContactId1, "[email protected]"); long rawContactId2 = RawContactUtil.createRawContact(mResolver, new Account("b", "b")); Uri mailUri21 = insertEmail(rawContactId2, "[email protected]"); Uri mailUri22 = insertEmail(rawContactId2, "[email protected]"); assertStoredValue(mailUri11, Data.IS_PRIMARY, 0); assertStoredValue(mailUri11, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 0); // Set super primary on the first pair, primary on the second { ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 1); mResolver.update(mailUri11, values, null, null); } { ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 1); mResolver.update(mailUri22, values, null, null); } assertStoredValue(mailUri11, Data.IS_PRIMARY, 1); assertStoredValue(mailUri11, Data.IS_SUPER_PRIMARY, 1); assertStoredValue(mailUri12, Data.IS_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 1); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 1); // Clear primary on the first pair, make sure second is not affected and super_primary is // also cleared { ContentValues values = new ContentValues(); values.put(Data.IS_PRIMARY, 0); mResolver.update(mailUri11, values, null, null); } assertStoredValue(mailUri11, Data.IS_PRIMARY, 0); assertStoredValue(mailUri11, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 1); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 1); // Ensure that we can only clear super_primary, if we specify the correct data row { ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 0); mResolver.update(mailUri21, values, null, null); } assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 1); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 1); // Ensure that we can only clear primary, if we specify the correct data row { ContentValues values = new ContentValues(); values.put(Data.IS_PRIMARY, 0); mResolver.update(mailUri21, values, null, null); } assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 1); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 1); // Now clear super-primary for real { ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 0); mResolver.update(mailUri22, values, null, null); } assertStoredValue(mailUri11, Data.IS_PRIMARY, 0); assertStoredValue(mailUri11, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 1); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 0); } /** * Common function for the testNewPrimaryIn* functions. Its four configurations * are each called from its own test */ public void testChangingPrimary(boolean inUpdate, boolean withSuperPrimary) { long rawContactId = RawContactUtil.createRawContact(mResolver, new Account("a", "a")); Uri mailUri1 = insertEmail(rawContactId, "[email protected]", true); if (withSuperPrimary) { final ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 1); mResolver.update(mailUri1, values, null, null); } assertStoredValue(mailUri1, Data.IS_PRIMARY, 1); assertStoredValue(mailUri1, Data.IS_SUPER_PRIMARY, withSuperPrimary ? 1 : 0); // Insert another item final Uri mailUri2; if (inUpdate) { mailUri2 = insertEmail(rawContactId, "[email protected]"); assertStoredValue(mailUri1, Data.IS_PRIMARY, 1); assertStoredValue(mailUri1, Data.IS_SUPER_PRIMARY, withSuperPrimary ? 1 : 0); assertStoredValue(mailUri2, Data.IS_PRIMARY, 0); assertStoredValue(mailUri2, Data.IS_SUPER_PRIMARY, 0); final ContentValues values = new ContentValues(); values.put(Data.IS_PRIMARY, 1); mResolver.update(mailUri2, values, null, null); } else { // directly add as default mailUri2 = insertEmail(rawContactId, "[email protected]", true); } // Ensure that primary has been unset on the first // If withSuperPrimary is set, also ensure that is has been moved to the new item assertStoredValue(mailUri1, Data.IS_PRIMARY, 0); assertStoredValue(mailUri1, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri2, Data.IS_PRIMARY, 1); assertStoredValue(mailUri2, Data.IS_SUPER_PRIMARY, withSuperPrimary ? 1 : 0); } public void testNewPrimaryInInsert() { testChangingPrimary(false, false); } public void testNewPrimaryInInsertWithSuperPrimary() { testChangingPrimary(false, true); } public void testNewPrimaryInUpdate() { testChangingPrimary(true, false); } public void testNewPrimaryInUpdateWithSuperPrimary() { testChangingPrimary(true, true); } public void testContactSortOrder() { assertEquals(ContactsColumns.PHONEBOOK_BUCKET_PRIMARY + ", " + Contacts.SORT_KEY_PRIMARY, ContactsProvider2.getLocalizedSortOrder(Contacts.SORT_KEY_PRIMARY)); assertEquals(ContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE + ", " + Contacts.SORT_KEY_ALTERNATIVE, ContactsProvider2.getLocalizedSortOrder(Contacts.SORT_KEY_ALTERNATIVE)); assertEquals(ContactsColumns.PHONEBOOK_BUCKET_PRIMARY + " DESC, " + Contacts.SORT_KEY_PRIMARY + " DESC", ContactsProvider2.getLocalizedSortOrder(Contacts.SORT_KEY_PRIMARY + " DESC")); String suffix = " COLLATE LOCALIZED DESC"; assertEquals(ContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE + suffix + ", " + Contacts.SORT_KEY_ALTERNATIVE + suffix, ContactsProvider2.getLocalizedSortOrder(Contacts.SORT_KEY_ALTERNATIVE + suffix)); } public void testContactCounts() { Uri uri = Contacts.CONTENT_URI.buildUpon() .appendQueryParameter(ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, "true").build(); RawContactUtil.createRawContact(mResolver); RawContactUtil.createRawContactWithName(mResolver, "James", "Sullivan"); RawContactUtil.createRawContactWithName(mResolver, "The Abominable", "Snowman"); RawContactUtil.createRawContactWithName(mResolver, "Mike", "Wazowski"); RawContactUtil.createRawContactWithName(mResolver, "randall", "boggs"); RawContactUtil.createRawContactWithName(mResolver, "Boo", null); RawContactUtil.createRawContactWithName(mResolver, "Mary", null); RawContactUtil.createRawContactWithName(mResolver, "Roz", null); Cursor cursor = mResolver.query(uri, new String[]{Contacts.DISPLAY_NAME}, null, null, Contacts.SORT_KEY_PRIMARY); assertFirstLetterValues(cursor, "", "B", "J", "M", "R", "T"); assertFirstLetterCounts(cursor, 1, 1, 1, 2, 2, 1); cursor.close(); cursor = mResolver.query(uri, new String[]{Contacts.DISPLAY_NAME}, null, null, Contacts.SORT_KEY_ALTERNATIVE + " COLLATE LOCALIZED DESC"); assertFirstLetterValues(cursor, "W", "S", "R", "M", "B", ""); assertFirstLetterCounts(cursor, 1, 2, 1, 1, 2, 1); cursor.close(); } public void testContactCountsWithGermanNames() { if (!hasGermanCollator()) { return; } ContactLocaleUtils.setLocale(Locale.GERMANY); Uri uri = Contacts.CONTENT_URI.buildUpon() .appendQueryParameter(ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, "true").build(); RawContactUtil.createRawContactWithName(mResolver, "Josef", "Sacher"); RawContactUtil.createRawContactWithName(mResolver, "Franz", "Schiller"); RawContactUtil.createRawContactWithName(mResolver, "Eckart", "Steiff"); RawContactUtil.createRawContactWithName(mResolver, "Klaus", "Seiler"); RawContactUtil.createRawContactWithName(mResolver, "Lars", "Sultan"); RawContactUtil.createRawContactWithName(mResolver, "Heidi", "Rilke"); RawContactUtil.createRawContactWithName(mResolver, "Suse", "Thomas"); Cursor cursor = mResolver.query(uri, new String[]{Contacts.DISPLAY_NAME}, null, null, Contacts.SORT_KEY_ALTERNATIVE); assertFirstLetterValues(cursor, "R", "S", "Sch", "St", "T"); assertFirstLetterCounts(cursor, 1, 3, 1, 1, 1); cursor.close(); } private void assertFirstLetterValues(Cursor cursor, String... expected) { String[] actual = cursor.getExtras() .getStringArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_TITLES); MoreAsserts.assertEquals(expected, actual); } private void assertFirstLetterCounts(Cursor cursor, int... expected) { int[] actual = cursor.getExtras() .getIntArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_COUNTS); MoreAsserts.assertEquals(expected, actual); } public void testReadBooleanQueryParameter() { assertBooleanUriParameter("foo:bar", "bool", true, true); assertBooleanUriParameter("foo:bar", "bool", false, false); assertBooleanUriParameter("foo:bar?bool=0", "bool", true, false); assertBooleanUriParameter("foo:bar?bool=1", "bool", false, true); assertBooleanUriParameter("foo:bar?bool=false", "bool", true, false); assertBooleanUriParameter("foo:bar?bool=true", "bool", false, true); assertBooleanUriParameter("foo:bar?bool=FaLsE", "bool", true, false); assertBooleanUriParameter("foo:bar?bool=false&some=some", "bool", true, false); assertBooleanUriParameter("foo:bar?bool=1&some=some", "bool", false, true); assertBooleanUriParameter("foo:bar?some=bool", "bool", true, true); assertBooleanUriParameter("foo:bar?bool", "bool", true, true); } private void assertBooleanUriParameter(String uriString, String parameter, boolean defaultValue, boolean expectedValue) { assertEquals(expectedValue, ContactsProvider2.readBooleanQueryParameter( Uri.parse(uriString), parameter, defaultValue)); } public void testGetQueryParameter() { assertQueryParameter("foo:bar", "param", null); assertQueryParameter("foo:bar?param", "param", null); assertQueryParameter("foo:bar?param=", "param", ""); assertQueryParameter("foo:bar?param=val", "param", "val"); assertQueryParameter("foo:bar?param=val&some=some", "param", "val"); assertQueryParameter("foo:bar?some=some&param=val", "param", "val"); assertQueryParameter("foo:bar?some=some&param=val&else=else", "param", "val"); assertQueryParameter("foo:bar?param=john%40doe.com", "param", "[email protected]"); assertQueryParameter("foo:bar?some_param=val", "param", null); assertQueryParameter("foo:bar?some_param=val1&param=val2", "param", "val2"); assertQueryParameter("foo:bar?some_param=val1&param=", "param", ""); assertQueryParameter("foo:bar?some_param=val1&param", "param", null); assertQueryParameter("foo:bar?some_param=val1&another_param=val2&param=val3", "param", "val3"); assertQueryParameter("foo:bar?some_param=val1&param=val2&some_param=val3", "param", "val2"); assertQueryParameter("foo:bar?param=val1&some_param=val2", "param", "val1"); assertQueryParameter("foo:bar?p=val1&pp=val2", "p", "val1"); assertQueryParameter("foo:bar?pp=val1&p=val2", "p", "val2"); assertQueryParameter("foo:bar?ppp=val1&pp=val2&p=val3", "p", "val3"); assertQueryParameter("foo:bar?ppp=val&", "p", null); } public void testMissingAccountTypeParameter() { // Try querying for RawContacts only using ACCOUNT_NAME final Uri queryUri = RawContacts.CONTENT_URI.buildUpon().appendQueryParameter( RawContacts.ACCOUNT_NAME, "lolwut").build(); try { final Cursor cursor = mResolver.query(queryUri, null, null, null, null); fail("Able to query with incomplete account query parameters"); } catch (IllegalArgumentException e) { // Expected behavior. } } public void testInsertInconsistentAccountType() { // Try inserting RawContact with inconsistent Accounts final Account red = new Account("red", "red"); final Account blue = new Account("blue", "blue"); final ContentValues values = new ContentValues(); values.put(RawContacts.ACCOUNT_NAME, red.name); values.put(RawContacts.ACCOUNT_TYPE, red.type); final Uri insertUri = TestUtil.maybeAddAccountQueryParameters(RawContacts.CONTENT_URI, blue); try { mResolver.insert(insertUri, values); fail("Able to insert RawContact with inconsistent account details"); } catch (IllegalArgumentException e) { // Expected behavior. } } public void testProviderStatusNoContactsNoAccounts() throws Exception { assertProviderStatus(ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS); } public void testProviderStatusOnlyLocalContacts() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); assertProviderStatus(ProviderStatus.STATUS_NORMAL); mResolver.delete( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), null, null); assertProviderStatus(ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS); } public void testProviderStatusWithAccounts() throws Exception { assertProviderStatus(ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS); mActor.setAccounts(new Account[]{TestUtil.ACCOUNT_1}); ((ContactsProvider2)getProvider()).onAccountsUpdated(new Account[]{TestUtil.ACCOUNT_1}); assertProviderStatus(ProviderStatus.STATUS_NORMAL); mActor.setAccounts(new Account[0]); ((ContactsProvider2)getProvider()).onAccountsUpdated(new Account[0]); assertProviderStatus(ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS); } private void assertProviderStatus(int expectedProviderStatus) { Cursor cursor = mResolver.query(ProviderStatus.CONTENT_URI, new String[]{ProviderStatus.DATA1, ProviderStatus.STATUS}, null, null, null); assertTrue(cursor.moveToFirst()); assertEquals(0, cursor.getLong(0)); assertEquals(expectedProviderStatus, cursor.getInt(1)); cursor.close(); } public void testProperties() throws Exception { ContactsProvider2 provider = (ContactsProvider2)getProvider(); ContactsDatabaseHelper helper = (ContactsDatabaseHelper)provider.getDatabaseHelper(); assertNull(helper.getProperty("non-existent", null)); assertEquals("default", helper.getProperty("non-existent", "default")); helper.setProperty("existent1", "string1"); helper.setProperty("existent2", "string2"); assertEquals("string1", helper.getProperty("existent1", "default")); assertEquals("string2", helper.getProperty("existent2", "default")); helper.setProperty("existent1", null); assertEquals("default", helper.getProperty("existent1", "default")); } private class VCardTestUriCreator { private String mLookup1; private String mLookup2; public VCardTestUriCreator(String lookup1, String lookup2) { super(); mLookup1 = lookup1; mLookup2 = lookup2; } public Uri getUri1() { return Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, mLookup1); } public Uri getUri2() { return Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, mLookup2); } public Uri getCombinedUri() { return Uri.withAppendedPath(Contacts.CONTENT_MULTI_VCARD_URI, Uri.encode(mLookup1 + ":" + mLookup2)); } } private VCardTestUriCreator createVCardTestContacts() { final long rawContactId1 = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "4:12"); DataUtil.insertStructuredName(mResolver, rawContactId1, "John", "Doe"); final long rawContactId2 = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "3:4%121"); DataUtil.insertStructuredName(mResolver, rawContactId2, "Jane", "Doh"); final long contactId1 = queryContactId(rawContactId1); final long contactId2 = queryContactId(rawContactId2); final Uri contact1Uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId1); final Uri contact2Uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId2); final String lookup1 = Uri.encode(Contacts.getLookupUri(mResolver, contact1Uri).getPathSegments().get(2)); final String lookup2 = Uri.encode(Contacts.getLookupUri(mResolver, contact2Uri).getPathSegments().get(2)); return new VCardTestUriCreator(lookup1, lookup2); } public void testQueryMultiVCard() { // No need to create any contacts here, because the query for multiple vcards // does not go into the database at all Uri uri = Uri.withAppendedPath(Contacts.CONTENT_MULTI_VCARD_URI, Uri.encode("123:456")); Cursor cursor = mResolver.query(uri, null, null, null, null); assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToFirst()); assertTrue(cursor.isNull(cursor.getColumnIndex(OpenableColumns.SIZE))); String filename = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); // The resulting name contains date and time. Ensure that before and after are correct assertTrue(filename.startsWith("vcards_")); assertTrue(filename.endsWith(".vcf")); cursor.close(); } public void testQueryFileSingleVCard() { final VCardTestUriCreator contacts = createVCardTestContacts(); { Cursor cursor = mResolver.query(contacts.getUri1(), null, null, null, null); assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToFirst()); assertTrue(cursor.isNull(cursor.getColumnIndex(OpenableColumns.SIZE))); String filename = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); assertEquals("John Doe.vcf", filename); cursor.close(); } { Cursor cursor = mResolver.query(contacts.getUri2(), null, null, null, null); assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToFirst()); assertTrue(cursor.isNull(cursor.getColumnIndex(OpenableColumns.SIZE))); String filename = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); assertEquals("Jane Doh.vcf", filename); cursor.close(); } } public void testQueryFileProfileVCard() { createBasicProfileContact(new ContentValues()); Cursor cursor = mResolver.query(Profile.CONTENT_VCARD_URI, null, null, null, null); assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToFirst()); assertTrue(cursor.isNull(cursor.getColumnIndex(OpenableColumns.SIZE))); String filename = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); assertEquals("Mia Prophyl.vcf", filename); cursor.close(); } public void testOpenAssetFileMultiVCard() throws IOException { final VCardTestUriCreator contacts = createVCardTestContacts(); final AssetFileDescriptor descriptor = mResolver.openAssetFileDescriptor(contacts.getCombinedUri(), "r"); final FileInputStream inputStream = descriptor.createInputStream(); String data = readToEnd(inputStream); inputStream.close(); descriptor.close(); // Ensure that the resulting VCard has both contacts assertTrue(data.contains("N:Doe;John;;;")); assertTrue(data.contains("N:Doh;Jane;;;")); } public void testOpenAssetFileSingleVCard() throws IOException { final VCardTestUriCreator contacts = createVCardTestContacts(); // Ensure that the right VCard is being created in each case { final AssetFileDescriptor descriptor = mResolver.openAssetFileDescriptor(contacts.getUri1(), "r"); final FileInputStream inputStream = descriptor.createInputStream(); final String data = readToEnd(inputStream); inputStream.close(); descriptor.close(); assertTrue(data.contains("N:Doe;John;;;")); assertFalse(data.contains("N:Doh;Jane;;;")); } { final AssetFileDescriptor descriptor = mResolver.openAssetFileDescriptor(contacts.getUri2(), "r"); final FileInputStream inputStream = descriptor.createInputStream(); final String data = readToEnd(inputStream); inputStream.close(); descriptor.close(); assertFalse(data.contains("N:Doe;John;;;")); assertTrue(data.contains("N:Doh;Jane;;;")); } } public void testAutoGroupMembership() { long g1 = createGroup(mAccount, "g1", "t1", 0, true /* autoAdd */, false /* favorite */); long g2 = createGroup(mAccount, "g2", "t2", 0, false /* autoAdd */, false /* favorite */); long g3 = createGroup(mAccountTwo, "g3", "t3", 0, true /* autoAdd */, false /* favorite */); long g4 = createGroup(mAccountTwo, "g4", "t4", 0, false /* autoAdd */, false/* favorite */); long r1 = RawContactUtil.createRawContact(mResolver, mAccount); long r2 = RawContactUtil.createRawContact(mResolver, mAccountTwo); long r3 = RawContactUtil.createRawContact(mResolver, null); Cursor c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } c = queryGroupMemberships(mAccountTwo); try { assertTrue(c.moveToNext()); assertEquals(g3, c.getLong(0)); assertEquals(r2, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } } public void testNoAutoAddMembershipAfterGroupCreation() { long r1 = RawContactUtil.createRawContact(mResolver, mAccount); long r2 = RawContactUtil.createRawContact(mResolver, mAccount); long r3 = RawContactUtil.createRawContact(mResolver, mAccount); long r4 = RawContactUtil.createRawContact(mResolver, mAccountTwo); long r5 = RawContactUtil.createRawContact(mResolver, mAccountTwo); long r6 = RawContactUtil.createRawContact(mResolver, null); assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); long g1 = createGroup(mAccount, "g1", "t1", 0, true /* autoAdd */, false /* favorite */); long g2 = createGroup(mAccount, "g2", "t2", 0, false /* autoAdd */, false /* favorite */); long g3 = createGroup(mAccountTwo, "g3", "t3", 0, true /* autoAdd */, false/* favorite */); assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); } // create some starred and non-starred contacts, some associated with account, some not // favorites group created // the starred contacts should be added to group // favorites group removed // no change to starred status public void testFavoritesMembershipAfterGroupCreation() { long r1 = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.STARRED, "1"); long r2 = RawContactUtil.createRawContact(mResolver, mAccount); long r3 = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.STARRED, "1"); long r4 = RawContactUtil.createRawContact(mResolver, mAccountTwo, RawContacts.STARRED, "1"); long r5 = RawContactUtil.createRawContact(mResolver, mAccountTwo); long r6 = RawContactUtil.createRawContact(mResolver, null, RawContacts.STARRED, "1"); long r7 = RawContactUtil.createRawContact(mResolver, null); assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); long g1 = createGroup(mAccount, "g1", "t1", 0, false /* autoAdd */, true /* favorite */); long g2 = createGroup(mAccount, "g2", "t2", 0, false /* autoAdd */, false /* favorite */); long g3 = createGroup(mAccountTwo, "g3", "t3", 0, false /* autoAdd */, false/* favorite */); assertTrue(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertTrue(queryRawContactIsStarred(r3)); assertTrue(queryRawContactIsStarred(r4)); assertFalse(queryRawContactIsStarred(r5)); assertTrue(queryRawContactIsStarred(r6)); assertFalse(queryRawContactIsStarred(r7)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); Cursor c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r3, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } updateItem(RawContacts.CONTENT_URI, r6, RawContacts.ACCOUNT_NAME, mAccount.name, RawContacts.ACCOUNT_TYPE, mAccount.type); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r3, c.getLong(1)); assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r6, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } mResolver.delete(ContentUris.withAppendedId(Groups.CONTENT_URI, g1), null, null); assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); assertTrue(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertTrue(queryRawContactIsStarred(r3)); assertTrue(queryRawContactIsStarred(r4)); assertFalse(queryRawContactIsStarred(r5)); assertTrue(queryRawContactIsStarred(r6)); assertFalse(queryRawContactIsStarred(r7)); } public void testFavoritesGroupMembershipChangeAfterStarChange() { long g1 = createGroup(mAccount, "g1", "t1", 0, false /* autoAdd */, true /* favorite */); long g2 = createGroup(mAccount, "g2", "t2", 0, false /* autoAdd */, false/* favorite */); long g4 = createGroup(mAccountTwo, "g4", "t4", 0, false /* autoAdd */, true /* favorite */); long g5 = createGroup(mAccountTwo, "g5", "t5", 0, false /* autoAdd */, false/* favorite */); long r1 = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.STARRED, "1"); long r2 = RawContactUtil.createRawContact(mResolver, mAccount); long r3 = RawContactUtil.createRawContact(mResolver, mAccountTwo); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); Cursor c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } // remove the star from r1 assertEquals(1, updateItem(RawContacts.CONTENT_URI, r1, RawContacts.STARRED, "0")); // Since no raw contacts are starred, there should be no group memberships. assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); // mark r1 as starred assertEquals(1, updateItem(RawContacts.CONTENT_URI, r1, RawContacts.STARRED, "1")); // Now that r1 is starred it should have a membership in the one groups from mAccount // that is marked as a favorite. // There should be no memberships in mAccountTwo since it has no starred raw contacts. assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } // remove the star from r1 assertEquals(1, updateItem(RawContacts.CONTENT_URI, r1, RawContacts.STARRED, "0")); // Since no raw contacts are starred, there should be no group memberships. assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(r1)); assertNotNull(contactUri); // mark r1 as starred via its contact lookup uri assertEquals(1, updateItem(contactUri, Contacts.STARRED, "1")); // Now that r1 is starred it should have a membership in the one groups from mAccount // that is marked as a favorite. // There should be no memberships in mAccountTwo since it has no starred raw contacts. assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } // remove the star from r1 updateItem(contactUri, Contacts.STARRED, "0"); // Since no raw contacts are starred, there should be no group memberships. assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); } public void testStarChangedAfterGroupMembershipChange() { long g1 = createGroup(mAccount, "g1", "t1", 0, false /* autoAdd */, true /* favorite */); long g2 = createGroup(mAccount, "g2", "t2", 0, false /* autoAdd */, false/* favorite */); long g4 = createGroup(mAccountTwo, "g4", "t4", 0, false /* autoAdd */, true /* favorite */); long g5 = createGroup(mAccountTwo, "g5", "t5", 0, false /* autoAdd */, false/* favorite */); long r1 = RawContactUtil.createRawContact(mResolver, mAccount); long r2 = RawContactUtil.createRawContact(mResolver, mAccount); long r3 = RawContactUtil.createRawContact(mResolver, mAccountTwo); assertFalse(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertFalse(queryRawContactIsStarred(r3)); Cursor c; // add r1 to one favorites group // r1's star should automatically be set // r1 should automatically be added to the other favorites group Uri urir1g1 = insertGroupMembership(r1, g1); assertTrue(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertFalse(queryRawContactIsStarred(r3)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } // remove r1 from one favorites group mResolver.delete(urir1g1, null, null); // r1's star should no longer be set assertFalse(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertFalse(queryRawContactIsStarred(r3)); // there should be no membership rows assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); // add r3 to the one favorites group for that account // r3's star should automatically be set Uri urir3g4 = insertGroupMembership(r3, g4); assertFalse(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertTrue(queryRawContactIsStarred(r3)); assertNoRowsAndClose(queryGroupMemberships(mAccount)); c = queryGroupMemberships(mAccountTwo); try { assertTrue(c.moveToNext()); assertEquals(g4, c.getLong(0)); assertEquals(r3, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } // remove r3 from the favorites group mResolver.delete(urir3g4, null, null); // r3's star should automatically be cleared assertFalse(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertFalse(queryRawContactIsStarred(r3)); assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); } public void testReadOnlyRawContact() { long rawContactId = RawContactUtil.createRawContact(mResolver); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); storeValue(rawContactUri, RawContacts.CUSTOM_RINGTONE, "first"); storeValue(rawContactUri, RawContacts.RAW_CONTACT_IS_READ_ONLY, 1); storeValue(rawContactUri, RawContacts.CUSTOM_RINGTONE, "second"); assertStoredValue(rawContactUri, RawContacts.CUSTOM_RINGTONE, "first"); Uri syncAdapterUri = rawContactUri.buildUpon() .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "1") .build(); storeValue(syncAdapterUri, RawContacts.CUSTOM_RINGTONE, "third"); assertStoredValue(rawContactUri, RawContacts.CUSTOM_RINGTONE, "third"); } public void testReadOnlyDataRow() { long rawContactId = RawContactUtil.createRawContact(mResolver); Uri emailUri = insertEmail(rawContactId, "email"); Uri phoneUri = insertPhoneNumber(rawContactId, "555-1111"); storeValue(emailUri, Data.IS_READ_ONLY, "1"); storeValue(emailUri, Email.ADDRESS, "changed"); storeValue(phoneUri, Phone.NUMBER, "555-2222"); assertStoredValue(emailUri, Email.ADDRESS, "email"); assertStoredValue(phoneUri, Phone.NUMBER, "555-2222"); Uri syncAdapterUri = emailUri.buildUpon() .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "1") .build(); storeValue(syncAdapterUri, Email.ADDRESS, "changed"); assertStoredValue(emailUri, Email.ADDRESS, "changed"); } public void testContactWithReadOnlyRawContact() { long rawContactId1 = RawContactUtil.createRawContact(mResolver); Uri rawContactUri1 = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId1); storeValue(rawContactUri1, RawContacts.CUSTOM_RINGTONE, "first"); long rawContactId2 = RawContactUtil.createRawContact(mResolver); Uri rawContactUri2 = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId2); storeValue(rawContactUri2, RawContacts.CUSTOM_RINGTONE, "second"); storeValue(rawContactUri2, RawContacts.RAW_CONTACT_IS_READ_ONLY, 1); setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); long contactId = queryContactId(rawContactId1); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); storeValue(contactUri, Contacts.CUSTOM_RINGTONE, "rt"); assertStoredValue(contactUri, Contacts.CUSTOM_RINGTONE, "rt"); assertStoredValue(rawContactUri1, RawContacts.CUSTOM_RINGTONE, "rt"); assertStoredValue(rawContactUri2, RawContacts.CUSTOM_RINGTONE, "second"); } public void testNameParsingQuery() { Uri uri = ContactsContract.AUTHORITY_URI.buildUpon().appendPath("complete_name") .appendQueryParameter(StructuredName.DISPLAY_NAME, "Mr. John Q. Doe Jr.").build(); Cursor cursor = mResolver.query(uri, null, null, null, null); ContentValues values = new ContentValues(); values.put(StructuredName.DISPLAY_NAME, "Mr. John Q. Doe Jr."); values.put(StructuredName.PREFIX, "Mr."); values.put(StructuredName.GIVEN_NAME, "John"); values.put(StructuredName.MIDDLE_NAME, "Q."); values.put(StructuredName.FAMILY_NAME, "Doe"); values.put(StructuredName.SUFFIX, "Jr."); values.put(StructuredName.FULL_NAME_STYLE, FullNameStyle.WESTERN); assertTrue(cursor.moveToFirst()); assertCursorValues(cursor, values); cursor.close(); } public void testNameConcatenationQuery() { Uri uri = ContactsContract.AUTHORITY_URI.buildUpon().appendPath("complete_name") .appendQueryParameter(StructuredName.PREFIX, "Mr") .appendQueryParameter(StructuredName.GIVEN_NAME, "John") .appendQueryParameter(StructuredName.MIDDLE_NAME, "Q.") .appendQueryParameter(StructuredName.FAMILY_NAME, "Doe") .appendQueryParameter(StructuredName.SUFFIX, "Jr.") .build(); Cursor cursor = mResolver.query(uri, null, null, null, null); ContentValues values = new ContentValues(); values.put(StructuredName.DISPLAY_NAME, "Mr John Q. Doe, Jr."); values.put(StructuredName.PREFIX, "Mr"); values.put(StructuredName.GIVEN_NAME, "John"); values.put(StructuredName.MIDDLE_NAME, "Q."); values.put(StructuredName.FAMILY_NAME, "Doe"); values.put(StructuredName.SUFFIX, "Jr."); values.put(StructuredName.FULL_NAME_STYLE, FullNameStyle.WESTERN); assertTrue(cursor.moveToFirst()); assertCursorValues(cursor, values); cursor.close(); } public void testBuildSingleRowResult() { checkBuildSingleRowResult( new String[] {"b"}, new String[] {"a", "b"}, new Integer[] {1, 2}, new Integer[] {2} ); checkBuildSingleRowResult( new String[] {"b", "a", "b"}, new String[] {"a", "b"}, new Integer[] {1, 2}, new Integer[] {2, 1, 2} ); checkBuildSingleRowResult( null, // all columns new String[] {"a", "b"}, new Integer[] {1, 2}, new Integer[] {1, 2} ); try { // Access non-existent column ContactsProvider2.buildSingleRowResult(new String[] {"a"}, new String[] {"b"}, new Object[] {1}); fail(); } catch (IllegalArgumentException expected) { } } private void checkBuildSingleRowResult(String[] projection, String[] availableColumns, Object[] data, Integer[] expectedValues) { final Cursor c = ContactsProvider2.buildSingleRowResult(projection, availableColumns, data); try { assertTrue(c.moveToFirst()); assertEquals(1, c.getCount()); assertEquals(expectedValues.length, c.getColumnCount()); for (int i = 0; i < expectedValues.length; i++) { assertEquals("column " + i, expectedValues[i], (Integer) c.getInt(i)); } } finally { c.close(); } } public void testDataUsageFeedbackAndDelete() { sMockClock.install(); final long startTime = sMockClock.currentTimeMillis(); final long rid1 = RawContactUtil.createRawContactWithName(mResolver, "contact", "a"); final long did1a = ContentUris.parseId(insertEmail(rid1, "[email protected]")); final long did1b = ContentUris.parseId(insertEmail(rid1, "[email protected]")); final long did1p = ContentUris.parseId(insertPhoneNumber(rid1, "555-555-5555")); final long rid2 = RawContactUtil.createRawContactWithName(mResolver, "contact", "b"); final long did2a = ContentUris.parseId(insertEmail(rid2, "[email protected]")); final long did2p = ContentUris.parseId(insertPhoneNumber(rid2, "555-555-5556")); // Aggregate 1 and 2 setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rid1, rid2); final long rid3 = RawContactUtil.createRawContactWithName(mResolver, "contact", "c"); final long did3a = ContentUris.parseId(insertEmail(rid3, "[email protected]")); final long did3p = ContentUris.parseId(insertPhoneNumber(rid3, "555-3333")); final long rid4 = RawContactUtil.createRawContactWithName(mResolver, "contact", "d"); final long did4p = ContentUris.parseId(insertPhoneNumber(rid4, "555-4444")); final long cid1 = queryContactId(rid1); final long cid3 = queryContactId(rid3); final long cid4 = queryContactId(rid4); // Make sure 1+2, 3 and 4 aren't aggregated MoreAsserts.assertNotEqual(cid1, cid3); MoreAsserts.assertNotEqual(cid1, cid4); MoreAsserts.assertNotEqual(cid3, cid4); // time = startTime // First, there's no frequent. (We use strequent here only because frequent is hidden // and may be removed someday.) assertRowCount(0, Contacts.CONTENT_STREQUENT_URI, null, null); // Test 1. touch data 1a updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_LONG_TEXT, did1a); // Now, there's a single frequent. (contact 1) assertRowCount(1, Contacts.CONTENT_STREQUENT_URI, null, null); // time = startTime + 1 sMockClock.advance(); // Test 2. touch data 1a, 2a and 3a updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_LONG_TEXT, did1a, did2a, did3a); // Now, contact 1 and 3 are in frequent. assertRowCount(2, Contacts.CONTENT_STREQUENT_URI, null, null); // time = startTime + 2 sMockClock.advance(); // Test 2. touch data 2p (call) updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_CALL, did2p); // There're still two frequent. assertRowCount(2, Contacts.CONTENT_STREQUENT_URI, null, null); // time = startTime + 3 sMockClock.advance(); // Test 3. touch data 2p and 3p (short text) updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_SHORT_TEXT, did2p, did3p); // Let's check the tables. // Fist, check the data_usage_stat table, which has no public URI. assertStoredValuesDb("SELECT " + DataUsageStatColumns.DATA_ID + "," + DataUsageStatColumns.USAGE_TYPE_INT + "," + DataUsageStatColumns.TIMES_USED + "," + DataUsageStatColumns.LAST_TIME_USED + " FROM " + Tables.DATA_USAGE_STAT, null, cv(DataUsageStatColumns.DATA_ID, did1a, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT, DataUsageStatColumns.TIMES_USED, 2, DataUsageStatColumns.LAST_TIME_USED, startTime + 1 ), cv(DataUsageStatColumns.DATA_ID, did2a, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT, DataUsageStatColumns.TIMES_USED, 1, DataUsageStatColumns.LAST_TIME_USED, startTime + 1 ), cv(DataUsageStatColumns.DATA_ID, did3a, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT, DataUsageStatColumns.TIMES_USED, 1, DataUsageStatColumns.LAST_TIME_USED, startTime + 1 ), cv(DataUsageStatColumns.DATA_ID, did2p, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_CALL, DataUsageStatColumns.TIMES_USED, 1, DataUsageStatColumns.LAST_TIME_USED, startTime + 2 ), cv(DataUsageStatColumns.DATA_ID, did2p, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_SHORT_TEXT, DataUsageStatColumns.TIMES_USED, 1, DataUsageStatColumns.LAST_TIME_USED, startTime + 3 ), cv(DataUsageStatColumns.DATA_ID, did3p, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_SHORT_TEXT, DataUsageStatColumns.TIMES_USED, 1, DataUsageStatColumns.LAST_TIME_USED, startTime + 3 ) ); // Next, check the raw_contacts table assertStoredValuesWithProjection(RawContacts.CONTENT_URI, cv(RawContacts._ID, rid1, RawContacts.TIMES_CONTACTED, 2, RawContacts.LAST_TIME_CONTACTED, startTime + 1 ), cv(RawContacts._ID, rid2, RawContacts.TIMES_CONTACTED, 3, RawContacts.LAST_TIME_CONTACTED, startTime + 3 ), cv(RawContacts._ID, rid3, RawContacts.TIMES_CONTACTED, 2, RawContacts.LAST_TIME_CONTACTED, startTime + 3 ), cv(RawContacts._ID, rid4, RawContacts.TIMES_CONTACTED, 0, RawContacts.LAST_TIME_CONTACTED, null // 4 wasn't touched. ) ); // Lastly, check the contacts table. // Note contact1.TIMES_CONTACTED = 4, even though raw_contact1.TIMES_CONTACTED + // raw_contact1.TIMES_CONTACTED = 5, because in test 2, data 1a and data 2a were touched // at once. assertStoredValuesWithProjection(Contacts.CONTENT_URI, cv(Contacts._ID, cid1, Contacts.TIMES_CONTACTED, 4, Contacts.LAST_TIME_CONTACTED, startTime + 3 ), cv(Contacts._ID, cid3, Contacts.TIMES_CONTACTED, 2, Contacts.LAST_TIME_CONTACTED, startTime + 3 ), cv(Contacts._ID, cid4, Contacts.TIMES_CONTACTED, 0, Contacts.LAST_TIME_CONTACTED, 0 // For contacts, the default is 0, not null. ) ); // Let's test the delete too. assertTrue(mResolver.delete(DataUsageFeedback.DELETE_USAGE_URI, null, null) > 0); // Now there's no frequent. assertRowCount(0, Contacts.CONTENT_STREQUENT_URI, null, null); // No rows in the stats table. assertStoredValuesDb("SELECT " + DataUsageStatColumns.DATA_ID + " FROM " + Tables.DATA_USAGE_STAT, null, new ContentValues[0]); // The following values should all be 0 or null. assertRowCount(0, Contacts.CONTENT_URI, Contacts.TIMES_CONTACTED + ">0", null); assertRowCount(0, Contacts.CONTENT_URI, Contacts.LAST_TIME_CONTACTED + ">0", null); assertRowCount(0, RawContacts.CONTENT_URI, RawContacts.TIMES_CONTACTED + ">0", null); assertRowCount(0, RawContacts.CONTENT_URI, RawContacts.LAST_TIME_CONTACTED + ">0", null); // Calling it when there's no usage stats will still return a positive value. assertTrue(mResolver.delete(DataUsageFeedback.DELETE_USAGE_URI, null, null) > 0); } /******************************************************* * Delta api tests. */ public void testContactDelete_hasDeleteLog() { sMockClock.install(); long start = sMockClock.currentTimeMillis(); DatabaseAsserts.ContactIdPair ids = assertContactCreateDelete(); DatabaseAsserts.assertHasDeleteLogGreaterThan(mResolver, ids.mContactId, start); // Clean up. Must also remove raw contact. RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testContactDelete_marksRawContactsForDeletion() { DatabaseAsserts.ContactIdPair ids = assertContactCreateDelete(); String[] projection = new String[]{ContactsContract.RawContacts.DIRTY, ContactsContract.RawContacts.DELETED}; List<String[]> records = RawContactUtil.queryByContactId(mResolver, ids.mContactId, projection); for (String[] arr : records) { assertEquals("1", arr[0]); assertEquals("1", arr[1]); } // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testContactUpdate_updatesContactUpdatedTimestamp() { sMockClock.install(); DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); ContentValues values = new ContentValues(); values.put(ContactsContract.Contacts.STARRED, 1); sMockClock.advance(); ContactUtil.update(mResolver, ids.mContactId, values); long newTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); assertTrue(newTime > baseTime); // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } // This implicitly tests the Contact create case. public void testRawContactCreate_updatesContactUpdatedTimestamp() { long startTime = System.currentTimeMillis(); long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long lastUpdated = getContactLastUpdatedTimestampByRawContactId(mResolver, rawContactId); assertTrue(lastUpdated > startTime); // Clean up RawContactUtil.delete(mResolver, rawContactId, true); } public void testRawContactUpdate_updatesContactUpdatedTimestamp() { DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); ContentValues values = new ContentValues(); values.put(ContactsContract.RawContacts.STARRED, 1); RawContactUtil.update(mResolver, ids.mRawContactId, values); long newTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); assertTrue(newTime > baseTime); // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testRawContactPsuedoDelete_hasDeleteLogForContact() { DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); RawContactUtil.delete(mResolver, ids.mRawContactId, false); DatabaseAsserts.assertHasDeleteLogGreaterThan(mResolver, ids.mContactId, baseTime); // clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testRawContactDelete_hasDeleteLogForContact() { DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); RawContactUtil.delete(mResolver, ids.mRawContactId, true); DatabaseAsserts.assertHasDeleteLogGreaterThan(mResolver, ids.mContactId, baseTime); // already clean } private long getContactLastUpdatedTimestampByRawContactId(ContentResolver resolver, long rawContactId) { long contactId = RawContactUtil.queryContactIdByRawContactId(mResolver, rawContactId); MoreAsserts.assertNotEqual(CommonDatabaseUtils.NOT_FOUND, contactId); return ContactUtil.queryContactLastUpdatedTimestamp(mResolver, contactId); } public void testDataInsert_updatesContactLastUpdatedTimestamp() { sMockClock.install(); DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); sMockClock.advance(); insertPhoneNumberAndReturnDataId(ids.mRawContactId); long newTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); assertTrue(newTime > baseTime); // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testDataDelete_updatesContactLastUpdatedTimestamp() { sMockClock.install(); DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long dataId = insertPhoneNumberAndReturnDataId(ids.mRawContactId); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); sMockClock.advance(); DataUtil.delete(mResolver, dataId); long newTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); assertTrue(newTime > baseTime); // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testDataUpdate_updatesContactLastUpdatedTimestamp() { sMockClock.install(); DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long dataId = insertPhoneNumberAndReturnDataId(ids.mRawContactId); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); sMockClock.advance(); ContentValues values = new ContentValues(); values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, "555-5555"); DataUtil.update(mResolver, dataId, values); long newTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); assertTrue(newTime > baseTime); // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } private long insertPhoneNumberAndReturnDataId(long rawContactId) { Uri uri = insertPhoneNumber(rawContactId, "1-800-GOOG-411"); return ContentUris.parseId(uri); } public void testDeletedContactsDelete_isUnsupported() { final Uri URI = ContactsContract.DeletedContacts.CONTENT_URI; DatabaseAsserts.assertDeleteIsUnsupported(mResolver, URI); Uri uri = ContentUris.withAppendedId(URI, 1L); DatabaseAsserts.assertDeleteIsUnsupported(mResolver, uri); } public void testDeletedContactsInsert_isUnsupported() { final Uri URI = ContactsContract.DeletedContacts.CONTENT_URI; DatabaseAsserts.assertInsertIsUnsupported(mResolver, URI); } public void testQueryDeletedContactsByContactId() { DatabaseAsserts.ContactIdPair ids = assertContactCreateDelete(); MoreAsserts.assertNotEqual(CommonDatabaseUtils.NOT_FOUND, DeletedContactUtil.queryDeletedTimestampForContactId(mResolver, ids.mContactId)); } public void testQueryDeletedContactsAll() { final int numDeletes = 10; // Since we cannot clean out delete log from previous tests, we need to account for that // by querying for the count first. final long startCount = DeletedContactUtil.getCount(mResolver); for (int i = 0; i < numDeletes; i++) { assertContactCreateDelete(); } final long endCount = DeletedContactUtil.getCount(mResolver); assertEquals(numDeletes, endCount - startCount); } public void testQueryDeletedContactsSinceTimestamp() { sMockClock.install(); // Before final HashSet<Long> beforeIds = new HashSet<Long>(); beforeIds.add(assertContactCreateDelete().mContactId); beforeIds.add(assertContactCreateDelete().mContactId); final long start = sMockClock.currentTimeMillis(); // After final HashSet<Long> afterIds = new HashSet<Long>(); afterIds.add(assertContactCreateDelete().mContactId); afterIds.add(assertContactCreateDelete().mContactId); afterIds.add(assertContactCreateDelete().mContactId); final String[] projection = new String[]{ ContactsContract.DeletedContacts.CONTACT_ID, ContactsContract.DeletedContacts.CONTACT_DELETED_TIMESTAMP }; final List<String[]> records = DeletedContactUtil.querySinceTimestamp(mResolver, projection, start); for (String[] record : records) { // Check ids to make sure we only have the ones that came after the time. final long contactId = Long.parseLong(record[0]); assertFalse(beforeIds.contains(contactId)); assertTrue(afterIds.contains(contactId)); // Check times to make sure they came after assertTrue(Long.parseLong(record[1]) > start); } } /** * Create a contact. Assert it's not present in the delete log. Delete it. * And assert that the contact record is no longer present. * * @return The contact id and raw contact id that was created. */ private DatabaseAsserts.ContactIdPair assertContactCreateDelete() { DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); assertEquals(CommonDatabaseUtils.NOT_FOUND, DeletedContactUtil.queryDeletedTimestampForContactId(mResolver, ids.mContactId)); sMockClock.advance(); ContactUtil.delete(mResolver, ids.mContactId); assertFalse(ContactUtil.recordExistsForContactId(mResolver, ids.mContactId)); return ids; } /** * End delta api tests. ******************************************************/ private Cursor queryGroupMemberships(Account account) { Cursor c = mResolver.query(TestUtil.maybeAddAccountQueryParameters(Data.CONTENT_URI, account), new String[]{GroupMembership.GROUP_ROW_ID, GroupMembership.RAW_CONTACT_ID}, Data.MIMETYPE + "=?", new String[]{GroupMembership.CONTENT_ITEM_TYPE}, GroupMembership.GROUP_SOURCE_ID); return c; } private String readToEnd(FileInputStream inputStream) { try { System.out.println("DECLARED INPUT STREAM LENGTH: " + inputStream.available()); int ch; StringBuilder stringBuilder = new StringBuilder(); int index = 0; while (true) { ch = inputStream.read(); System.out.println("READ CHARACTER: " + index + " " + ch); if (ch == -1) { break; } stringBuilder.append((char)ch); index++; } return stringBuilder.toString(); } catch (IOException e) { return null; } } private void assertQueryParameter(String uriString, String parameter, String expectedValue) { assertEquals(expectedValue, ContactsProvider2.getQueryParameter( Uri.parse(uriString), parameter)); } private long createContact(ContentValues values, String firstName, String givenName, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode) { return createContact(values, firstName, givenName, phoneNumber, email, presenceStatus, timesContacted, starred, groupId, chatMode, false); } private long createContact(ContentValues values, String firstName, String givenName, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode, boolean isUserProfile) { return queryContactId(createRawContact(values, firstName, givenName, phoneNumber, email, presenceStatus, timesContacted, starred, groupId, chatMode, isUserProfile)); } private long createRawContact(ContentValues values, String firstName, String givenName, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode) { long rawContactId = createRawContact(values, phoneNumber, email, presenceStatus, timesContacted, starred, groupId, chatMode); DataUtil.insertStructuredName(mResolver, rawContactId, firstName, givenName); return rawContactId; } private long createRawContact(ContentValues values, String firstName, String givenName, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode, boolean isUserProfile) { long rawContactId = createRawContact(values, phoneNumber, email, presenceStatus, timesContacted, starred, groupId, chatMode, isUserProfile); DataUtil.insertStructuredName(mResolver, rawContactId, firstName, givenName); return rawContactId; } private long createRawContact(ContentValues values, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode) { return createRawContact(values, phoneNumber, email, presenceStatus, timesContacted, starred, groupId, chatMode, false); } private long createRawContact(ContentValues values, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode, boolean isUserProfile) { values.put(RawContacts.STARRED, starred); values.put(RawContacts.SEND_TO_VOICEMAIL, 1); values.put(RawContacts.CUSTOM_RINGTONE, "beethoven5"); values.put(RawContacts.TIMES_CONTACTED, timesContacted); Uri insertionUri = isUserProfile ? Profile.CONTENT_RAW_CONTACTS_URI : RawContacts.CONTENT_URI; Uri rawContactUri = mResolver.insert(insertionUri, values); long rawContactId = ContentUris.parseId(rawContactUri); Uri photoUri = insertPhoto(rawContactId); long photoId = ContentUris.parseId(photoUri); values.put(Contacts.PHOTO_ID, photoId); if (!TextUtils.isEmpty(phoneNumber)) { insertPhoneNumber(rawContactId, phoneNumber); } if (!TextUtils.isEmpty(email)) { insertEmail(rawContactId, email); } insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, email, presenceStatus, "hacking", chatMode, isUserProfile); if (groupId != 0) { insertGroupMembership(rawContactId, groupId); } return rawContactId; } /** * Creates a raw contact with pre-set values under the user's profile. * @param profileValues Values to be used to create the entry (common values will be * automatically populated in createRawContact()). * @return the raw contact ID that was created. */ private long createBasicProfileContact(ContentValues profileValues) { long profileRawContactId = createRawContact(profileValues, "Mia", "Prophyl", "18005554411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_CAMERA, true); profileValues.put(Contacts.DISPLAY_NAME, "Mia Prophyl"); return profileRawContactId; } /** * Creates a raw contact with pre-set values that is not under the user's profile. * @param nonProfileValues Values to be used to create the entry (common values will be * automatically populated in createRawContact()). * @return the raw contact ID that was created. */ private long createBasicNonProfileContact(ContentValues nonProfileValues) { long nonProfileRawContactId = createRawContact(nonProfileValues, "John", "Doe", "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_CAMERA, false); nonProfileValues.put(Contacts.DISPLAY_NAME, "John Doe"); return nonProfileRawContactId; } private void putDataValues(ContentValues values, long rawContactId) { values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, "testmimetype"); values.put(Data.RES_PACKAGE, "oldpackage"); values.put(Data.IS_PRIMARY, 1); values.put(Data.IS_SUPER_PRIMARY, 1); values.put(Data.DATA1, "one"); values.put(Data.DATA2, "two"); values.put(Data.DATA3, "three"); values.put(Data.DATA4, "four"); values.put(Data.DATA5, "five"); values.put(Data.DATA6, "six"); values.put(Data.DATA7, "seven"); values.put(Data.DATA8, "eight"); values.put(Data.DATA9, "nine"); values.put(Data.DATA10, "ten"); values.put(Data.DATA11, "eleven"); values.put(Data.DATA12, "twelve"); values.put(Data.DATA13, "thirteen"); values.put(Data.DATA14, "fourteen"); values.put(Data.DATA15, "fifteen"); values.put(Data.SYNC1, "sync1"); values.put(Data.SYNC2, "sync2"); values.put(Data.SYNC3, "sync3"); values.put(Data.SYNC4, "sync4"); } /** * @param data1 email address or phone number * @param usageType One of {@link DataUsageFeedback#USAGE_TYPE} * @param values ContentValues for this feedback. Useful for incrementing * {Contacts#TIMES_CONTACTED} in the ContentValue. Can be null. */ private void sendFeedback(String data1, String usageType, ContentValues values) { final long dataId = getStoredLongValue(Data.CONTENT_URI, Data.DATA1 + "=?", new String[] { data1 }, Data._ID); MoreAsserts.assertNotEqual(0, updateDataUsageFeedback(usageType, dataId)); if (values != null && values.containsKey(Contacts.TIMES_CONTACTED)) { values.put(Contacts.TIMES_CONTACTED, values.getAsInteger(Contacts.TIMES_CONTACTED) + 1); } } private void updateDataUsageFeedback(String usageType, Uri resultUri) { final long id = ContentUris.parseId(resultUri); final boolean successful = updateDataUsageFeedback(usageType, id) > 0; assertTrue(successful); } private int updateDataUsageFeedback(String usageType, long... ids) { final StringBuilder idList = new StringBuilder(); for (long id : ids) { if (idList.length() > 0) idList.append(","); idList.append(id); } return mResolver.update(DataUsageFeedback.FEEDBACK_URI.buildUpon() .appendPath(idList.toString()) .appendQueryParameter(DataUsageFeedback.USAGE_TYPE, usageType) .build(), new ContentValues(), null, null); } private boolean hasChineseCollator() { final Locale locale[] = Collator.getAvailableLocales(); for (int i = 0; i < locale.length; i++) { if (locale[i].equals(Locale.CHINA)) { return true; } } return false; } private boolean hasJapaneseCollator() { final Locale locale[] = Collator.getAvailableLocales(); for (int i = 0; i < locale.length; i++) { if (locale[i].equals(Locale.JAPAN)) { return true; } } return false; } private boolean hasGermanCollator() { final Locale locale[] = Collator.getAvailableLocales(); for (int i = 0; i < locale.length; i++) { if (locale[i].equals(Locale.GERMANY)) { return true; } } return false; } }
false
true
public void testSettingsInsertionPreventsDuplicates() { Account account1 = new Account("a", "b"); AccountWithDataSet account2 = new AccountWithDataSet("c", "d", "plus"); createSettings(account1, "0", "0"); createSettings(account2, "1", "1"); // Now try creating the settings rows again. It should update the existing settings rows. createSettings(account1, "1", "0"); assertStoredValue(Settings.CONTENT_URI, Settings.ACCOUNT_NAME + "=? AND " + Settings.ACCOUNT_TYPE + "=?", new String[] {"a", "b"}, Settings.SHOULD_SYNC, "1"); createSettings(account2, "0", "1"); assertStoredValue(Settings.CONTENT_URI, Settings.ACCOUNT_NAME + "=? AND " + Settings.ACCOUNT_TYPE + "=? AND " + Settings.DATA_SET + "=?", new String[] {"c", "d", "plus"}, Settings.SHOULD_SYNC, "0"); } public void testDisplayNameParsingWhenPartsUnspecified() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = new ContentValues(); values.put(StructuredName.DISPLAY_NAME, "Mr.John Kevin von Smith, Jr."); DataUtil.insertStructuredName(mResolver, rawContactId, values); assertStructuredName(rawContactId, "Mr.", "John", "Kevin", "von Smith", "Jr."); } public void testDisplayNameParsingWhenPartsAreNull() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = new ContentValues(); values.put(StructuredName.DISPLAY_NAME, "Mr.John Kevin von Smith, Jr."); values.putNull(StructuredName.GIVEN_NAME); values.putNull(StructuredName.FAMILY_NAME); DataUtil.insertStructuredName(mResolver, rawContactId, values); assertStructuredName(rawContactId, "Mr.", "John", "Kevin", "von Smith", "Jr."); } public void testDisplayNameParsingWhenPartsSpecified() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = new ContentValues(); values.put(StructuredName.DISPLAY_NAME, "Mr.John Kevin von Smith, Jr."); values.put(StructuredName.FAMILY_NAME, "Johnson"); DataUtil.insertStructuredName(mResolver, rawContactId, values); assertStructuredName(rawContactId, null, null, null, "Johnson", null); } public void testContactWithoutPhoneticName() { ContactLocaleUtils.setLocale(Locale.ENGLISH); final long rawContactId = RawContactUtil.createRawContact(mResolver, null); ContentValues values = new ContentValues(); values.put(StructuredName.PREFIX, "Mr"); values.put(StructuredName.GIVEN_NAME, "John"); values.put(StructuredName.MIDDLE_NAME, "K."); values.put(StructuredName.FAMILY_NAME, "Doe"); values.put(StructuredName.SUFFIX, "Jr."); Uri dataUri = DataUtil.insertStructuredName(mResolver, rawContactId, values); values.clear(); values.put(RawContacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(RawContacts.DISPLAY_NAME_PRIMARY, "Mr John K. Doe, Jr."); values.put(RawContacts.DISPLAY_NAME_ALTERNATIVE, "Mr Doe, John K., Jr."); values.putNull(RawContacts.PHONETIC_NAME); values.put(RawContacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(RawContacts.SORT_KEY_PRIMARY, "John K. Doe, Jr."); values.put(RawContactsColumns.PHONEBOOK_LABEL_PRIMARY, "J"); values.put(RawContacts.SORT_KEY_ALTERNATIVE, "Doe, John K., Jr."); values.put(RawContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "D"); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); assertStoredValues(rawContactUri, values); values.clear(); values.put(Contacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(Contacts.DISPLAY_NAME_PRIMARY, "Mr John K. Doe, Jr."); values.put(Contacts.DISPLAY_NAME_ALTERNATIVE, "Mr Doe, John K., Jr."); values.putNull(Contacts.PHONETIC_NAME); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(Contacts.SORT_KEY_PRIMARY, "John K. Doe, Jr."); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "J"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "Doe, John K., Jr."); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "D"); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId)); assertStoredValues(contactUri, values); // The same values should be available through a join with Data assertStoredValues(dataUri, values); } public void testContactWithChineseName() { if (!hasChineseCollator()) { return; } ContactLocaleUtils.setLocale(Locale.SIMPLIFIED_CHINESE); long rawContactId = RawContactUtil.createRawContact(mResolver, null); ContentValues values = new ContentValues(); // "DUAN \u6BB5 XIAO \u5C0F TAO \u6D9B" values.put(StructuredName.DISPLAY_NAME, "\u6BB5\u5C0F\u6D9B"); Uri dataUri = DataUtil.insertStructuredName(mResolver, rawContactId, values); values.clear(); values.put(RawContacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(RawContacts.DISPLAY_NAME_PRIMARY, "\u6BB5\u5C0F\u6D9B"); values.put(RawContacts.DISPLAY_NAME_ALTERNATIVE, "\u6BB5\u5C0F\u6D9B"); values.putNull(RawContacts.PHONETIC_NAME); values.put(RawContacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(RawContacts.SORT_KEY_PRIMARY, "\u6BB5\u5C0F\u6D9B"); values.put(RawContactsColumns.PHONEBOOK_LABEL_PRIMARY, "D"); values.put(RawContacts.SORT_KEY_ALTERNATIVE, "\u6BB5\u5C0F\u6D9B"); values.put(RawContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "D"); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); assertStoredValues(rawContactUri, values); values.clear(); values.put(Contacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(Contacts.DISPLAY_NAME_PRIMARY, "\u6BB5\u5C0F\u6D9B"); values.put(Contacts.DISPLAY_NAME_ALTERNATIVE, "\u6BB5\u5C0F\u6D9B"); values.putNull(Contacts.PHONETIC_NAME); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(Contacts.SORT_KEY_PRIMARY, "\u6BB5\u5C0F\u6D9B"); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "D"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "\u6BB5\u5C0F\u6D9B"); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "D"); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId)); assertStoredValues(contactUri, values); // The same values should be available through a join with Data assertStoredValues(dataUri, values); } public void testJapaneseNameContactInEnglishLocale() { // Need Japanese locale data for transliteration if (!hasJapaneseCollator()) { return; } ContactLocaleUtils.setLocale(Locale.US); long rawContactId = createRawContact(null); ContentValues values = new ContentValues(); values.put(StructuredName.GIVEN_NAME, "\u7A7A\u6D77"); values.put(StructuredName.PHONETIC_GIVEN_NAME, "\u304B\u3044\u304F\u3046"); insertStructuredName(rawContactId, values); long contactId = queryContactId(rawContactId); // en_US should behave same as ja_JP (match on Hiragana and Romaji // but not Pinyin) assertContactFilter(contactId, "\u304B\u3044\u304F\u3046"); assertContactFilter(contactId, "kaiku"); assertContactFilterNoResult("kong"); } public void testContactWithJapaneseName() { if (!hasJapaneseCollator()) { return; } ContactLocaleUtils.setLocale(Locale.JAPAN); long rawContactId = RawContactUtil.createRawContact(mResolver, null); ContentValues values = new ContentValues(); values.put(StructuredName.GIVEN_NAME, "\u7A7A\u6D77"); values.put(StructuredName.PHONETIC_GIVEN_NAME, "\u304B\u3044\u304F\u3046"); Uri dataUri = DataUtil.insertStructuredName(mResolver, rawContactId, values); values.clear(); values.put(RawContacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(RawContacts.DISPLAY_NAME_PRIMARY, "\u7A7A\u6D77"); values.put(RawContacts.DISPLAY_NAME_ALTERNATIVE, "\u7A7A\u6D77"); values.put(RawContacts.PHONETIC_NAME, "\u304B\u3044\u304F\u3046"); values.put(RawContacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.JAPANESE); values.put(RawContacts.SORT_KEY_PRIMARY, "\u304B\u3044\u304F\u3046"); values.put(RawContacts.SORT_KEY_ALTERNATIVE, "\u304B\u3044\u304F\u3046"); values.put(RawContactsColumns.PHONEBOOK_LABEL_PRIMARY, "\u304B"); values.put(RawContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "\u304B"); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); assertStoredValues(rawContactUri, values); values.clear(); values.put(Contacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(Contacts.DISPLAY_NAME_PRIMARY, "\u7A7A\u6D77"); values.put(Contacts.DISPLAY_NAME_ALTERNATIVE, "\u7A7A\u6D77"); values.put(Contacts.PHONETIC_NAME, "\u304B\u3044\u304F\u3046"); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.JAPANESE); values.put(Contacts.SORT_KEY_PRIMARY, "\u304B\u3044\u304F\u3046"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "\u304B\u3044\u304F\u3046"); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "\u304B"); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "\u304B"); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId)); assertStoredValues(contactUri, values); // The same values should be available through a join with Data assertStoredValues(dataUri, values); long contactId = queryContactId(rawContactId); // ja_JP should match on Hiragana and Romaji but not Pinyin assertContactFilter(contactId, "\u304B\u3044\u304F\u3046"); assertContactFilter(contactId, "kaiku"); assertContactFilterNoResult("kong"); } public void testDisplayNameUpdate() { long rawContactId1 = RawContactUtil.createRawContact(mResolver); insertEmail(rawContactId1, "[email protected]", true); long rawContactId2 = RawContactUtil.createRawContact(mResolver); insertPhoneNumber(rawContactId2, "123456789", true); setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); assertAggregated(rawContactId1, rawContactId2, "123456789"); DataUtil.insertStructuredName(mResolver, rawContactId2, "Potato", "Head"); assertAggregated(rawContactId1, rawContactId2, "Potato Head"); assertNetworkNotified(true); } public void testDisplayNameFromData() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); assertStoredValue(uri, Contacts.DISPLAY_NAME, null); insertEmail(rawContactId, "[email protected]"); assertStoredValue(uri, Contacts.DISPLAY_NAME, "[email protected]"); insertEmail(rawContactId, "[email protected]", true); assertStoredValue(uri, Contacts.DISPLAY_NAME, "[email protected]"); insertPhoneNumber(rawContactId, "1-800-466-4411"); assertStoredValue(uri, Contacts.DISPLAY_NAME, "1-800-466-4411"); // If there are title and company, the company is display name. values.clear(); values.put(Organization.COMPANY, "Monsters Inc"); Uri organizationUri = insertOrganization(rawContactId, values); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Monsters Inc"); // If there is nickname, that is display name. insertNickname(rawContactId, "Sully"); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Sully"); // If there is structured name, that is display name. values.clear(); values.put(StructuredName.GIVEN_NAME, "James"); values.put(StructuredName.MIDDLE_NAME, "P."); values.put(StructuredName.FAMILY_NAME, "Sullivan"); DataUtil.insertStructuredName(mResolver, rawContactId, values); assertStoredValue(uri, Contacts.DISPLAY_NAME, "James P. Sullivan"); } public void testDisplayNameFromOrganizationWithoutPhoneticName() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); // If there is title without company, the title is display name. values.clear(); values.put(Organization.TITLE, "Protagonist"); Uri organizationUri = insertOrganization(rawContactId, values); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Protagonist"); // If there are title and company, the company is display name. values.clear(); values.put(Organization.COMPANY, "Monsters Inc"); mResolver.update(organizationUri, values, null, null); values.clear(); values.put(Contacts.DISPLAY_NAME, "Monsters Inc"); values.putNull(Contacts.PHONETIC_NAME); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(Contacts.SORT_KEY_PRIMARY, "Monsters Inc"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "Monsters Inc"); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "M"); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "M"); assertStoredValues(uri, values); } public void testDisplayNameFromOrganizationWithJapanesePhoneticName() { if (!hasJapaneseCollator()) { return; } ContactLocaleUtils.setLocale(Locale.JAPAN); long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); // If there is title without company, the title is display name. values.clear(); values.put(Organization.COMPANY, "DoCoMo"); values.put(Organization.PHONETIC_NAME, "\u30C9\u30B3\u30E2"); Uri organizationUri = insertOrganization(rawContactId, values); values.clear(); values.put(Contacts.DISPLAY_NAME, "DoCoMo"); values.put(Contacts.PHONETIC_NAME, "\u30C9\u30B3\u30E2"); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.JAPANESE); values.put(Contacts.SORT_KEY_PRIMARY, "\u30C9\u30B3\u30E2"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "\u30C9\u30B3\u30E2"); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "\u305F"); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "\u305F"); assertStoredValues(uri, values); } public void testDisplayNameFromOrganizationWithChineseName() { if (!hasChineseCollator()) { return; } ContactLocaleUtils.setLocale(Locale.SIMPLIFIED_CHINESE); long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); // If there is title without company, the title is display name. values.clear(); values.put(Organization.COMPANY, "\u4E2D\u56FD\u7535\u4FE1"); Uri organizationUri = insertOrganization(rawContactId, values); values.clear(); values.put(Contacts.DISPLAY_NAME, "\u4E2D\u56FD\u7535\u4FE1"); values.putNull(Contacts.PHONETIC_NAME); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(Contacts.SORT_KEY_PRIMARY, "\u4E2D\u56FD\u7535\u4FE1"); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "Z"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "\u4E2D\u56FD\u7535\u4FE1"); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "Z"); assertStoredValues(uri, values); } public void testLookupByOrganization() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); values.clear(); values.put(Organization.COMPANY, "acmecorp"); values.put(Organization.TITLE, "president"); Uri organizationUri = insertOrganization(rawContactId, values); assertContactFilter(contactId, "acmecorp"); assertContactFilter(contactId, "president"); values.clear(); values.put(Organization.DEPARTMENT, "software"); mResolver.update(organizationUri, values, null, null); assertContactFilter(contactId, "acmecorp"); assertContactFilter(contactId, "president"); values.clear(); values.put(Organization.COMPANY, "incredibles"); mResolver.update(organizationUri, values, null, null); assertContactFilter(contactId, "incredibles"); assertContactFilter(contactId, "president"); values.clear(); values.put(Organization.TITLE, "director"); mResolver.update(organizationUri, values, null, null); assertContactFilter(contactId, "incredibles"); assertContactFilter(contactId, "director"); values.clear(); values.put(Organization.COMPANY, "monsters"); values.put(Organization.TITLE, "scarer"); mResolver.update(organizationUri, values, null, null); assertContactFilter(contactId, "monsters"); assertContactFilter(contactId, "scarer"); } private void assertContactFilter(long contactId, String filter) { Uri filterUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode(filter)); assertStoredValue(filterUri, Contacts._ID, contactId); } private void assertContactFilterNoResult(String filter) { Uri filterUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode(filter)); assertEquals(0, getCount(filterUri, null, null)); } public void testSearchSnippetOrganization() throws Exception { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); // Some random data element insertEmail(rawContactId, "[email protected]"); ContentValues values = new ContentValues(); values.clear(); values.put(Organization.COMPANY, "acmecorp"); values.put(Organization.TITLE, "engineer"); Uri organizationUri = insertOrganization(rawContactId, values); // Add another matching organization values.put(Organization.COMPANY, "acmeinc"); insertOrganization(rawContactId, values); // Add another non-matching organization values.put(Organization.COMPANY, "corpacme"); insertOrganization(rawContactId, values); // And another data element insertEmail(rawContactId, "[email protected]", true, Email.TYPE_CUSTOM, "Custom"); Uri filterUri = buildFilterUri("acme", true); values.clear(); values.put(Contacts._ID, contactId); values.put(SearchSnippetColumns.SNIPPET, "engineer, [acmecorp]"); assertStoredValues(filterUri, values); } public void testSearchSnippetEmail() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); DataUtil.insertStructuredName(mResolver, rawContactId, "John", "Doe"); Uri dataUri = insertEmail(rawContactId, "[email protected]", true, Email.TYPE_CUSTOM, "Custom"); Uri filterUri = buildFilterUri("acme", true); values.clear(); values.put(Contacts._ID, contactId); values.put(SearchSnippetColumns.SNIPPET, "[[email protected]]"); assertStoredValues(filterUri, values); } public void testCountPhoneNumberDigits() { assertEquals(10, ContactsProvider2.countPhoneNumberDigits("86 (0) 5-55-12-34")); assertEquals(10, ContactsProvider2.countPhoneNumberDigits("860 555-1234")); assertEquals(3, ContactsProvider2.countPhoneNumberDigits("860")); assertEquals(10, ContactsProvider2.countPhoneNumberDigits("8605551234")); assertEquals(6, ContactsProvider2.countPhoneNumberDigits("860555")); assertEquals(6, ContactsProvider2.countPhoneNumberDigits("860 555")); assertEquals(6, ContactsProvider2.countPhoneNumberDigits("860-555")); assertEquals(12, ContactsProvider2.countPhoneNumberDigits("+441234098765")); assertEquals(0, ContactsProvider2.countPhoneNumberDigits("44+1234098765")); assertEquals(0, ContactsProvider2.countPhoneNumberDigits("+441234098foo")); } public void testSearchSnippetPhone() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); DataUtil.insertStructuredName(mResolver, rawContactId, "Cave", "Johnson"); insertPhoneNumber(rawContactId, "(860) 555-1234"); values.clear(); values.put(Contacts._ID, contactId); values.put(SearchSnippetColumns.SNIPPET, "[(860) 555-1234]"); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("86 (0) 5-55-12-34")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("860 555-1234")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("860")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("8605551234")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("860555")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("860 555")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("860-555")), values); } private Uri buildFilterUri(String query, boolean deferredSnippeting) { Uri.Builder builder = Contacts.CONTENT_FILTER_URI.buildUpon() .appendPath(Uri.encode(query)); if (deferredSnippeting) { builder.appendQueryParameter(ContactsContract.DEFERRED_SNIPPETING, "1"); } return builder.build(); } public void testSearchSnippetNickname() throws Exception { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); Uri dataUri = insertNickname(rawContactId, "Incredible"); Uri filterUri = buildFilterUri("inc", true); values.clear(); values.put(Contacts._ID, contactId); values.put(SearchSnippetColumns.SNIPPET, "[Incredible]"); assertStoredValues(filterUri, values); } public void testSearchSnippetEmptyForNameInDisplayName() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); DataUtil.insertStructuredName(mResolver, rawContactId, "Cave", "Johnson"); insertEmail(rawContactId, "[email protected]", true); ContentValues emptySnippet = new ContentValues(); emptySnippet.clear(); emptySnippet.put(Contacts._ID, contactId); emptySnippet.put(SearchSnippetColumns.SNIPPET, (String) null); assertStoredValues(buildFilterUri("cave", true), emptySnippet); assertStoredValues(buildFilterUri("john", true), emptySnippet); } public void testSearchSnippetEmptyForNicknameInDisplayName() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); insertNickname(rawContactId, "Caveman"); insertEmail(rawContactId, "[email protected]", true); ContentValues emptySnippet = new ContentValues(); emptySnippet.clear(); emptySnippet.put(Contacts._ID, contactId); emptySnippet.put(SearchSnippetColumns.SNIPPET, (String) null); assertStoredValues(buildFilterUri("cave", true), emptySnippet); } public void testSearchSnippetEmptyForCompanyInDisplayName() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues company = new ContentValues(); company.clear(); company.put(Organization.COMPANY, "Aperture Science"); company.put(Organization.TITLE, "President"); insertOrganization(rawContactId, company); insertEmail(rawContactId, "[email protected]", true); ContentValues emptySnippet = new ContentValues(); emptySnippet.clear(); emptySnippet.put(Contacts._ID, contactId); emptySnippet.put(SearchSnippetColumns.SNIPPET, (String) null); assertStoredValues(buildFilterUri("aperture", true), emptySnippet); } public void testSearchSnippetEmptyForPhoneInDisplayName() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); insertPhoneNumber(rawContactId, "860-555-1234"); insertEmail(rawContactId, "[email protected]", true); ContentValues emptySnippet = new ContentValues(); emptySnippet.clear(); emptySnippet.put(Contacts._ID, contactId); emptySnippet.put(SearchSnippetColumns.SNIPPET, (String) null); assertStoredValues(buildFilterUri("860", true), emptySnippet); } public void testSearchSnippetEmptyForEmailInDisplayName() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); insertEmail(rawContactId, "[email protected]", true); insertNote(rawContactId, "Cave Johnson is president of Aperture Science"); ContentValues emptySnippet = new ContentValues(); emptySnippet.clear(); emptySnippet.put(Contacts._ID, contactId); emptySnippet.put(SearchSnippetColumns.SNIPPET, (String) null); assertStoredValues(buildFilterUri("cave", true), emptySnippet); } public void testDisplayNameUpdateFromStructuredNameUpdate() { long rawContactId = RawContactUtil.createRawContact(mResolver); Uri nameUri = DataUtil.insertStructuredName(mResolver, rawContactId, "Slinky", "Dog"); long contactId = queryContactId(rawContactId); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Slinky Dog"); ContentValues values = new ContentValues(); values.putNull(StructuredName.FAMILY_NAME); mResolver.update(nameUri, values, null, null); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Slinky"); values.putNull(StructuredName.GIVEN_NAME); mResolver.update(nameUri, values, null, null); assertStoredValue(uri, Contacts.DISPLAY_NAME, null); values.put(StructuredName.FAMILY_NAME, "Dog"); mResolver.update(nameUri, values, null, null); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Dog"); } public void testInsertDataWithContentProviderOperations() throws Exception { ContentProviderOperation cpo1 = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI) .withValues(new ContentValues()) .build(); ContentProviderOperation cpo2 = ContentProviderOperation.newInsert(Data.CONTENT_URI) .withValueBackReference(Data.RAW_CONTACT_ID, 0) .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE) .withValue(StructuredName.GIVEN_NAME, "John") .withValue(StructuredName.FAMILY_NAME, "Doe") .build(); ContentProviderResult[] results = mResolver.applyBatch(ContactsContract.AUTHORITY, Lists.newArrayList(cpo1, cpo2)); long contactId = queryContactId(ContentUris.parseId(results[0].uri)); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); assertStoredValue(uri, Contacts.DISPLAY_NAME, "John Doe"); } public void testSendToVoicemailDefault() { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); Cursor c = queryContact(contactId); assertTrue(c.moveToNext()); int sendToVoicemail = c.getInt(c.getColumnIndex(Contacts.SEND_TO_VOICEMAIL)); assertEquals(0, sendToVoicemail); c.close(); } public void testSetSendToVoicemailAndRingtone() { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); updateSendToVoicemailAndRingtone(contactId, true, "foo"); assertSendToVoicemailAndRingtone(contactId, true, "foo"); assertNetworkNotified(false); updateSendToVoicemailAndRingtoneWithSelection(contactId, false, "bar"); assertSendToVoicemailAndRingtone(contactId, false, "bar"); assertNetworkNotified(false); } public void testSendToVoicemailAndRingtoneAfterAggregation() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "a", "b"); long contactId1 = queryContactId(rawContactId1); updateSendToVoicemailAndRingtone(contactId1, true, "foo"); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "c", "d"); long contactId2 = queryContactId(rawContactId2); updateSendToVoicemailAndRingtone(contactId2, true, "bar"); // Aggregate them setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); // Both contacts had "send to VM", the contact now has the same value assertSendToVoicemailAndRingtone(contactId1, true, "foo,bar"); // Either foo or bar } public void testDoNotSendToVoicemailAfterAggregation() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "e", "f"); long contactId1 = queryContactId(rawContactId1); updateSendToVoicemailAndRingtone(contactId1, true, null); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "g", "h"); long contactId2 = queryContactId(rawContactId2); updateSendToVoicemailAndRingtone(contactId2, false, null); // Aggregate them setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); // Since one of the contacts had "don't send to VM" that setting wins for the aggregate assertSendToVoicemailAndRingtone(queryContactId(rawContactId1), false, null); } public void testSetSendToVoicemailAndRingtonePreservedAfterJoinAndSplit() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "i", "j"); long contactId1 = queryContactId(rawContactId1); updateSendToVoicemailAndRingtone(contactId1, true, "foo"); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "k", "l"); long contactId2 = queryContactId(rawContactId2); updateSendToVoicemailAndRingtone(contactId2, false, "bar"); // Aggregate them setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); // Split them setAggregationException(AggregationExceptions.TYPE_KEEP_SEPARATE, rawContactId1, rawContactId2); assertSendToVoicemailAndRingtone(queryContactId(rawContactId1), true, "foo"); assertSendToVoicemailAndRingtone(queryContactId(rawContactId2), false, "bar"); } public void testStatusUpdateInsert() { long rawContactId = RawContactUtil.createRawContact(mResolver); Uri imUri = insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); long dataId = ContentUris.parseId(imUri); ContentValues values = new ContentValues(); values.put(StatusUpdates.DATA_ID, dataId); values.put(StatusUpdates.PROTOCOL, Im.PROTOCOL_AIM); values.putNull(StatusUpdates.CUSTOM_PROTOCOL); values.put(StatusUpdates.IM_HANDLE, "aim"); values.put(StatusUpdates.PRESENCE, StatusUpdates.INVISIBLE); values.put(StatusUpdates.STATUS, "Hiding"); values.put(StatusUpdates.STATUS_TIMESTAMP, 100); values.put(StatusUpdates.STATUS_RES_PACKAGE, "a.b.c"); values.put(StatusUpdates.STATUS_ICON, 1234); values.put(StatusUpdates.STATUS_LABEL, 2345); Uri resultUri = mResolver.insert(StatusUpdates.CONTENT_URI, values); assertStoredValues(resultUri, values); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); values.clear(); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.INVISIBLE); values.put(Contacts.CONTACT_STATUS, "Hiding"); values.put(Contacts.CONTACT_STATUS_TIMESTAMP, 100); values.put(Contacts.CONTACT_STATUS_RES_PACKAGE, "a.b.c"); values.put(Contacts.CONTACT_STATUS_ICON, 1234); values.put(Contacts.CONTACT_STATUS_LABEL, 2345); assertStoredValues(contactUri, values); values.clear(); values.put(StatusUpdates.DATA_ID, dataId); values.put(StatusUpdates.STATUS, "Cloaked"); values.put(StatusUpdates.STATUS_TIMESTAMP, 200); values.put(StatusUpdates.STATUS_RES_PACKAGE, "d.e.f"); values.put(StatusUpdates.STATUS_ICON, 4321); values.put(StatusUpdates.STATUS_LABEL, 5432); mResolver.insert(StatusUpdates.CONTENT_URI, values); values.clear(); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.INVISIBLE); values.put(Contacts.CONTACT_STATUS, "Cloaked"); values.put(Contacts.CONTACT_STATUS_TIMESTAMP, 200); values.put(Contacts.CONTACT_STATUS_RES_PACKAGE, "d.e.f"); values.put(Contacts.CONTACT_STATUS_ICON, 4321); values.put(Contacts.CONTACT_STATUS_LABEL, 5432); assertStoredValues(contactUri, values); } public void testStatusUpdateInferAttribution() { long rawContactId = RawContactUtil.createRawContact(mResolver); Uri imUri = insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); long dataId = ContentUris.parseId(imUri); ContentValues values = new ContentValues(); values.put(StatusUpdates.DATA_ID, dataId); values.put(StatusUpdates.PROTOCOL, Im.PROTOCOL_AIM); values.put(StatusUpdates.IM_HANDLE, "aim"); values.put(StatusUpdates.STATUS, "Hiding"); Uri resultUri = mResolver.insert(StatusUpdates.CONTENT_URI, values); values.clear(); values.put(StatusUpdates.DATA_ID, dataId); values.put(StatusUpdates.STATUS_LABEL, com.android.internal.R.string.imProtocolAim); values.put(StatusUpdates.STATUS, "Hiding"); assertStoredValues(resultUri, values); } public void testStatusUpdateMatchingImOrEmail() { long rawContactId = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); insertImHandle(rawContactId, Im.PROTOCOL_CUSTOM, "my_im_proto", "my_im"); insertEmail(rawContactId, "[email protected]"); // Match on IM (standard) insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", StatusUpdates.AVAILABLE, "Available", StatusUpdates.CAPABILITY_HAS_CAMERA); // Match on IM (custom) insertStatusUpdate(Im.PROTOCOL_CUSTOM, "my_im_proto", "my_im", StatusUpdates.IDLE, "Idle", StatusUpdates.CAPABILITY_HAS_CAMERA | StatusUpdates.CAPABILITY_HAS_VIDEO); // Match on Email insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.AWAY, "Away", StatusUpdates.CAPABILITY_HAS_VOICE); // No match insertStatusUpdate(Im.PROTOCOL_ICQ, null, "12345", StatusUpdates.DO_NOT_DISTURB, "Go away", StatusUpdates.CAPABILITY_HAS_CAMERA); Cursor c = mResolver.query(StatusUpdates.CONTENT_URI, new String[] { StatusUpdates.DATA_ID, StatusUpdates.PROTOCOL, StatusUpdates.CUSTOM_PROTOCOL, StatusUpdates.PRESENCE, StatusUpdates.STATUS}, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId, null, StatusUpdates.DATA_ID); assertTrue(c.moveToNext()); assertStatusUpdate(c, Im.PROTOCOL_AIM, null, StatusUpdates.AVAILABLE, "Available"); assertTrue(c.moveToNext()); assertStatusUpdate(c, Im.PROTOCOL_CUSTOM, "my_im_proto", StatusUpdates.IDLE, "Idle"); assertTrue(c.moveToNext()); assertStatusUpdate(c, Im.PROTOCOL_GOOGLE_TALK, null, StatusUpdates.AWAY, "Away"); assertFalse(c.moveToNext()); c.close(); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); ContentValues values = new ContentValues(); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.AVAILABLE); values.put(Contacts.CONTACT_STATUS, "Available"); assertStoredValuesWithProjection(contactUri, values); } public void testStatusUpdateUpdateAndDelete() { long rawContactId = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); ContentValues values = new ContentValues(); values.putNull(Contacts.CONTACT_PRESENCE); values.putNull(Contacts.CONTACT_STATUS); assertStoredValuesWithProjection(contactUri, values); insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", StatusUpdates.AWAY, "BUSY", StatusUpdates.CAPABILITY_HAS_CAMERA); insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", StatusUpdates.DO_NOT_DISTURB, "GO AWAY", StatusUpdates.CAPABILITY_HAS_CAMERA); Uri statusUri = insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", StatusUpdates.AVAILABLE, "Available", StatusUpdates.CAPABILITY_HAS_CAMERA); long statusId = ContentUris.parseId(statusUri); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.AVAILABLE); values.put(Contacts.CONTACT_STATUS, "Available"); assertStoredValuesWithProjection(contactUri, values); // update status_updates table to set new values for // status_updates.status // status_updates.status_ts // presence long updatedTs = 200; String testUpdate = "test_update"; String selection = StatusUpdates.DATA_ID + "=" + statusId; values.clear(); values.put(StatusUpdates.STATUS_TIMESTAMP, updatedTs); values.put(StatusUpdates.STATUS, testUpdate); values.put(StatusUpdates.PRESENCE, "presence_test"); mResolver.update(StatusUpdates.CONTENT_URI, values, StatusUpdates.DATA_ID + "=" + statusId, null); assertStoredValuesWithProjection(StatusUpdates.CONTENT_URI, values); // update status_updates table to set new values for columns in status_updates table ONLY // i.e., no rows in presence table are to be updated. updatedTs = 300; testUpdate = "test_update_new"; selection = StatusUpdates.DATA_ID + "=" + statusId; values.clear(); values.put(StatusUpdates.STATUS_TIMESTAMP, updatedTs); values.put(StatusUpdates.STATUS, testUpdate); mResolver.update(StatusUpdates.CONTENT_URI, values, StatusUpdates.DATA_ID + "=" + statusId, null); // make sure the presence column value is still the old value values.put(StatusUpdates.PRESENCE, "presence_test"); assertStoredValuesWithProjection(StatusUpdates.CONTENT_URI, values); // update status_updates table to set new values for columns in presence table ONLY // i.e., no rows in status_updates table are to be updated. selection = StatusUpdates.DATA_ID + "=" + statusId; values.clear(); values.put(StatusUpdates.PRESENCE, "presence_test_new"); mResolver.update(StatusUpdates.CONTENT_URI, values, StatusUpdates.DATA_ID + "=" + statusId, null); // make sure the status_updates table is not updated values.put(StatusUpdates.STATUS_TIMESTAMP, updatedTs); values.put(StatusUpdates.STATUS, testUpdate); assertStoredValuesWithProjection(StatusUpdates.CONTENT_URI, values); // effect "delete status_updates" operation and expect the following // data deleted from status_updates table // presence set to null mResolver.delete(StatusUpdates.CONTENT_URI, StatusUpdates.DATA_ID + "=" + statusId, null); values.clear(); values.putNull(Contacts.CONTACT_PRESENCE); assertStoredValuesWithProjection(contactUri, values); } public void testStatusUpdateUpdateToNull() { long rawContactId = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); ContentValues values = new ContentValues(); Uri statusUri = insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", StatusUpdates.AVAILABLE, "Available", StatusUpdates.CAPABILITY_HAS_CAMERA); long statusId = ContentUris.parseId(statusUri); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.AVAILABLE); values.put(Contacts.CONTACT_STATUS, "Available"); assertStoredValuesWithProjection(contactUri, values); values.clear(); values.putNull(StatusUpdates.PRESENCE); mResolver.update(StatusUpdates.CONTENT_URI, values, StatusUpdates.DATA_ID + "=" + statusId, null); values.clear(); values.putNull(Contacts.CONTACT_PRESENCE); values.put(Contacts.CONTACT_STATUS, "Available"); assertStoredValuesWithProjection(contactUri, values); } public void testStatusUpdateWithTimestamp() { long rawContactId = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); insertImHandle(rawContactId, Im.PROTOCOL_GOOGLE_TALK, null, "gtalk"); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", 0, "Offline", 80, StatusUpdates.CAPABILITY_HAS_CAMERA, false); insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", 0, "Available", 100, StatusUpdates.CAPABILITY_HAS_CAMERA, false); insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "gtalk", 0, "Busy", 90, StatusUpdates.CAPABILITY_HAS_CAMERA, false); // Should return the latest status ContentValues values = new ContentValues(); values.put(Contacts.CONTACT_STATUS_TIMESTAMP, 100); values.put(Contacts.CONTACT_STATUS, "Available"); assertStoredValuesWithProjection(contactUri, values); } private void assertStatusUpdate(Cursor c, int protocol, String customProtocol, int presence, String status) { ContentValues values = new ContentValues(); values.put(StatusUpdates.PROTOCOL, protocol); values.put(StatusUpdates.CUSTOM_PROTOCOL, customProtocol); values.put(StatusUpdates.PRESENCE, presence); values.put(StatusUpdates.STATUS, status); assertCursorValues(c, values); } // Stream item query test cases. public void testQueryStreamItemsByRawContactId() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); ContentValues values = buildGenericStreamItemValues(); insertStreamItem(rawContactId, values, mAccount); assertStoredValues( Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), values); } public void testQueryStreamItemsByContactId() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = buildGenericStreamItemValues(); insertStreamItem(rawContactId, values, null); assertStoredValues( Uri.withAppendedPath( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.StreamItems.CONTENT_DIRECTORY), values); } public void testQueryStreamItemsByLookupKey() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); String lookupKey = queryLookupKey(contactId); ContentValues values = buildGenericStreamItemValues(); insertStreamItem(rawContactId, values, null); assertStoredValues( Uri.withAppendedPath( Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey), Contacts.StreamItems.CONTENT_DIRECTORY), values); } public void testQueryStreamItemsByLookupKeyAndContactId() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); String lookupKey = queryLookupKey(contactId); ContentValues values = buildGenericStreamItemValues(); insertStreamItem(rawContactId, values, null); assertStoredValues( Uri.withAppendedPath( ContentUris.withAppendedId( Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey), contactId), Contacts.StreamItems.CONTENT_DIRECTORY), values); } public void testQueryStreamItems() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); insertStreamItem(rawContactId, values, null); assertStoredValues(StreamItems.CONTENT_URI, values); } public void testQueryStreamItemsWithSelection() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues firstValues = buildGenericStreamItemValues(); insertStreamItem(rawContactId, firstValues, null); ContentValues secondValues = buildGenericStreamItemValues(); secondValues.put(StreamItems.TEXT, "Goodbye world"); insertStreamItem(rawContactId, secondValues, null); // Select only the first stream item. assertStoredValues(StreamItems.CONTENT_URI, StreamItems.TEXT + "=?", new String[]{"Hello world"}, firstValues); // Select only the second stream item. assertStoredValues(StreamItems.CONTENT_URI, StreamItems.TEXT + "=?", new String[]{"Goodbye world"}, secondValues); } public void testQueryStreamItemById() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues firstValues = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, firstValues, null); long firstStreamItemId = ContentUris.parseId(resultUri); ContentValues secondValues = buildGenericStreamItemValues(); secondValues.put(StreamItems.TEXT, "Goodbye world"); resultUri = insertStreamItem(rawContactId, secondValues, null); long secondStreamItemId = ContentUris.parseId(resultUri); // Select only the first stream item. assertStoredValues(ContentUris.withAppendedId(StreamItems.CONTENT_URI, firstStreamItemId), firstValues); // Select only the second stream item. assertStoredValues(ContentUris.withAppendedId(StreamItems.CONTENT_URI, secondStreamItemId), secondValues); } // Stream item photo insertion + query test cases. public void testQueryStreamItemPhotoWithSelection() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, values, null); long streamItemId = ContentUris.parseId(resultUri); ContentValues photo1Values = buildGenericStreamItemPhotoValues(1); insertStreamItemPhoto(streamItemId, photo1Values, null); photo1Values.remove(StreamItemPhotos.PHOTO); // Removed during processing. ContentValues photo2Values = buildGenericStreamItemPhotoValues(2); insertStreamItemPhoto(streamItemId, photo2Values, null); // Select only the first photo. assertStoredValues(StreamItems.CONTENT_PHOTO_URI, StreamItemPhotos.SORT_INDEX + "=?", new String[]{"1"}, photo1Values); } public void testQueryStreamItemPhotoByStreamItemId() { long rawContactId = RawContactUtil.createRawContact(mResolver); // Insert a first stream item. ContentValues firstValues = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, firstValues, null); long firstStreamItemId = ContentUris.parseId(resultUri); // Insert a second stream item. ContentValues secondValues = buildGenericStreamItemValues(); resultUri = insertStreamItem(rawContactId, secondValues, null); long secondStreamItemId = ContentUris.parseId(resultUri); // Add a photo to the first stream item. ContentValues photo1Values = buildGenericStreamItemPhotoValues(1); insertStreamItemPhoto(firstStreamItemId, photo1Values, null); photo1Values.remove(StreamItemPhotos.PHOTO); // Removed during processing. // Add a photo to the second stream item. ContentValues photo2Values = buildGenericStreamItemPhotoValues(1); photo2Values.put(StreamItemPhotos.PHOTO, loadPhotoFromResource( R.drawable.nebula, PhotoSize.ORIGINAL)); insertStreamItemPhoto(secondStreamItemId, photo2Values, null); photo2Values.remove(StreamItemPhotos.PHOTO); // Removed during processing. // Select only the photos from the second stream item. assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, secondStreamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), photo2Values); } public void testQueryStreamItemPhotoByStreamItemPhotoId() { long rawContactId = RawContactUtil.createRawContact(mResolver); // Insert a first stream item. ContentValues firstValues = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, firstValues, null); long firstStreamItemId = ContentUris.parseId(resultUri); // Insert a second stream item. ContentValues secondValues = buildGenericStreamItemValues(); resultUri = insertStreamItem(rawContactId, secondValues, null); long secondStreamItemId = ContentUris.parseId(resultUri); // Add a photo to the first stream item. ContentValues photo1Values = buildGenericStreamItemPhotoValues(1); resultUri = insertStreamItemPhoto(firstStreamItemId, photo1Values, null); long firstPhotoId = ContentUris.parseId(resultUri); photo1Values.remove(StreamItemPhotos.PHOTO); // Removed during processing. // Add a photo to the second stream item. ContentValues photo2Values = buildGenericStreamItemPhotoValues(1); photo2Values.put(StreamItemPhotos.PHOTO, loadPhotoFromResource( R.drawable.galaxy, PhotoSize.ORIGINAL)); resultUri = insertStreamItemPhoto(secondStreamItemId, photo2Values, null); long secondPhotoId = ContentUris.parseId(resultUri); photo2Values.remove(StreamItemPhotos.PHOTO); // Removed during processing. // Select the first photo. assertStoredValues(ContentUris.withAppendedId( Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, firstStreamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), firstPhotoId), photo1Values); // Select the second photo. assertStoredValues(ContentUris.withAppendedId( Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, secondStreamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), secondPhotoId), photo2Values); } // Stream item insertion test cases. public void testInsertStreamItemInProfileRequiresWriteProfileAccess() { long profileRawContactId = createBasicProfileContact(new ContentValues()); // With our (default) write profile permission, we should be able to insert a stream item. ContentValues values = buildGenericStreamItemValues(); insertStreamItem(profileRawContactId, values, null); // Now take away write profile permission. mActor.removePermissions("android.permission.WRITE_PROFILE"); // Try inserting another stream item. try { insertStreamItem(profileRawContactId, values, null); fail("Should require WRITE_PROFILE access to insert a stream item in the profile."); } catch (SecurityException expected) { // Trying to insert a stream item in the profile without WRITE_PROFILE permission // should fail. } } public void testInsertStreamItemWithContentValues() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); values.put(StreamItems.RAW_CONTACT_ID, rawContactId); mResolver.insert(StreamItems.CONTENT_URI, values); assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), values); } public void testInsertStreamItemOverLimit() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); values.put(StreamItems.RAW_CONTACT_ID, rawContactId); List<Long> streamItemIds = Lists.newArrayList(); // Insert MAX + 1 stream items. long baseTime = System.currentTimeMillis(); for (int i = 0; i < 6; i++) { values.put(StreamItems.TIMESTAMP, baseTime + i); Uri resultUri = mResolver.insert(StreamItems.CONTENT_URI, values); streamItemIds.add(ContentUris.parseId(resultUri)); } Long doomedStreamItemId = streamItemIds.get(0); // There should only be MAX items. The oldest one should have been cleaned up. Cursor c = mResolver.query( Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), new String[]{StreamItems._ID}, null, null, null); try { while(c.moveToNext()) { long streamItemId = c.getLong(0); streamItemIds.remove(streamItemId); } } finally { c.close(); } assertEquals(1, streamItemIds.size()); assertEquals(doomedStreamItemId, streamItemIds.get(0)); } public void testInsertStreamItemOlderThanOldestInLimit() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); values.put(StreamItems.RAW_CONTACT_ID, rawContactId); // Insert MAX stream items. long baseTime = System.currentTimeMillis(); for (int i = 0; i < 5; i++) { values.put(StreamItems.TIMESTAMP, baseTime + i); Uri resultUri = mResolver.insert(StreamItems.CONTENT_URI, values); assertNotSame("Expected non-0 stream item ID to be inserted", 0L, ContentUris.parseId(resultUri)); } // Now try to insert a stream item that's older. It should be deleted immediately // and return an ID of 0. values.put(StreamItems.TIMESTAMP, baseTime - 1); Uri resultUri = mResolver.insert(StreamItems.CONTENT_URI, values); assertEquals(0L, ContentUris.parseId(resultUri)); } // Stream item photo insertion test cases. public void testInsertStreamItemsAndPhotosInBatch() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues streamItemValues = buildGenericStreamItemValues(); ContentValues streamItemPhotoValues = buildGenericStreamItemPhotoValues(0); ArrayList<ContentProviderOperation> ops = Lists.newArrayList(); ops.add(ContentProviderOperation.newInsert( Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY)) .withValues(streamItemValues).build()); for (int i = 0; i < 5; i++) { streamItemPhotoValues.put(StreamItemPhotos.SORT_INDEX, i); ops.add(ContentProviderOperation.newInsert(StreamItems.CONTENT_PHOTO_URI) .withValues(streamItemPhotoValues) .withValueBackReference(StreamItemPhotos.STREAM_ITEM_ID, 0) .build()); } mResolver.applyBatch(ContactsContract.AUTHORITY, ops); // Check that all five photos were inserted under the raw contact. Cursor c = mResolver.query(StreamItems.CONTENT_URI, new String[]{StreamItems._ID}, StreamItems.RAW_CONTACT_ID + "=?", new String[]{String.valueOf(rawContactId)}, null); long streamItemId = 0; try { assertEquals(1, c.getCount()); c.moveToFirst(); streamItemId = c.getLong(0); } finally { c.close(); } c = mResolver.query(Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), new String[]{StreamItemPhotos._ID, StreamItemPhotos.PHOTO_URI}, null, null, null); try { assertEquals(5, c.getCount()); byte[] expectedPhotoBytes = loadPhotoFromResource( R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO); while (c.moveToNext()) { String photoUri = c.getString(1); EvenMoreAsserts.assertImageRawData(getContext(), expectedPhotoBytes, mResolver.openInputStream(Uri.parse(photoUri))); } } finally { c.close(); } } // Stream item update test cases. public void testUpdateStreamItemById() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, values, null); long streamItemId = ContentUris.parseId(resultUri); values.put(StreamItems.TEXT, "Goodbye world"); mResolver.update(ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), values, null, null); assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), values); } public void testUpdateStreamItemWithContentValues() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, values, null); long streamItemId = ContentUris.parseId(resultUri); values.put(StreamItems._ID, streamItemId); values.put(StreamItems.TEXT, "Goodbye world"); mResolver.update(StreamItems.CONTENT_URI, values, null, null); assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), values); } // Stream item photo update test cases. public void testUpdateStreamItemPhotoById() throws IOException { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, values, null); long streamItemId = ContentUris.parseId(resultUri); ContentValues photoValues = buildGenericStreamItemPhotoValues(1); resultUri = insertStreamItemPhoto(streamItemId, photoValues, null); long streamItemPhotoId = ContentUris.parseId(resultUri); photoValues.put(StreamItemPhotos.PHOTO, loadPhotoFromResource( R.drawable.nebula, PhotoSize.ORIGINAL)); Uri photoUri = ContentUris.withAppendedId( Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), streamItemPhotoId); mResolver.update(photoUri, photoValues, null, null); photoValues.remove(StreamItemPhotos.PHOTO); // Removed during processing. assertStoredValues(photoUri, photoValues); // Check that the photo stored is the expected one. String displayPhotoUri = getStoredValue(photoUri, StreamItemPhotos.PHOTO_URI); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.nebula, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(Uri.parse(displayPhotoUri))); } public void testUpdateStreamItemPhotoWithContentValues() throws IOException { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, values, null); long streamItemId = ContentUris.parseId(resultUri); ContentValues photoValues = buildGenericStreamItemPhotoValues(1); resultUri = insertStreamItemPhoto(streamItemId, photoValues, null); long streamItemPhotoId = ContentUris.parseId(resultUri); photoValues.put(StreamItemPhotos._ID, streamItemPhotoId); photoValues.put(StreamItemPhotos.PHOTO, loadPhotoFromResource( R.drawable.nebula, PhotoSize.ORIGINAL)); Uri photoUri = Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY); mResolver.update(photoUri, photoValues, null, null); photoValues.remove(StreamItemPhotos.PHOTO); // Removed during processing. assertStoredValues(photoUri, photoValues); // Check that the photo stored is the expected one. String displayPhotoUri = getStoredValue(photoUri, StreamItemPhotos.PHOTO_URI); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.nebula, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(Uri.parse(displayPhotoUri))); } // Stream item deletion test cases. public void testDeleteStreamItemById() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues firstValues = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, firstValues, null); long firstStreamItemId = ContentUris.parseId(resultUri); ContentValues secondValues = buildGenericStreamItemValues(); secondValues.put(StreamItems.TEXT, "Goodbye world"); insertStreamItem(rawContactId, secondValues, null); // Delete the first stream item. mResolver.delete(ContentUris.withAppendedId(StreamItems.CONTENT_URI, firstStreamItemId), null, null); // Check that only the second item remains. assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), secondValues); } public void testDeleteStreamItemWithSelection() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues firstValues = buildGenericStreamItemValues(); insertStreamItem(rawContactId, firstValues, null); ContentValues secondValues = buildGenericStreamItemValues(); secondValues.put(StreamItems.TEXT, "Goodbye world"); insertStreamItem(rawContactId, secondValues, null); // Delete the first stream item with a custom selection. mResolver.delete(StreamItems.CONTENT_URI, StreamItems.TEXT + "=?", new String[]{"Hello world"}); // Check that only the second item remains. assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), secondValues); } // Stream item photo deletion test cases. public void testDeleteStreamItemPhotoById() { long rawContactId = RawContactUtil.createRawContact(mResolver); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); long streamItemPhotoId = ContentUris.parseId( insertStreamItemPhoto(streamItemId, buildGenericStreamItemPhotoValues(0), null)); mResolver.delete( ContentUris.withAppendedId( Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), streamItemPhotoId), null, null); Cursor c = mResolver.query(StreamItems.CONTENT_PHOTO_URI, new String[]{StreamItemPhotos._ID}, StreamItemPhotos.STREAM_ITEM_ID + "=?", new String[]{String.valueOf(streamItemId)}, null); try { assertEquals("Expected photo to be deleted.", 0, c.getCount()); } finally { c.close(); } } public void testDeleteStreamItemPhotoWithSelection() { long rawContactId = RawContactUtil.createRawContact(mResolver); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); ContentValues firstPhotoValues = buildGenericStreamItemPhotoValues(0); ContentValues secondPhotoValues = buildGenericStreamItemPhotoValues(1); insertStreamItemPhoto(streamItemId, firstPhotoValues, null); firstPhotoValues.remove(StreamItemPhotos.PHOTO); // Removed while processing. insertStreamItemPhoto(streamItemId, secondPhotoValues, null); Uri photoUri = Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY); mResolver.delete(photoUri, StreamItemPhotos.SORT_INDEX + "=1", null); assertStoredValues(photoUri, firstPhotoValues); } public void testDeleteStreamItemsWhenRawContactDeleted() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri streamItemUri = insertStreamItem(rawContactId, buildGenericStreamItemValues(), mAccount); Uri streamItemPhotoUri = insertStreamItemPhoto(ContentUris.parseId(streamItemUri), buildGenericStreamItemPhotoValues(0), mAccount); mResolver.delete(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), null, null); ContentValues[] emptyValues = new ContentValues[0]; // The stream item and its photo should be gone. assertStoredValues(streamItemUri, emptyValues); assertStoredValues(streamItemPhotoUri, emptyValues); } public void testQueryStreamItemLimit() { ContentValues values = new ContentValues(); values.put(StreamItems.MAX_ITEMS, 5); assertStoredValues(StreamItems.CONTENT_LIMIT_URI, values); } // Tests for inserting or updating stream items as a side-effect of making status updates // (forward-compatibility of status updates into the new social stream API). public void testStreamItemInsertedOnStatusUpdate() { // This method of creating a raw contact automatically inserts a status update with // the status message "hacking". ContentValues values = new ContentValues(); long rawContactId = createRawContact(values, "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_CAMERA | StatusUpdates.CAPABILITY_HAS_VIDEO | StatusUpdates.CAPABILITY_HAS_VOICE); ContentValues expectedValues = new ContentValues(); expectedValues.put(StreamItems.RAW_CONTACT_ID, rawContactId); expectedValues.put(StreamItems.TEXT, "hacking"); assertStoredValues(RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.StreamItems.CONTENT_DIRECTORY).build(), expectedValues); } public void testStreamItemInsertedOnStatusUpdate_HtmlQuoting() { // This method of creating a raw contact automatically inserts a status update with // the status message "hacking". ContentValues values = new ContentValues(); long rawContactId = createRawContact(values, "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_VOICE); // Insert a new status update for the raw contact. insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.INVISIBLE, "& <b> test &#39;", StatusUpdates.CAPABILITY_HAS_VOICE); ContentValues expectedValues = new ContentValues(); expectedValues.put(StreamItems.RAW_CONTACT_ID, rawContactId); expectedValues.put(StreamItems.TEXT, "&amp; &lt;b&gt; test &amp;#39;"); assertStoredValues(RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.StreamItems.CONTENT_DIRECTORY).build(), expectedValues); } public void testStreamItemUpdatedOnSecondStatusUpdate() { // This method of creating a raw contact automatically inserts a status update with // the status message "hacking". ContentValues values = new ContentValues(); int chatMode = StatusUpdates.CAPABILITY_HAS_CAMERA | StatusUpdates.CAPABILITY_HAS_VIDEO | StatusUpdates.CAPABILITY_HAS_VOICE; long rawContactId = createRawContact(values, "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, chatMode); // Insert a new status update for the raw contact. insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.INVISIBLE, "finished hacking", chatMode); ContentValues expectedValues = new ContentValues(); expectedValues.put(StreamItems.RAW_CONTACT_ID, rawContactId); expectedValues.put(StreamItems.TEXT, "finished hacking"); assertStoredValues(RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.StreamItems.CONTENT_DIRECTORY).build(), expectedValues); } public void testStreamItemReadRequiresReadSocialStreamPermission() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); String lookupKey = queryLookupKey(contactId); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); mActor.removePermissions("android.permission.READ_SOCIAL_STREAM"); // Try selecting the stream item in various ways. expectSecurityException( "Querying stream items by contact ID requires social stream read permission", Uri.withAppendedPath( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.StreamItems.CONTENT_DIRECTORY), null, null, null, null); expectSecurityException( "Querying stream items by lookup key requires social stream read permission", Contacts.CONTENT_LOOKUP_URI.buildUpon().appendPath(lookupKey) .appendPath(Contacts.StreamItems.CONTENT_DIRECTORY).build(), null, null, null, null); expectSecurityException( "Querying stream items by lookup key and ID requires social stream read permission", Uri.withAppendedPath(Contacts.getLookupUri(contactId, lookupKey), Contacts.StreamItems.CONTENT_DIRECTORY), null, null, null, null); expectSecurityException( "Querying stream items by raw contact ID requires social stream read permission", Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), null, null, null, null); expectSecurityException( "Querying stream items by raw contact ID and stream item ID requires social " + "stream read permission", ContentUris.withAppendedId( Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), streamItemId), null, null, null, null); expectSecurityException( "Querying all stream items requires social stream read permission", StreamItems.CONTENT_URI, null, null, null, null); expectSecurityException( "Querying stream item by ID requires social stream read permission", ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), null, null, null, null); } public void testStreamItemPhotoReadRequiresReadSocialStreamPermission() { long rawContactId = RawContactUtil.createRawContact(mResolver); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); long streamItemPhotoId = ContentUris.parseId( insertStreamItemPhoto(streamItemId, buildGenericStreamItemPhotoValues(0), null)); mActor.removePermissions("android.permission.READ_SOCIAL_STREAM"); // Try selecting the stream item photo in various ways. expectSecurityException( "Querying all stream item photos requires social stream read permission", StreamItems.CONTENT_URI.buildUpon() .appendPath(StreamItems.StreamItemPhotos.CONTENT_DIRECTORY).build(), null, null, null, null); expectSecurityException( "Querying all stream item photos requires social stream read permission", StreamItems.CONTENT_URI.buildUpon() .appendPath(String.valueOf(streamItemId)) .appendPath(StreamItems.StreamItemPhotos.CONTENT_DIRECTORY) .appendPath(String.valueOf(streamItemPhotoId)).build(), null, null, null, null); } public void testStreamItemModificationRequiresWriteSocialStreamPermission() { long rawContactId = RawContactUtil.createRawContact(mResolver); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); mActor.removePermissions("android.permission.WRITE_SOCIAL_STREAM"); try { insertStreamItem(rawContactId, buildGenericStreamItemValues(), null); fail("Should not be able to insert to stream without write social stream permission"); } catch (SecurityException expected) { } try { ContentValues values = new ContentValues(); values.put(StreamItems.TEXT, "Goodbye world"); mResolver.update(ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), values, null, null); fail("Should not be able to update stream without write social stream permission"); } catch (SecurityException expected) { } try { mResolver.delete(ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), null, null); fail("Should not be able to delete from stream without write social stream permission"); } catch (SecurityException expected) { } } public void testStreamItemPhotoModificationRequiresWriteSocialStreamPermission() { long rawContactId = RawContactUtil.createRawContact(mResolver); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); long streamItemPhotoId = ContentUris.parseId( insertStreamItemPhoto(streamItemId, buildGenericStreamItemPhotoValues(0), null)); mActor.removePermissions("android.permission.WRITE_SOCIAL_STREAM"); Uri photoUri = StreamItems.CONTENT_URI.buildUpon() .appendPath(String.valueOf(streamItemId)) .appendPath(StreamItems.StreamItemPhotos.CONTENT_DIRECTORY) .appendPath(String.valueOf(streamItemPhotoId)).build(); try { insertStreamItemPhoto(streamItemId, buildGenericStreamItemPhotoValues(1), null); fail("Should not be able to insert photos without write social stream permission"); } catch (SecurityException expected) { } try { ContentValues values = new ContentValues(); values.put(StreamItemPhotos.PHOTO, loadPhotoFromResource(R.drawable.galaxy, PhotoSize.ORIGINAL)); mResolver.update(photoUri, values, null, null); fail("Should not be able to update photos without write social stream permission"); } catch (SecurityException expected) { } try { mResolver.delete(photoUri, null, null); fail("Should not be able to delete photos without write social stream permission"); } catch (SecurityException expected) { } } public void testStatusUpdateDoesNotRequireReadOrWriteSocialStreamPermission() { int protocol1 = Im.PROTOCOL_GOOGLE_TALK; String handle1 = "[email protected]"; long rawContactId = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId, protocol1, null, handle1); mActor.removePermissions("android.permission.READ_SOCIAL_STREAM"); mActor.removePermissions("android.permission.WRITE_SOCIAL_STREAM"); insertStatusUpdate(protocol1, null, handle1, StatusUpdates.AVAILABLE, "Green", StatusUpdates.CAPABILITY_HAS_CAMERA); mActor.addPermissions("android.permission.READ_SOCIAL_STREAM"); ContentValues expectedValues = new ContentValues(); expectedValues.put(StreamItems.TEXT, "Green"); assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), expectedValues); } private ContentValues buildGenericStreamItemValues() { ContentValues values = new ContentValues(); values.put(StreamItems.TEXT, "Hello world"); values.put(StreamItems.TIMESTAMP, System.currentTimeMillis()); values.put(StreamItems.COMMENTS, "Reshared by 123 others"); return values; } private ContentValues buildGenericStreamItemPhotoValues(int sortIndex) { ContentValues values = new ContentValues(); values.put(StreamItemPhotos.SORT_INDEX, sortIndex); values.put(StreamItemPhotos.PHOTO, loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.ORIGINAL)); return values; } public void testSingleStatusUpdateRowPerContact() { int protocol1 = Im.PROTOCOL_GOOGLE_TALK; String handle1 = "[email protected]"; long rawContactId1 = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId1, protocol1, null, handle1); insertStatusUpdate(protocol1, null, handle1, StatusUpdates.AVAILABLE, "Green", StatusUpdates.CAPABILITY_HAS_CAMERA); insertStatusUpdate(protocol1, null, handle1, StatusUpdates.AWAY, "Yellow", StatusUpdates.CAPABILITY_HAS_CAMERA); insertStatusUpdate(protocol1, null, handle1, StatusUpdates.INVISIBLE, "Red", StatusUpdates.CAPABILITY_HAS_CAMERA); Cursor c = queryContact(queryContactId(rawContactId1), new String[] {Contacts.CONTACT_PRESENCE, Contacts.CONTACT_STATUS}); assertEquals(1, c.getCount()); c.moveToFirst(); assertEquals(StatusUpdates.INVISIBLE, c.getInt(0)); assertEquals("Red", c.getString(1)); c.close(); } private void updateSendToVoicemailAndRingtone(long contactId, boolean sendToVoicemail, String ringtone) { ContentValues values = new ContentValues(); values.put(Contacts.SEND_TO_VOICEMAIL, sendToVoicemail); if (ringtone != null) { values.put(Contacts.CUSTOM_RINGTONE, ringtone); } final Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); int count = mResolver.update(uri, values, null, null); assertEquals(1, count); } private void updateSendToVoicemailAndRingtoneWithSelection(long contactId, boolean sendToVoicemail, String ringtone) { ContentValues values = new ContentValues(); values.put(Contacts.SEND_TO_VOICEMAIL, sendToVoicemail); if (ringtone != null) { values.put(Contacts.CUSTOM_RINGTONE, ringtone); } int count = mResolver.update(Contacts.CONTENT_URI, values, Contacts._ID + "=" + contactId, null); assertEquals(1, count); } private void assertSendToVoicemailAndRingtone(long contactId, boolean expectedSendToVoicemail, String expectedRingtone) { Cursor c = queryContact(contactId); assertTrue(c.moveToNext()); int sendToVoicemail = c.getInt(c.getColumnIndex(Contacts.SEND_TO_VOICEMAIL)); assertEquals(expectedSendToVoicemail ? 1 : 0, sendToVoicemail); String ringtone = c.getString(c.getColumnIndex(Contacts.CUSTOM_RINGTONE)); if (expectedRingtone == null) { assertNull(ringtone); } else { assertTrue(ArrayUtils.contains(expectedRingtone.split(","), ringtone)); } c.close(); } public void testContactVisibilityUpdateOnMembershipChange() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); assertVisibility(rawContactId, "0"); long visibleGroupId = createGroup(mAccount, "123", "Visible", 1); long invisibleGroupId = createGroup(mAccount, "567", "Invisible", 0); Uri membership1 = insertGroupMembership(rawContactId, visibleGroupId); assertVisibility(rawContactId, "1"); Uri membership2 = insertGroupMembership(rawContactId, invisibleGroupId); assertVisibility(rawContactId, "1"); mResolver.delete(membership1, null, null); assertVisibility(rawContactId, "0"); ContentValues values = new ContentValues(); values.put(GroupMembership.GROUP_ROW_ID, visibleGroupId); mResolver.update(membership2, values, null, null); assertVisibility(rawContactId, "1"); } private void assertVisibility(long rawContactId, String expectedValue) { assertStoredValue(Contacts.CONTENT_URI, Contacts._ID + "=" + queryContactId(rawContactId), null, Contacts.IN_VISIBLE_GROUP, expectedValue); } public void testSupplyingBothValuesAndParameters() throws Exception { Account account = new Account("account 1", "type%/:1"); Uri uri = ContactsContract.Groups.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.Groups.ACCOUNT_NAME, account.name) .appendQueryParameter(ContactsContract.Groups.ACCOUNT_TYPE, account.type) .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true") .build(); ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(uri); builder.withValue(ContactsContract.Groups.ACCOUNT_TYPE, account.type); builder.withValue(ContactsContract.Groups.ACCOUNT_NAME, account.name); builder.withValue(ContactsContract.Groups.SYSTEM_ID, "some id"); builder.withValue(ContactsContract.Groups.TITLE, "some name"); builder.withValue(ContactsContract.Groups.GROUP_VISIBLE, 1); mResolver.applyBatch(ContactsContract.AUTHORITY, Lists.newArrayList(builder.build())); builder = ContentProviderOperation.newInsert(uri); builder.withValue(ContactsContract.Groups.ACCOUNT_TYPE, account.type + "diff"); builder.withValue(ContactsContract.Groups.ACCOUNT_NAME, account.name); builder.withValue(ContactsContract.Groups.SYSTEM_ID, "some other id"); builder.withValue(ContactsContract.Groups.TITLE, "some other name"); builder.withValue(ContactsContract.Groups.GROUP_VISIBLE, 1); try { mResolver.applyBatch(ContactsContract.AUTHORITY, Lists.newArrayList(builder.build())); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException ex) { // Expected } } public void testContentEntityIterator() { // create multiple contacts and check that the selected ones are returned long id; long groupId1 = createGroup(mAccount, "gsid1", "title1"); long groupId2 = createGroup(mAccount, "gsid2", "title2"); id = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "c0"); insertGroupMembership(id, "gsid1"); insertEmail(id, "[email protected]"); insertPhoneNumber(id, "5551212c0"); long c1 = id = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "c1"); Uri id_1_0 = insertGroupMembership(id, "gsid1"); Uri id_1_1 = insertGroupMembership(id, "gsid2"); Uri id_1_2 = insertEmail(id, "[email protected]"); Uri id_1_3 = insertPhoneNumber(id, "5551212c1"); long c2 = id = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "c2"); Uri id_2_0 = insertGroupMembership(id, "gsid1"); Uri id_2_1 = insertEmail(id, "[email protected]"); Uri id_2_2 = insertPhoneNumber(id, "5551212c2"); long c3 = id = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "c3"); Uri id_3_0 = insertGroupMembership(id, groupId2); Uri id_3_1 = insertEmail(id, "[email protected]"); Uri id_3_2 = insertPhoneNumber(id, "5551212c3"); EntityIterator iterator = RawContacts.newEntityIterator(mResolver.query( TestUtil.maybeAddAccountQueryParameters(RawContactsEntity.CONTENT_URI, mAccount), null, RawContacts.SOURCE_ID + " in ('c1', 'c2', 'c3')", null, null)); Entity entity; ContentValues[] subValues; entity = iterator.next(); assertEquals(c1, (long) entity.getEntityValues().getAsLong(RawContacts._ID)); subValues = asSortedContentValuesArray(entity.getSubValues()); assertEquals(4, subValues.length); assertDataRow(subValues[0], GroupMembership.CONTENT_ITEM_TYPE, Data._ID, id_1_0, GroupMembership.GROUP_ROW_ID, groupId1, GroupMembership.GROUP_SOURCE_ID, "gsid1"); assertDataRow(subValues[1], GroupMembership.CONTENT_ITEM_TYPE, Data._ID, id_1_1, GroupMembership.GROUP_ROW_ID, groupId2, GroupMembership.GROUP_SOURCE_ID, "gsid2"); assertDataRow(subValues[2], Email.CONTENT_ITEM_TYPE, Data._ID, id_1_2, Email.DATA, "[email protected]"); assertDataRow(subValues[3], Phone.CONTENT_ITEM_TYPE, Data._ID, id_1_3, Email.DATA, "5551212c1"); entity = iterator.next(); assertEquals(c2, (long) entity.getEntityValues().getAsLong(RawContacts._ID)); subValues = asSortedContentValuesArray(entity.getSubValues()); assertEquals(3, subValues.length); assertDataRow(subValues[0], GroupMembership.CONTENT_ITEM_TYPE, Data._ID, id_2_0, GroupMembership.GROUP_ROW_ID, groupId1, GroupMembership.GROUP_SOURCE_ID, "gsid1"); assertDataRow(subValues[1], Email.CONTENT_ITEM_TYPE, Data._ID, id_2_1, Email.DATA, "[email protected]"); assertDataRow(subValues[2], Phone.CONTENT_ITEM_TYPE, Data._ID, id_2_2, Email.DATA, "5551212c2"); entity = iterator.next(); assertEquals(c3, (long) entity.getEntityValues().getAsLong(RawContacts._ID)); subValues = asSortedContentValuesArray(entity.getSubValues()); assertEquals(3, subValues.length); assertDataRow(subValues[0], GroupMembership.CONTENT_ITEM_TYPE, Data._ID, id_3_0, GroupMembership.GROUP_ROW_ID, groupId2, GroupMembership.GROUP_SOURCE_ID, "gsid2"); assertDataRow(subValues[1], Email.CONTENT_ITEM_TYPE, Data._ID, id_3_1, Email.DATA, "[email protected]"); assertDataRow(subValues[2], Phone.CONTENT_ITEM_TYPE, Data._ID, id_3_2, Email.DATA, "5551212c3"); assertFalse(iterator.hasNext()); iterator.close(); } public void testDataCreateUpdateDeleteByMimeType() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = new ContentValues(); values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, "testmimetype"); values.put(Data.RES_PACKAGE, "oldpackage"); values.put(Data.IS_PRIMARY, 1); values.put(Data.IS_SUPER_PRIMARY, 1); values.put(Data.DATA1, "old1"); values.put(Data.DATA2, "old2"); values.put(Data.DATA3, "old3"); values.put(Data.DATA4, "old4"); values.put(Data.DATA5, "old5"); values.put(Data.DATA6, "old6"); values.put(Data.DATA7, "old7"); values.put(Data.DATA8, "old8"); values.put(Data.DATA9, "old9"); values.put(Data.DATA10, "old10"); values.put(Data.DATA11, "old11"); values.put(Data.DATA12, "old12"); values.put(Data.DATA13, "old13"); values.put(Data.DATA14, "old14"); values.put(Data.DATA15, "old15"); Uri uri = mResolver.insert(Data.CONTENT_URI, values); assertStoredValues(uri, values); assertNetworkNotified(true); values.clear(); values.put(Data.RES_PACKAGE, "newpackage"); values.put(Data.IS_PRIMARY, 0); values.put(Data.IS_SUPER_PRIMARY, 0); values.put(Data.DATA1, "new1"); values.put(Data.DATA2, "new2"); values.put(Data.DATA3, "new3"); values.put(Data.DATA4, "new4"); values.put(Data.DATA5, "new5"); values.put(Data.DATA6, "new6"); values.put(Data.DATA7, "new7"); values.put(Data.DATA8, "new8"); values.put(Data.DATA9, "new9"); values.put(Data.DATA10, "new10"); values.put(Data.DATA11, "new11"); values.put(Data.DATA12, "new12"); values.put(Data.DATA13, "new13"); values.put(Data.DATA14, "new14"); values.put(Data.DATA15, "new15"); mResolver.update(Data.CONTENT_URI, values, Data.RAW_CONTACT_ID + "=" + rawContactId + " AND " + Data.MIMETYPE + "='testmimetype'", null); assertNetworkNotified(true); assertStoredValues(uri, values); int count = mResolver.delete(Data.CONTENT_URI, Data.RAW_CONTACT_ID + "=" + rawContactId + " AND " + Data.MIMETYPE + "='testmimetype'", null); assertEquals(1, count); assertEquals(0, getCount(Data.CONTENT_URI, Data.RAW_CONTACT_ID + "=" + rawContactId + " AND " + Data.MIMETYPE + "='testmimetype'", null)); assertNetworkNotified(true); } public void testRawContactQuery() { Account account1 = new Account("a", "b"); Account account2 = new Account("c", "d"); long rawContactId1 = RawContactUtil.createRawContact(mResolver, account1); long rawContactId2 = RawContactUtil.createRawContact(mResolver, account2); Uri uri1 = TestUtil.maybeAddAccountQueryParameters(RawContacts.CONTENT_URI, account1); Uri uri2 = TestUtil.maybeAddAccountQueryParameters(RawContacts.CONTENT_URI, account2); assertEquals(1, getCount(uri1, null, null)); assertEquals(1, getCount(uri2, null, null)); assertStoredValue(uri1, RawContacts._ID, rawContactId1) ; assertStoredValue(uri2, RawContacts._ID, rawContactId2) ; Uri rowUri1 = ContentUris.withAppendedId(uri1, rawContactId1); Uri rowUri2 = ContentUris.withAppendedId(uri2, rawContactId2); assertStoredValue(rowUri1, RawContacts._ID, rawContactId1) ; assertStoredValue(rowUri2, RawContacts._ID, rawContactId2) ; } public void testRawContactDeletion() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); insertImHandle(rawContactId, Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]"); insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.AVAILABLE, null, StatusUpdates.CAPABILITY_HAS_CAMERA); long contactId = queryContactId(rawContactId); assertEquals(1, getCount(Uri.withAppendedPath(uri, RawContacts.Data.CONTENT_DIRECTORY), null, null)); assertEquals(1, getCount(StatusUpdates.CONTENT_URI, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId, null)); mResolver.delete(uri, null, null); assertStoredValue(uri, RawContacts.DELETED, "1"); assertNetworkNotified(true); Uri permanentDeletionUri = setCallerIsSyncAdapter(uri, mAccount); mResolver.delete(permanentDeletionUri, null, null); assertEquals(0, getCount(uri, null, null)); assertEquals(0, getCount(Uri.withAppendedPath(uri, RawContacts.Data.CONTENT_DIRECTORY), null, null)); assertEquals(0, getCount(StatusUpdates.CONTENT_URI, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId, null)); assertEquals(0, getCount(Contacts.CONTENT_URI, Contacts._ID + "=" + contactId, null)); assertNetworkNotified(false); } public void testRawContactDeletionKeepingAggregateContact() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, mAccount); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, mAccount); setAggregationException( AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); long contactId = queryContactId(rawContactId1); Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId1); Uri permanentDeletionUri = setCallerIsSyncAdapter(uri, mAccount); mResolver.delete(permanentDeletionUri, null, null); assertEquals(0, getCount(uri, null, null)); assertEquals(1, getCount(Contacts.CONTENT_URI, Contacts._ID + "=" + contactId, null)); } public void testRawContactDeletion_byAccountParam() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); insertImHandle(rawContactId, Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]"); insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.AVAILABLE, null, StatusUpdates.CAPABILITY_HAS_CAMERA); assertEquals(1, getCount(Uri.withAppendedPath(uri, RawContacts.Data.CONTENT_DIRECTORY), null, null)); assertEquals(1, getCount(StatusUpdates.CONTENT_URI, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId, null)); // Do not delete if we are deleting with wrong account. Uri deleteWithWrongAccountUri = RawContacts.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, mAccountTwo.name) .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, mAccountTwo.type) .build(); int numDeleted = mResolver.delete(deleteWithWrongAccountUri, null, null); assertEquals(0, numDeleted); assertStoredValue(uri, RawContacts.DELETED, "0"); // Delete if we are deleting with correct account. Uri deleteWithCorrectAccountUri = RawContacts.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, mAccount.name) .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, mAccount.type) .build(); numDeleted = mResolver.delete(deleteWithCorrectAccountUri, null, null); assertEquals(1, numDeleted); assertStoredValue(uri, RawContacts.DELETED, "1"); } public void testRawContactDeletion_byAccountSelection() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); // Do not delete if we are deleting with wrong account. int numDeleted = mResolver.delete(RawContacts.CONTENT_URI, RawContacts.ACCOUNT_NAME + "=? AND " + RawContacts.ACCOUNT_TYPE + "=?", new String[] {mAccountTwo.name, mAccountTwo.type}); assertEquals(0, numDeleted); assertStoredValue(uri, RawContacts.DELETED, "0"); // Delete if we are deleting with correct account. numDeleted = mResolver.delete(RawContacts.CONTENT_URI, RawContacts.ACCOUNT_NAME + "=? AND " + RawContacts.ACCOUNT_TYPE + "=?", new String[] {mAccount.name, mAccount.type}); assertEquals(1, numDeleted); assertStoredValue(uri, RawContacts.DELETED, "1"); } /** * Test for {@link ContactsProvider2#stringToAccounts} and * {@link ContactsProvider2#accountsToString}. */ public void testAccountsToString() { final Set<Account> EXPECTED_0 = Sets.newHashSet(); final Set<Account> EXPECTED_1 = Sets.newHashSet(TestUtil.ACCOUNT_1); final Set<Account> EXPECTED_2 = Sets.newHashSet(TestUtil.ACCOUNT_2); final Set<Account> EXPECTED_1_2 = Sets.newHashSet(TestUtil.ACCOUNT_1, TestUtil.ACCOUNT_2); final Set<Account> ACTUAL_0 = Sets.newHashSet(); final Set<Account> ACTUAL_1 = Sets.newHashSet(TestUtil.ACCOUNT_1); final Set<Account> ACTUAL_2 = Sets.newHashSet(TestUtil.ACCOUNT_2); final Set<Account> ACTUAL_1_2 = Sets.newHashSet(TestUtil.ACCOUNT_2, TestUtil.ACCOUNT_1); assertTrue(EXPECTED_0.equals(accountsToStringToAccounts(ACTUAL_0))); assertFalse(EXPECTED_0.equals(accountsToStringToAccounts(ACTUAL_1))); assertFalse(EXPECTED_0.equals(accountsToStringToAccounts(ACTUAL_2))); assertFalse(EXPECTED_0.equals(accountsToStringToAccounts(ACTUAL_1_2))); assertFalse(EXPECTED_1.equals(accountsToStringToAccounts(ACTUAL_0))); assertTrue(EXPECTED_1.equals(accountsToStringToAccounts(ACTUAL_1))); assertFalse(EXPECTED_1.equals(accountsToStringToAccounts(ACTUAL_2))); assertFalse(EXPECTED_1.equals(accountsToStringToAccounts(ACTUAL_1_2))); assertFalse(EXPECTED_2.equals(accountsToStringToAccounts(ACTUAL_0))); assertFalse(EXPECTED_2.equals(accountsToStringToAccounts(ACTUAL_1))); assertTrue(EXPECTED_2.equals(accountsToStringToAccounts(ACTUAL_2))); assertFalse(EXPECTED_2.equals(accountsToStringToAccounts(ACTUAL_1_2))); assertFalse(EXPECTED_1_2.equals(accountsToStringToAccounts(ACTUAL_0))); assertFalse(EXPECTED_1_2.equals(accountsToStringToAccounts(ACTUAL_1))); assertFalse(EXPECTED_1_2.equals(accountsToStringToAccounts(ACTUAL_2))); assertTrue(EXPECTED_1_2.equals(accountsToStringToAccounts(ACTUAL_1_2))); try { ContactsProvider2.stringToAccounts("x"); fail("Didn't throw for malformed input"); } catch (IllegalArgumentException expected) { } } private static final Set<Account> accountsToStringToAccounts(Set<Account> accounts) { return ContactsProvider2.stringToAccounts(ContactsProvider2.accountsToString(accounts)); } /** * Test for {@link ContactsProvider2#haveAccountsChanged} and * {@link ContactsProvider2#saveAccounts}. */ public void testHaveAccountsChanged() { final ContactsProvider2 cp = (ContactsProvider2) getProvider(); final Account[] ACCOUNTS_0 = new Account[] {}; final Account[] ACCOUNTS_1 = new Account[] {TestUtil.ACCOUNT_1}; final Account[] ACCOUNTS_2 = new Account[] {TestUtil.ACCOUNT_2}; final Account[] ACCOUNTS_1_2 = new Account[] {TestUtil.ACCOUNT_1, TestUtil.ACCOUNT_2}; final Account[] ACCOUNTS_2_1 = new Account[] {TestUtil.ACCOUNT_2, TestUtil.ACCOUNT_1}; // Add ACCOUNT_1 assertTrue(cp.haveAccountsChanged(ACCOUNTS_1)); cp.saveAccounts(ACCOUNTS_1); assertFalse(cp.haveAccountsChanged(ACCOUNTS_1)); // Add ACCOUNT_2 assertTrue(cp.haveAccountsChanged(ACCOUNTS_1_2)); // (try with reverse order) assertTrue(cp.haveAccountsChanged(ACCOUNTS_2_1)); cp.saveAccounts(ACCOUNTS_1_2); assertFalse(cp.haveAccountsChanged(ACCOUNTS_1_2)); // (try with reverse order) assertFalse(cp.haveAccountsChanged(ACCOUNTS_2_1)); // Remove ACCOUNT_1 assertTrue(cp.haveAccountsChanged(ACCOUNTS_2)); cp.saveAccounts(ACCOUNTS_2); assertFalse(cp.haveAccountsChanged(ACCOUNTS_2)); // Remove ACCOUNT_2 assertTrue(cp.haveAccountsChanged(ACCOUNTS_0)); cp.saveAccounts(ACCOUNTS_0); assertFalse(cp.haveAccountsChanged(ACCOUNTS_0)); // Test with malformed DB property. final ContactsDatabaseHelper dbHelper = cp.getThreadActiveDatabaseHelperForTest(); dbHelper.setProperty(DbProperties.KNOWN_ACCOUNTS, "x"); // With malformed property the method always return true. assertTrue(cp.haveAccountsChanged(ACCOUNTS_0)); assertTrue(cp.haveAccountsChanged(ACCOUNTS_1)); } public void testAccountsUpdated() { // This is to ensure we do not delete contacts with null, null (account name, type) // accidentally. long rawContactId3 = RawContactUtil.createRawContactWithName(mResolver, "James", "Sullivan"); insertPhoneNumber(rawContactId3, "5234567890"); Uri rawContact3 = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId3); assertEquals(1, getCount(RawContacts.CONTENT_URI, null, null)); ContactsProvider2 cp = (ContactsProvider2) getProvider(); mActor.setAccounts(new Account[]{mAccount, mAccountTwo}); cp.onAccountsUpdated(new Account[]{mAccount, mAccountTwo}); assertEquals(1, getCount(RawContacts.CONTENT_URI, null, null)); assertStoredValue(rawContact3, RawContacts.ACCOUNT_NAME, null); assertStoredValue(rawContact3, RawContacts.ACCOUNT_TYPE, null); long rawContactId1 = RawContactUtil.createRawContact(mResolver, mAccount); insertEmail(rawContactId1, "[email protected]"); long rawContactId2 = RawContactUtil.createRawContact(mResolver, mAccountTwo); insertEmail(rawContactId2, "[email protected]"); insertImHandle(rawContactId2, Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]"); insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.AVAILABLE, null, StatusUpdates.CAPABILITY_HAS_CAMERA); mActor.setAccounts(new Account[]{mAccount}); cp.onAccountsUpdated(new Account[]{mAccount}); assertEquals(2, getCount(RawContacts.CONTENT_URI, null, null)); assertEquals(0, getCount(StatusUpdates.CONTENT_URI, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId2, null)); } public void testAccountDeletion() { Account readOnlyAccount = new Account("act", READ_ONLY_ACCOUNT_TYPE); ContactsProvider2 cp = (ContactsProvider2) getProvider(); mActor.setAccounts(new Account[]{readOnlyAccount, mAccount}); cp.onAccountsUpdated(new Account[]{readOnlyAccount, mAccount}); long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "John", "Doe", readOnlyAccount); Uri photoUri1 = insertPhoto(rawContactId1); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "john", "doe", mAccount); Uri photoUri2 = insertPhoto(rawContactId2); storeValue(photoUri2, Photo.IS_SUPER_PRIMARY, "1"); assertAggregated(rawContactId1, rawContactId2); long contactId = queryContactId(rawContactId1); // The display name should come from the writable account assertStoredValue(Uri.withAppendedPath( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.Data.CONTENT_DIRECTORY), Contacts.DISPLAY_NAME, "john doe"); // The photo should be the one we marked as super-primary assertStoredValue(Contacts.CONTENT_URI, contactId, Contacts.PHOTO_ID, ContentUris.parseId(photoUri2)); mActor.setAccounts(new Account[]{readOnlyAccount}); // Remove the writable account cp.onAccountsUpdated(new Account[]{readOnlyAccount}); // The display name should come from the remaining account assertStoredValue(Uri.withAppendedPath( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.Data.CONTENT_DIRECTORY), Contacts.DISPLAY_NAME, "John Doe"); // The photo should be the remaining one assertStoredValue(Contacts.CONTENT_URI, contactId, Contacts.PHOTO_ID, ContentUris.parseId(photoUri1)); } public void testStreamItemsCleanedUpOnAccountRemoval() { Account doomedAccount = new Account("doom", "doom"); Account safeAccount = mAccount; ContactsProvider2 cp = (ContactsProvider2) getProvider(); mActor.setAccounts(new Account[]{doomedAccount, safeAccount}); cp.onAccountsUpdated(new Account[]{doomedAccount, safeAccount}); // Create a doomed raw contact, stream item, and photo. long doomedRawContactId = RawContactUtil.createRawContactWithName(mResolver, doomedAccount); Uri doomedStreamItemUri = insertStreamItem(doomedRawContactId, buildGenericStreamItemValues(), doomedAccount); long doomedStreamItemId = ContentUris.parseId(doomedStreamItemUri); Uri doomedStreamItemPhotoUri = insertStreamItemPhoto( doomedStreamItemId, buildGenericStreamItemPhotoValues(0), doomedAccount); // Create a safe raw contact, stream item, and photo. long safeRawContactId = RawContactUtil.createRawContactWithName(mResolver, safeAccount); Uri safeStreamItemUri = insertStreamItem(safeRawContactId, buildGenericStreamItemValues(), safeAccount); long safeStreamItemId = ContentUris.parseId(safeStreamItemUri); Uri safeStreamItemPhotoUri = insertStreamItemPhoto( safeStreamItemId, buildGenericStreamItemPhotoValues(0), safeAccount); long safeStreamItemPhotoId = ContentUris.parseId(safeStreamItemPhotoUri); // Remove the doomed account. mActor.setAccounts(new Account[]{safeAccount}); cp.onAccountsUpdated(new Account[]{safeAccount}); // Check that the doomed stuff has all been nuked. ContentValues[] noValues = new ContentValues[0]; assertStoredValues(ContentUris.withAppendedId(RawContacts.CONTENT_URI, doomedRawContactId), noValues); assertStoredValues(doomedStreamItemUri, noValues); assertStoredValues(doomedStreamItemPhotoUri, noValues); // Check that the safe stuff lives on. assertStoredValue(RawContacts.CONTENT_URI, safeRawContactId, RawContacts._ID, safeRawContactId); assertStoredValue(safeStreamItemUri, StreamItems._ID, safeStreamItemId); assertStoredValue(safeStreamItemPhotoUri, StreamItemPhotos._ID, safeStreamItemPhotoId); } public void testContactDeletion() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "John", "Doe", TestUtil.ACCOUNT_1); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "John", "Doe", TestUtil.ACCOUNT_2); long contactId = queryContactId(rawContactId1); mResolver.delete(ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), null, null); assertStoredValue(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId1), RawContacts.DELETED, "1"); assertStoredValue(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId2), RawContacts.DELETED, "1"); } public void testMarkAsDirtyParameter() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); Uri uri = DataUtil.insertStructuredName(mResolver, rawContactId, "John", "Doe"); clearDirty(rawContactUri); Uri updateUri = setCallerIsSyncAdapter(uri, mAccount); ContentValues values = new ContentValues(); values.put(StructuredName.FAMILY_NAME, "Dough"); mResolver.update(updateUri, values, null, null); assertStoredValue(uri, StructuredName.FAMILY_NAME, "Dough"); assertDirty(rawContactUri, false); assertNetworkNotified(false); } public void testRawContactDirtyAndVersion() { final long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, rawContactId); assertDirty(uri, false); long version = getVersion(uri); ContentValues values = new ContentValues(); values.put(ContactsContract.RawContacts.DIRTY, 0); values.put(ContactsContract.RawContacts.SEND_TO_VOICEMAIL, 1); values.put(ContactsContract.RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_IMMEDIATE); values.put(ContactsContract.RawContacts.STARRED, 1); assertEquals(1, mResolver.update(uri, values, null, null)); assertEquals(version, getVersion(uri)); assertDirty(uri, false); assertNetworkNotified(false); Uri emailUri = insertEmail(rawContactId, "[email protected]"); assertDirty(uri, true); assertNetworkNotified(true); ++version; assertEquals(version, getVersion(uri)); clearDirty(uri); values = new ContentValues(); values.put(Email.DATA, "[email protected]"); mResolver.update(emailUri, values, null, null); assertDirty(uri, true); assertNetworkNotified(true); ++version; assertEquals(version, getVersion(uri)); clearDirty(uri); mResolver.delete(emailUri, null, null); assertDirty(uri, true); assertNetworkNotified(true); ++version; assertEquals(version, getVersion(uri)); } public void testRawContactClearDirty() { final long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, rawContactId); long version = getVersion(uri); insertEmail(rawContactId, "[email protected]"); assertDirty(uri, true); version++; assertEquals(version, getVersion(uri)); clearDirty(uri); assertDirty(uri, false); assertEquals(version, getVersion(uri)); } public void testRawContactDeletionSetsDirty() { final long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, rawContactId); long version = getVersion(uri); clearDirty(uri); assertDirty(uri, false); mResolver.delete(uri, null, null); assertStoredValue(uri, RawContacts.DELETED, "1"); assertDirty(uri, true); assertNetworkNotified(true); version++; assertEquals(version, getVersion(uri)); } public void testDeleteContactWithoutName() { Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, new ContentValues()); long rawContactId = ContentUris.parseId(rawContactUri); Uri phoneUri = insertPhoneNumber(rawContactId, "555-123-45678", true); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri lookupUri = Contacts.getLookupUri(mResolver, contactUri); int numDeleted = mResolver.delete(lookupUri, null, null); assertEquals(1, numDeleted); } public void testDeleteContactWithoutAnyData() { Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, new ContentValues()); long rawContactId = ContentUris.parseId(rawContactUri); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri lookupUri = Contacts.getLookupUri(mResolver, contactUri); int numDeleted = mResolver.delete(lookupUri, null, null); assertEquals(1, numDeleted); } public void testDeleteContactWithEscapedUri() { ContentValues values = new ContentValues(); values.put(RawContacts.SOURCE_ID, "!@#$%^&*()_+=-/.,<>?;'\":[]}{\\|`~"); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri lookupUri = Contacts.getLookupUri(mResolver, contactUri); assertEquals(1, mResolver.delete(lookupUri, null, null)); } public void testQueryContactWithEscapedUri() { ContentValues values = new ContentValues(); values.put(RawContacts.SOURCE_ID, "!@#$%^&*()_+=-/.,<>?;'\":[]}{\\|`~"); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri lookupUri = Contacts.getLookupUri(mResolver, contactUri); Cursor c = mResolver.query(lookupUri, null, null, null, ""); assertEquals(1, c.getCount()); c.close(); } public void testGetPhotoUri() { ContentValues values = new ContentValues(); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); DataUtil.insertStructuredName(mResolver, rawContactId, "John", "Doe"); long dataId = ContentUris.parseId(insertPhoto(rawContactId, R.drawable.earth_normal)); long photoFileId = getStoredLongValue(Data.CONTENT_URI, Data._ID + "=?", new String[]{String.valueOf(dataId)}, Photo.PHOTO_FILE_ID); String photoUri = ContentUris.withAppendedId(DisplayPhoto.CONTENT_URI, photoFileId) .toString(); assertStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId)), Contacts.PHOTO_URI, photoUri); } public void testGetPhotoViaLookupUri() throws IOException { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri lookupUri = Contacts.getLookupUri(mResolver, contactUri); String lookupKey = lookupUri.getPathSegments().get(2); insertPhoto(rawContactId, R.drawable.earth_small); byte[] thumbnail = loadPhotoFromResource(R.drawable.earth_small, PhotoSize.THUMBNAIL); // Two forms of lookup key URIs should be valid - one with the contact ID, one without. Uri photoLookupUriWithId = Uri.withAppendedPath(lookupUri, "photo"); Uri photoLookupUriWithoutId = Contacts.CONTENT_LOOKUP_URI.buildUpon() .appendPath(lookupKey).appendPath("photo").build(); // Try retrieving as a data record. ContentValues values = new ContentValues(); values.put(Photo.PHOTO, thumbnail); assertStoredValues(photoLookupUriWithId, values); assertStoredValues(photoLookupUriWithoutId, values); // Try opening as an input stream. EvenMoreAsserts.assertImageRawData(getContext(), thumbnail, mResolver.openInputStream(photoLookupUriWithId)); EvenMoreAsserts.assertImageRawData(getContext(), thumbnail, mResolver.openInputStream(photoLookupUriWithoutId)); } public void testInputStreamForPhoto() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); insertPhoto(rawContactId); Uri photoUri = Uri.parse(getStoredValue(contactUri, Contacts.PHOTO_URI)); Uri photoThumbnailUri = Uri.parse(getStoredValue(contactUri, Contacts.PHOTO_THUMBNAIL_URI)); // Check the thumbnail. EvenMoreAsserts.assertImageRawData(getContext(), loadTestPhoto(PhotoSize.THUMBNAIL), mResolver.openInputStream(photoThumbnailUri)); // Then check the display photo. Note because we only inserted a small photo, but not a // display photo, this returns the thumbnail image itself, which was compressed at // the thumnail compression rate, which is why we compare to // loadTestPhoto(PhotoSize.THUMBNAIL) rather than loadTestPhoto(PhotoSize.DISPLAY_PHOTO) // here. // (In other words, loadTestPhoto(PhotoSize.DISPLAY_PHOTO) returns the same photo as // loadTestPhoto(PhotoSize.THUMBNAIL), except it's compressed at a lower compression rate.) EvenMoreAsserts.assertImageRawData(getContext(), loadTestPhoto(PhotoSize.THUMBNAIL), mResolver.openInputStream(photoUri)); } public void testSuperPrimaryPhoto() { long rawContactId1 = RawContactUtil.createRawContact(mResolver, new Account("a", "a")); Uri photoUri1 = insertPhoto(rawContactId1, R.drawable.earth_normal); long photoId1 = ContentUris.parseId(photoUri1); long rawContactId2 = RawContactUtil.createRawContact(mResolver, new Account("b", "b")); Uri photoUri2 = insertPhoto(rawContactId2, R.drawable.earth_normal); long photoId2 = ContentUris.parseId(photoUri2); setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId1)); long photoFileId1 = getStoredLongValue(Data.CONTENT_URI, Data._ID + "=?", new String[]{String.valueOf(photoId1)}, Photo.PHOTO_FILE_ID); String photoUri = ContentUris.withAppendedId(DisplayPhoto.CONTENT_URI, photoFileId1) .toString(); assertStoredValue(contactUri, Contacts.PHOTO_ID, photoId1); assertStoredValue(contactUri, Contacts.PHOTO_URI, photoUri); setAggregationException(AggregationExceptions.TYPE_KEEP_SEPARATE, rawContactId1, rawContactId2); ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 1); mResolver.update(photoUri2, values, null, null); setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId1)); assertStoredValue(contactUri, Contacts.PHOTO_ID, photoId2); mResolver.update(photoUri1, values, null, null); assertStoredValue(contactUri, Contacts.PHOTO_ID, photoId1); } public void testUpdatePhoto() { ContentValues values = new ContentValues(); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); DataUtil.insertStructuredName(mResolver, rawContactId, "John", "Doe"); Uri twigUri = Uri.withAppendedPath(ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId)), Contacts.Photo.CONTENT_DIRECTORY); values.clear(); values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); values.putNull(Photo.PHOTO); Uri dataUri = mResolver.insert(Data.CONTENT_URI, values); long photoId = ContentUris.parseId(dataUri); assertEquals(0, getCount(twigUri, null, null)); values.clear(); values.put(Photo.PHOTO, loadTestPhoto()); mResolver.update(dataUri, values, null, null); assertNetworkNotified(true); long twigId = getStoredLongValue(twigUri, Data._ID); assertEquals(photoId, twigId); } public void testUpdateRawContactDataPhoto() { // setup a contact with a null photo ContentValues values = new ContentValues(); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); // setup a photo values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); values.putNull(Photo.PHOTO); // try to do an update before insert should return count == 0 Uri dataUri = Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.Data.CONTENT_DIRECTORY); assertEquals(0, mResolver.update(dataUri, values, Data.MIMETYPE + "=?", new String[] {Photo.CONTENT_ITEM_TYPE})); mResolver.insert(Data.CONTENT_URI, values); // save a photo to the db values.clear(); values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); values.put(Photo.PHOTO, loadTestPhoto()); assertEquals(1, mResolver.update(dataUri, values, Data.MIMETYPE + "=?", new String[] {Photo.CONTENT_ITEM_TYPE})); // verify the photo Cursor storedPhoto = mResolver.query(dataUri, new String[] {Photo.PHOTO}, Data.MIMETYPE + "=?", new String[] {Photo.CONTENT_ITEM_TYPE}, null); storedPhoto.moveToFirst(); MoreAsserts.assertEquals(loadTestPhoto(PhotoSize.THUMBNAIL), storedPhoto.getBlob(0)); storedPhoto.close(); } public void testOpenDisplayPhotoForContactId() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); insertPhoto(rawContactId, R.drawable.earth_normal); Uri photoUri = Contacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(contactId)) .appendPath(Contacts.Photo.DISPLAY_PHOTO).build(); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(photoUri)); } public void testOpenDisplayPhotoForContactLookupKey() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); String lookupKey = queryLookupKey(contactId); insertPhoto(rawContactId, R.drawable.earth_normal); Uri photoUri = Contacts.CONTENT_LOOKUP_URI.buildUpon() .appendPath(lookupKey) .appendPath(Contacts.Photo.DISPLAY_PHOTO).build(); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(photoUri)); } public void testOpenDisplayPhotoForContactLookupKeyAndId() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); String lookupKey = queryLookupKey(contactId); insertPhoto(rawContactId, R.drawable.earth_normal); Uri photoUri = Contacts.CONTENT_LOOKUP_URI.buildUpon() .appendPath(lookupKey) .appendPath(String.valueOf(contactId)) .appendPath(Contacts.Photo.DISPLAY_PHOTO).build(); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(photoUri)); } public void testOpenDisplayPhotoForRawContactId() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); insertPhoto(rawContactId, R.drawable.earth_normal); Uri photoUri = RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.DisplayPhoto.CONTENT_DIRECTORY).build(); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(photoUri)); } public void testOpenDisplayPhotoByPhotoUri() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); insertPhoto(rawContactId, R.drawable.earth_normal); // Get the photo URI out and check the content. String photoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(Uri.parse(photoUri))); } public void testPhotoUriForDisplayPhoto() { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); // Photo being inserted is larger than a thumbnail, so it will be stored as a file. long dataId = ContentUris.parseId(insertPhoto(rawContactId, R.drawable.earth_normal)); String photoFileId = getStoredValue(ContentUris.withAppendedId(Data.CONTENT_URI, dataId), Photo.PHOTO_FILE_ID); String photoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); // Check that the photo URI differs from the thumbnail. String thumbnailUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_THUMBNAIL_URI); assertFalse(photoUri.equals(thumbnailUri)); // URI should be of the form display_photo/ID assertEquals(Uri.withAppendedPath(DisplayPhoto.CONTENT_URI, photoFileId).toString(), photoUri); } public void testPhotoUriForThumbnailPhoto() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); // Photo being inserted is a thumbnail, so it will only be stored in a BLOB. The photo URI // will fall back to the thumbnail URI. insertPhoto(rawContactId, R.drawable.earth_small); String photoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); // Check that the photo URI is equal to the thumbnail URI. String thumbnailUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_THUMBNAIL_URI); assertEquals(photoUri, thumbnailUri); // URI should be of the form contacts/ID/photo assertEquals(Uri.withAppendedPath( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.Photo.CONTENT_DIRECTORY).toString(), photoUri); // Loading the photo URI content should get the thumbnail. EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_small, PhotoSize.THUMBNAIL), mResolver.openInputStream(Uri.parse(photoUri))); } public void testWriteNewPhotoToAssetFile() throws Exception { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); // Load in a huge photo. final byte[] originalPhoto = loadPhotoFromResource( R.drawable.earth_huge, PhotoSize.ORIGINAL); // Write it out. final Uri writeablePhotoUri = RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.DisplayPhoto.CONTENT_DIRECTORY).build(); writePhotoAsync(writeablePhotoUri, originalPhoto); // Check that the display photo and thumbnail have been set. String photoUri = null; for (int i = 0; i < 10 && photoUri == null; i++) { // Wait a tick for the photo processing to occur. Thread.sleep(100); photoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); } assertFalse(TextUtils.isEmpty(photoUri)); String thumbnailUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_THUMBNAIL_URI); assertFalse(TextUtils.isEmpty(thumbnailUri)); assertNotSame(photoUri, thumbnailUri); // Check the content of the display photo and thumbnail. EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(Uri.parse(photoUri))); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.THUMBNAIL), mResolver.openInputStream(Uri.parse(thumbnailUri))); } public void testWriteUpdatedPhotoToAssetFile() throws Exception { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); // Insert a large photo first. insertPhoto(rawContactId, R.drawable.earth_large); String largeEarthPhotoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); // Load in a huge photo. byte[] originalPhoto = loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.ORIGINAL); // Write it out. Uri writeablePhotoUri = RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.DisplayPhoto.CONTENT_DIRECTORY).build(); writePhotoAsync(writeablePhotoUri, originalPhoto); // Allow a second for processing to occur. Thread.sleep(1000); // Check that the display photo URI has been modified. String hugeEarthPhotoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); assertFalse(hugeEarthPhotoUri.equals(largeEarthPhotoUri)); // Check the content of the display photo and thumbnail. String hugeEarthThumbnailUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_THUMBNAIL_URI); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(Uri.parse(hugeEarthPhotoUri))); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.THUMBNAIL), mResolver.openInputStream(Uri.parse(hugeEarthThumbnailUri))); } private void writePhotoAsync(final Uri uri, final byte[] photoBytes) throws Exception { AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() { @Override protected Object doInBackground(Object... params) { OutputStream os; try { os = mResolver.openOutputStream(uri, "rw"); os.write(photoBytes); os.close(); return null; } catch (IOException ioe) { throw new RuntimeException(ioe); } } }; task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null).get(); } public void testPhotoDimensionLimits() { ContentValues values = new ContentValues(); values.put(DisplayPhoto.DISPLAY_MAX_DIM, 256); values.put(DisplayPhoto.THUMBNAIL_MAX_DIM, 96); assertStoredValues(DisplayPhoto.CONTENT_MAX_DIMENSIONS_URI, values); } public void testPhotoStoreCleanup() throws IOException { SynchronousContactsProvider2 provider = (SynchronousContactsProvider2) mActor.provider; PhotoStore photoStore = provider.getPhotoStore(); // Trigger an initial cleanup so another one won't happen while we're running this test. provider.cleanupPhotoStore(); // Insert a couple of contacts with photos. long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver); long contactId1 = queryContactId(rawContactId1); long dataId1 = ContentUris.parseId(insertPhoto(rawContactId1, R.drawable.earth_normal)); long photoFileId1 = getStoredLongValue(ContentUris.withAppendedId(Data.CONTENT_URI, dataId1), Photo.PHOTO_FILE_ID); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver); long contactId2 = queryContactId(rawContactId2); long dataId2 = ContentUris.parseId(insertPhoto(rawContactId2, R.drawable.earth_normal)); long photoFileId2 = getStoredLongValue(ContentUris.withAppendedId(Data.CONTENT_URI, dataId2), Photo.PHOTO_FILE_ID); // Update the second raw contact with a different photo. ContentValues values = new ContentValues(); values.put(Data.RAW_CONTACT_ID, rawContactId2); values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); values.put(Photo.PHOTO, loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.ORIGINAL)); assertEquals(1, mResolver.update(Data.CONTENT_URI, values, Data._ID + "=?", new String[]{String.valueOf(dataId2)})); long replacementPhotoFileId = getStoredLongValue(ContentUris.withAppendedId(Data.CONTENT_URI, dataId2), Photo.PHOTO_FILE_ID); // Insert a third raw contact that has a bogus photo file ID. long bogusFileId = 1234567; long rawContactId3 = RawContactUtil.createRawContactWithName(mResolver); long contactId3 = queryContactId(rawContactId3); values.clear(); values.put(Data.RAW_CONTACT_ID, rawContactId3); values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); values.put(Photo.PHOTO, loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.THUMBNAIL)); values.put(Photo.PHOTO_FILE_ID, bogusFileId); values.put(DataRowHandlerForPhoto.SKIP_PROCESSING_KEY, true); mResolver.insert(Data.CONTENT_URI, values); // Insert a fourth raw contact with a stream item that has a photo, then remove that photo // from the photo store. Account socialAccount = new Account("social", "social"); long rawContactId4 = RawContactUtil.createRawContactWithName(mResolver, socialAccount); Uri streamItemUri = insertStreamItem(rawContactId4, buildGenericStreamItemValues(), socialAccount); long streamItemId = ContentUris.parseId(streamItemUri); Uri streamItemPhotoUri = insertStreamItemPhoto( streamItemId, buildGenericStreamItemPhotoValues(0), socialAccount); long streamItemPhotoFileId = getStoredLongValue(streamItemPhotoUri, StreamItemPhotos.PHOTO_FILE_ID); photoStore.remove(streamItemPhotoFileId); // Also insert a bogus photo that nobody is using. long bogusPhotoId = photoStore.insert(new PhotoProcessor(loadPhotoFromResource( R.drawable.earth_huge, PhotoSize.ORIGINAL), 256, 96)); // Manually trigger another cleanup in the provider. provider.cleanupPhotoStore(); // The following things should have happened. // 1. Raw contact 1 and its photo remain unaffected. assertEquals(photoFileId1, (long) getStoredLongValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId1), Contacts.PHOTO_FILE_ID)); // 2. Raw contact 2 retains its new photo. The old one is deleted from the photo store. assertEquals(replacementPhotoFileId, (long) getStoredLongValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId2), Contacts.PHOTO_FILE_ID)); assertNull(photoStore.get(photoFileId2)); // 3. Raw contact 3 should have its photo file reference cleared. assertNull(getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId3), Contacts.PHOTO_FILE_ID)); // 4. The bogus photo that nobody was using should be cleared from the photo store. assertNull(photoStore.get(bogusPhotoId)); // 5. The bogus stream item photo should be cleared from the stream item. assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), new ContentValues[0]); } public void testPhotoStoreCleanupForProfile() { SynchronousContactsProvider2 provider = (SynchronousContactsProvider2) mActor.provider; PhotoStore profilePhotoStore = provider.getProfilePhotoStore(); // Trigger an initial cleanup so another one won't happen while we're running this test. provider.switchToProfileModeForTest(); provider.cleanupPhotoStore(); // Create the profile contact and add a photo. Account socialAccount = new Account("social", "social"); ContentValues values = new ContentValues(); values.put(RawContacts.ACCOUNT_NAME, socialAccount.name); values.put(RawContacts.ACCOUNT_TYPE, socialAccount.type); long profileRawContactId = createBasicProfileContact(values); long profileContactId = queryContactId(profileRawContactId); long dataId = ContentUris.parseId( insertPhoto(profileRawContactId, R.drawable.earth_normal)); long profilePhotoFileId = getStoredLongValue(ContentUris.withAppendedId(Data.CONTENT_URI, dataId), Photo.PHOTO_FILE_ID); // Also add a stream item with a photo. Uri streamItemUri = insertStreamItem(profileRawContactId, buildGenericStreamItemValues(), socialAccount); long streamItemId = ContentUris.parseId(streamItemUri); Uri streamItemPhotoUri = insertStreamItemPhoto( streamItemId, buildGenericStreamItemPhotoValues(0), socialAccount); long streamItemPhotoFileId = getStoredLongValue(streamItemPhotoUri, StreamItemPhotos.PHOTO_FILE_ID); // Remove the stream item photo and the profile photo. profilePhotoStore.remove(profilePhotoFileId); profilePhotoStore.remove(streamItemPhotoFileId); // Manually trigger another cleanup in the provider. provider.switchToProfileModeForTest(); provider.cleanupPhotoStore(); // The following things should have happened. // The stream item photo should have been removed. assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), new ContentValues[0]); // The profile photo should have been cleared. assertNull(getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, profileContactId), Contacts.PHOTO_FILE_ID)); } public void testOverwritePhotoWithThumbnail() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); // Write a regular-size photo. long dataId = ContentUris.parseId(insertPhoto(rawContactId, R.drawable.earth_normal)); Long photoFileId = getStoredLongValue(contactUri, Contacts.PHOTO_FILE_ID); assertTrue(photoFileId != null && photoFileId > 0); // Now overwrite the photo with a thumbnail-sized photo. ContentValues update = new ContentValues(); update.put(Photo.PHOTO, loadPhotoFromResource(R.drawable.earth_small, PhotoSize.ORIGINAL)); mResolver.update(ContentUris.withAppendedId(Data.CONTENT_URI, dataId), update, null, null); // Photo file ID should have been nulled out, and the photo URI should be the same as the // thumbnail URI. assertNull(getStoredValue(contactUri, Contacts.PHOTO_FILE_ID)); String photoUri = getStoredValue(contactUri, Contacts.PHOTO_URI); String thumbnailUri = getStoredValue(contactUri, Contacts.PHOTO_THUMBNAIL_URI); assertEquals(photoUri, thumbnailUri); // Retrieving the photo URI should get the thumbnail content. EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_small, PhotoSize.THUMBNAIL), mResolver.openInputStream(Uri.parse(photoUri))); } public void testUpdateRawContactSetStarred() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver); Uri rawContactUri1 = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId1); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver); Uri rawContactUri2 = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId2); setAggregationException( AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); long contactId = queryContactId(rawContactId1); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); assertStoredValue(contactUri, Contacts.STARRED, "0"); ContentValues values = new ContentValues(); values.put(RawContacts.STARRED, "1"); mResolver.update(rawContactUri1, values, null, null); assertStoredValue(rawContactUri1, RawContacts.STARRED, "1"); assertStoredValue(rawContactUri2, RawContacts.STARRED, "0"); assertStoredValue(contactUri, Contacts.STARRED, "1"); values.put(RawContacts.STARRED, "0"); mResolver.update(rawContactUri1, values, null, null); assertStoredValue(rawContactUri1, RawContacts.STARRED, "0"); assertStoredValue(rawContactUri2, RawContacts.STARRED, "0"); assertStoredValue(contactUri, Contacts.STARRED, "0"); values.put(Contacts.STARRED, "1"); mResolver.update(contactUri, values, null, null); assertStoredValue(rawContactUri1, RawContacts.STARRED, "1"); assertStoredValue(rawContactUri2, RawContacts.STARRED, "1"); assertStoredValue(contactUri, Contacts.STARRED, "1"); } public void testSetAndClearSuperPrimaryEmail() { long rawContactId1 = RawContactUtil.createRawContact(mResolver, new Account("a", "a")); Uri mailUri11 = insertEmail(rawContactId1, "[email protected]"); Uri mailUri12 = insertEmail(rawContactId1, "[email protected]"); long rawContactId2 = RawContactUtil.createRawContact(mResolver, new Account("b", "b")); Uri mailUri21 = insertEmail(rawContactId2, "[email protected]"); Uri mailUri22 = insertEmail(rawContactId2, "[email protected]"); assertStoredValue(mailUri11, Data.IS_PRIMARY, 0); assertStoredValue(mailUri11, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 0); // Set super primary on the first pair, primary on the second { ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 1); mResolver.update(mailUri11, values, null, null); } { ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 1); mResolver.update(mailUri22, values, null, null); } assertStoredValue(mailUri11, Data.IS_PRIMARY, 1); assertStoredValue(mailUri11, Data.IS_SUPER_PRIMARY, 1); assertStoredValue(mailUri12, Data.IS_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 1); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 1); // Clear primary on the first pair, make sure second is not affected and super_primary is // also cleared { ContentValues values = new ContentValues(); values.put(Data.IS_PRIMARY, 0); mResolver.update(mailUri11, values, null, null); } assertStoredValue(mailUri11, Data.IS_PRIMARY, 0); assertStoredValue(mailUri11, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 1); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 1); // Ensure that we can only clear super_primary, if we specify the correct data row { ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 0); mResolver.update(mailUri21, values, null, null); } assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 1); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 1); // Ensure that we can only clear primary, if we specify the correct data row { ContentValues values = new ContentValues(); values.put(Data.IS_PRIMARY, 0); mResolver.update(mailUri21, values, null, null); } assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 1); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 1); // Now clear super-primary for real { ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 0); mResolver.update(mailUri22, values, null, null); } assertStoredValue(mailUri11, Data.IS_PRIMARY, 0); assertStoredValue(mailUri11, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 1); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 0); } /** * Common function for the testNewPrimaryIn* functions. Its four configurations * are each called from its own test */ public void testChangingPrimary(boolean inUpdate, boolean withSuperPrimary) { long rawContactId = RawContactUtil.createRawContact(mResolver, new Account("a", "a")); Uri mailUri1 = insertEmail(rawContactId, "[email protected]", true); if (withSuperPrimary) { final ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 1); mResolver.update(mailUri1, values, null, null); } assertStoredValue(mailUri1, Data.IS_PRIMARY, 1); assertStoredValue(mailUri1, Data.IS_SUPER_PRIMARY, withSuperPrimary ? 1 : 0); // Insert another item final Uri mailUri2; if (inUpdate) { mailUri2 = insertEmail(rawContactId, "[email protected]"); assertStoredValue(mailUri1, Data.IS_PRIMARY, 1); assertStoredValue(mailUri1, Data.IS_SUPER_PRIMARY, withSuperPrimary ? 1 : 0); assertStoredValue(mailUri2, Data.IS_PRIMARY, 0); assertStoredValue(mailUri2, Data.IS_SUPER_PRIMARY, 0); final ContentValues values = new ContentValues(); values.put(Data.IS_PRIMARY, 1); mResolver.update(mailUri2, values, null, null); } else { // directly add as default mailUri2 = insertEmail(rawContactId, "[email protected]", true); } // Ensure that primary has been unset on the first // If withSuperPrimary is set, also ensure that is has been moved to the new item assertStoredValue(mailUri1, Data.IS_PRIMARY, 0); assertStoredValue(mailUri1, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri2, Data.IS_PRIMARY, 1); assertStoredValue(mailUri2, Data.IS_SUPER_PRIMARY, withSuperPrimary ? 1 : 0); } public void testNewPrimaryInInsert() { testChangingPrimary(false, false); } public void testNewPrimaryInInsertWithSuperPrimary() { testChangingPrimary(false, true); } public void testNewPrimaryInUpdate() { testChangingPrimary(true, false); } public void testNewPrimaryInUpdateWithSuperPrimary() { testChangingPrimary(true, true); } public void testContactSortOrder() { assertEquals(ContactsColumns.PHONEBOOK_BUCKET_PRIMARY + ", " + Contacts.SORT_KEY_PRIMARY, ContactsProvider2.getLocalizedSortOrder(Contacts.SORT_KEY_PRIMARY)); assertEquals(ContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE + ", " + Contacts.SORT_KEY_ALTERNATIVE, ContactsProvider2.getLocalizedSortOrder(Contacts.SORT_KEY_ALTERNATIVE)); assertEquals(ContactsColumns.PHONEBOOK_BUCKET_PRIMARY + " DESC, " + Contacts.SORT_KEY_PRIMARY + " DESC", ContactsProvider2.getLocalizedSortOrder(Contacts.SORT_KEY_PRIMARY + " DESC")); String suffix = " COLLATE LOCALIZED DESC"; assertEquals(ContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE + suffix + ", " + Contacts.SORT_KEY_ALTERNATIVE + suffix, ContactsProvider2.getLocalizedSortOrder(Contacts.SORT_KEY_ALTERNATIVE + suffix)); } public void testContactCounts() { Uri uri = Contacts.CONTENT_URI.buildUpon() .appendQueryParameter(ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, "true").build(); RawContactUtil.createRawContact(mResolver); RawContactUtil.createRawContactWithName(mResolver, "James", "Sullivan"); RawContactUtil.createRawContactWithName(mResolver, "The Abominable", "Snowman"); RawContactUtil.createRawContactWithName(mResolver, "Mike", "Wazowski"); RawContactUtil.createRawContactWithName(mResolver, "randall", "boggs"); RawContactUtil.createRawContactWithName(mResolver, "Boo", null); RawContactUtil.createRawContactWithName(mResolver, "Mary", null); RawContactUtil.createRawContactWithName(mResolver, "Roz", null); Cursor cursor = mResolver.query(uri, new String[]{Contacts.DISPLAY_NAME}, null, null, Contacts.SORT_KEY_PRIMARY); assertFirstLetterValues(cursor, "", "B", "J", "M", "R", "T"); assertFirstLetterCounts(cursor, 1, 1, 1, 2, 2, 1); cursor.close(); cursor = mResolver.query(uri, new String[]{Contacts.DISPLAY_NAME}, null, null, Contacts.SORT_KEY_ALTERNATIVE + " COLLATE LOCALIZED DESC"); assertFirstLetterValues(cursor, "W", "S", "R", "M", "B", ""); assertFirstLetterCounts(cursor, 1, 2, 1, 1, 2, 1); cursor.close(); } public void testContactCountsWithGermanNames() { if (!hasGermanCollator()) { return; } ContactLocaleUtils.setLocale(Locale.GERMANY); Uri uri = Contacts.CONTENT_URI.buildUpon() .appendQueryParameter(ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, "true").build(); RawContactUtil.createRawContactWithName(mResolver, "Josef", "Sacher"); RawContactUtil.createRawContactWithName(mResolver, "Franz", "Schiller"); RawContactUtil.createRawContactWithName(mResolver, "Eckart", "Steiff"); RawContactUtil.createRawContactWithName(mResolver, "Klaus", "Seiler"); RawContactUtil.createRawContactWithName(mResolver, "Lars", "Sultan"); RawContactUtil.createRawContactWithName(mResolver, "Heidi", "Rilke"); RawContactUtil.createRawContactWithName(mResolver, "Suse", "Thomas"); Cursor cursor = mResolver.query(uri, new String[]{Contacts.DISPLAY_NAME}, null, null, Contacts.SORT_KEY_ALTERNATIVE); assertFirstLetterValues(cursor, "R", "S", "Sch", "St", "T"); assertFirstLetterCounts(cursor, 1, 3, 1, 1, 1); cursor.close(); } private void assertFirstLetterValues(Cursor cursor, String... expected) { String[] actual = cursor.getExtras() .getStringArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_TITLES); MoreAsserts.assertEquals(expected, actual); } private void assertFirstLetterCounts(Cursor cursor, int... expected) { int[] actual = cursor.getExtras() .getIntArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_COUNTS); MoreAsserts.assertEquals(expected, actual); } public void testReadBooleanQueryParameter() { assertBooleanUriParameter("foo:bar", "bool", true, true); assertBooleanUriParameter("foo:bar", "bool", false, false); assertBooleanUriParameter("foo:bar?bool=0", "bool", true, false); assertBooleanUriParameter("foo:bar?bool=1", "bool", false, true); assertBooleanUriParameter("foo:bar?bool=false", "bool", true, false); assertBooleanUriParameter("foo:bar?bool=true", "bool", false, true); assertBooleanUriParameter("foo:bar?bool=FaLsE", "bool", true, false); assertBooleanUriParameter("foo:bar?bool=false&some=some", "bool", true, false); assertBooleanUriParameter("foo:bar?bool=1&some=some", "bool", false, true); assertBooleanUriParameter("foo:bar?some=bool", "bool", true, true); assertBooleanUriParameter("foo:bar?bool", "bool", true, true); } private void assertBooleanUriParameter(String uriString, String parameter, boolean defaultValue, boolean expectedValue) { assertEquals(expectedValue, ContactsProvider2.readBooleanQueryParameter( Uri.parse(uriString), parameter, defaultValue)); } public void testGetQueryParameter() { assertQueryParameter("foo:bar", "param", null); assertQueryParameter("foo:bar?param", "param", null); assertQueryParameter("foo:bar?param=", "param", ""); assertQueryParameter("foo:bar?param=val", "param", "val"); assertQueryParameter("foo:bar?param=val&some=some", "param", "val"); assertQueryParameter("foo:bar?some=some&param=val", "param", "val"); assertQueryParameter("foo:bar?some=some&param=val&else=else", "param", "val"); assertQueryParameter("foo:bar?param=john%40doe.com", "param", "[email protected]"); assertQueryParameter("foo:bar?some_param=val", "param", null); assertQueryParameter("foo:bar?some_param=val1&param=val2", "param", "val2"); assertQueryParameter("foo:bar?some_param=val1&param=", "param", ""); assertQueryParameter("foo:bar?some_param=val1&param", "param", null); assertQueryParameter("foo:bar?some_param=val1&another_param=val2&param=val3", "param", "val3"); assertQueryParameter("foo:bar?some_param=val1&param=val2&some_param=val3", "param", "val2"); assertQueryParameter("foo:bar?param=val1&some_param=val2", "param", "val1"); assertQueryParameter("foo:bar?p=val1&pp=val2", "p", "val1"); assertQueryParameter("foo:bar?pp=val1&p=val2", "p", "val2"); assertQueryParameter("foo:bar?ppp=val1&pp=val2&p=val3", "p", "val3"); assertQueryParameter("foo:bar?ppp=val&", "p", null); } public void testMissingAccountTypeParameter() { // Try querying for RawContacts only using ACCOUNT_NAME final Uri queryUri = RawContacts.CONTENT_URI.buildUpon().appendQueryParameter( RawContacts.ACCOUNT_NAME, "lolwut").build(); try { final Cursor cursor = mResolver.query(queryUri, null, null, null, null); fail("Able to query with incomplete account query parameters"); } catch (IllegalArgumentException e) { // Expected behavior. } } public void testInsertInconsistentAccountType() { // Try inserting RawContact with inconsistent Accounts final Account red = new Account("red", "red"); final Account blue = new Account("blue", "blue"); final ContentValues values = new ContentValues(); values.put(RawContacts.ACCOUNT_NAME, red.name); values.put(RawContacts.ACCOUNT_TYPE, red.type); final Uri insertUri = TestUtil.maybeAddAccountQueryParameters(RawContacts.CONTENT_URI, blue); try { mResolver.insert(insertUri, values); fail("Able to insert RawContact with inconsistent account details"); } catch (IllegalArgumentException e) { // Expected behavior. } } public void testProviderStatusNoContactsNoAccounts() throws Exception { assertProviderStatus(ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS); } public void testProviderStatusOnlyLocalContacts() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); assertProviderStatus(ProviderStatus.STATUS_NORMAL); mResolver.delete( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), null, null); assertProviderStatus(ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS); } public void testProviderStatusWithAccounts() throws Exception { assertProviderStatus(ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS); mActor.setAccounts(new Account[]{TestUtil.ACCOUNT_1}); ((ContactsProvider2)getProvider()).onAccountsUpdated(new Account[]{TestUtil.ACCOUNT_1}); assertProviderStatus(ProviderStatus.STATUS_NORMAL); mActor.setAccounts(new Account[0]); ((ContactsProvider2)getProvider()).onAccountsUpdated(new Account[0]); assertProviderStatus(ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS); } private void assertProviderStatus(int expectedProviderStatus) { Cursor cursor = mResolver.query(ProviderStatus.CONTENT_URI, new String[]{ProviderStatus.DATA1, ProviderStatus.STATUS}, null, null, null); assertTrue(cursor.moveToFirst()); assertEquals(0, cursor.getLong(0)); assertEquals(expectedProviderStatus, cursor.getInt(1)); cursor.close(); } public void testProperties() throws Exception { ContactsProvider2 provider = (ContactsProvider2)getProvider(); ContactsDatabaseHelper helper = (ContactsDatabaseHelper)provider.getDatabaseHelper(); assertNull(helper.getProperty("non-existent", null)); assertEquals("default", helper.getProperty("non-existent", "default")); helper.setProperty("existent1", "string1"); helper.setProperty("existent2", "string2"); assertEquals("string1", helper.getProperty("existent1", "default")); assertEquals("string2", helper.getProperty("existent2", "default")); helper.setProperty("existent1", null); assertEquals("default", helper.getProperty("existent1", "default")); } private class VCardTestUriCreator { private String mLookup1; private String mLookup2; public VCardTestUriCreator(String lookup1, String lookup2) { super(); mLookup1 = lookup1; mLookup2 = lookup2; } public Uri getUri1() { return Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, mLookup1); } public Uri getUri2() { return Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, mLookup2); } public Uri getCombinedUri() { return Uri.withAppendedPath(Contacts.CONTENT_MULTI_VCARD_URI, Uri.encode(mLookup1 + ":" + mLookup2)); } } private VCardTestUriCreator createVCardTestContacts() { final long rawContactId1 = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "4:12"); DataUtil.insertStructuredName(mResolver, rawContactId1, "John", "Doe"); final long rawContactId2 = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "3:4%121"); DataUtil.insertStructuredName(mResolver, rawContactId2, "Jane", "Doh"); final long contactId1 = queryContactId(rawContactId1); final long contactId2 = queryContactId(rawContactId2); final Uri contact1Uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId1); final Uri contact2Uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId2); final String lookup1 = Uri.encode(Contacts.getLookupUri(mResolver, contact1Uri).getPathSegments().get(2)); final String lookup2 = Uri.encode(Contacts.getLookupUri(mResolver, contact2Uri).getPathSegments().get(2)); return new VCardTestUriCreator(lookup1, lookup2); } public void testQueryMultiVCard() { // No need to create any contacts here, because the query for multiple vcards // does not go into the database at all Uri uri = Uri.withAppendedPath(Contacts.CONTENT_MULTI_VCARD_URI, Uri.encode("123:456")); Cursor cursor = mResolver.query(uri, null, null, null, null); assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToFirst()); assertTrue(cursor.isNull(cursor.getColumnIndex(OpenableColumns.SIZE))); String filename = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); // The resulting name contains date and time. Ensure that before and after are correct assertTrue(filename.startsWith("vcards_")); assertTrue(filename.endsWith(".vcf")); cursor.close(); } public void testQueryFileSingleVCard() { final VCardTestUriCreator contacts = createVCardTestContacts(); { Cursor cursor = mResolver.query(contacts.getUri1(), null, null, null, null); assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToFirst()); assertTrue(cursor.isNull(cursor.getColumnIndex(OpenableColumns.SIZE))); String filename = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); assertEquals("John Doe.vcf", filename); cursor.close(); } { Cursor cursor = mResolver.query(contacts.getUri2(), null, null, null, null); assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToFirst()); assertTrue(cursor.isNull(cursor.getColumnIndex(OpenableColumns.SIZE))); String filename = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); assertEquals("Jane Doh.vcf", filename); cursor.close(); } } public void testQueryFileProfileVCard() { createBasicProfileContact(new ContentValues()); Cursor cursor = mResolver.query(Profile.CONTENT_VCARD_URI, null, null, null, null); assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToFirst()); assertTrue(cursor.isNull(cursor.getColumnIndex(OpenableColumns.SIZE))); String filename = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); assertEquals("Mia Prophyl.vcf", filename); cursor.close(); } public void testOpenAssetFileMultiVCard() throws IOException { final VCardTestUriCreator contacts = createVCardTestContacts(); final AssetFileDescriptor descriptor = mResolver.openAssetFileDescriptor(contacts.getCombinedUri(), "r"); final FileInputStream inputStream = descriptor.createInputStream(); String data = readToEnd(inputStream); inputStream.close(); descriptor.close(); // Ensure that the resulting VCard has both contacts assertTrue(data.contains("N:Doe;John;;;")); assertTrue(data.contains("N:Doh;Jane;;;")); } public void testOpenAssetFileSingleVCard() throws IOException { final VCardTestUriCreator contacts = createVCardTestContacts(); // Ensure that the right VCard is being created in each case { final AssetFileDescriptor descriptor = mResolver.openAssetFileDescriptor(contacts.getUri1(), "r"); final FileInputStream inputStream = descriptor.createInputStream(); final String data = readToEnd(inputStream); inputStream.close(); descriptor.close(); assertTrue(data.contains("N:Doe;John;;;")); assertFalse(data.contains("N:Doh;Jane;;;")); } { final AssetFileDescriptor descriptor = mResolver.openAssetFileDescriptor(contacts.getUri2(), "r"); final FileInputStream inputStream = descriptor.createInputStream(); final String data = readToEnd(inputStream); inputStream.close(); descriptor.close(); assertFalse(data.contains("N:Doe;John;;;")); assertTrue(data.contains("N:Doh;Jane;;;")); } } public void testAutoGroupMembership() { long g1 = createGroup(mAccount, "g1", "t1", 0, true /* autoAdd */, false /* favorite */); long g2 = createGroup(mAccount, "g2", "t2", 0, false /* autoAdd */, false /* favorite */); long g3 = createGroup(mAccountTwo, "g3", "t3", 0, true /* autoAdd */, false /* favorite */); long g4 = createGroup(mAccountTwo, "g4", "t4", 0, false /* autoAdd */, false/* favorite */); long r1 = RawContactUtil.createRawContact(mResolver, mAccount); long r2 = RawContactUtil.createRawContact(mResolver, mAccountTwo); long r3 = RawContactUtil.createRawContact(mResolver, null); Cursor c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } c = queryGroupMemberships(mAccountTwo); try { assertTrue(c.moveToNext()); assertEquals(g3, c.getLong(0)); assertEquals(r2, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } } public void testNoAutoAddMembershipAfterGroupCreation() { long r1 = RawContactUtil.createRawContact(mResolver, mAccount); long r2 = RawContactUtil.createRawContact(mResolver, mAccount); long r3 = RawContactUtil.createRawContact(mResolver, mAccount); long r4 = RawContactUtil.createRawContact(mResolver, mAccountTwo); long r5 = RawContactUtil.createRawContact(mResolver, mAccountTwo); long r6 = RawContactUtil.createRawContact(mResolver, null); assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); long g1 = createGroup(mAccount, "g1", "t1", 0, true /* autoAdd */, false /* favorite */); long g2 = createGroup(mAccount, "g2", "t2", 0, false /* autoAdd */, false /* favorite */); long g3 = createGroup(mAccountTwo, "g3", "t3", 0, true /* autoAdd */, false/* favorite */); assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); } // create some starred and non-starred contacts, some associated with account, some not // favorites group created // the starred contacts should be added to group // favorites group removed // no change to starred status public void testFavoritesMembershipAfterGroupCreation() { long r1 = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.STARRED, "1"); long r2 = RawContactUtil.createRawContact(mResolver, mAccount); long r3 = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.STARRED, "1"); long r4 = RawContactUtil.createRawContact(mResolver, mAccountTwo, RawContacts.STARRED, "1"); long r5 = RawContactUtil.createRawContact(mResolver, mAccountTwo); long r6 = RawContactUtil.createRawContact(mResolver, null, RawContacts.STARRED, "1"); long r7 = RawContactUtil.createRawContact(mResolver, null); assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); long g1 = createGroup(mAccount, "g1", "t1", 0, false /* autoAdd */, true /* favorite */); long g2 = createGroup(mAccount, "g2", "t2", 0, false /* autoAdd */, false /* favorite */); long g3 = createGroup(mAccountTwo, "g3", "t3", 0, false /* autoAdd */, false/* favorite */); assertTrue(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertTrue(queryRawContactIsStarred(r3)); assertTrue(queryRawContactIsStarred(r4)); assertFalse(queryRawContactIsStarred(r5)); assertTrue(queryRawContactIsStarred(r6)); assertFalse(queryRawContactIsStarred(r7)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); Cursor c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r3, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } updateItem(RawContacts.CONTENT_URI, r6, RawContacts.ACCOUNT_NAME, mAccount.name, RawContacts.ACCOUNT_TYPE, mAccount.type); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r3, c.getLong(1)); assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r6, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } mResolver.delete(ContentUris.withAppendedId(Groups.CONTENT_URI, g1), null, null); assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); assertTrue(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertTrue(queryRawContactIsStarred(r3)); assertTrue(queryRawContactIsStarred(r4)); assertFalse(queryRawContactIsStarred(r5)); assertTrue(queryRawContactIsStarred(r6)); assertFalse(queryRawContactIsStarred(r7)); } public void testFavoritesGroupMembershipChangeAfterStarChange() { long g1 = createGroup(mAccount, "g1", "t1", 0, false /* autoAdd */, true /* favorite */); long g2 = createGroup(mAccount, "g2", "t2", 0, false /* autoAdd */, false/* favorite */); long g4 = createGroup(mAccountTwo, "g4", "t4", 0, false /* autoAdd */, true /* favorite */); long g5 = createGroup(mAccountTwo, "g5", "t5", 0, false /* autoAdd */, false/* favorite */); long r1 = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.STARRED, "1"); long r2 = RawContactUtil.createRawContact(mResolver, mAccount); long r3 = RawContactUtil.createRawContact(mResolver, mAccountTwo); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); Cursor c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } // remove the star from r1 assertEquals(1, updateItem(RawContacts.CONTENT_URI, r1, RawContacts.STARRED, "0")); // Since no raw contacts are starred, there should be no group memberships. assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); // mark r1 as starred assertEquals(1, updateItem(RawContacts.CONTENT_URI, r1, RawContacts.STARRED, "1")); // Now that r1 is starred it should have a membership in the one groups from mAccount // that is marked as a favorite. // There should be no memberships in mAccountTwo since it has no starred raw contacts. assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } // remove the star from r1 assertEquals(1, updateItem(RawContacts.CONTENT_URI, r1, RawContacts.STARRED, "0")); // Since no raw contacts are starred, there should be no group memberships. assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(r1)); assertNotNull(contactUri); // mark r1 as starred via its contact lookup uri assertEquals(1, updateItem(contactUri, Contacts.STARRED, "1")); // Now that r1 is starred it should have a membership in the one groups from mAccount // that is marked as a favorite. // There should be no memberships in mAccountTwo since it has no starred raw contacts. assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } // remove the star from r1 updateItem(contactUri, Contacts.STARRED, "0"); // Since no raw contacts are starred, there should be no group memberships. assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); } public void testStarChangedAfterGroupMembershipChange() { long g1 = createGroup(mAccount, "g1", "t1", 0, false /* autoAdd */, true /* favorite */); long g2 = createGroup(mAccount, "g2", "t2", 0, false /* autoAdd */, false/* favorite */); long g4 = createGroup(mAccountTwo, "g4", "t4", 0, false /* autoAdd */, true /* favorite */); long g5 = createGroup(mAccountTwo, "g5", "t5", 0, false /* autoAdd */, false/* favorite */); long r1 = RawContactUtil.createRawContact(mResolver, mAccount); long r2 = RawContactUtil.createRawContact(mResolver, mAccount); long r3 = RawContactUtil.createRawContact(mResolver, mAccountTwo); assertFalse(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertFalse(queryRawContactIsStarred(r3)); Cursor c; // add r1 to one favorites group // r1's star should automatically be set // r1 should automatically be added to the other favorites group Uri urir1g1 = insertGroupMembership(r1, g1); assertTrue(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertFalse(queryRawContactIsStarred(r3)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } // remove r1 from one favorites group mResolver.delete(urir1g1, null, null); // r1's star should no longer be set assertFalse(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertFalse(queryRawContactIsStarred(r3)); // there should be no membership rows assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); // add r3 to the one favorites group for that account // r3's star should automatically be set Uri urir3g4 = insertGroupMembership(r3, g4); assertFalse(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertTrue(queryRawContactIsStarred(r3)); assertNoRowsAndClose(queryGroupMemberships(mAccount)); c = queryGroupMemberships(mAccountTwo); try { assertTrue(c.moveToNext()); assertEquals(g4, c.getLong(0)); assertEquals(r3, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } // remove r3 from the favorites group mResolver.delete(urir3g4, null, null); // r3's star should automatically be cleared assertFalse(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertFalse(queryRawContactIsStarred(r3)); assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); } public void testReadOnlyRawContact() { long rawContactId = RawContactUtil.createRawContact(mResolver); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); storeValue(rawContactUri, RawContacts.CUSTOM_RINGTONE, "first"); storeValue(rawContactUri, RawContacts.RAW_CONTACT_IS_READ_ONLY, 1); storeValue(rawContactUri, RawContacts.CUSTOM_RINGTONE, "second"); assertStoredValue(rawContactUri, RawContacts.CUSTOM_RINGTONE, "first"); Uri syncAdapterUri = rawContactUri.buildUpon() .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "1") .build(); storeValue(syncAdapterUri, RawContacts.CUSTOM_RINGTONE, "third"); assertStoredValue(rawContactUri, RawContacts.CUSTOM_RINGTONE, "third"); } public void testReadOnlyDataRow() { long rawContactId = RawContactUtil.createRawContact(mResolver); Uri emailUri = insertEmail(rawContactId, "email"); Uri phoneUri = insertPhoneNumber(rawContactId, "555-1111"); storeValue(emailUri, Data.IS_READ_ONLY, "1"); storeValue(emailUri, Email.ADDRESS, "changed"); storeValue(phoneUri, Phone.NUMBER, "555-2222"); assertStoredValue(emailUri, Email.ADDRESS, "email"); assertStoredValue(phoneUri, Phone.NUMBER, "555-2222"); Uri syncAdapterUri = emailUri.buildUpon() .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "1") .build(); storeValue(syncAdapterUri, Email.ADDRESS, "changed"); assertStoredValue(emailUri, Email.ADDRESS, "changed"); } public void testContactWithReadOnlyRawContact() { long rawContactId1 = RawContactUtil.createRawContact(mResolver); Uri rawContactUri1 = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId1); storeValue(rawContactUri1, RawContacts.CUSTOM_RINGTONE, "first"); long rawContactId2 = RawContactUtil.createRawContact(mResolver); Uri rawContactUri2 = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId2); storeValue(rawContactUri2, RawContacts.CUSTOM_RINGTONE, "second"); storeValue(rawContactUri2, RawContacts.RAW_CONTACT_IS_READ_ONLY, 1); setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); long contactId = queryContactId(rawContactId1); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); storeValue(contactUri, Contacts.CUSTOM_RINGTONE, "rt"); assertStoredValue(contactUri, Contacts.CUSTOM_RINGTONE, "rt"); assertStoredValue(rawContactUri1, RawContacts.CUSTOM_RINGTONE, "rt"); assertStoredValue(rawContactUri2, RawContacts.CUSTOM_RINGTONE, "second"); } public void testNameParsingQuery() { Uri uri = ContactsContract.AUTHORITY_URI.buildUpon().appendPath("complete_name") .appendQueryParameter(StructuredName.DISPLAY_NAME, "Mr. John Q. Doe Jr.").build(); Cursor cursor = mResolver.query(uri, null, null, null, null); ContentValues values = new ContentValues(); values.put(StructuredName.DISPLAY_NAME, "Mr. John Q. Doe Jr."); values.put(StructuredName.PREFIX, "Mr."); values.put(StructuredName.GIVEN_NAME, "John"); values.put(StructuredName.MIDDLE_NAME, "Q."); values.put(StructuredName.FAMILY_NAME, "Doe"); values.put(StructuredName.SUFFIX, "Jr."); values.put(StructuredName.FULL_NAME_STYLE, FullNameStyle.WESTERN); assertTrue(cursor.moveToFirst()); assertCursorValues(cursor, values); cursor.close(); } public void testNameConcatenationQuery() { Uri uri = ContactsContract.AUTHORITY_URI.buildUpon().appendPath("complete_name") .appendQueryParameter(StructuredName.PREFIX, "Mr") .appendQueryParameter(StructuredName.GIVEN_NAME, "John") .appendQueryParameter(StructuredName.MIDDLE_NAME, "Q.") .appendQueryParameter(StructuredName.FAMILY_NAME, "Doe") .appendQueryParameter(StructuredName.SUFFIX, "Jr.") .build(); Cursor cursor = mResolver.query(uri, null, null, null, null); ContentValues values = new ContentValues(); values.put(StructuredName.DISPLAY_NAME, "Mr John Q. Doe, Jr."); values.put(StructuredName.PREFIX, "Mr"); values.put(StructuredName.GIVEN_NAME, "John"); values.put(StructuredName.MIDDLE_NAME, "Q."); values.put(StructuredName.FAMILY_NAME, "Doe"); values.put(StructuredName.SUFFIX, "Jr."); values.put(StructuredName.FULL_NAME_STYLE, FullNameStyle.WESTERN); assertTrue(cursor.moveToFirst()); assertCursorValues(cursor, values); cursor.close(); } public void testBuildSingleRowResult() { checkBuildSingleRowResult( new String[] {"b"}, new String[] {"a", "b"}, new Integer[] {1, 2}, new Integer[] {2} ); checkBuildSingleRowResult( new String[] {"b", "a", "b"}, new String[] {"a", "b"}, new Integer[] {1, 2}, new Integer[] {2, 1, 2} ); checkBuildSingleRowResult( null, // all columns new String[] {"a", "b"}, new Integer[] {1, 2}, new Integer[] {1, 2} ); try { // Access non-existent column ContactsProvider2.buildSingleRowResult(new String[] {"a"}, new String[] {"b"}, new Object[] {1}); fail(); } catch (IllegalArgumentException expected) { } } private void checkBuildSingleRowResult(String[] projection, String[] availableColumns, Object[] data, Integer[] expectedValues) { final Cursor c = ContactsProvider2.buildSingleRowResult(projection, availableColumns, data); try { assertTrue(c.moveToFirst()); assertEquals(1, c.getCount()); assertEquals(expectedValues.length, c.getColumnCount()); for (int i = 0; i < expectedValues.length; i++) { assertEquals("column " + i, expectedValues[i], (Integer) c.getInt(i)); } } finally { c.close(); } } public void testDataUsageFeedbackAndDelete() { sMockClock.install(); final long startTime = sMockClock.currentTimeMillis(); final long rid1 = RawContactUtil.createRawContactWithName(mResolver, "contact", "a"); final long did1a = ContentUris.parseId(insertEmail(rid1, "[email protected]")); final long did1b = ContentUris.parseId(insertEmail(rid1, "[email protected]")); final long did1p = ContentUris.parseId(insertPhoneNumber(rid1, "555-555-5555")); final long rid2 = RawContactUtil.createRawContactWithName(mResolver, "contact", "b"); final long did2a = ContentUris.parseId(insertEmail(rid2, "[email protected]")); final long did2p = ContentUris.parseId(insertPhoneNumber(rid2, "555-555-5556")); // Aggregate 1 and 2 setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rid1, rid2); final long rid3 = RawContactUtil.createRawContactWithName(mResolver, "contact", "c"); final long did3a = ContentUris.parseId(insertEmail(rid3, "[email protected]")); final long did3p = ContentUris.parseId(insertPhoneNumber(rid3, "555-3333")); final long rid4 = RawContactUtil.createRawContactWithName(mResolver, "contact", "d"); final long did4p = ContentUris.parseId(insertPhoneNumber(rid4, "555-4444")); final long cid1 = queryContactId(rid1); final long cid3 = queryContactId(rid3); final long cid4 = queryContactId(rid4); // Make sure 1+2, 3 and 4 aren't aggregated MoreAsserts.assertNotEqual(cid1, cid3); MoreAsserts.assertNotEqual(cid1, cid4); MoreAsserts.assertNotEqual(cid3, cid4); // time = startTime // First, there's no frequent. (We use strequent here only because frequent is hidden // and may be removed someday.) assertRowCount(0, Contacts.CONTENT_STREQUENT_URI, null, null); // Test 1. touch data 1a updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_LONG_TEXT, did1a); // Now, there's a single frequent. (contact 1) assertRowCount(1, Contacts.CONTENT_STREQUENT_URI, null, null); // time = startTime + 1 sMockClock.advance(); // Test 2. touch data 1a, 2a and 3a updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_LONG_TEXT, did1a, did2a, did3a); // Now, contact 1 and 3 are in frequent. assertRowCount(2, Contacts.CONTENT_STREQUENT_URI, null, null); // time = startTime + 2 sMockClock.advance(); // Test 2. touch data 2p (call) updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_CALL, did2p); // There're still two frequent. assertRowCount(2, Contacts.CONTENT_STREQUENT_URI, null, null); // time = startTime + 3 sMockClock.advance(); // Test 3. touch data 2p and 3p (short text) updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_SHORT_TEXT, did2p, did3p); // Let's check the tables. // Fist, check the data_usage_stat table, which has no public URI. assertStoredValuesDb("SELECT " + DataUsageStatColumns.DATA_ID + "," + DataUsageStatColumns.USAGE_TYPE_INT + "," + DataUsageStatColumns.TIMES_USED + "," + DataUsageStatColumns.LAST_TIME_USED + " FROM " + Tables.DATA_USAGE_STAT, null, cv(DataUsageStatColumns.DATA_ID, did1a, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT, DataUsageStatColumns.TIMES_USED, 2, DataUsageStatColumns.LAST_TIME_USED, startTime + 1 ), cv(DataUsageStatColumns.DATA_ID, did2a, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT, DataUsageStatColumns.TIMES_USED, 1, DataUsageStatColumns.LAST_TIME_USED, startTime + 1 ), cv(DataUsageStatColumns.DATA_ID, did3a, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT, DataUsageStatColumns.TIMES_USED, 1, DataUsageStatColumns.LAST_TIME_USED, startTime + 1 ), cv(DataUsageStatColumns.DATA_ID, did2p, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_CALL, DataUsageStatColumns.TIMES_USED, 1, DataUsageStatColumns.LAST_TIME_USED, startTime + 2 ), cv(DataUsageStatColumns.DATA_ID, did2p, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_SHORT_TEXT, DataUsageStatColumns.TIMES_USED, 1, DataUsageStatColumns.LAST_TIME_USED, startTime + 3 ), cv(DataUsageStatColumns.DATA_ID, did3p, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_SHORT_TEXT, DataUsageStatColumns.TIMES_USED, 1, DataUsageStatColumns.LAST_TIME_USED, startTime + 3 ) ); // Next, check the raw_contacts table assertStoredValuesWithProjection(RawContacts.CONTENT_URI, cv(RawContacts._ID, rid1, RawContacts.TIMES_CONTACTED, 2, RawContacts.LAST_TIME_CONTACTED, startTime + 1 ), cv(RawContacts._ID, rid2, RawContacts.TIMES_CONTACTED, 3, RawContacts.LAST_TIME_CONTACTED, startTime + 3 ), cv(RawContacts._ID, rid3, RawContacts.TIMES_CONTACTED, 2, RawContacts.LAST_TIME_CONTACTED, startTime + 3 ), cv(RawContacts._ID, rid4, RawContacts.TIMES_CONTACTED, 0, RawContacts.LAST_TIME_CONTACTED, null // 4 wasn't touched. ) ); // Lastly, check the contacts table. // Note contact1.TIMES_CONTACTED = 4, even though raw_contact1.TIMES_CONTACTED + // raw_contact1.TIMES_CONTACTED = 5, because in test 2, data 1a and data 2a were touched // at once. assertStoredValuesWithProjection(Contacts.CONTENT_URI, cv(Contacts._ID, cid1, Contacts.TIMES_CONTACTED, 4, Contacts.LAST_TIME_CONTACTED, startTime + 3 ), cv(Contacts._ID, cid3, Contacts.TIMES_CONTACTED, 2, Contacts.LAST_TIME_CONTACTED, startTime + 3 ), cv(Contacts._ID, cid4, Contacts.TIMES_CONTACTED, 0, Contacts.LAST_TIME_CONTACTED, 0 // For contacts, the default is 0, not null. ) ); // Let's test the delete too. assertTrue(mResolver.delete(DataUsageFeedback.DELETE_USAGE_URI, null, null) > 0); // Now there's no frequent. assertRowCount(0, Contacts.CONTENT_STREQUENT_URI, null, null); // No rows in the stats table. assertStoredValuesDb("SELECT " + DataUsageStatColumns.DATA_ID + " FROM " + Tables.DATA_USAGE_STAT, null, new ContentValues[0]); // The following values should all be 0 or null. assertRowCount(0, Contacts.CONTENT_URI, Contacts.TIMES_CONTACTED + ">0", null); assertRowCount(0, Contacts.CONTENT_URI, Contacts.LAST_TIME_CONTACTED + ">0", null); assertRowCount(0, RawContacts.CONTENT_URI, RawContacts.TIMES_CONTACTED + ">0", null); assertRowCount(0, RawContacts.CONTENT_URI, RawContacts.LAST_TIME_CONTACTED + ">0", null); // Calling it when there's no usage stats will still return a positive value. assertTrue(mResolver.delete(DataUsageFeedback.DELETE_USAGE_URI, null, null) > 0); } /******************************************************* * Delta api tests. */ public void testContactDelete_hasDeleteLog() { sMockClock.install(); long start = sMockClock.currentTimeMillis(); DatabaseAsserts.ContactIdPair ids = assertContactCreateDelete(); DatabaseAsserts.assertHasDeleteLogGreaterThan(mResolver, ids.mContactId, start); // Clean up. Must also remove raw contact. RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testContactDelete_marksRawContactsForDeletion() { DatabaseAsserts.ContactIdPair ids = assertContactCreateDelete(); String[] projection = new String[]{ContactsContract.RawContacts.DIRTY, ContactsContract.RawContacts.DELETED}; List<String[]> records = RawContactUtil.queryByContactId(mResolver, ids.mContactId, projection); for (String[] arr : records) { assertEquals("1", arr[0]); assertEquals("1", arr[1]); } // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testContactUpdate_updatesContactUpdatedTimestamp() { sMockClock.install(); DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); ContentValues values = new ContentValues(); values.put(ContactsContract.Contacts.STARRED, 1); sMockClock.advance(); ContactUtil.update(mResolver, ids.mContactId, values); long newTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); assertTrue(newTime > baseTime); // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } // This implicitly tests the Contact create case. public void testRawContactCreate_updatesContactUpdatedTimestamp() { long startTime = System.currentTimeMillis(); long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long lastUpdated = getContactLastUpdatedTimestampByRawContactId(mResolver, rawContactId); assertTrue(lastUpdated > startTime); // Clean up RawContactUtil.delete(mResolver, rawContactId, true); } public void testRawContactUpdate_updatesContactUpdatedTimestamp() { DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); ContentValues values = new ContentValues(); values.put(ContactsContract.RawContacts.STARRED, 1); RawContactUtil.update(mResolver, ids.mRawContactId, values); long newTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); assertTrue(newTime > baseTime); // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testRawContactPsuedoDelete_hasDeleteLogForContact() { DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); RawContactUtil.delete(mResolver, ids.mRawContactId, false); DatabaseAsserts.assertHasDeleteLogGreaterThan(mResolver, ids.mContactId, baseTime); // clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testRawContactDelete_hasDeleteLogForContact() { DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); RawContactUtil.delete(mResolver, ids.mRawContactId, true); DatabaseAsserts.assertHasDeleteLogGreaterThan(mResolver, ids.mContactId, baseTime); // already clean } private long getContactLastUpdatedTimestampByRawContactId(ContentResolver resolver, long rawContactId) { long contactId = RawContactUtil.queryContactIdByRawContactId(mResolver, rawContactId); MoreAsserts.assertNotEqual(CommonDatabaseUtils.NOT_FOUND, contactId); return ContactUtil.queryContactLastUpdatedTimestamp(mResolver, contactId); } public void testDataInsert_updatesContactLastUpdatedTimestamp() { sMockClock.install(); DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); sMockClock.advance(); insertPhoneNumberAndReturnDataId(ids.mRawContactId); long newTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); assertTrue(newTime > baseTime); // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testDataDelete_updatesContactLastUpdatedTimestamp() { sMockClock.install(); DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long dataId = insertPhoneNumberAndReturnDataId(ids.mRawContactId); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); sMockClock.advance(); DataUtil.delete(mResolver, dataId); long newTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); assertTrue(newTime > baseTime); // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testDataUpdate_updatesContactLastUpdatedTimestamp() { sMockClock.install(); DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long dataId = insertPhoneNumberAndReturnDataId(ids.mRawContactId); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); sMockClock.advance(); ContentValues values = new ContentValues(); values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, "555-5555"); DataUtil.update(mResolver, dataId, values); long newTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); assertTrue(newTime > baseTime); // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } private long insertPhoneNumberAndReturnDataId(long rawContactId) { Uri uri = insertPhoneNumber(rawContactId, "1-800-GOOG-411"); return ContentUris.parseId(uri); } public void testDeletedContactsDelete_isUnsupported() { final Uri URI = ContactsContract.DeletedContacts.CONTENT_URI; DatabaseAsserts.assertDeleteIsUnsupported(mResolver, URI); Uri uri = ContentUris.withAppendedId(URI, 1L); DatabaseAsserts.assertDeleteIsUnsupported(mResolver, uri); } public void testDeletedContactsInsert_isUnsupported() { final Uri URI = ContactsContract.DeletedContacts.CONTENT_URI; DatabaseAsserts.assertInsertIsUnsupported(mResolver, URI); } public void testQueryDeletedContactsByContactId() { DatabaseAsserts.ContactIdPair ids = assertContactCreateDelete(); MoreAsserts.assertNotEqual(CommonDatabaseUtils.NOT_FOUND, DeletedContactUtil.queryDeletedTimestampForContactId(mResolver, ids.mContactId)); } public void testQueryDeletedContactsAll() { final int numDeletes = 10; // Since we cannot clean out delete log from previous tests, we need to account for that // by querying for the count first. final long startCount = DeletedContactUtil.getCount(mResolver); for (int i = 0; i < numDeletes; i++) { assertContactCreateDelete(); } final long endCount = DeletedContactUtil.getCount(mResolver); assertEquals(numDeletes, endCount - startCount); } public void testQueryDeletedContactsSinceTimestamp() { sMockClock.install(); // Before final HashSet<Long> beforeIds = new HashSet<Long>(); beforeIds.add(assertContactCreateDelete().mContactId); beforeIds.add(assertContactCreateDelete().mContactId); final long start = sMockClock.currentTimeMillis(); // After final HashSet<Long> afterIds = new HashSet<Long>(); afterIds.add(assertContactCreateDelete().mContactId); afterIds.add(assertContactCreateDelete().mContactId); afterIds.add(assertContactCreateDelete().mContactId); final String[] projection = new String[]{ ContactsContract.DeletedContacts.CONTACT_ID, ContactsContract.DeletedContacts.CONTACT_DELETED_TIMESTAMP }; final List<String[]> records = DeletedContactUtil.querySinceTimestamp(mResolver, projection, start); for (String[] record : records) { // Check ids to make sure we only have the ones that came after the time. final long contactId = Long.parseLong(record[0]); assertFalse(beforeIds.contains(contactId)); assertTrue(afterIds.contains(contactId)); // Check times to make sure they came after assertTrue(Long.parseLong(record[1]) > start); } } /** * Create a contact. Assert it's not present in the delete log. Delete it. * And assert that the contact record is no longer present. * * @return The contact id and raw contact id that was created. */ private DatabaseAsserts.ContactIdPair assertContactCreateDelete() { DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); assertEquals(CommonDatabaseUtils.NOT_FOUND, DeletedContactUtil.queryDeletedTimestampForContactId(mResolver, ids.mContactId)); sMockClock.advance(); ContactUtil.delete(mResolver, ids.mContactId); assertFalse(ContactUtil.recordExistsForContactId(mResolver, ids.mContactId)); return ids; } /** * End delta api tests. ******************************************************/ private Cursor queryGroupMemberships(Account account) { Cursor c = mResolver.query(TestUtil.maybeAddAccountQueryParameters(Data.CONTENT_URI, account), new String[]{GroupMembership.GROUP_ROW_ID, GroupMembership.RAW_CONTACT_ID}, Data.MIMETYPE + "=?", new String[]{GroupMembership.CONTENT_ITEM_TYPE}, GroupMembership.GROUP_SOURCE_ID); return c; } private String readToEnd(FileInputStream inputStream) { try { System.out.println("DECLARED INPUT STREAM LENGTH: " + inputStream.available()); int ch; StringBuilder stringBuilder = new StringBuilder(); int index = 0; while (true) { ch = inputStream.read(); System.out.println("READ CHARACTER: " + index + " " + ch); if (ch == -1) { break; } stringBuilder.append((char)ch); index++; } return stringBuilder.toString(); } catch (IOException e) { return null; } } private void assertQueryParameter(String uriString, String parameter, String expectedValue) { assertEquals(expectedValue, ContactsProvider2.getQueryParameter( Uri.parse(uriString), parameter)); } private long createContact(ContentValues values, String firstName, String givenName, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode) { return createContact(values, firstName, givenName, phoneNumber, email, presenceStatus, timesContacted, starred, groupId, chatMode, false); } private long createContact(ContentValues values, String firstName, String givenName, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode, boolean isUserProfile) { return queryContactId(createRawContact(values, firstName, givenName, phoneNumber, email, presenceStatus, timesContacted, starred, groupId, chatMode, isUserProfile)); } private long createRawContact(ContentValues values, String firstName, String givenName, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode) { long rawContactId = createRawContact(values, phoneNumber, email, presenceStatus, timesContacted, starred, groupId, chatMode); DataUtil.insertStructuredName(mResolver, rawContactId, firstName, givenName); return rawContactId; } private long createRawContact(ContentValues values, String firstName, String givenName, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode, boolean isUserProfile) { long rawContactId = createRawContact(values, phoneNumber, email, presenceStatus, timesContacted, starred, groupId, chatMode, isUserProfile); DataUtil.insertStructuredName(mResolver, rawContactId, firstName, givenName); return rawContactId; } private long createRawContact(ContentValues values, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode) { return createRawContact(values, phoneNumber, email, presenceStatus, timesContacted, starred, groupId, chatMode, false); } private long createRawContact(ContentValues values, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode, boolean isUserProfile) { values.put(RawContacts.STARRED, starred); values.put(RawContacts.SEND_TO_VOICEMAIL, 1); values.put(RawContacts.CUSTOM_RINGTONE, "beethoven5"); values.put(RawContacts.TIMES_CONTACTED, timesContacted); Uri insertionUri = isUserProfile ? Profile.CONTENT_RAW_CONTACTS_URI : RawContacts.CONTENT_URI; Uri rawContactUri = mResolver.insert(insertionUri, values); long rawContactId = ContentUris.parseId(rawContactUri); Uri photoUri = insertPhoto(rawContactId); long photoId = ContentUris.parseId(photoUri); values.put(Contacts.PHOTO_ID, photoId); if (!TextUtils.isEmpty(phoneNumber)) { insertPhoneNumber(rawContactId, phoneNumber); } if (!TextUtils.isEmpty(email)) { insertEmail(rawContactId, email); } insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, email, presenceStatus, "hacking", chatMode, isUserProfile); if (groupId != 0) { insertGroupMembership(rawContactId, groupId); } return rawContactId; } /** * Creates a raw contact with pre-set values under the user's profile. * @param profileValues Values to be used to create the entry (common values will be * automatically populated in createRawContact()). * @return the raw contact ID that was created. */ private long createBasicProfileContact(ContentValues profileValues) { long profileRawContactId = createRawContact(profileValues, "Mia", "Prophyl", "18005554411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_CAMERA, true); profileValues.put(Contacts.DISPLAY_NAME, "Mia Prophyl"); return profileRawContactId; } /** * Creates a raw contact with pre-set values that is not under the user's profile. * @param nonProfileValues Values to be used to create the entry (common values will be * automatically populated in createRawContact()). * @return the raw contact ID that was created. */ private long createBasicNonProfileContact(ContentValues nonProfileValues) { long nonProfileRawContactId = createRawContact(nonProfileValues, "John", "Doe", "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_CAMERA, false); nonProfileValues.put(Contacts.DISPLAY_NAME, "John Doe"); return nonProfileRawContactId; } private void putDataValues(ContentValues values, long rawContactId) { values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, "testmimetype"); values.put(Data.RES_PACKAGE, "oldpackage"); values.put(Data.IS_PRIMARY, 1); values.put(Data.IS_SUPER_PRIMARY, 1); values.put(Data.DATA1, "one"); values.put(Data.DATA2, "two"); values.put(Data.DATA3, "three"); values.put(Data.DATA4, "four"); values.put(Data.DATA5, "five"); values.put(Data.DATA6, "six"); values.put(Data.DATA7, "seven"); values.put(Data.DATA8, "eight"); values.put(Data.DATA9, "nine"); values.put(Data.DATA10, "ten"); values.put(Data.DATA11, "eleven"); values.put(Data.DATA12, "twelve"); values.put(Data.DATA13, "thirteen"); values.put(Data.DATA14, "fourteen"); values.put(Data.DATA15, "fifteen"); values.put(Data.SYNC1, "sync1"); values.put(Data.SYNC2, "sync2"); values.put(Data.SYNC3, "sync3"); values.put(Data.SYNC4, "sync4"); } /** * @param data1 email address or phone number * @param usageType One of {@link DataUsageFeedback#USAGE_TYPE} * @param values ContentValues for this feedback. Useful for incrementing * {Contacts#TIMES_CONTACTED} in the ContentValue. Can be null. */ private void sendFeedback(String data1, String usageType, ContentValues values) { final long dataId = getStoredLongValue(Data.CONTENT_URI, Data.DATA1 + "=?", new String[] { data1 }, Data._ID); MoreAsserts.assertNotEqual(0, updateDataUsageFeedback(usageType, dataId)); if (values != null && values.containsKey(Contacts.TIMES_CONTACTED)) { values.put(Contacts.TIMES_CONTACTED, values.getAsInteger(Contacts.TIMES_CONTACTED) + 1); } } private void updateDataUsageFeedback(String usageType, Uri resultUri) { final long id = ContentUris.parseId(resultUri); final boolean successful = updateDataUsageFeedback(usageType, id) > 0; assertTrue(successful); } private int updateDataUsageFeedback(String usageType, long... ids) { final StringBuilder idList = new StringBuilder(); for (long id : ids) { if (idList.length() > 0) idList.append(","); idList.append(id); } return mResolver.update(DataUsageFeedback.FEEDBACK_URI.buildUpon() .appendPath(idList.toString()) .appendQueryParameter(DataUsageFeedback.USAGE_TYPE, usageType) .build(), new ContentValues(), null, null); } private boolean hasChineseCollator() { final Locale locale[] = Collator.getAvailableLocales(); for (int i = 0; i < locale.length; i++) { if (locale[i].equals(Locale.CHINA)) { return true; } } return false; } private boolean hasJapaneseCollator() { final Locale locale[] = Collator.getAvailableLocales(); for (int i = 0; i < locale.length; i++) { if (locale[i].equals(Locale.JAPAN)) { return true; } } return false; } private boolean hasGermanCollator() { final Locale locale[] = Collator.getAvailableLocales(); for (int i = 0; i < locale.length; i++) { if (locale[i].equals(Locale.GERMANY)) { return true; } } return false; } }
public void testSettingsInsertionPreventsDuplicates() { Account account1 = new Account("a", "b"); AccountWithDataSet account2 = new AccountWithDataSet("c", "d", "plus"); createSettings(account1, "0", "0"); createSettings(account2, "1", "1"); // Now try creating the settings rows again. It should update the existing settings rows. createSettings(account1, "1", "0"); assertStoredValue(Settings.CONTENT_URI, Settings.ACCOUNT_NAME + "=? AND " + Settings.ACCOUNT_TYPE + "=?", new String[] {"a", "b"}, Settings.SHOULD_SYNC, "1"); createSettings(account2, "0", "1"); assertStoredValue(Settings.CONTENT_URI, Settings.ACCOUNT_NAME + "=? AND " + Settings.ACCOUNT_TYPE + "=? AND " + Settings.DATA_SET + "=?", new String[] {"c", "d", "plus"}, Settings.SHOULD_SYNC, "0"); } public void testDisplayNameParsingWhenPartsUnspecified() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = new ContentValues(); values.put(StructuredName.DISPLAY_NAME, "Mr.John Kevin von Smith, Jr."); DataUtil.insertStructuredName(mResolver, rawContactId, values); assertStructuredName(rawContactId, "Mr.", "John", "Kevin", "von Smith", "Jr."); } public void testDisplayNameParsingWhenPartsAreNull() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = new ContentValues(); values.put(StructuredName.DISPLAY_NAME, "Mr.John Kevin von Smith, Jr."); values.putNull(StructuredName.GIVEN_NAME); values.putNull(StructuredName.FAMILY_NAME); DataUtil.insertStructuredName(mResolver, rawContactId, values); assertStructuredName(rawContactId, "Mr.", "John", "Kevin", "von Smith", "Jr."); } public void testDisplayNameParsingWhenPartsSpecified() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = new ContentValues(); values.put(StructuredName.DISPLAY_NAME, "Mr.John Kevin von Smith, Jr."); values.put(StructuredName.FAMILY_NAME, "Johnson"); DataUtil.insertStructuredName(mResolver, rawContactId, values); assertStructuredName(rawContactId, null, null, null, "Johnson", null); } public void testContactWithoutPhoneticName() { ContactLocaleUtils.setLocale(Locale.ENGLISH); final long rawContactId = RawContactUtil.createRawContact(mResolver, null); ContentValues values = new ContentValues(); values.put(StructuredName.PREFIX, "Mr"); values.put(StructuredName.GIVEN_NAME, "John"); values.put(StructuredName.MIDDLE_NAME, "K."); values.put(StructuredName.FAMILY_NAME, "Doe"); values.put(StructuredName.SUFFIX, "Jr."); Uri dataUri = DataUtil.insertStructuredName(mResolver, rawContactId, values); values.clear(); values.put(RawContacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(RawContacts.DISPLAY_NAME_PRIMARY, "Mr John K. Doe, Jr."); values.put(RawContacts.DISPLAY_NAME_ALTERNATIVE, "Mr Doe, John K., Jr."); values.putNull(RawContacts.PHONETIC_NAME); values.put(RawContacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(RawContacts.SORT_KEY_PRIMARY, "John K. Doe, Jr."); values.put(RawContactsColumns.PHONEBOOK_LABEL_PRIMARY, "J"); values.put(RawContacts.SORT_KEY_ALTERNATIVE, "Doe, John K., Jr."); values.put(RawContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "D"); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); assertStoredValues(rawContactUri, values); values.clear(); values.put(Contacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(Contacts.DISPLAY_NAME_PRIMARY, "Mr John K. Doe, Jr."); values.put(Contacts.DISPLAY_NAME_ALTERNATIVE, "Mr Doe, John K., Jr."); values.putNull(Contacts.PHONETIC_NAME); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(Contacts.SORT_KEY_PRIMARY, "John K. Doe, Jr."); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "J"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "Doe, John K., Jr."); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "D"); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId)); assertStoredValues(contactUri, values); // The same values should be available through a join with Data assertStoredValues(dataUri, values); } public void testContactWithChineseName() { if (!hasChineseCollator()) { return; } ContactLocaleUtils.setLocale(Locale.SIMPLIFIED_CHINESE); long rawContactId = RawContactUtil.createRawContact(mResolver, null); ContentValues values = new ContentValues(); // "DUAN \u6BB5 XIAO \u5C0F TAO \u6D9B" values.put(StructuredName.DISPLAY_NAME, "\u6BB5\u5C0F\u6D9B"); Uri dataUri = DataUtil.insertStructuredName(mResolver, rawContactId, values); values.clear(); values.put(RawContacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(RawContacts.DISPLAY_NAME_PRIMARY, "\u6BB5\u5C0F\u6D9B"); values.put(RawContacts.DISPLAY_NAME_ALTERNATIVE, "\u6BB5\u5C0F\u6D9B"); values.putNull(RawContacts.PHONETIC_NAME); values.put(RawContacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(RawContacts.SORT_KEY_PRIMARY, "\u6BB5\u5C0F\u6D9B"); values.put(RawContactsColumns.PHONEBOOK_LABEL_PRIMARY, "D"); values.put(RawContacts.SORT_KEY_ALTERNATIVE, "\u6BB5\u5C0F\u6D9B"); values.put(RawContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "D"); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); assertStoredValues(rawContactUri, values); values.clear(); values.put(Contacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(Contacts.DISPLAY_NAME_PRIMARY, "\u6BB5\u5C0F\u6D9B"); values.put(Contacts.DISPLAY_NAME_ALTERNATIVE, "\u6BB5\u5C0F\u6D9B"); values.putNull(Contacts.PHONETIC_NAME); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(Contacts.SORT_KEY_PRIMARY, "\u6BB5\u5C0F\u6D9B"); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "D"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "\u6BB5\u5C0F\u6D9B"); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "D"); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId)); assertStoredValues(contactUri, values); // The same values should be available through a join with Data assertStoredValues(dataUri, values); } public void testJapaneseNameContactInEnglishLocale() { // Need Japanese locale data for transliteration if (!hasJapaneseCollator()) { return; } ContactLocaleUtils.setLocale(Locale.US); long rawContactId = RawContactUtil.createRawContact(null); ContentValues values = new ContentValues(); values.put(StructuredName.GIVEN_NAME, "\u7A7A\u6D77"); values.put(StructuredName.PHONETIC_GIVEN_NAME, "\u304B\u3044\u304F\u3046"); DataUtil.insertStructuredName(mResolver, rawContactId, values); long contactId = queryContactId(rawContactId); // en_US should behave same as ja_JP (match on Hiragana and Romaji // but not Pinyin) assertContactFilter(contactId, "\u304B\u3044\u304F\u3046"); assertContactFilter(contactId, "kaiku"); assertContactFilterNoResult("kong"); } public void testContactWithJapaneseName() { if (!hasJapaneseCollator()) { return; } ContactLocaleUtils.setLocale(Locale.JAPAN); long rawContactId = RawContactUtil.createRawContact(mResolver, null); ContentValues values = new ContentValues(); values.put(StructuredName.GIVEN_NAME, "\u7A7A\u6D77"); values.put(StructuredName.PHONETIC_GIVEN_NAME, "\u304B\u3044\u304F\u3046"); Uri dataUri = DataUtil.insertStructuredName(mResolver, rawContactId, values); values.clear(); values.put(RawContacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(RawContacts.DISPLAY_NAME_PRIMARY, "\u7A7A\u6D77"); values.put(RawContacts.DISPLAY_NAME_ALTERNATIVE, "\u7A7A\u6D77"); values.put(RawContacts.PHONETIC_NAME, "\u304B\u3044\u304F\u3046"); values.put(RawContacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.JAPANESE); values.put(RawContacts.SORT_KEY_PRIMARY, "\u304B\u3044\u304F\u3046"); values.put(RawContacts.SORT_KEY_ALTERNATIVE, "\u304B\u3044\u304F\u3046"); values.put(RawContactsColumns.PHONEBOOK_LABEL_PRIMARY, "\u304B"); values.put(RawContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "\u304B"); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); assertStoredValues(rawContactUri, values); values.clear(); values.put(Contacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME); values.put(Contacts.DISPLAY_NAME_PRIMARY, "\u7A7A\u6D77"); values.put(Contacts.DISPLAY_NAME_ALTERNATIVE, "\u7A7A\u6D77"); values.put(Contacts.PHONETIC_NAME, "\u304B\u3044\u304F\u3046"); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.JAPANESE); values.put(Contacts.SORT_KEY_PRIMARY, "\u304B\u3044\u304F\u3046"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "\u304B\u3044\u304F\u3046"); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "\u304B"); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "\u304B"); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId)); assertStoredValues(contactUri, values); // The same values should be available through a join with Data assertStoredValues(dataUri, values); long contactId = queryContactId(rawContactId); // ja_JP should match on Hiragana and Romaji but not Pinyin assertContactFilter(contactId, "\u304B\u3044\u304F\u3046"); assertContactFilter(contactId, "kaiku"); assertContactFilterNoResult("kong"); } public void testDisplayNameUpdate() { long rawContactId1 = RawContactUtil.createRawContact(mResolver); insertEmail(rawContactId1, "[email protected]", true); long rawContactId2 = RawContactUtil.createRawContact(mResolver); insertPhoneNumber(rawContactId2, "123456789", true); setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); assertAggregated(rawContactId1, rawContactId2, "123456789"); DataUtil.insertStructuredName(mResolver, rawContactId2, "Potato", "Head"); assertAggregated(rawContactId1, rawContactId2, "Potato Head"); assertNetworkNotified(true); } public void testDisplayNameFromData() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); assertStoredValue(uri, Contacts.DISPLAY_NAME, null); insertEmail(rawContactId, "[email protected]"); assertStoredValue(uri, Contacts.DISPLAY_NAME, "[email protected]"); insertEmail(rawContactId, "[email protected]", true); assertStoredValue(uri, Contacts.DISPLAY_NAME, "[email protected]"); insertPhoneNumber(rawContactId, "1-800-466-4411"); assertStoredValue(uri, Contacts.DISPLAY_NAME, "1-800-466-4411"); // If there are title and company, the company is display name. values.clear(); values.put(Organization.COMPANY, "Monsters Inc"); Uri organizationUri = insertOrganization(rawContactId, values); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Monsters Inc"); // If there is nickname, that is display name. insertNickname(rawContactId, "Sully"); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Sully"); // If there is structured name, that is display name. values.clear(); values.put(StructuredName.GIVEN_NAME, "James"); values.put(StructuredName.MIDDLE_NAME, "P."); values.put(StructuredName.FAMILY_NAME, "Sullivan"); DataUtil.insertStructuredName(mResolver, rawContactId, values); assertStoredValue(uri, Contacts.DISPLAY_NAME, "James P. Sullivan"); } public void testDisplayNameFromOrganizationWithoutPhoneticName() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); // If there is title without company, the title is display name. values.clear(); values.put(Organization.TITLE, "Protagonist"); Uri organizationUri = insertOrganization(rawContactId, values); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Protagonist"); // If there are title and company, the company is display name. values.clear(); values.put(Organization.COMPANY, "Monsters Inc"); mResolver.update(organizationUri, values, null, null); values.clear(); values.put(Contacts.DISPLAY_NAME, "Monsters Inc"); values.putNull(Contacts.PHONETIC_NAME); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(Contacts.SORT_KEY_PRIMARY, "Monsters Inc"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "Monsters Inc"); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "M"); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "M"); assertStoredValues(uri, values); } public void testDisplayNameFromOrganizationWithJapanesePhoneticName() { if (!hasJapaneseCollator()) { return; } ContactLocaleUtils.setLocale(Locale.JAPAN); long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); // If there is title without company, the title is display name. values.clear(); values.put(Organization.COMPANY, "DoCoMo"); values.put(Organization.PHONETIC_NAME, "\u30C9\u30B3\u30E2"); Uri organizationUri = insertOrganization(rawContactId, values); values.clear(); values.put(Contacts.DISPLAY_NAME, "DoCoMo"); values.put(Contacts.PHONETIC_NAME, "\u30C9\u30B3\u30E2"); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.JAPANESE); values.put(Contacts.SORT_KEY_PRIMARY, "\u30C9\u30B3\u30E2"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "\u30C9\u30B3\u30E2"); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "\u305F"); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "\u305F"); assertStoredValues(uri, values); } public void testDisplayNameFromOrganizationWithChineseName() { if (!hasChineseCollator()) { return; } ContactLocaleUtils.setLocale(Locale.SIMPLIFIED_CHINESE); long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); // If there is title without company, the title is display name. values.clear(); values.put(Organization.COMPANY, "\u4E2D\u56FD\u7535\u4FE1"); Uri organizationUri = insertOrganization(rawContactId, values); values.clear(); values.put(Contacts.DISPLAY_NAME, "\u4E2D\u56FD\u7535\u4FE1"); values.putNull(Contacts.PHONETIC_NAME); values.put(Contacts.PHONETIC_NAME_STYLE, PhoneticNameStyle.UNDEFINED); values.put(Contacts.SORT_KEY_PRIMARY, "\u4E2D\u56FD\u7535\u4FE1"); values.put(ContactsColumns.PHONEBOOK_LABEL_PRIMARY, "Z"); values.put(Contacts.SORT_KEY_ALTERNATIVE, "\u4E2D\u56FD\u7535\u4FE1"); values.put(ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE, "Z"); assertStoredValues(uri, values); } public void testLookupByOrganization() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); values.clear(); values.put(Organization.COMPANY, "acmecorp"); values.put(Organization.TITLE, "president"); Uri organizationUri = insertOrganization(rawContactId, values); assertContactFilter(contactId, "acmecorp"); assertContactFilter(contactId, "president"); values.clear(); values.put(Organization.DEPARTMENT, "software"); mResolver.update(organizationUri, values, null, null); assertContactFilter(contactId, "acmecorp"); assertContactFilter(contactId, "president"); values.clear(); values.put(Organization.COMPANY, "incredibles"); mResolver.update(organizationUri, values, null, null); assertContactFilter(contactId, "incredibles"); assertContactFilter(contactId, "president"); values.clear(); values.put(Organization.TITLE, "director"); mResolver.update(organizationUri, values, null, null); assertContactFilter(contactId, "incredibles"); assertContactFilter(contactId, "director"); values.clear(); values.put(Organization.COMPANY, "monsters"); values.put(Organization.TITLE, "scarer"); mResolver.update(organizationUri, values, null, null); assertContactFilter(contactId, "monsters"); assertContactFilter(contactId, "scarer"); } private void assertContactFilter(long contactId, String filter) { Uri filterUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode(filter)); assertStoredValue(filterUri, Contacts._ID, contactId); } private void assertContactFilterNoResult(String filter) { Uri filterUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode(filter)); assertEquals(0, getCount(filterUri, null, null)); } public void testSearchSnippetOrganization() throws Exception { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); // Some random data element insertEmail(rawContactId, "[email protected]"); ContentValues values = new ContentValues(); values.clear(); values.put(Organization.COMPANY, "acmecorp"); values.put(Organization.TITLE, "engineer"); Uri organizationUri = insertOrganization(rawContactId, values); // Add another matching organization values.put(Organization.COMPANY, "acmeinc"); insertOrganization(rawContactId, values); // Add another non-matching organization values.put(Organization.COMPANY, "corpacme"); insertOrganization(rawContactId, values); // And another data element insertEmail(rawContactId, "[email protected]", true, Email.TYPE_CUSTOM, "Custom"); Uri filterUri = buildFilterUri("acme", true); values.clear(); values.put(Contacts._ID, contactId); values.put(SearchSnippetColumns.SNIPPET, "engineer, [acmecorp]"); assertStoredValues(filterUri, values); } public void testSearchSnippetEmail() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); DataUtil.insertStructuredName(mResolver, rawContactId, "John", "Doe"); Uri dataUri = insertEmail(rawContactId, "[email protected]", true, Email.TYPE_CUSTOM, "Custom"); Uri filterUri = buildFilterUri("acme", true); values.clear(); values.put(Contacts._ID, contactId); values.put(SearchSnippetColumns.SNIPPET, "[[email protected]]"); assertStoredValues(filterUri, values); } public void testCountPhoneNumberDigits() { assertEquals(10, ContactsProvider2.countPhoneNumberDigits("86 (0) 5-55-12-34")); assertEquals(10, ContactsProvider2.countPhoneNumberDigits("860 555-1234")); assertEquals(3, ContactsProvider2.countPhoneNumberDigits("860")); assertEquals(10, ContactsProvider2.countPhoneNumberDigits("8605551234")); assertEquals(6, ContactsProvider2.countPhoneNumberDigits("860555")); assertEquals(6, ContactsProvider2.countPhoneNumberDigits("860 555")); assertEquals(6, ContactsProvider2.countPhoneNumberDigits("860-555")); assertEquals(12, ContactsProvider2.countPhoneNumberDigits("+441234098765")); assertEquals(0, ContactsProvider2.countPhoneNumberDigits("44+1234098765")); assertEquals(0, ContactsProvider2.countPhoneNumberDigits("+441234098foo")); } public void testSearchSnippetPhone() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); DataUtil.insertStructuredName(mResolver, rawContactId, "Cave", "Johnson"); insertPhoneNumber(rawContactId, "(860) 555-1234"); values.clear(); values.put(Contacts._ID, contactId); values.put(SearchSnippetColumns.SNIPPET, "[(860) 555-1234]"); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("86 (0) 5-55-12-34")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("860 555-1234")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("860")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("8605551234")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("860555")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("860 555")), values); assertStoredValues(Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode("860-555")), values); } private Uri buildFilterUri(String query, boolean deferredSnippeting) { Uri.Builder builder = Contacts.CONTENT_FILTER_URI.buildUpon() .appendPath(Uri.encode(query)); if (deferredSnippeting) { builder.appendQueryParameter(ContactsContract.DEFERRED_SNIPPETING, "1"); } return builder.build(); } public void testSearchSnippetNickname() throws Exception { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = new ContentValues(); Uri dataUri = insertNickname(rawContactId, "Incredible"); Uri filterUri = buildFilterUri("inc", true); values.clear(); values.put(Contacts._ID, contactId); values.put(SearchSnippetColumns.SNIPPET, "[Incredible]"); assertStoredValues(filterUri, values); } public void testSearchSnippetEmptyForNameInDisplayName() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); DataUtil.insertStructuredName(mResolver, rawContactId, "Cave", "Johnson"); insertEmail(rawContactId, "[email protected]", true); ContentValues emptySnippet = new ContentValues(); emptySnippet.clear(); emptySnippet.put(Contacts._ID, contactId); emptySnippet.put(SearchSnippetColumns.SNIPPET, (String) null); assertStoredValues(buildFilterUri("cave", true), emptySnippet); assertStoredValues(buildFilterUri("john", true), emptySnippet); } public void testSearchSnippetEmptyForNicknameInDisplayName() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); insertNickname(rawContactId, "Caveman"); insertEmail(rawContactId, "[email protected]", true); ContentValues emptySnippet = new ContentValues(); emptySnippet.clear(); emptySnippet.put(Contacts._ID, contactId); emptySnippet.put(SearchSnippetColumns.SNIPPET, (String) null); assertStoredValues(buildFilterUri("cave", true), emptySnippet); } public void testSearchSnippetEmptyForCompanyInDisplayName() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues company = new ContentValues(); company.clear(); company.put(Organization.COMPANY, "Aperture Science"); company.put(Organization.TITLE, "President"); insertOrganization(rawContactId, company); insertEmail(rawContactId, "[email protected]", true); ContentValues emptySnippet = new ContentValues(); emptySnippet.clear(); emptySnippet.put(Contacts._ID, contactId); emptySnippet.put(SearchSnippetColumns.SNIPPET, (String) null); assertStoredValues(buildFilterUri("aperture", true), emptySnippet); } public void testSearchSnippetEmptyForPhoneInDisplayName() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); insertPhoneNumber(rawContactId, "860-555-1234"); insertEmail(rawContactId, "[email protected]", true); ContentValues emptySnippet = new ContentValues(); emptySnippet.clear(); emptySnippet.put(Contacts._ID, contactId); emptySnippet.put(SearchSnippetColumns.SNIPPET, (String) null); assertStoredValues(buildFilterUri("860", true), emptySnippet); } public void testSearchSnippetEmptyForEmailInDisplayName() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); insertEmail(rawContactId, "[email protected]", true); insertNote(rawContactId, "Cave Johnson is president of Aperture Science"); ContentValues emptySnippet = new ContentValues(); emptySnippet.clear(); emptySnippet.put(Contacts._ID, contactId); emptySnippet.put(SearchSnippetColumns.SNIPPET, (String) null); assertStoredValues(buildFilterUri("cave", true), emptySnippet); } public void testDisplayNameUpdateFromStructuredNameUpdate() { long rawContactId = RawContactUtil.createRawContact(mResolver); Uri nameUri = DataUtil.insertStructuredName(mResolver, rawContactId, "Slinky", "Dog"); long contactId = queryContactId(rawContactId); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Slinky Dog"); ContentValues values = new ContentValues(); values.putNull(StructuredName.FAMILY_NAME); mResolver.update(nameUri, values, null, null); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Slinky"); values.putNull(StructuredName.GIVEN_NAME); mResolver.update(nameUri, values, null, null); assertStoredValue(uri, Contacts.DISPLAY_NAME, null); values.put(StructuredName.FAMILY_NAME, "Dog"); mResolver.update(nameUri, values, null, null); assertStoredValue(uri, Contacts.DISPLAY_NAME, "Dog"); } public void testInsertDataWithContentProviderOperations() throws Exception { ContentProviderOperation cpo1 = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI) .withValues(new ContentValues()) .build(); ContentProviderOperation cpo2 = ContentProviderOperation.newInsert(Data.CONTENT_URI) .withValueBackReference(Data.RAW_CONTACT_ID, 0) .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE) .withValue(StructuredName.GIVEN_NAME, "John") .withValue(StructuredName.FAMILY_NAME, "Doe") .build(); ContentProviderResult[] results = mResolver.applyBatch(ContactsContract.AUTHORITY, Lists.newArrayList(cpo1, cpo2)); long contactId = queryContactId(ContentUris.parseId(results[0].uri)); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); assertStoredValue(uri, Contacts.DISPLAY_NAME, "John Doe"); } public void testSendToVoicemailDefault() { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); Cursor c = queryContact(contactId); assertTrue(c.moveToNext()); int sendToVoicemail = c.getInt(c.getColumnIndex(Contacts.SEND_TO_VOICEMAIL)); assertEquals(0, sendToVoicemail); c.close(); } public void testSetSendToVoicemailAndRingtone() { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); updateSendToVoicemailAndRingtone(contactId, true, "foo"); assertSendToVoicemailAndRingtone(contactId, true, "foo"); assertNetworkNotified(false); updateSendToVoicemailAndRingtoneWithSelection(contactId, false, "bar"); assertSendToVoicemailAndRingtone(contactId, false, "bar"); assertNetworkNotified(false); } public void testSendToVoicemailAndRingtoneAfterAggregation() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "a", "b"); long contactId1 = queryContactId(rawContactId1); updateSendToVoicemailAndRingtone(contactId1, true, "foo"); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "c", "d"); long contactId2 = queryContactId(rawContactId2); updateSendToVoicemailAndRingtone(contactId2, true, "bar"); // Aggregate them setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); // Both contacts had "send to VM", the contact now has the same value assertSendToVoicemailAndRingtone(contactId1, true, "foo,bar"); // Either foo or bar } public void testDoNotSendToVoicemailAfterAggregation() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "e", "f"); long contactId1 = queryContactId(rawContactId1); updateSendToVoicemailAndRingtone(contactId1, true, null); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "g", "h"); long contactId2 = queryContactId(rawContactId2); updateSendToVoicemailAndRingtone(contactId2, false, null); // Aggregate them setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); // Since one of the contacts had "don't send to VM" that setting wins for the aggregate assertSendToVoicemailAndRingtone(queryContactId(rawContactId1), false, null); } public void testSetSendToVoicemailAndRingtonePreservedAfterJoinAndSplit() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "i", "j"); long contactId1 = queryContactId(rawContactId1); updateSendToVoicemailAndRingtone(contactId1, true, "foo"); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "k", "l"); long contactId2 = queryContactId(rawContactId2); updateSendToVoicemailAndRingtone(contactId2, false, "bar"); // Aggregate them setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); // Split them setAggregationException(AggregationExceptions.TYPE_KEEP_SEPARATE, rawContactId1, rawContactId2); assertSendToVoicemailAndRingtone(queryContactId(rawContactId1), true, "foo"); assertSendToVoicemailAndRingtone(queryContactId(rawContactId2), false, "bar"); } public void testStatusUpdateInsert() { long rawContactId = RawContactUtil.createRawContact(mResolver); Uri imUri = insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); long dataId = ContentUris.parseId(imUri); ContentValues values = new ContentValues(); values.put(StatusUpdates.DATA_ID, dataId); values.put(StatusUpdates.PROTOCOL, Im.PROTOCOL_AIM); values.putNull(StatusUpdates.CUSTOM_PROTOCOL); values.put(StatusUpdates.IM_HANDLE, "aim"); values.put(StatusUpdates.PRESENCE, StatusUpdates.INVISIBLE); values.put(StatusUpdates.STATUS, "Hiding"); values.put(StatusUpdates.STATUS_TIMESTAMP, 100); values.put(StatusUpdates.STATUS_RES_PACKAGE, "a.b.c"); values.put(StatusUpdates.STATUS_ICON, 1234); values.put(StatusUpdates.STATUS_LABEL, 2345); Uri resultUri = mResolver.insert(StatusUpdates.CONTENT_URI, values); assertStoredValues(resultUri, values); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); values.clear(); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.INVISIBLE); values.put(Contacts.CONTACT_STATUS, "Hiding"); values.put(Contacts.CONTACT_STATUS_TIMESTAMP, 100); values.put(Contacts.CONTACT_STATUS_RES_PACKAGE, "a.b.c"); values.put(Contacts.CONTACT_STATUS_ICON, 1234); values.put(Contacts.CONTACT_STATUS_LABEL, 2345); assertStoredValues(contactUri, values); values.clear(); values.put(StatusUpdates.DATA_ID, dataId); values.put(StatusUpdates.STATUS, "Cloaked"); values.put(StatusUpdates.STATUS_TIMESTAMP, 200); values.put(StatusUpdates.STATUS_RES_PACKAGE, "d.e.f"); values.put(StatusUpdates.STATUS_ICON, 4321); values.put(StatusUpdates.STATUS_LABEL, 5432); mResolver.insert(StatusUpdates.CONTENT_URI, values); values.clear(); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.INVISIBLE); values.put(Contacts.CONTACT_STATUS, "Cloaked"); values.put(Contacts.CONTACT_STATUS_TIMESTAMP, 200); values.put(Contacts.CONTACT_STATUS_RES_PACKAGE, "d.e.f"); values.put(Contacts.CONTACT_STATUS_ICON, 4321); values.put(Contacts.CONTACT_STATUS_LABEL, 5432); assertStoredValues(contactUri, values); } public void testStatusUpdateInferAttribution() { long rawContactId = RawContactUtil.createRawContact(mResolver); Uri imUri = insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); long dataId = ContentUris.parseId(imUri); ContentValues values = new ContentValues(); values.put(StatusUpdates.DATA_ID, dataId); values.put(StatusUpdates.PROTOCOL, Im.PROTOCOL_AIM); values.put(StatusUpdates.IM_HANDLE, "aim"); values.put(StatusUpdates.STATUS, "Hiding"); Uri resultUri = mResolver.insert(StatusUpdates.CONTENT_URI, values); values.clear(); values.put(StatusUpdates.DATA_ID, dataId); values.put(StatusUpdates.STATUS_LABEL, com.android.internal.R.string.imProtocolAim); values.put(StatusUpdates.STATUS, "Hiding"); assertStoredValues(resultUri, values); } public void testStatusUpdateMatchingImOrEmail() { long rawContactId = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); insertImHandle(rawContactId, Im.PROTOCOL_CUSTOM, "my_im_proto", "my_im"); insertEmail(rawContactId, "[email protected]"); // Match on IM (standard) insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", StatusUpdates.AVAILABLE, "Available", StatusUpdates.CAPABILITY_HAS_CAMERA); // Match on IM (custom) insertStatusUpdate(Im.PROTOCOL_CUSTOM, "my_im_proto", "my_im", StatusUpdates.IDLE, "Idle", StatusUpdates.CAPABILITY_HAS_CAMERA | StatusUpdates.CAPABILITY_HAS_VIDEO); // Match on Email insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.AWAY, "Away", StatusUpdates.CAPABILITY_HAS_VOICE); // No match insertStatusUpdate(Im.PROTOCOL_ICQ, null, "12345", StatusUpdates.DO_NOT_DISTURB, "Go away", StatusUpdates.CAPABILITY_HAS_CAMERA); Cursor c = mResolver.query(StatusUpdates.CONTENT_URI, new String[] { StatusUpdates.DATA_ID, StatusUpdates.PROTOCOL, StatusUpdates.CUSTOM_PROTOCOL, StatusUpdates.PRESENCE, StatusUpdates.STATUS}, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId, null, StatusUpdates.DATA_ID); assertTrue(c.moveToNext()); assertStatusUpdate(c, Im.PROTOCOL_AIM, null, StatusUpdates.AVAILABLE, "Available"); assertTrue(c.moveToNext()); assertStatusUpdate(c, Im.PROTOCOL_CUSTOM, "my_im_proto", StatusUpdates.IDLE, "Idle"); assertTrue(c.moveToNext()); assertStatusUpdate(c, Im.PROTOCOL_GOOGLE_TALK, null, StatusUpdates.AWAY, "Away"); assertFalse(c.moveToNext()); c.close(); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); ContentValues values = new ContentValues(); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.AVAILABLE); values.put(Contacts.CONTACT_STATUS, "Available"); assertStoredValuesWithProjection(contactUri, values); } public void testStatusUpdateUpdateAndDelete() { long rawContactId = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); ContentValues values = new ContentValues(); values.putNull(Contacts.CONTACT_PRESENCE); values.putNull(Contacts.CONTACT_STATUS); assertStoredValuesWithProjection(contactUri, values); insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", StatusUpdates.AWAY, "BUSY", StatusUpdates.CAPABILITY_HAS_CAMERA); insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", StatusUpdates.DO_NOT_DISTURB, "GO AWAY", StatusUpdates.CAPABILITY_HAS_CAMERA); Uri statusUri = insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", StatusUpdates.AVAILABLE, "Available", StatusUpdates.CAPABILITY_HAS_CAMERA); long statusId = ContentUris.parseId(statusUri); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.AVAILABLE); values.put(Contacts.CONTACT_STATUS, "Available"); assertStoredValuesWithProjection(contactUri, values); // update status_updates table to set new values for // status_updates.status // status_updates.status_ts // presence long updatedTs = 200; String testUpdate = "test_update"; String selection = StatusUpdates.DATA_ID + "=" + statusId; values.clear(); values.put(StatusUpdates.STATUS_TIMESTAMP, updatedTs); values.put(StatusUpdates.STATUS, testUpdate); values.put(StatusUpdates.PRESENCE, "presence_test"); mResolver.update(StatusUpdates.CONTENT_URI, values, StatusUpdates.DATA_ID + "=" + statusId, null); assertStoredValuesWithProjection(StatusUpdates.CONTENT_URI, values); // update status_updates table to set new values for columns in status_updates table ONLY // i.e., no rows in presence table are to be updated. updatedTs = 300; testUpdate = "test_update_new"; selection = StatusUpdates.DATA_ID + "=" + statusId; values.clear(); values.put(StatusUpdates.STATUS_TIMESTAMP, updatedTs); values.put(StatusUpdates.STATUS, testUpdate); mResolver.update(StatusUpdates.CONTENT_URI, values, StatusUpdates.DATA_ID + "=" + statusId, null); // make sure the presence column value is still the old value values.put(StatusUpdates.PRESENCE, "presence_test"); assertStoredValuesWithProjection(StatusUpdates.CONTENT_URI, values); // update status_updates table to set new values for columns in presence table ONLY // i.e., no rows in status_updates table are to be updated. selection = StatusUpdates.DATA_ID + "=" + statusId; values.clear(); values.put(StatusUpdates.PRESENCE, "presence_test_new"); mResolver.update(StatusUpdates.CONTENT_URI, values, StatusUpdates.DATA_ID + "=" + statusId, null); // make sure the status_updates table is not updated values.put(StatusUpdates.STATUS_TIMESTAMP, updatedTs); values.put(StatusUpdates.STATUS, testUpdate); assertStoredValuesWithProjection(StatusUpdates.CONTENT_URI, values); // effect "delete status_updates" operation and expect the following // data deleted from status_updates table // presence set to null mResolver.delete(StatusUpdates.CONTENT_URI, StatusUpdates.DATA_ID + "=" + statusId, null); values.clear(); values.putNull(Contacts.CONTACT_PRESENCE); assertStoredValuesWithProjection(contactUri, values); } public void testStatusUpdateUpdateToNull() { long rawContactId = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); ContentValues values = new ContentValues(); Uri statusUri = insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", StatusUpdates.AVAILABLE, "Available", StatusUpdates.CAPABILITY_HAS_CAMERA); long statusId = ContentUris.parseId(statusUri); values.put(Contacts.CONTACT_PRESENCE, StatusUpdates.AVAILABLE); values.put(Contacts.CONTACT_STATUS, "Available"); assertStoredValuesWithProjection(contactUri, values); values.clear(); values.putNull(StatusUpdates.PRESENCE); mResolver.update(StatusUpdates.CONTENT_URI, values, StatusUpdates.DATA_ID + "=" + statusId, null); values.clear(); values.putNull(Contacts.CONTACT_PRESENCE); values.put(Contacts.CONTACT_STATUS, "Available"); assertStoredValuesWithProjection(contactUri, values); } public void testStatusUpdateWithTimestamp() { long rawContactId = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId, Im.PROTOCOL_AIM, null, "aim"); insertImHandle(rawContactId, Im.PROTOCOL_GOOGLE_TALK, null, "gtalk"); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", 0, "Offline", 80, StatusUpdates.CAPABILITY_HAS_CAMERA, false); insertStatusUpdate(Im.PROTOCOL_AIM, null, "aim", 0, "Available", 100, StatusUpdates.CAPABILITY_HAS_CAMERA, false); insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "gtalk", 0, "Busy", 90, StatusUpdates.CAPABILITY_HAS_CAMERA, false); // Should return the latest status ContentValues values = new ContentValues(); values.put(Contacts.CONTACT_STATUS_TIMESTAMP, 100); values.put(Contacts.CONTACT_STATUS, "Available"); assertStoredValuesWithProjection(contactUri, values); } private void assertStatusUpdate(Cursor c, int protocol, String customProtocol, int presence, String status) { ContentValues values = new ContentValues(); values.put(StatusUpdates.PROTOCOL, protocol); values.put(StatusUpdates.CUSTOM_PROTOCOL, customProtocol); values.put(StatusUpdates.PRESENCE, presence); values.put(StatusUpdates.STATUS, status); assertCursorValues(c, values); } // Stream item query test cases. public void testQueryStreamItemsByRawContactId() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); ContentValues values = buildGenericStreamItemValues(); insertStreamItem(rawContactId, values, mAccount); assertStoredValues( Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), values); } public void testQueryStreamItemsByContactId() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); ContentValues values = buildGenericStreamItemValues(); insertStreamItem(rawContactId, values, null); assertStoredValues( Uri.withAppendedPath( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.StreamItems.CONTENT_DIRECTORY), values); } public void testQueryStreamItemsByLookupKey() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); String lookupKey = queryLookupKey(contactId); ContentValues values = buildGenericStreamItemValues(); insertStreamItem(rawContactId, values, null); assertStoredValues( Uri.withAppendedPath( Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey), Contacts.StreamItems.CONTENT_DIRECTORY), values); } public void testQueryStreamItemsByLookupKeyAndContactId() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); String lookupKey = queryLookupKey(contactId); ContentValues values = buildGenericStreamItemValues(); insertStreamItem(rawContactId, values, null); assertStoredValues( Uri.withAppendedPath( ContentUris.withAppendedId( Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey), contactId), Contacts.StreamItems.CONTENT_DIRECTORY), values); } public void testQueryStreamItems() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); insertStreamItem(rawContactId, values, null); assertStoredValues(StreamItems.CONTENT_URI, values); } public void testQueryStreamItemsWithSelection() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues firstValues = buildGenericStreamItemValues(); insertStreamItem(rawContactId, firstValues, null); ContentValues secondValues = buildGenericStreamItemValues(); secondValues.put(StreamItems.TEXT, "Goodbye world"); insertStreamItem(rawContactId, secondValues, null); // Select only the first stream item. assertStoredValues(StreamItems.CONTENT_URI, StreamItems.TEXT + "=?", new String[]{"Hello world"}, firstValues); // Select only the second stream item. assertStoredValues(StreamItems.CONTENT_URI, StreamItems.TEXT + "=?", new String[]{"Goodbye world"}, secondValues); } public void testQueryStreamItemById() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues firstValues = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, firstValues, null); long firstStreamItemId = ContentUris.parseId(resultUri); ContentValues secondValues = buildGenericStreamItemValues(); secondValues.put(StreamItems.TEXT, "Goodbye world"); resultUri = insertStreamItem(rawContactId, secondValues, null); long secondStreamItemId = ContentUris.parseId(resultUri); // Select only the first stream item. assertStoredValues(ContentUris.withAppendedId(StreamItems.CONTENT_URI, firstStreamItemId), firstValues); // Select only the second stream item. assertStoredValues(ContentUris.withAppendedId(StreamItems.CONTENT_URI, secondStreamItemId), secondValues); } // Stream item photo insertion + query test cases. public void testQueryStreamItemPhotoWithSelection() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, values, null); long streamItemId = ContentUris.parseId(resultUri); ContentValues photo1Values = buildGenericStreamItemPhotoValues(1); insertStreamItemPhoto(streamItemId, photo1Values, null); photo1Values.remove(StreamItemPhotos.PHOTO); // Removed during processing. ContentValues photo2Values = buildGenericStreamItemPhotoValues(2); insertStreamItemPhoto(streamItemId, photo2Values, null); // Select only the first photo. assertStoredValues(StreamItems.CONTENT_PHOTO_URI, StreamItemPhotos.SORT_INDEX + "=?", new String[]{"1"}, photo1Values); } public void testQueryStreamItemPhotoByStreamItemId() { long rawContactId = RawContactUtil.createRawContact(mResolver); // Insert a first stream item. ContentValues firstValues = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, firstValues, null); long firstStreamItemId = ContentUris.parseId(resultUri); // Insert a second stream item. ContentValues secondValues = buildGenericStreamItemValues(); resultUri = insertStreamItem(rawContactId, secondValues, null); long secondStreamItemId = ContentUris.parseId(resultUri); // Add a photo to the first stream item. ContentValues photo1Values = buildGenericStreamItemPhotoValues(1); insertStreamItemPhoto(firstStreamItemId, photo1Values, null); photo1Values.remove(StreamItemPhotos.PHOTO); // Removed during processing. // Add a photo to the second stream item. ContentValues photo2Values = buildGenericStreamItemPhotoValues(1); photo2Values.put(StreamItemPhotos.PHOTO, loadPhotoFromResource( R.drawable.nebula, PhotoSize.ORIGINAL)); insertStreamItemPhoto(secondStreamItemId, photo2Values, null); photo2Values.remove(StreamItemPhotos.PHOTO); // Removed during processing. // Select only the photos from the second stream item. assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, secondStreamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), photo2Values); } public void testQueryStreamItemPhotoByStreamItemPhotoId() { long rawContactId = RawContactUtil.createRawContact(mResolver); // Insert a first stream item. ContentValues firstValues = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, firstValues, null); long firstStreamItemId = ContentUris.parseId(resultUri); // Insert a second stream item. ContentValues secondValues = buildGenericStreamItemValues(); resultUri = insertStreamItem(rawContactId, secondValues, null); long secondStreamItemId = ContentUris.parseId(resultUri); // Add a photo to the first stream item. ContentValues photo1Values = buildGenericStreamItemPhotoValues(1); resultUri = insertStreamItemPhoto(firstStreamItemId, photo1Values, null); long firstPhotoId = ContentUris.parseId(resultUri); photo1Values.remove(StreamItemPhotos.PHOTO); // Removed during processing. // Add a photo to the second stream item. ContentValues photo2Values = buildGenericStreamItemPhotoValues(1); photo2Values.put(StreamItemPhotos.PHOTO, loadPhotoFromResource( R.drawable.galaxy, PhotoSize.ORIGINAL)); resultUri = insertStreamItemPhoto(secondStreamItemId, photo2Values, null); long secondPhotoId = ContentUris.parseId(resultUri); photo2Values.remove(StreamItemPhotos.PHOTO); // Removed during processing. // Select the first photo. assertStoredValues(ContentUris.withAppendedId( Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, firstStreamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), firstPhotoId), photo1Values); // Select the second photo. assertStoredValues(ContentUris.withAppendedId( Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, secondStreamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), secondPhotoId), photo2Values); } // Stream item insertion test cases. public void testInsertStreamItemInProfileRequiresWriteProfileAccess() { long profileRawContactId = createBasicProfileContact(new ContentValues()); // With our (default) write profile permission, we should be able to insert a stream item. ContentValues values = buildGenericStreamItemValues(); insertStreamItem(profileRawContactId, values, null); // Now take away write profile permission. mActor.removePermissions("android.permission.WRITE_PROFILE"); // Try inserting another stream item. try { insertStreamItem(profileRawContactId, values, null); fail("Should require WRITE_PROFILE access to insert a stream item in the profile."); } catch (SecurityException expected) { // Trying to insert a stream item in the profile without WRITE_PROFILE permission // should fail. } } public void testInsertStreamItemWithContentValues() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); values.put(StreamItems.RAW_CONTACT_ID, rawContactId); mResolver.insert(StreamItems.CONTENT_URI, values); assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), values); } public void testInsertStreamItemOverLimit() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); values.put(StreamItems.RAW_CONTACT_ID, rawContactId); List<Long> streamItemIds = Lists.newArrayList(); // Insert MAX + 1 stream items. long baseTime = System.currentTimeMillis(); for (int i = 0; i < 6; i++) { values.put(StreamItems.TIMESTAMP, baseTime + i); Uri resultUri = mResolver.insert(StreamItems.CONTENT_URI, values); streamItemIds.add(ContentUris.parseId(resultUri)); } Long doomedStreamItemId = streamItemIds.get(0); // There should only be MAX items. The oldest one should have been cleaned up. Cursor c = mResolver.query( Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), new String[]{StreamItems._ID}, null, null, null); try { while(c.moveToNext()) { long streamItemId = c.getLong(0); streamItemIds.remove(streamItemId); } } finally { c.close(); } assertEquals(1, streamItemIds.size()); assertEquals(doomedStreamItemId, streamItemIds.get(0)); } public void testInsertStreamItemOlderThanOldestInLimit() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); values.put(StreamItems.RAW_CONTACT_ID, rawContactId); // Insert MAX stream items. long baseTime = System.currentTimeMillis(); for (int i = 0; i < 5; i++) { values.put(StreamItems.TIMESTAMP, baseTime + i); Uri resultUri = mResolver.insert(StreamItems.CONTENT_URI, values); assertNotSame("Expected non-0 stream item ID to be inserted", 0L, ContentUris.parseId(resultUri)); } // Now try to insert a stream item that's older. It should be deleted immediately // and return an ID of 0. values.put(StreamItems.TIMESTAMP, baseTime - 1); Uri resultUri = mResolver.insert(StreamItems.CONTENT_URI, values); assertEquals(0L, ContentUris.parseId(resultUri)); } // Stream item photo insertion test cases. public void testInsertStreamItemsAndPhotosInBatch() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues streamItemValues = buildGenericStreamItemValues(); ContentValues streamItemPhotoValues = buildGenericStreamItemPhotoValues(0); ArrayList<ContentProviderOperation> ops = Lists.newArrayList(); ops.add(ContentProviderOperation.newInsert( Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY)) .withValues(streamItemValues).build()); for (int i = 0; i < 5; i++) { streamItemPhotoValues.put(StreamItemPhotos.SORT_INDEX, i); ops.add(ContentProviderOperation.newInsert(StreamItems.CONTENT_PHOTO_URI) .withValues(streamItemPhotoValues) .withValueBackReference(StreamItemPhotos.STREAM_ITEM_ID, 0) .build()); } mResolver.applyBatch(ContactsContract.AUTHORITY, ops); // Check that all five photos were inserted under the raw contact. Cursor c = mResolver.query(StreamItems.CONTENT_URI, new String[]{StreamItems._ID}, StreamItems.RAW_CONTACT_ID + "=?", new String[]{String.valueOf(rawContactId)}, null); long streamItemId = 0; try { assertEquals(1, c.getCount()); c.moveToFirst(); streamItemId = c.getLong(0); } finally { c.close(); } c = mResolver.query(Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), new String[]{StreamItemPhotos._ID, StreamItemPhotos.PHOTO_URI}, null, null, null); try { assertEquals(5, c.getCount()); byte[] expectedPhotoBytes = loadPhotoFromResource( R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO); while (c.moveToNext()) { String photoUri = c.getString(1); EvenMoreAsserts.assertImageRawData(getContext(), expectedPhotoBytes, mResolver.openInputStream(Uri.parse(photoUri))); } } finally { c.close(); } } // Stream item update test cases. public void testUpdateStreamItemById() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, values, null); long streamItemId = ContentUris.parseId(resultUri); values.put(StreamItems.TEXT, "Goodbye world"); mResolver.update(ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), values, null, null); assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), values); } public void testUpdateStreamItemWithContentValues() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, values, null); long streamItemId = ContentUris.parseId(resultUri); values.put(StreamItems._ID, streamItemId); values.put(StreamItems.TEXT, "Goodbye world"); mResolver.update(StreamItems.CONTENT_URI, values, null, null); assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), values); } // Stream item photo update test cases. public void testUpdateStreamItemPhotoById() throws IOException { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, values, null); long streamItemId = ContentUris.parseId(resultUri); ContentValues photoValues = buildGenericStreamItemPhotoValues(1); resultUri = insertStreamItemPhoto(streamItemId, photoValues, null); long streamItemPhotoId = ContentUris.parseId(resultUri); photoValues.put(StreamItemPhotos.PHOTO, loadPhotoFromResource( R.drawable.nebula, PhotoSize.ORIGINAL)); Uri photoUri = ContentUris.withAppendedId( Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), streamItemPhotoId); mResolver.update(photoUri, photoValues, null, null); photoValues.remove(StreamItemPhotos.PHOTO); // Removed during processing. assertStoredValues(photoUri, photoValues); // Check that the photo stored is the expected one. String displayPhotoUri = getStoredValue(photoUri, StreamItemPhotos.PHOTO_URI); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.nebula, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(Uri.parse(displayPhotoUri))); } public void testUpdateStreamItemPhotoWithContentValues() throws IOException { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, values, null); long streamItemId = ContentUris.parseId(resultUri); ContentValues photoValues = buildGenericStreamItemPhotoValues(1); resultUri = insertStreamItemPhoto(streamItemId, photoValues, null); long streamItemPhotoId = ContentUris.parseId(resultUri); photoValues.put(StreamItemPhotos._ID, streamItemPhotoId); photoValues.put(StreamItemPhotos.PHOTO, loadPhotoFromResource( R.drawable.nebula, PhotoSize.ORIGINAL)); Uri photoUri = Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY); mResolver.update(photoUri, photoValues, null, null); photoValues.remove(StreamItemPhotos.PHOTO); // Removed during processing. assertStoredValues(photoUri, photoValues); // Check that the photo stored is the expected one. String displayPhotoUri = getStoredValue(photoUri, StreamItemPhotos.PHOTO_URI); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.nebula, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(Uri.parse(displayPhotoUri))); } // Stream item deletion test cases. public void testDeleteStreamItemById() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues firstValues = buildGenericStreamItemValues(); Uri resultUri = insertStreamItem(rawContactId, firstValues, null); long firstStreamItemId = ContentUris.parseId(resultUri); ContentValues secondValues = buildGenericStreamItemValues(); secondValues.put(StreamItems.TEXT, "Goodbye world"); insertStreamItem(rawContactId, secondValues, null); // Delete the first stream item. mResolver.delete(ContentUris.withAppendedId(StreamItems.CONTENT_URI, firstStreamItemId), null, null); // Check that only the second item remains. assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), secondValues); } public void testDeleteStreamItemWithSelection() { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues firstValues = buildGenericStreamItemValues(); insertStreamItem(rawContactId, firstValues, null); ContentValues secondValues = buildGenericStreamItemValues(); secondValues.put(StreamItems.TEXT, "Goodbye world"); insertStreamItem(rawContactId, secondValues, null); // Delete the first stream item with a custom selection. mResolver.delete(StreamItems.CONTENT_URI, StreamItems.TEXT + "=?", new String[]{"Hello world"}); // Check that only the second item remains. assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), secondValues); } // Stream item photo deletion test cases. public void testDeleteStreamItemPhotoById() { long rawContactId = RawContactUtil.createRawContact(mResolver); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); long streamItemPhotoId = ContentUris.parseId( insertStreamItemPhoto(streamItemId, buildGenericStreamItemPhotoValues(0), null)); mResolver.delete( ContentUris.withAppendedId( Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), streamItemPhotoId), null, null); Cursor c = mResolver.query(StreamItems.CONTENT_PHOTO_URI, new String[]{StreamItemPhotos._ID}, StreamItemPhotos.STREAM_ITEM_ID + "=?", new String[]{String.valueOf(streamItemId)}, null); try { assertEquals("Expected photo to be deleted.", 0, c.getCount()); } finally { c.close(); } } public void testDeleteStreamItemPhotoWithSelection() { long rawContactId = RawContactUtil.createRawContact(mResolver); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); ContentValues firstPhotoValues = buildGenericStreamItemPhotoValues(0); ContentValues secondPhotoValues = buildGenericStreamItemPhotoValues(1); insertStreamItemPhoto(streamItemId, firstPhotoValues, null); firstPhotoValues.remove(StreamItemPhotos.PHOTO); // Removed while processing. insertStreamItemPhoto(streamItemId, secondPhotoValues, null); Uri photoUri = Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY); mResolver.delete(photoUri, StreamItemPhotos.SORT_INDEX + "=1", null); assertStoredValues(photoUri, firstPhotoValues); } public void testDeleteStreamItemsWhenRawContactDeleted() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri streamItemUri = insertStreamItem(rawContactId, buildGenericStreamItemValues(), mAccount); Uri streamItemPhotoUri = insertStreamItemPhoto(ContentUris.parseId(streamItemUri), buildGenericStreamItemPhotoValues(0), mAccount); mResolver.delete(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), null, null); ContentValues[] emptyValues = new ContentValues[0]; // The stream item and its photo should be gone. assertStoredValues(streamItemUri, emptyValues); assertStoredValues(streamItemPhotoUri, emptyValues); } public void testQueryStreamItemLimit() { ContentValues values = new ContentValues(); values.put(StreamItems.MAX_ITEMS, 5); assertStoredValues(StreamItems.CONTENT_LIMIT_URI, values); } // Tests for inserting or updating stream items as a side-effect of making status updates // (forward-compatibility of status updates into the new social stream API). public void testStreamItemInsertedOnStatusUpdate() { // This method of creating a raw contact automatically inserts a status update with // the status message "hacking". ContentValues values = new ContentValues(); long rawContactId = createRawContact(values, "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_CAMERA | StatusUpdates.CAPABILITY_HAS_VIDEO | StatusUpdates.CAPABILITY_HAS_VOICE); ContentValues expectedValues = new ContentValues(); expectedValues.put(StreamItems.RAW_CONTACT_ID, rawContactId); expectedValues.put(StreamItems.TEXT, "hacking"); assertStoredValues(RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.StreamItems.CONTENT_DIRECTORY).build(), expectedValues); } public void testStreamItemInsertedOnStatusUpdate_HtmlQuoting() { // This method of creating a raw contact automatically inserts a status update with // the status message "hacking". ContentValues values = new ContentValues(); long rawContactId = createRawContact(values, "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_VOICE); // Insert a new status update for the raw contact. insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.INVISIBLE, "& <b> test &#39;", StatusUpdates.CAPABILITY_HAS_VOICE); ContentValues expectedValues = new ContentValues(); expectedValues.put(StreamItems.RAW_CONTACT_ID, rawContactId); expectedValues.put(StreamItems.TEXT, "&amp; &lt;b&gt; test &amp;#39;"); assertStoredValues(RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.StreamItems.CONTENT_DIRECTORY).build(), expectedValues); } public void testStreamItemUpdatedOnSecondStatusUpdate() { // This method of creating a raw contact automatically inserts a status update with // the status message "hacking". ContentValues values = new ContentValues(); int chatMode = StatusUpdates.CAPABILITY_HAS_CAMERA | StatusUpdates.CAPABILITY_HAS_VIDEO | StatusUpdates.CAPABILITY_HAS_VOICE; long rawContactId = createRawContact(values, "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, chatMode); // Insert a new status update for the raw contact. insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.INVISIBLE, "finished hacking", chatMode); ContentValues expectedValues = new ContentValues(); expectedValues.put(StreamItems.RAW_CONTACT_ID, rawContactId); expectedValues.put(StreamItems.TEXT, "finished hacking"); assertStoredValues(RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.StreamItems.CONTENT_DIRECTORY).build(), expectedValues); } public void testStreamItemReadRequiresReadSocialStreamPermission() { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); String lookupKey = queryLookupKey(contactId); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); mActor.removePermissions("android.permission.READ_SOCIAL_STREAM"); // Try selecting the stream item in various ways. expectSecurityException( "Querying stream items by contact ID requires social stream read permission", Uri.withAppendedPath( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.StreamItems.CONTENT_DIRECTORY), null, null, null, null); expectSecurityException( "Querying stream items by lookup key requires social stream read permission", Contacts.CONTENT_LOOKUP_URI.buildUpon().appendPath(lookupKey) .appendPath(Contacts.StreamItems.CONTENT_DIRECTORY).build(), null, null, null, null); expectSecurityException( "Querying stream items by lookup key and ID requires social stream read permission", Uri.withAppendedPath(Contacts.getLookupUri(contactId, lookupKey), Contacts.StreamItems.CONTENT_DIRECTORY), null, null, null, null); expectSecurityException( "Querying stream items by raw contact ID requires social stream read permission", Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), null, null, null, null); expectSecurityException( "Querying stream items by raw contact ID and stream item ID requires social " + "stream read permission", ContentUris.withAppendedId( Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), streamItemId), null, null, null, null); expectSecurityException( "Querying all stream items requires social stream read permission", StreamItems.CONTENT_URI, null, null, null, null); expectSecurityException( "Querying stream item by ID requires social stream read permission", ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), null, null, null, null); } public void testStreamItemPhotoReadRequiresReadSocialStreamPermission() { long rawContactId = RawContactUtil.createRawContact(mResolver); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); long streamItemPhotoId = ContentUris.parseId( insertStreamItemPhoto(streamItemId, buildGenericStreamItemPhotoValues(0), null)); mActor.removePermissions("android.permission.READ_SOCIAL_STREAM"); // Try selecting the stream item photo in various ways. expectSecurityException( "Querying all stream item photos requires social stream read permission", StreamItems.CONTENT_URI.buildUpon() .appendPath(StreamItems.StreamItemPhotos.CONTENT_DIRECTORY).build(), null, null, null, null); expectSecurityException( "Querying all stream item photos requires social stream read permission", StreamItems.CONTENT_URI.buildUpon() .appendPath(String.valueOf(streamItemId)) .appendPath(StreamItems.StreamItemPhotos.CONTENT_DIRECTORY) .appendPath(String.valueOf(streamItemPhotoId)).build(), null, null, null, null); } public void testStreamItemModificationRequiresWriteSocialStreamPermission() { long rawContactId = RawContactUtil.createRawContact(mResolver); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); mActor.removePermissions("android.permission.WRITE_SOCIAL_STREAM"); try { insertStreamItem(rawContactId, buildGenericStreamItemValues(), null); fail("Should not be able to insert to stream without write social stream permission"); } catch (SecurityException expected) { } try { ContentValues values = new ContentValues(); values.put(StreamItems.TEXT, "Goodbye world"); mResolver.update(ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), values, null, null); fail("Should not be able to update stream without write social stream permission"); } catch (SecurityException expected) { } try { mResolver.delete(ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), null, null); fail("Should not be able to delete from stream without write social stream permission"); } catch (SecurityException expected) { } } public void testStreamItemPhotoModificationRequiresWriteSocialStreamPermission() { long rawContactId = RawContactUtil.createRawContact(mResolver); long streamItemId = ContentUris.parseId( insertStreamItem(rawContactId, buildGenericStreamItemValues(), null)); long streamItemPhotoId = ContentUris.parseId( insertStreamItemPhoto(streamItemId, buildGenericStreamItemPhotoValues(0), null)); mActor.removePermissions("android.permission.WRITE_SOCIAL_STREAM"); Uri photoUri = StreamItems.CONTENT_URI.buildUpon() .appendPath(String.valueOf(streamItemId)) .appendPath(StreamItems.StreamItemPhotos.CONTENT_DIRECTORY) .appendPath(String.valueOf(streamItemPhotoId)).build(); try { insertStreamItemPhoto(streamItemId, buildGenericStreamItemPhotoValues(1), null); fail("Should not be able to insert photos without write social stream permission"); } catch (SecurityException expected) { } try { ContentValues values = new ContentValues(); values.put(StreamItemPhotos.PHOTO, loadPhotoFromResource(R.drawable.galaxy, PhotoSize.ORIGINAL)); mResolver.update(photoUri, values, null, null); fail("Should not be able to update photos without write social stream permission"); } catch (SecurityException expected) { } try { mResolver.delete(photoUri, null, null); fail("Should not be able to delete photos without write social stream permission"); } catch (SecurityException expected) { } } public void testStatusUpdateDoesNotRequireReadOrWriteSocialStreamPermission() { int protocol1 = Im.PROTOCOL_GOOGLE_TALK; String handle1 = "[email protected]"; long rawContactId = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId, protocol1, null, handle1); mActor.removePermissions("android.permission.READ_SOCIAL_STREAM"); mActor.removePermissions("android.permission.WRITE_SOCIAL_STREAM"); insertStatusUpdate(protocol1, null, handle1, StatusUpdates.AVAILABLE, "Green", StatusUpdates.CAPABILITY_HAS_CAMERA); mActor.addPermissions("android.permission.READ_SOCIAL_STREAM"); ContentValues expectedValues = new ContentValues(); expectedValues.put(StreamItems.TEXT, "Green"); assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.StreamItems.CONTENT_DIRECTORY), expectedValues); } private ContentValues buildGenericStreamItemValues() { ContentValues values = new ContentValues(); values.put(StreamItems.TEXT, "Hello world"); values.put(StreamItems.TIMESTAMP, System.currentTimeMillis()); values.put(StreamItems.COMMENTS, "Reshared by 123 others"); return values; } private ContentValues buildGenericStreamItemPhotoValues(int sortIndex) { ContentValues values = new ContentValues(); values.put(StreamItemPhotos.SORT_INDEX, sortIndex); values.put(StreamItemPhotos.PHOTO, loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.ORIGINAL)); return values; } public void testSingleStatusUpdateRowPerContact() { int protocol1 = Im.PROTOCOL_GOOGLE_TALK; String handle1 = "[email protected]"; long rawContactId1 = RawContactUtil.createRawContact(mResolver); insertImHandle(rawContactId1, protocol1, null, handle1); insertStatusUpdate(protocol1, null, handle1, StatusUpdates.AVAILABLE, "Green", StatusUpdates.CAPABILITY_HAS_CAMERA); insertStatusUpdate(protocol1, null, handle1, StatusUpdates.AWAY, "Yellow", StatusUpdates.CAPABILITY_HAS_CAMERA); insertStatusUpdate(protocol1, null, handle1, StatusUpdates.INVISIBLE, "Red", StatusUpdates.CAPABILITY_HAS_CAMERA); Cursor c = queryContact(queryContactId(rawContactId1), new String[] {Contacts.CONTACT_PRESENCE, Contacts.CONTACT_STATUS}); assertEquals(1, c.getCount()); c.moveToFirst(); assertEquals(StatusUpdates.INVISIBLE, c.getInt(0)); assertEquals("Red", c.getString(1)); c.close(); } private void updateSendToVoicemailAndRingtone(long contactId, boolean sendToVoicemail, String ringtone) { ContentValues values = new ContentValues(); values.put(Contacts.SEND_TO_VOICEMAIL, sendToVoicemail); if (ringtone != null) { values.put(Contacts.CUSTOM_RINGTONE, ringtone); } final Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); int count = mResolver.update(uri, values, null, null); assertEquals(1, count); } private void updateSendToVoicemailAndRingtoneWithSelection(long contactId, boolean sendToVoicemail, String ringtone) { ContentValues values = new ContentValues(); values.put(Contacts.SEND_TO_VOICEMAIL, sendToVoicemail); if (ringtone != null) { values.put(Contacts.CUSTOM_RINGTONE, ringtone); } int count = mResolver.update(Contacts.CONTENT_URI, values, Contacts._ID + "=" + contactId, null); assertEquals(1, count); } private void assertSendToVoicemailAndRingtone(long contactId, boolean expectedSendToVoicemail, String expectedRingtone) { Cursor c = queryContact(contactId); assertTrue(c.moveToNext()); int sendToVoicemail = c.getInt(c.getColumnIndex(Contacts.SEND_TO_VOICEMAIL)); assertEquals(expectedSendToVoicemail ? 1 : 0, sendToVoicemail); String ringtone = c.getString(c.getColumnIndex(Contacts.CUSTOM_RINGTONE)); if (expectedRingtone == null) { assertNull(ringtone); } else { assertTrue(ArrayUtils.contains(expectedRingtone.split(","), ringtone)); } c.close(); } public void testContactVisibilityUpdateOnMembershipChange() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); assertVisibility(rawContactId, "0"); long visibleGroupId = createGroup(mAccount, "123", "Visible", 1); long invisibleGroupId = createGroup(mAccount, "567", "Invisible", 0); Uri membership1 = insertGroupMembership(rawContactId, visibleGroupId); assertVisibility(rawContactId, "1"); Uri membership2 = insertGroupMembership(rawContactId, invisibleGroupId); assertVisibility(rawContactId, "1"); mResolver.delete(membership1, null, null); assertVisibility(rawContactId, "0"); ContentValues values = new ContentValues(); values.put(GroupMembership.GROUP_ROW_ID, visibleGroupId); mResolver.update(membership2, values, null, null); assertVisibility(rawContactId, "1"); } private void assertVisibility(long rawContactId, String expectedValue) { assertStoredValue(Contacts.CONTENT_URI, Contacts._ID + "=" + queryContactId(rawContactId), null, Contacts.IN_VISIBLE_GROUP, expectedValue); } public void testSupplyingBothValuesAndParameters() throws Exception { Account account = new Account("account 1", "type%/:1"); Uri uri = ContactsContract.Groups.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.Groups.ACCOUNT_NAME, account.name) .appendQueryParameter(ContactsContract.Groups.ACCOUNT_TYPE, account.type) .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true") .build(); ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(uri); builder.withValue(ContactsContract.Groups.ACCOUNT_TYPE, account.type); builder.withValue(ContactsContract.Groups.ACCOUNT_NAME, account.name); builder.withValue(ContactsContract.Groups.SYSTEM_ID, "some id"); builder.withValue(ContactsContract.Groups.TITLE, "some name"); builder.withValue(ContactsContract.Groups.GROUP_VISIBLE, 1); mResolver.applyBatch(ContactsContract.AUTHORITY, Lists.newArrayList(builder.build())); builder = ContentProviderOperation.newInsert(uri); builder.withValue(ContactsContract.Groups.ACCOUNT_TYPE, account.type + "diff"); builder.withValue(ContactsContract.Groups.ACCOUNT_NAME, account.name); builder.withValue(ContactsContract.Groups.SYSTEM_ID, "some other id"); builder.withValue(ContactsContract.Groups.TITLE, "some other name"); builder.withValue(ContactsContract.Groups.GROUP_VISIBLE, 1); try { mResolver.applyBatch(ContactsContract.AUTHORITY, Lists.newArrayList(builder.build())); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException ex) { // Expected } } public void testContentEntityIterator() { // create multiple contacts and check that the selected ones are returned long id; long groupId1 = createGroup(mAccount, "gsid1", "title1"); long groupId2 = createGroup(mAccount, "gsid2", "title2"); id = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "c0"); insertGroupMembership(id, "gsid1"); insertEmail(id, "[email protected]"); insertPhoneNumber(id, "5551212c0"); long c1 = id = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "c1"); Uri id_1_0 = insertGroupMembership(id, "gsid1"); Uri id_1_1 = insertGroupMembership(id, "gsid2"); Uri id_1_2 = insertEmail(id, "[email protected]"); Uri id_1_3 = insertPhoneNumber(id, "5551212c1"); long c2 = id = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "c2"); Uri id_2_0 = insertGroupMembership(id, "gsid1"); Uri id_2_1 = insertEmail(id, "[email protected]"); Uri id_2_2 = insertPhoneNumber(id, "5551212c2"); long c3 = id = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "c3"); Uri id_3_0 = insertGroupMembership(id, groupId2); Uri id_3_1 = insertEmail(id, "[email protected]"); Uri id_3_2 = insertPhoneNumber(id, "5551212c3"); EntityIterator iterator = RawContacts.newEntityIterator(mResolver.query( TestUtil.maybeAddAccountQueryParameters(RawContactsEntity.CONTENT_URI, mAccount), null, RawContacts.SOURCE_ID + " in ('c1', 'c2', 'c3')", null, null)); Entity entity; ContentValues[] subValues; entity = iterator.next(); assertEquals(c1, (long) entity.getEntityValues().getAsLong(RawContacts._ID)); subValues = asSortedContentValuesArray(entity.getSubValues()); assertEquals(4, subValues.length); assertDataRow(subValues[0], GroupMembership.CONTENT_ITEM_TYPE, Data._ID, id_1_0, GroupMembership.GROUP_ROW_ID, groupId1, GroupMembership.GROUP_SOURCE_ID, "gsid1"); assertDataRow(subValues[1], GroupMembership.CONTENT_ITEM_TYPE, Data._ID, id_1_1, GroupMembership.GROUP_ROW_ID, groupId2, GroupMembership.GROUP_SOURCE_ID, "gsid2"); assertDataRow(subValues[2], Email.CONTENT_ITEM_TYPE, Data._ID, id_1_2, Email.DATA, "[email protected]"); assertDataRow(subValues[3], Phone.CONTENT_ITEM_TYPE, Data._ID, id_1_3, Email.DATA, "5551212c1"); entity = iterator.next(); assertEquals(c2, (long) entity.getEntityValues().getAsLong(RawContacts._ID)); subValues = asSortedContentValuesArray(entity.getSubValues()); assertEquals(3, subValues.length); assertDataRow(subValues[0], GroupMembership.CONTENT_ITEM_TYPE, Data._ID, id_2_0, GroupMembership.GROUP_ROW_ID, groupId1, GroupMembership.GROUP_SOURCE_ID, "gsid1"); assertDataRow(subValues[1], Email.CONTENT_ITEM_TYPE, Data._ID, id_2_1, Email.DATA, "[email protected]"); assertDataRow(subValues[2], Phone.CONTENT_ITEM_TYPE, Data._ID, id_2_2, Email.DATA, "5551212c2"); entity = iterator.next(); assertEquals(c3, (long) entity.getEntityValues().getAsLong(RawContacts._ID)); subValues = asSortedContentValuesArray(entity.getSubValues()); assertEquals(3, subValues.length); assertDataRow(subValues[0], GroupMembership.CONTENT_ITEM_TYPE, Data._ID, id_3_0, GroupMembership.GROUP_ROW_ID, groupId2, GroupMembership.GROUP_SOURCE_ID, "gsid2"); assertDataRow(subValues[1], Email.CONTENT_ITEM_TYPE, Data._ID, id_3_1, Email.DATA, "[email protected]"); assertDataRow(subValues[2], Phone.CONTENT_ITEM_TYPE, Data._ID, id_3_2, Email.DATA, "5551212c3"); assertFalse(iterator.hasNext()); iterator.close(); } public void testDataCreateUpdateDeleteByMimeType() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); ContentValues values = new ContentValues(); values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, "testmimetype"); values.put(Data.RES_PACKAGE, "oldpackage"); values.put(Data.IS_PRIMARY, 1); values.put(Data.IS_SUPER_PRIMARY, 1); values.put(Data.DATA1, "old1"); values.put(Data.DATA2, "old2"); values.put(Data.DATA3, "old3"); values.put(Data.DATA4, "old4"); values.put(Data.DATA5, "old5"); values.put(Data.DATA6, "old6"); values.put(Data.DATA7, "old7"); values.put(Data.DATA8, "old8"); values.put(Data.DATA9, "old9"); values.put(Data.DATA10, "old10"); values.put(Data.DATA11, "old11"); values.put(Data.DATA12, "old12"); values.put(Data.DATA13, "old13"); values.put(Data.DATA14, "old14"); values.put(Data.DATA15, "old15"); Uri uri = mResolver.insert(Data.CONTENT_URI, values); assertStoredValues(uri, values); assertNetworkNotified(true); values.clear(); values.put(Data.RES_PACKAGE, "newpackage"); values.put(Data.IS_PRIMARY, 0); values.put(Data.IS_SUPER_PRIMARY, 0); values.put(Data.DATA1, "new1"); values.put(Data.DATA2, "new2"); values.put(Data.DATA3, "new3"); values.put(Data.DATA4, "new4"); values.put(Data.DATA5, "new5"); values.put(Data.DATA6, "new6"); values.put(Data.DATA7, "new7"); values.put(Data.DATA8, "new8"); values.put(Data.DATA9, "new9"); values.put(Data.DATA10, "new10"); values.put(Data.DATA11, "new11"); values.put(Data.DATA12, "new12"); values.put(Data.DATA13, "new13"); values.put(Data.DATA14, "new14"); values.put(Data.DATA15, "new15"); mResolver.update(Data.CONTENT_URI, values, Data.RAW_CONTACT_ID + "=" + rawContactId + " AND " + Data.MIMETYPE + "='testmimetype'", null); assertNetworkNotified(true); assertStoredValues(uri, values); int count = mResolver.delete(Data.CONTENT_URI, Data.RAW_CONTACT_ID + "=" + rawContactId + " AND " + Data.MIMETYPE + "='testmimetype'", null); assertEquals(1, count); assertEquals(0, getCount(Data.CONTENT_URI, Data.RAW_CONTACT_ID + "=" + rawContactId + " AND " + Data.MIMETYPE + "='testmimetype'", null)); assertNetworkNotified(true); } public void testRawContactQuery() { Account account1 = new Account("a", "b"); Account account2 = new Account("c", "d"); long rawContactId1 = RawContactUtil.createRawContact(mResolver, account1); long rawContactId2 = RawContactUtil.createRawContact(mResolver, account2); Uri uri1 = TestUtil.maybeAddAccountQueryParameters(RawContacts.CONTENT_URI, account1); Uri uri2 = TestUtil.maybeAddAccountQueryParameters(RawContacts.CONTENT_URI, account2); assertEquals(1, getCount(uri1, null, null)); assertEquals(1, getCount(uri2, null, null)); assertStoredValue(uri1, RawContacts._ID, rawContactId1) ; assertStoredValue(uri2, RawContacts._ID, rawContactId2) ; Uri rowUri1 = ContentUris.withAppendedId(uri1, rawContactId1); Uri rowUri2 = ContentUris.withAppendedId(uri2, rawContactId2); assertStoredValue(rowUri1, RawContacts._ID, rawContactId1) ; assertStoredValue(rowUri2, RawContacts._ID, rawContactId2) ; } public void testRawContactDeletion() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); insertImHandle(rawContactId, Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]"); insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.AVAILABLE, null, StatusUpdates.CAPABILITY_HAS_CAMERA); long contactId = queryContactId(rawContactId); assertEquals(1, getCount(Uri.withAppendedPath(uri, RawContacts.Data.CONTENT_DIRECTORY), null, null)); assertEquals(1, getCount(StatusUpdates.CONTENT_URI, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId, null)); mResolver.delete(uri, null, null); assertStoredValue(uri, RawContacts.DELETED, "1"); assertNetworkNotified(true); Uri permanentDeletionUri = setCallerIsSyncAdapter(uri, mAccount); mResolver.delete(permanentDeletionUri, null, null); assertEquals(0, getCount(uri, null, null)); assertEquals(0, getCount(Uri.withAppendedPath(uri, RawContacts.Data.CONTENT_DIRECTORY), null, null)); assertEquals(0, getCount(StatusUpdates.CONTENT_URI, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId, null)); assertEquals(0, getCount(Contacts.CONTENT_URI, Contacts._ID + "=" + contactId, null)); assertNetworkNotified(false); } public void testRawContactDeletionKeepingAggregateContact() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, mAccount); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, mAccount); setAggregationException( AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); long contactId = queryContactId(rawContactId1); Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId1); Uri permanentDeletionUri = setCallerIsSyncAdapter(uri, mAccount); mResolver.delete(permanentDeletionUri, null, null); assertEquals(0, getCount(uri, null, null)); assertEquals(1, getCount(Contacts.CONTENT_URI, Contacts._ID + "=" + contactId, null)); } public void testRawContactDeletion_byAccountParam() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); insertImHandle(rawContactId, Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]"); insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.AVAILABLE, null, StatusUpdates.CAPABILITY_HAS_CAMERA); assertEquals(1, getCount(Uri.withAppendedPath(uri, RawContacts.Data.CONTENT_DIRECTORY), null, null)); assertEquals(1, getCount(StatusUpdates.CONTENT_URI, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId, null)); // Do not delete if we are deleting with wrong account. Uri deleteWithWrongAccountUri = RawContacts.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, mAccountTwo.name) .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, mAccountTwo.type) .build(); int numDeleted = mResolver.delete(deleteWithWrongAccountUri, null, null); assertEquals(0, numDeleted); assertStoredValue(uri, RawContacts.DELETED, "0"); // Delete if we are deleting with correct account. Uri deleteWithCorrectAccountUri = RawContacts.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, mAccount.name) .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, mAccount.type) .build(); numDeleted = mResolver.delete(deleteWithCorrectAccountUri, null, null); assertEquals(1, numDeleted); assertStoredValue(uri, RawContacts.DELETED, "1"); } public void testRawContactDeletion_byAccountSelection() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); // Do not delete if we are deleting with wrong account. int numDeleted = mResolver.delete(RawContacts.CONTENT_URI, RawContacts.ACCOUNT_NAME + "=? AND " + RawContacts.ACCOUNT_TYPE + "=?", new String[] {mAccountTwo.name, mAccountTwo.type}); assertEquals(0, numDeleted); assertStoredValue(uri, RawContacts.DELETED, "0"); // Delete if we are deleting with correct account. numDeleted = mResolver.delete(RawContacts.CONTENT_URI, RawContacts.ACCOUNT_NAME + "=? AND " + RawContacts.ACCOUNT_TYPE + "=?", new String[] {mAccount.name, mAccount.type}); assertEquals(1, numDeleted); assertStoredValue(uri, RawContacts.DELETED, "1"); } /** * Test for {@link ContactsProvider2#stringToAccounts} and * {@link ContactsProvider2#accountsToString}. */ public void testAccountsToString() { final Set<Account> EXPECTED_0 = Sets.newHashSet(); final Set<Account> EXPECTED_1 = Sets.newHashSet(TestUtil.ACCOUNT_1); final Set<Account> EXPECTED_2 = Sets.newHashSet(TestUtil.ACCOUNT_2); final Set<Account> EXPECTED_1_2 = Sets.newHashSet(TestUtil.ACCOUNT_1, TestUtil.ACCOUNT_2); final Set<Account> ACTUAL_0 = Sets.newHashSet(); final Set<Account> ACTUAL_1 = Sets.newHashSet(TestUtil.ACCOUNT_1); final Set<Account> ACTUAL_2 = Sets.newHashSet(TestUtil.ACCOUNT_2); final Set<Account> ACTUAL_1_2 = Sets.newHashSet(TestUtil.ACCOUNT_2, TestUtil.ACCOUNT_1); assertTrue(EXPECTED_0.equals(accountsToStringToAccounts(ACTUAL_0))); assertFalse(EXPECTED_0.equals(accountsToStringToAccounts(ACTUAL_1))); assertFalse(EXPECTED_0.equals(accountsToStringToAccounts(ACTUAL_2))); assertFalse(EXPECTED_0.equals(accountsToStringToAccounts(ACTUAL_1_2))); assertFalse(EXPECTED_1.equals(accountsToStringToAccounts(ACTUAL_0))); assertTrue(EXPECTED_1.equals(accountsToStringToAccounts(ACTUAL_1))); assertFalse(EXPECTED_1.equals(accountsToStringToAccounts(ACTUAL_2))); assertFalse(EXPECTED_1.equals(accountsToStringToAccounts(ACTUAL_1_2))); assertFalse(EXPECTED_2.equals(accountsToStringToAccounts(ACTUAL_0))); assertFalse(EXPECTED_2.equals(accountsToStringToAccounts(ACTUAL_1))); assertTrue(EXPECTED_2.equals(accountsToStringToAccounts(ACTUAL_2))); assertFalse(EXPECTED_2.equals(accountsToStringToAccounts(ACTUAL_1_2))); assertFalse(EXPECTED_1_2.equals(accountsToStringToAccounts(ACTUAL_0))); assertFalse(EXPECTED_1_2.equals(accountsToStringToAccounts(ACTUAL_1))); assertFalse(EXPECTED_1_2.equals(accountsToStringToAccounts(ACTUAL_2))); assertTrue(EXPECTED_1_2.equals(accountsToStringToAccounts(ACTUAL_1_2))); try { ContactsProvider2.stringToAccounts("x"); fail("Didn't throw for malformed input"); } catch (IllegalArgumentException expected) { } } private static final Set<Account> accountsToStringToAccounts(Set<Account> accounts) { return ContactsProvider2.stringToAccounts(ContactsProvider2.accountsToString(accounts)); } /** * Test for {@link ContactsProvider2#haveAccountsChanged} and * {@link ContactsProvider2#saveAccounts}. */ public void testHaveAccountsChanged() { final ContactsProvider2 cp = (ContactsProvider2) getProvider(); final Account[] ACCOUNTS_0 = new Account[] {}; final Account[] ACCOUNTS_1 = new Account[] {TestUtil.ACCOUNT_1}; final Account[] ACCOUNTS_2 = new Account[] {TestUtil.ACCOUNT_2}; final Account[] ACCOUNTS_1_2 = new Account[] {TestUtil.ACCOUNT_1, TestUtil.ACCOUNT_2}; final Account[] ACCOUNTS_2_1 = new Account[] {TestUtil.ACCOUNT_2, TestUtil.ACCOUNT_1}; // Add ACCOUNT_1 assertTrue(cp.haveAccountsChanged(ACCOUNTS_1)); cp.saveAccounts(ACCOUNTS_1); assertFalse(cp.haveAccountsChanged(ACCOUNTS_1)); // Add ACCOUNT_2 assertTrue(cp.haveAccountsChanged(ACCOUNTS_1_2)); // (try with reverse order) assertTrue(cp.haveAccountsChanged(ACCOUNTS_2_1)); cp.saveAccounts(ACCOUNTS_1_2); assertFalse(cp.haveAccountsChanged(ACCOUNTS_1_2)); // (try with reverse order) assertFalse(cp.haveAccountsChanged(ACCOUNTS_2_1)); // Remove ACCOUNT_1 assertTrue(cp.haveAccountsChanged(ACCOUNTS_2)); cp.saveAccounts(ACCOUNTS_2); assertFalse(cp.haveAccountsChanged(ACCOUNTS_2)); // Remove ACCOUNT_2 assertTrue(cp.haveAccountsChanged(ACCOUNTS_0)); cp.saveAccounts(ACCOUNTS_0); assertFalse(cp.haveAccountsChanged(ACCOUNTS_0)); // Test with malformed DB property. final ContactsDatabaseHelper dbHelper = cp.getThreadActiveDatabaseHelperForTest(); dbHelper.setProperty(DbProperties.KNOWN_ACCOUNTS, "x"); // With malformed property the method always return true. assertTrue(cp.haveAccountsChanged(ACCOUNTS_0)); assertTrue(cp.haveAccountsChanged(ACCOUNTS_1)); } public void testAccountsUpdated() { // This is to ensure we do not delete contacts with null, null (account name, type) // accidentally. long rawContactId3 = RawContactUtil.createRawContactWithName(mResolver, "James", "Sullivan"); insertPhoneNumber(rawContactId3, "5234567890"); Uri rawContact3 = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId3); assertEquals(1, getCount(RawContacts.CONTENT_URI, null, null)); ContactsProvider2 cp = (ContactsProvider2) getProvider(); mActor.setAccounts(new Account[]{mAccount, mAccountTwo}); cp.onAccountsUpdated(new Account[]{mAccount, mAccountTwo}); assertEquals(1, getCount(RawContacts.CONTENT_URI, null, null)); assertStoredValue(rawContact3, RawContacts.ACCOUNT_NAME, null); assertStoredValue(rawContact3, RawContacts.ACCOUNT_TYPE, null); long rawContactId1 = RawContactUtil.createRawContact(mResolver, mAccount); insertEmail(rawContactId1, "[email protected]"); long rawContactId2 = RawContactUtil.createRawContact(mResolver, mAccountTwo); insertEmail(rawContactId2, "[email protected]"); insertImHandle(rawContactId2, Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]"); insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, "[email protected]", StatusUpdates.AVAILABLE, null, StatusUpdates.CAPABILITY_HAS_CAMERA); mActor.setAccounts(new Account[]{mAccount}); cp.onAccountsUpdated(new Account[]{mAccount}); assertEquals(2, getCount(RawContacts.CONTENT_URI, null, null)); assertEquals(0, getCount(StatusUpdates.CONTENT_URI, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId2, null)); } public void testAccountDeletion() { Account readOnlyAccount = new Account("act", READ_ONLY_ACCOUNT_TYPE); ContactsProvider2 cp = (ContactsProvider2) getProvider(); mActor.setAccounts(new Account[]{readOnlyAccount, mAccount}); cp.onAccountsUpdated(new Account[]{readOnlyAccount, mAccount}); long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "John", "Doe", readOnlyAccount); Uri photoUri1 = insertPhoto(rawContactId1); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "john", "doe", mAccount); Uri photoUri2 = insertPhoto(rawContactId2); storeValue(photoUri2, Photo.IS_SUPER_PRIMARY, "1"); assertAggregated(rawContactId1, rawContactId2); long contactId = queryContactId(rawContactId1); // The display name should come from the writable account assertStoredValue(Uri.withAppendedPath( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.Data.CONTENT_DIRECTORY), Contacts.DISPLAY_NAME, "john doe"); // The photo should be the one we marked as super-primary assertStoredValue(Contacts.CONTENT_URI, contactId, Contacts.PHOTO_ID, ContentUris.parseId(photoUri2)); mActor.setAccounts(new Account[]{readOnlyAccount}); // Remove the writable account cp.onAccountsUpdated(new Account[]{readOnlyAccount}); // The display name should come from the remaining account assertStoredValue(Uri.withAppendedPath( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.Data.CONTENT_DIRECTORY), Contacts.DISPLAY_NAME, "John Doe"); // The photo should be the remaining one assertStoredValue(Contacts.CONTENT_URI, contactId, Contacts.PHOTO_ID, ContentUris.parseId(photoUri1)); } public void testStreamItemsCleanedUpOnAccountRemoval() { Account doomedAccount = new Account("doom", "doom"); Account safeAccount = mAccount; ContactsProvider2 cp = (ContactsProvider2) getProvider(); mActor.setAccounts(new Account[]{doomedAccount, safeAccount}); cp.onAccountsUpdated(new Account[]{doomedAccount, safeAccount}); // Create a doomed raw contact, stream item, and photo. long doomedRawContactId = RawContactUtil.createRawContactWithName(mResolver, doomedAccount); Uri doomedStreamItemUri = insertStreamItem(doomedRawContactId, buildGenericStreamItemValues(), doomedAccount); long doomedStreamItemId = ContentUris.parseId(doomedStreamItemUri); Uri doomedStreamItemPhotoUri = insertStreamItemPhoto( doomedStreamItemId, buildGenericStreamItemPhotoValues(0), doomedAccount); // Create a safe raw contact, stream item, and photo. long safeRawContactId = RawContactUtil.createRawContactWithName(mResolver, safeAccount); Uri safeStreamItemUri = insertStreamItem(safeRawContactId, buildGenericStreamItemValues(), safeAccount); long safeStreamItemId = ContentUris.parseId(safeStreamItemUri); Uri safeStreamItemPhotoUri = insertStreamItemPhoto( safeStreamItemId, buildGenericStreamItemPhotoValues(0), safeAccount); long safeStreamItemPhotoId = ContentUris.parseId(safeStreamItemPhotoUri); // Remove the doomed account. mActor.setAccounts(new Account[]{safeAccount}); cp.onAccountsUpdated(new Account[]{safeAccount}); // Check that the doomed stuff has all been nuked. ContentValues[] noValues = new ContentValues[0]; assertStoredValues(ContentUris.withAppendedId(RawContacts.CONTENT_URI, doomedRawContactId), noValues); assertStoredValues(doomedStreamItemUri, noValues); assertStoredValues(doomedStreamItemPhotoUri, noValues); // Check that the safe stuff lives on. assertStoredValue(RawContacts.CONTENT_URI, safeRawContactId, RawContacts._ID, safeRawContactId); assertStoredValue(safeStreamItemUri, StreamItems._ID, safeStreamItemId); assertStoredValue(safeStreamItemPhotoUri, StreamItemPhotos._ID, safeStreamItemPhotoId); } public void testContactDeletion() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver, "John", "Doe", TestUtil.ACCOUNT_1); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver, "John", "Doe", TestUtil.ACCOUNT_2); long contactId = queryContactId(rawContactId1); mResolver.delete(ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), null, null); assertStoredValue(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId1), RawContacts.DELETED, "1"); assertStoredValue(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId2), RawContacts.DELETED, "1"); } public void testMarkAsDirtyParameter() { long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); Uri uri = DataUtil.insertStructuredName(mResolver, rawContactId, "John", "Doe"); clearDirty(rawContactUri); Uri updateUri = setCallerIsSyncAdapter(uri, mAccount); ContentValues values = new ContentValues(); values.put(StructuredName.FAMILY_NAME, "Dough"); mResolver.update(updateUri, values, null, null); assertStoredValue(uri, StructuredName.FAMILY_NAME, "Dough"); assertDirty(rawContactUri, false); assertNetworkNotified(false); } public void testRawContactDirtyAndVersion() { final long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, rawContactId); assertDirty(uri, false); long version = getVersion(uri); ContentValues values = new ContentValues(); values.put(ContactsContract.RawContacts.DIRTY, 0); values.put(ContactsContract.RawContacts.SEND_TO_VOICEMAIL, 1); values.put(ContactsContract.RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_IMMEDIATE); values.put(ContactsContract.RawContacts.STARRED, 1); assertEquals(1, mResolver.update(uri, values, null, null)); assertEquals(version, getVersion(uri)); assertDirty(uri, false); assertNetworkNotified(false); Uri emailUri = insertEmail(rawContactId, "[email protected]"); assertDirty(uri, true); assertNetworkNotified(true); ++version; assertEquals(version, getVersion(uri)); clearDirty(uri); values = new ContentValues(); values.put(Email.DATA, "[email protected]"); mResolver.update(emailUri, values, null, null); assertDirty(uri, true); assertNetworkNotified(true); ++version; assertEquals(version, getVersion(uri)); clearDirty(uri); mResolver.delete(emailUri, null, null); assertDirty(uri, true); assertNetworkNotified(true); ++version; assertEquals(version, getVersion(uri)); } public void testRawContactClearDirty() { final long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, rawContactId); long version = getVersion(uri); insertEmail(rawContactId, "[email protected]"); assertDirty(uri, true); version++; assertEquals(version, getVersion(uri)); clearDirty(uri); assertDirty(uri, false); assertEquals(version, getVersion(uri)); } public void testRawContactDeletionSetsDirty() { final long rawContactId = RawContactUtil.createRawContact(mResolver, mAccount); Uri uri = ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, rawContactId); long version = getVersion(uri); clearDirty(uri); assertDirty(uri, false); mResolver.delete(uri, null, null); assertStoredValue(uri, RawContacts.DELETED, "1"); assertDirty(uri, true); assertNetworkNotified(true); version++; assertEquals(version, getVersion(uri)); } public void testDeleteContactWithoutName() { Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, new ContentValues()); long rawContactId = ContentUris.parseId(rawContactUri); Uri phoneUri = insertPhoneNumber(rawContactId, "555-123-45678", true); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri lookupUri = Contacts.getLookupUri(mResolver, contactUri); int numDeleted = mResolver.delete(lookupUri, null, null); assertEquals(1, numDeleted); } public void testDeleteContactWithoutAnyData() { Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, new ContentValues()); long rawContactId = ContentUris.parseId(rawContactUri); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri lookupUri = Contacts.getLookupUri(mResolver, contactUri); int numDeleted = mResolver.delete(lookupUri, null, null); assertEquals(1, numDeleted); } public void testDeleteContactWithEscapedUri() { ContentValues values = new ContentValues(); values.put(RawContacts.SOURCE_ID, "!@#$%^&*()_+=-/.,<>?;'\":[]}{\\|`~"); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri lookupUri = Contacts.getLookupUri(mResolver, contactUri); assertEquals(1, mResolver.delete(lookupUri, null, null)); } public void testQueryContactWithEscapedUri() { ContentValues values = new ContentValues(); values.put(RawContacts.SOURCE_ID, "!@#$%^&*()_+=-/.,<>?;'\":[]}{\\|`~"); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri lookupUri = Contacts.getLookupUri(mResolver, contactUri); Cursor c = mResolver.query(lookupUri, null, null, null, ""); assertEquals(1, c.getCount()); c.close(); } public void testGetPhotoUri() { ContentValues values = new ContentValues(); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); DataUtil.insertStructuredName(mResolver, rawContactId, "John", "Doe"); long dataId = ContentUris.parseId(insertPhoto(rawContactId, R.drawable.earth_normal)); long photoFileId = getStoredLongValue(Data.CONTENT_URI, Data._ID + "=?", new String[]{String.valueOf(dataId)}, Photo.PHOTO_FILE_ID); String photoUri = ContentUris.withAppendedId(DisplayPhoto.CONTENT_URI, photoFileId) .toString(); assertStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId)), Contacts.PHOTO_URI, photoUri); } public void testGetPhotoViaLookupUri() throws IOException { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri lookupUri = Contacts.getLookupUri(mResolver, contactUri); String lookupKey = lookupUri.getPathSegments().get(2); insertPhoto(rawContactId, R.drawable.earth_small); byte[] thumbnail = loadPhotoFromResource(R.drawable.earth_small, PhotoSize.THUMBNAIL); // Two forms of lookup key URIs should be valid - one with the contact ID, one without. Uri photoLookupUriWithId = Uri.withAppendedPath(lookupUri, "photo"); Uri photoLookupUriWithoutId = Contacts.CONTENT_LOOKUP_URI.buildUpon() .appendPath(lookupKey).appendPath("photo").build(); // Try retrieving as a data record. ContentValues values = new ContentValues(); values.put(Photo.PHOTO, thumbnail); assertStoredValues(photoLookupUriWithId, values); assertStoredValues(photoLookupUriWithoutId, values); // Try opening as an input stream. EvenMoreAsserts.assertImageRawData(getContext(), thumbnail, mResolver.openInputStream(photoLookupUriWithId)); EvenMoreAsserts.assertImageRawData(getContext(), thumbnail, mResolver.openInputStream(photoLookupUriWithoutId)); } public void testInputStreamForPhoto() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); insertPhoto(rawContactId); Uri photoUri = Uri.parse(getStoredValue(contactUri, Contacts.PHOTO_URI)); Uri photoThumbnailUri = Uri.parse(getStoredValue(contactUri, Contacts.PHOTO_THUMBNAIL_URI)); // Check the thumbnail. EvenMoreAsserts.assertImageRawData(getContext(), loadTestPhoto(PhotoSize.THUMBNAIL), mResolver.openInputStream(photoThumbnailUri)); // Then check the display photo. Note because we only inserted a small photo, but not a // display photo, this returns the thumbnail image itself, which was compressed at // the thumnail compression rate, which is why we compare to // loadTestPhoto(PhotoSize.THUMBNAIL) rather than loadTestPhoto(PhotoSize.DISPLAY_PHOTO) // here. // (In other words, loadTestPhoto(PhotoSize.DISPLAY_PHOTO) returns the same photo as // loadTestPhoto(PhotoSize.THUMBNAIL), except it's compressed at a lower compression rate.) EvenMoreAsserts.assertImageRawData(getContext(), loadTestPhoto(PhotoSize.THUMBNAIL), mResolver.openInputStream(photoUri)); } public void testSuperPrimaryPhoto() { long rawContactId1 = RawContactUtil.createRawContact(mResolver, new Account("a", "a")); Uri photoUri1 = insertPhoto(rawContactId1, R.drawable.earth_normal); long photoId1 = ContentUris.parseId(photoUri1); long rawContactId2 = RawContactUtil.createRawContact(mResolver, new Account("b", "b")); Uri photoUri2 = insertPhoto(rawContactId2, R.drawable.earth_normal); long photoId2 = ContentUris.parseId(photoUri2); setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId1)); long photoFileId1 = getStoredLongValue(Data.CONTENT_URI, Data._ID + "=?", new String[]{String.valueOf(photoId1)}, Photo.PHOTO_FILE_ID); String photoUri = ContentUris.withAppendedId(DisplayPhoto.CONTENT_URI, photoFileId1) .toString(); assertStoredValue(contactUri, Contacts.PHOTO_ID, photoId1); assertStoredValue(contactUri, Contacts.PHOTO_URI, photoUri); setAggregationException(AggregationExceptions.TYPE_KEEP_SEPARATE, rawContactId1, rawContactId2); ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 1); mResolver.update(photoUri2, values, null, null); setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId1)); assertStoredValue(contactUri, Contacts.PHOTO_ID, photoId2); mResolver.update(photoUri1, values, null, null); assertStoredValue(contactUri, Contacts.PHOTO_ID, photoId1); } public void testUpdatePhoto() { ContentValues values = new ContentValues(); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); DataUtil.insertStructuredName(mResolver, rawContactId, "John", "Doe"); Uri twigUri = Uri.withAppendedPath(ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(rawContactId)), Contacts.Photo.CONTENT_DIRECTORY); values.clear(); values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); values.putNull(Photo.PHOTO); Uri dataUri = mResolver.insert(Data.CONTENT_URI, values); long photoId = ContentUris.parseId(dataUri); assertEquals(0, getCount(twigUri, null, null)); values.clear(); values.put(Photo.PHOTO, loadTestPhoto()); mResolver.update(dataUri, values, null, null); assertNetworkNotified(true); long twigId = getStoredLongValue(twigUri, Data._ID); assertEquals(photoId, twigId); } public void testUpdateRawContactDataPhoto() { // setup a contact with a null photo ContentValues values = new ContentValues(); Uri rawContactUri = mResolver.insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); // setup a photo values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); values.putNull(Photo.PHOTO); // try to do an update before insert should return count == 0 Uri dataUri = Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.Data.CONTENT_DIRECTORY); assertEquals(0, mResolver.update(dataUri, values, Data.MIMETYPE + "=?", new String[] {Photo.CONTENT_ITEM_TYPE})); mResolver.insert(Data.CONTENT_URI, values); // save a photo to the db values.clear(); values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); values.put(Photo.PHOTO, loadTestPhoto()); assertEquals(1, mResolver.update(dataUri, values, Data.MIMETYPE + "=?", new String[] {Photo.CONTENT_ITEM_TYPE})); // verify the photo Cursor storedPhoto = mResolver.query(dataUri, new String[] {Photo.PHOTO}, Data.MIMETYPE + "=?", new String[] {Photo.CONTENT_ITEM_TYPE}, null); storedPhoto.moveToFirst(); MoreAsserts.assertEquals(loadTestPhoto(PhotoSize.THUMBNAIL), storedPhoto.getBlob(0)); storedPhoto.close(); } public void testOpenDisplayPhotoForContactId() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); insertPhoto(rawContactId, R.drawable.earth_normal); Uri photoUri = Contacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(contactId)) .appendPath(Contacts.Photo.DISPLAY_PHOTO).build(); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(photoUri)); } public void testOpenDisplayPhotoForContactLookupKey() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); String lookupKey = queryLookupKey(contactId); insertPhoto(rawContactId, R.drawable.earth_normal); Uri photoUri = Contacts.CONTENT_LOOKUP_URI.buildUpon() .appendPath(lookupKey) .appendPath(Contacts.Photo.DISPLAY_PHOTO).build(); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(photoUri)); } public void testOpenDisplayPhotoForContactLookupKeyAndId() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); String lookupKey = queryLookupKey(contactId); insertPhoto(rawContactId, R.drawable.earth_normal); Uri photoUri = Contacts.CONTENT_LOOKUP_URI.buildUpon() .appendPath(lookupKey) .appendPath(String.valueOf(contactId)) .appendPath(Contacts.Photo.DISPLAY_PHOTO).build(); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(photoUri)); } public void testOpenDisplayPhotoForRawContactId() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); insertPhoto(rawContactId, R.drawable.earth_normal); Uri photoUri = RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.DisplayPhoto.CONTENT_DIRECTORY).build(); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(photoUri)); } public void testOpenDisplayPhotoByPhotoUri() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); insertPhoto(rawContactId, R.drawable.earth_normal); // Get the photo URI out and check the content. String photoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(Uri.parse(photoUri))); } public void testPhotoUriForDisplayPhoto() { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); // Photo being inserted is larger than a thumbnail, so it will be stored as a file. long dataId = ContentUris.parseId(insertPhoto(rawContactId, R.drawable.earth_normal)); String photoFileId = getStoredValue(ContentUris.withAppendedId(Data.CONTENT_URI, dataId), Photo.PHOTO_FILE_ID); String photoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); // Check that the photo URI differs from the thumbnail. String thumbnailUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_THUMBNAIL_URI); assertFalse(photoUri.equals(thumbnailUri)); // URI should be of the form display_photo/ID assertEquals(Uri.withAppendedPath(DisplayPhoto.CONTENT_URI, photoFileId).toString(), photoUri); } public void testPhotoUriForThumbnailPhoto() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); // Photo being inserted is a thumbnail, so it will only be stored in a BLOB. The photo URI // will fall back to the thumbnail URI. insertPhoto(rawContactId, R.drawable.earth_small); String photoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); // Check that the photo URI is equal to the thumbnail URI. String thumbnailUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_THUMBNAIL_URI); assertEquals(photoUri, thumbnailUri); // URI should be of the form contacts/ID/photo assertEquals(Uri.withAppendedPath( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.Photo.CONTENT_DIRECTORY).toString(), photoUri); // Loading the photo URI content should get the thumbnail. EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_small, PhotoSize.THUMBNAIL), mResolver.openInputStream(Uri.parse(photoUri))); } public void testWriteNewPhotoToAssetFile() throws Exception { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); // Load in a huge photo. final byte[] originalPhoto = loadPhotoFromResource( R.drawable.earth_huge, PhotoSize.ORIGINAL); // Write it out. final Uri writeablePhotoUri = RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.DisplayPhoto.CONTENT_DIRECTORY).build(); writePhotoAsync(writeablePhotoUri, originalPhoto); // Check that the display photo and thumbnail have been set. String photoUri = null; for (int i = 0; i < 10 && photoUri == null; i++) { // Wait a tick for the photo processing to occur. Thread.sleep(100); photoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); } assertFalse(TextUtils.isEmpty(photoUri)); String thumbnailUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_THUMBNAIL_URI); assertFalse(TextUtils.isEmpty(thumbnailUri)); assertNotSame(photoUri, thumbnailUri); // Check the content of the display photo and thumbnail. EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(Uri.parse(photoUri))); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.THUMBNAIL), mResolver.openInputStream(Uri.parse(thumbnailUri))); } public void testWriteUpdatedPhotoToAssetFile() throws Exception { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); // Insert a large photo first. insertPhoto(rawContactId, R.drawable.earth_large); String largeEarthPhotoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); // Load in a huge photo. byte[] originalPhoto = loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.ORIGINAL); // Write it out. Uri writeablePhotoUri = RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(rawContactId)) .appendPath(RawContacts.DisplayPhoto.CONTENT_DIRECTORY).build(); writePhotoAsync(writeablePhotoUri, originalPhoto); // Allow a second for processing to occur. Thread.sleep(1000); // Check that the display photo URI has been modified. String hugeEarthPhotoUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_URI); assertFalse(hugeEarthPhotoUri.equals(largeEarthPhotoUri)); // Check the content of the display photo and thumbnail. String hugeEarthThumbnailUri = getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.PHOTO_THUMBNAIL_URI); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.DISPLAY_PHOTO), mResolver.openInputStream(Uri.parse(hugeEarthPhotoUri))); EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.THUMBNAIL), mResolver.openInputStream(Uri.parse(hugeEarthThumbnailUri))); } private void writePhotoAsync(final Uri uri, final byte[] photoBytes) throws Exception { AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() { @Override protected Object doInBackground(Object... params) { OutputStream os; try { os = mResolver.openOutputStream(uri, "rw"); os.write(photoBytes); os.close(); return null; } catch (IOException ioe) { throw new RuntimeException(ioe); } } }; task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null).get(); } public void testPhotoDimensionLimits() { ContentValues values = new ContentValues(); values.put(DisplayPhoto.DISPLAY_MAX_DIM, 256); values.put(DisplayPhoto.THUMBNAIL_MAX_DIM, 96); assertStoredValues(DisplayPhoto.CONTENT_MAX_DIMENSIONS_URI, values); } public void testPhotoStoreCleanup() throws IOException { SynchronousContactsProvider2 provider = (SynchronousContactsProvider2) mActor.provider; PhotoStore photoStore = provider.getPhotoStore(); // Trigger an initial cleanup so another one won't happen while we're running this test. provider.cleanupPhotoStore(); // Insert a couple of contacts with photos. long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver); long contactId1 = queryContactId(rawContactId1); long dataId1 = ContentUris.parseId(insertPhoto(rawContactId1, R.drawable.earth_normal)); long photoFileId1 = getStoredLongValue(ContentUris.withAppendedId(Data.CONTENT_URI, dataId1), Photo.PHOTO_FILE_ID); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver); long contactId2 = queryContactId(rawContactId2); long dataId2 = ContentUris.parseId(insertPhoto(rawContactId2, R.drawable.earth_normal)); long photoFileId2 = getStoredLongValue(ContentUris.withAppendedId(Data.CONTENT_URI, dataId2), Photo.PHOTO_FILE_ID); // Update the second raw contact with a different photo. ContentValues values = new ContentValues(); values.put(Data.RAW_CONTACT_ID, rawContactId2); values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); values.put(Photo.PHOTO, loadPhotoFromResource(R.drawable.earth_huge, PhotoSize.ORIGINAL)); assertEquals(1, mResolver.update(Data.CONTENT_URI, values, Data._ID + "=?", new String[]{String.valueOf(dataId2)})); long replacementPhotoFileId = getStoredLongValue(ContentUris.withAppendedId(Data.CONTENT_URI, dataId2), Photo.PHOTO_FILE_ID); // Insert a third raw contact that has a bogus photo file ID. long bogusFileId = 1234567; long rawContactId3 = RawContactUtil.createRawContactWithName(mResolver); long contactId3 = queryContactId(rawContactId3); values.clear(); values.put(Data.RAW_CONTACT_ID, rawContactId3); values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); values.put(Photo.PHOTO, loadPhotoFromResource(R.drawable.earth_normal, PhotoSize.THUMBNAIL)); values.put(Photo.PHOTO_FILE_ID, bogusFileId); values.put(DataRowHandlerForPhoto.SKIP_PROCESSING_KEY, true); mResolver.insert(Data.CONTENT_URI, values); // Insert a fourth raw contact with a stream item that has a photo, then remove that photo // from the photo store. Account socialAccount = new Account("social", "social"); long rawContactId4 = RawContactUtil.createRawContactWithName(mResolver, socialAccount); Uri streamItemUri = insertStreamItem(rawContactId4, buildGenericStreamItemValues(), socialAccount); long streamItemId = ContentUris.parseId(streamItemUri); Uri streamItemPhotoUri = insertStreamItemPhoto( streamItemId, buildGenericStreamItemPhotoValues(0), socialAccount); long streamItemPhotoFileId = getStoredLongValue(streamItemPhotoUri, StreamItemPhotos.PHOTO_FILE_ID); photoStore.remove(streamItemPhotoFileId); // Also insert a bogus photo that nobody is using. long bogusPhotoId = photoStore.insert(new PhotoProcessor(loadPhotoFromResource( R.drawable.earth_huge, PhotoSize.ORIGINAL), 256, 96)); // Manually trigger another cleanup in the provider. provider.cleanupPhotoStore(); // The following things should have happened. // 1. Raw contact 1 and its photo remain unaffected. assertEquals(photoFileId1, (long) getStoredLongValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId1), Contacts.PHOTO_FILE_ID)); // 2. Raw contact 2 retains its new photo. The old one is deleted from the photo store. assertEquals(replacementPhotoFileId, (long) getStoredLongValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId2), Contacts.PHOTO_FILE_ID)); assertNull(photoStore.get(photoFileId2)); // 3. Raw contact 3 should have its photo file reference cleared. assertNull(getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId3), Contacts.PHOTO_FILE_ID)); // 4. The bogus photo that nobody was using should be cleared from the photo store. assertNull(photoStore.get(bogusPhotoId)); // 5. The bogus stream item photo should be cleared from the stream item. assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), new ContentValues[0]); } public void testPhotoStoreCleanupForProfile() { SynchronousContactsProvider2 provider = (SynchronousContactsProvider2) mActor.provider; PhotoStore profilePhotoStore = provider.getProfilePhotoStore(); // Trigger an initial cleanup so another one won't happen while we're running this test. provider.switchToProfileModeForTest(); provider.cleanupPhotoStore(); // Create the profile contact and add a photo. Account socialAccount = new Account("social", "social"); ContentValues values = new ContentValues(); values.put(RawContacts.ACCOUNT_NAME, socialAccount.name); values.put(RawContacts.ACCOUNT_TYPE, socialAccount.type); long profileRawContactId = createBasicProfileContact(values); long profileContactId = queryContactId(profileRawContactId); long dataId = ContentUris.parseId( insertPhoto(profileRawContactId, R.drawable.earth_normal)); long profilePhotoFileId = getStoredLongValue(ContentUris.withAppendedId(Data.CONTENT_URI, dataId), Photo.PHOTO_FILE_ID); // Also add a stream item with a photo. Uri streamItemUri = insertStreamItem(profileRawContactId, buildGenericStreamItemValues(), socialAccount); long streamItemId = ContentUris.parseId(streamItemUri); Uri streamItemPhotoUri = insertStreamItemPhoto( streamItemId, buildGenericStreamItemPhotoValues(0), socialAccount); long streamItemPhotoFileId = getStoredLongValue(streamItemPhotoUri, StreamItemPhotos.PHOTO_FILE_ID); // Remove the stream item photo and the profile photo. profilePhotoStore.remove(profilePhotoFileId); profilePhotoStore.remove(streamItemPhotoFileId); // Manually trigger another cleanup in the provider. provider.switchToProfileModeForTest(); provider.cleanupPhotoStore(); // The following things should have happened. // The stream item photo should have been removed. assertStoredValues(Uri.withAppendedPath( ContentUris.withAppendedId(StreamItems.CONTENT_URI, streamItemId), StreamItems.StreamItemPhotos.CONTENT_DIRECTORY), new ContentValues[0]); // The profile photo should have been cleared. assertNull(getStoredValue( ContentUris.withAppendedId(Contacts.CONTENT_URI, profileContactId), Contacts.PHOTO_FILE_ID)); } public void testOverwritePhotoWithThumbnail() throws IOException { long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long contactId = queryContactId(rawContactId); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); // Write a regular-size photo. long dataId = ContentUris.parseId(insertPhoto(rawContactId, R.drawable.earth_normal)); Long photoFileId = getStoredLongValue(contactUri, Contacts.PHOTO_FILE_ID); assertTrue(photoFileId != null && photoFileId > 0); // Now overwrite the photo with a thumbnail-sized photo. ContentValues update = new ContentValues(); update.put(Photo.PHOTO, loadPhotoFromResource(R.drawable.earth_small, PhotoSize.ORIGINAL)); mResolver.update(ContentUris.withAppendedId(Data.CONTENT_URI, dataId), update, null, null); // Photo file ID should have been nulled out, and the photo URI should be the same as the // thumbnail URI. assertNull(getStoredValue(contactUri, Contacts.PHOTO_FILE_ID)); String photoUri = getStoredValue(contactUri, Contacts.PHOTO_URI); String thumbnailUri = getStoredValue(contactUri, Contacts.PHOTO_THUMBNAIL_URI); assertEquals(photoUri, thumbnailUri); // Retrieving the photo URI should get the thumbnail content. EvenMoreAsserts.assertImageRawData(getContext(), loadPhotoFromResource(R.drawable.earth_small, PhotoSize.THUMBNAIL), mResolver.openInputStream(Uri.parse(photoUri))); } public void testUpdateRawContactSetStarred() { long rawContactId1 = RawContactUtil.createRawContactWithName(mResolver); Uri rawContactUri1 = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId1); long rawContactId2 = RawContactUtil.createRawContactWithName(mResolver); Uri rawContactUri2 = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId2); setAggregationException( AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); long contactId = queryContactId(rawContactId1); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); assertStoredValue(contactUri, Contacts.STARRED, "0"); ContentValues values = new ContentValues(); values.put(RawContacts.STARRED, "1"); mResolver.update(rawContactUri1, values, null, null); assertStoredValue(rawContactUri1, RawContacts.STARRED, "1"); assertStoredValue(rawContactUri2, RawContacts.STARRED, "0"); assertStoredValue(contactUri, Contacts.STARRED, "1"); values.put(RawContacts.STARRED, "0"); mResolver.update(rawContactUri1, values, null, null); assertStoredValue(rawContactUri1, RawContacts.STARRED, "0"); assertStoredValue(rawContactUri2, RawContacts.STARRED, "0"); assertStoredValue(contactUri, Contacts.STARRED, "0"); values.put(Contacts.STARRED, "1"); mResolver.update(contactUri, values, null, null); assertStoredValue(rawContactUri1, RawContacts.STARRED, "1"); assertStoredValue(rawContactUri2, RawContacts.STARRED, "1"); assertStoredValue(contactUri, Contacts.STARRED, "1"); } public void testSetAndClearSuperPrimaryEmail() { long rawContactId1 = RawContactUtil.createRawContact(mResolver, new Account("a", "a")); Uri mailUri11 = insertEmail(rawContactId1, "[email protected]"); Uri mailUri12 = insertEmail(rawContactId1, "[email protected]"); long rawContactId2 = RawContactUtil.createRawContact(mResolver, new Account("b", "b")); Uri mailUri21 = insertEmail(rawContactId2, "[email protected]"); Uri mailUri22 = insertEmail(rawContactId2, "[email protected]"); assertStoredValue(mailUri11, Data.IS_PRIMARY, 0); assertStoredValue(mailUri11, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 0); // Set super primary on the first pair, primary on the second { ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 1); mResolver.update(mailUri11, values, null, null); } { ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 1); mResolver.update(mailUri22, values, null, null); } assertStoredValue(mailUri11, Data.IS_PRIMARY, 1); assertStoredValue(mailUri11, Data.IS_SUPER_PRIMARY, 1); assertStoredValue(mailUri12, Data.IS_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 1); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 1); // Clear primary on the first pair, make sure second is not affected and super_primary is // also cleared { ContentValues values = new ContentValues(); values.put(Data.IS_PRIMARY, 0); mResolver.update(mailUri11, values, null, null); } assertStoredValue(mailUri11, Data.IS_PRIMARY, 0); assertStoredValue(mailUri11, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 1); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 1); // Ensure that we can only clear super_primary, if we specify the correct data row { ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 0); mResolver.update(mailUri21, values, null, null); } assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 1); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 1); // Ensure that we can only clear primary, if we specify the correct data row { ContentValues values = new ContentValues(); values.put(Data.IS_PRIMARY, 0); mResolver.update(mailUri21, values, null, null); } assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 1); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 1); // Now clear super-primary for real { ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 0); mResolver.update(mailUri22, values, null, null); } assertStoredValue(mailUri11, Data.IS_PRIMARY, 0); assertStoredValue(mailUri11, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_PRIMARY, 0); assertStoredValue(mailUri12, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_PRIMARY, 0); assertStoredValue(mailUri21, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri22, Data.IS_PRIMARY, 1); assertStoredValue(mailUri22, Data.IS_SUPER_PRIMARY, 0); } /** * Common function for the testNewPrimaryIn* functions. Its four configurations * are each called from its own test */ public void testChangingPrimary(boolean inUpdate, boolean withSuperPrimary) { long rawContactId = RawContactUtil.createRawContact(mResolver, new Account("a", "a")); Uri mailUri1 = insertEmail(rawContactId, "[email protected]", true); if (withSuperPrimary) { final ContentValues values = new ContentValues(); values.put(Data.IS_SUPER_PRIMARY, 1); mResolver.update(mailUri1, values, null, null); } assertStoredValue(mailUri1, Data.IS_PRIMARY, 1); assertStoredValue(mailUri1, Data.IS_SUPER_PRIMARY, withSuperPrimary ? 1 : 0); // Insert another item final Uri mailUri2; if (inUpdate) { mailUri2 = insertEmail(rawContactId, "[email protected]"); assertStoredValue(mailUri1, Data.IS_PRIMARY, 1); assertStoredValue(mailUri1, Data.IS_SUPER_PRIMARY, withSuperPrimary ? 1 : 0); assertStoredValue(mailUri2, Data.IS_PRIMARY, 0); assertStoredValue(mailUri2, Data.IS_SUPER_PRIMARY, 0); final ContentValues values = new ContentValues(); values.put(Data.IS_PRIMARY, 1); mResolver.update(mailUri2, values, null, null); } else { // directly add as default mailUri2 = insertEmail(rawContactId, "[email protected]", true); } // Ensure that primary has been unset on the first // If withSuperPrimary is set, also ensure that is has been moved to the new item assertStoredValue(mailUri1, Data.IS_PRIMARY, 0); assertStoredValue(mailUri1, Data.IS_SUPER_PRIMARY, 0); assertStoredValue(mailUri2, Data.IS_PRIMARY, 1); assertStoredValue(mailUri2, Data.IS_SUPER_PRIMARY, withSuperPrimary ? 1 : 0); } public void testNewPrimaryInInsert() { testChangingPrimary(false, false); } public void testNewPrimaryInInsertWithSuperPrimary() { testChangingPrimary(false, true); } public void testNewPrimaryInUpdate() { testChangingPrimary(true, false); } public void testNewPrimaryInUpdateWithSuperPrimary() { testChangingPrimary(true, true); } public void testContactSortOrder() { assertEquals(ContactsColumns.PHONEBOOK_BUCKET_PRIMARY + ", " + Contacts.SORT_KEY_PRIMARY, ContactsProvider2.getLocalizedSortOrder(Contacts.SORT_KEY_PRIMARY)); assertEquals(ContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE + ", " + Contacts.SORT_KEY_ALTERNATIVE, ContactsProvider2.getLocalizedSortOrder(Contacts.SORT_KEY_ALTERNATIVE)); assertEquals(ContactsColumns.PHONEBOOK_BUCKET_PRIMARY + " DESC, " + Contacts.SORT_KEY_PRIMARY + " DESC", ContactsProvider2.getLocalizedSortOrder(Contacts.SORT_KEY_PRIMARY + " DESC")); String suffix = " COLLATE LOCALIZED DESC"; assertEquals(ContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE + suffix + ", " + Contacts.SORT_KEY_ALTERNATIVE + suffix, ContactsProvider2.getLocalizedSortOrder(Contacts.SORT_KEY_ALTERNATIVE + suffix)); } public void testContactCounts() { Uri uri = Contacts.CONTENT_URI.buildUpon() .appendQueryParameter(ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, "true").build(); RawContactUtil.createRawContact(mResolver); RawContactUtil.createRawContactWithName(mResolver, "James", "Sullivan"); RawContactUtil.createRawContactWithName(mResolver, "The Abominable", "Snowman"); RawContactUtil.createRawContactWithName(mResolver, "Mike", "Wazowski"); RawContactUtil.createRawContactWithName(mResolver, "randall", "boggs"); RawContactUtil.createRawContactWithName(mResolver, "Boo", null); RawContactUtil.createRawContactWithName(mResolver, "Mary", null); RawContactUtil.createRawContactWithName(mResolver, "Roz", null); Cursor cursor = mResolver.query(uri, new String[]{Contacts.DISPLAY_NAME}, null, null, Contacts.SORT_KEY_PRIMARY); assertFirstLetterValues(cursor, "", "B", "J", "M", "R", "T"); assertFirstLetterCounts(cursor, 1, 1, 1, 2, 2, 1); cursor.close(); cursor = mResolver.query(uri, new String[]{Contacts.DISPLAY_NAME}, null, null, Contacts.SORT_KEY_ALTERNATIVE + " COLLATE LOCALIZED DESC"); assertFirstLetterValues(cursor, "W", "S", "R", "M", "B", ""); assertFirstLetterCounts(cursor, 1, 2, 1, 1, 2, 1); cursor.close(); } public void testContactCountsWithGermanNames() { if (!hasGermanCollator()) { return; } ContactLocaleUtils.setLocale(Locale.GERMANY); Uri uri = Contacts.CONTENT_URI.buildUpon() .appendQueryParameter(ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, "true").build(); RawContactUtil.createRawContactWithName(mResolver, "Josef", "Sacher"); RawContactUtil.createRawContactWithName(mResolver, "Franz", "Schiller"); RawContactUtil.createRawContactWithName(mResolver, "Eckart", "Steiff"); RawContactUtil.createRawContactWithName(mResolver, "Klaus", "Seiler"); RawContactUtil.createRawContactWithName(mResolver, "Lars", "Sultan"); RawContactUtil.createRawContactWithName(mResolver, "Heidi", "Rilke"); RawContactUtil.createRawContactWithName(mResolver, "Suse", "Thomas"); Cursor cursor = mResolver.query(uri, new String[]{Contacts.DISPLAY_NAME}, null, null, Contacts.SORT_KEY_ALTERNATIVE); assertFirstLetterValues(cursor, "R", "S", "Sch", "St", "T"); assertFirstLetterCounts(cursor, 1, 3, 1, 1, 1); cursor.close(); } private void assertFirstLetterValues(Cursor cursor, String... expected) { String[] actual = cursor.getExtras() .getStringArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_TITLES); MoreAsserts.assertEquals(expected, actual); } private void assertFirstLetterCounts(Cursor cursor, int... expected) { int[] actual = cursor.getExtras() .getIntArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_COUNTS); MoreAsserts.assertEquals(expected, actual); } public void testReadBooleanQueryParameter() { assertBooleanUriParameter("foo:bar", "bool", true, true); assertBooleanUriParameter("foo:bar", "bool", false, false); assertBooleanUriParameter("foo:bar?bool=0", "bool", true, false); assertBooleanUriParameter("foo:bar?bool=1", "bool", false, true); assertBooleanUriParameter("foo:bar?bool=false", "bool", true, false); assertBooleanUriParameter("foo:bar?bool=true", "bool", false, true); assertBooleanUriParameter("foo:bar?bool=FaLsE", "bool", true, false); assertBooleanUriParameter("foo:bar?bool=false&some=some", "bool", true, false); assertBooleanUriParameter("foo:bar?bool=1&some=some", "bool", false, true); assertBooleanUriParameter("foo:bar?some=bool", "bool", true, true); assertBooleanUriParameter("foo:bar?bool", "bool", true, true); } private void assertBooleanUriParameter(String uriString, String parameter, boolean defaultValue, boolean expectedValue) { assertEquals(expectedValue, ContactsProvider2.readBooleanQueryParameter( Uri.parse(uriString), parameter, defaultValue)); } public void testGetQueryParameter() { assertQueryParameter("foo:bar", "param", null); assertQueryParameter("foo:bar?param", "param", null); assertQueryParameter("foo:bar?param=", "param", ""); assertQueryParameter("foo:bar?param=val", "param", "val"); assertQueryParameter("foo:bar?param=val&some=some", "param", "val"); assertQueryParameter("foo:bar?some=some&param=val", "param", "val"); assertQueryParameter("foo:bar?some=some&param=val&else=else", "param", "val"); assertQueryParameter("foo:bar?param=john%40doe.com", "param", "[email protected]"); assertQueryParameter("foo:bar?some_param=val", "param", null); assertQueryParameter("foo:bar?some_param=val1&param=val2", "param", "val2"); assertQueryParameter("foo:bar?some_param=val1&param=", "param", ""); assertQueryParameter("foo:bar?some_param=val1&param", "param", null); assertQueryParameter("foo:bar?some_param=val1&another_param=val2&param=val3", "param", "val3"); assertQueryParameter("foo:bar?some_param=val1&param=val2&some_param=val3", "param", "val2"); assertQueryParameter("foo:bar?param=val1&some_param=val2", "param", "val1"); assertQueryParameter("foo:bar?p=val1&pp=val2", "p", "val1"); assertQueryParameter("foo:bar?pp=val1&p=val2", "p", "val2"); assertQueryParameter("foo:bar?ppp=val1&pp=val2&p=val3", "p", "val3"); assertQueryParameter("foo:bar?ppp=val&", "p", null); } public void testMissingAccountTypeParameter() { // Try querying for RawContacts only using ACCOUNT_NAME final Uri queryUri = RawContacts.CONTENT_URI.buildUpon().appendQueryParameter( RawContacts.ACCOUNT_NAME, "lolwut").build(); try { final Cursor cursor = mResolver.query(queryUri, null, null, null, null); fail("Able to query with incomplete account query parameters"); } catch (IllegalArgumentException e) { // Expected behavior. } } public void testInsertInconsistentAccountType() { // Try inserting RawContact with inconsistent Accounts final Account red = new Account("red", "red"); final Account blue = new Account("blue", "blue"); final ContentValues values = new ContentValues(); values.put(RawContacts.ACCOUNT_NAME, red.name); values.put(RawContacts.ACCOUNT_TYPE, red.type); final Uri insertUri = TestUtil.maybeAddAccountQueryParameters(RawContacts.CONTENT_URI, blue); try { mResolver.insert(insertUri, values); fail("Able to insert RawContact with inconsistent account details"); } catch (IllegalArgumentException e) { // Expected behavior. } } public void testProviderStatusNoContactsNoAccounts() throws Exception { assertProviderStatus(ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS); } public void testProviderStatusOnlyLocalContacts() throws Exception { long rawContactId = RawContactUtil.createRawContact(mResolver); assertProviderStatus(ProviderStatus.STATUS_NORMAL); mResolver.delete( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), null, null); assertProviderStatus(ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS); } public void testProviderStatusWithAccounts() throws Exception { assertProviderStatus(ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS); mActor.setAccounts(new Account[]{TestUtil.ACCOUNT_1}); ((ContactsProvider2)getProvider()).onAccountsUpdated(new Account[]{TestUtil.ACCOUNT_1}); assertProviderStatus(ProviderStatus.STATUS_NORMAL); mActor.setAccounts(new Account[0]); ((ContactsProvider2)getProvider()).onAccountsUpdated(new Account[0]); assertProviderStatus(ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS); } private void assertProviderStatus(int expectedProviderStatus) { Cursor cursor = mResolver.query(ProviderStatus.CONTENT_URI, new String[]{ProviderStatus.DATA1, ProviderStatus.STATUS}, null, null, null); assertTrue(cursor.moveToFirst()); assertEquals(0, cursor.getLong(0)); assertEquals(expectedProviderStatus, cursor.getInt(1)); cursor.close(); } public void testProperties() throws Exception { ContactsProvider2 provider = (ContactsProvider2)getProvider(); ContactsDatabaseHelper helper = (ContactsDatabaseHelper)provider.getDatabaseHelper(); assertNull(helper.getProperty("non-existent", null)); assertEquals("default", helper.getProperty("non-existent", "default")); helper.setProperty("existent1", "string1"); helper.setProperty("existent2", "string2"); assertEquals("string1", helper.getProperty("existent1", "default")); assertEquals("string2", helper.getProperty("existent2", "default")); helper.setProperty("existent1", null); assertEquals("default", helper.getProperty("existent1", "default")); } private class VCardTestUriCreator { private String mLookup1; private String mLookup2; public VCardTestUriCreator(String lookup1, String lookup2) { super(); mLookup1 = lookup1; mLookup2 = lookup2; } public Uri getUri1() { return Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, mLookup1); } public Uri getUri2() { return Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, mLookup2); } public Uri getCombinedUri() { return Uri.withAppendedPath(Contacts.CONTENT_MULTI_VCARD_URI, Uri.encode(mLookup1 + ":" + mLookup2)); } } private VCardTestUriCreator createVCardTestContacts() { final long rawContactId1 = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "4:12"); DataUtil.insertStructuredName(mResolver, rawContactId1, "John", "Doe"); final long rawContactId2 = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.SOURCE_ID, "3:4%121"); DataUtil.insertStructuredName(mResolver, rawContactId2, "Jane", "Doh"); final long contactId1 = queryContactId(rawContactId1); final long contactId2 = queryContactId(rawContactId2); final Uri contact1Uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId1); final Uri contact2Uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId2); final String lookup1 = Uri.encode(Contacts.getLookupUri(mResolver, contact1Uri).getPathSegments().get(2)); final String lookup2 = Uri.encode(Contacts.getLookupUri(mResolver, contact2Uri).getPathSegments().get(2)); return new VCardTestUriCreator(lookup1, lookup2); } public void testQueryMultiVCard() { // No need to create any contacts here, because the query for multiple vcards // does not go into the database at all Uri uri = Uri.withAppendedPath(Contacts.CONTENT_MULTI_VCARD_URI, Uri.encode("123:456")); Cursor cursor = mResolver.query(uri, null, null, null, null); assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToFirst()); assertTrue(cursor.isNull(cursor.getColumnIndex(OpenableColumns.SIZE))); String filename = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); // The resulting name contains date and time. Ensure that before and after are correct assertTrue(filename.startsWith("vcards_")); assertTrue(filename.endsWith(".vcf")); cursor.close(); } public void testQueryFileSingleVCard() { final VCardTestUriCreator contacts = createVCardTestContacts(); { Cursor cursor = mResolver.query(contacts.getUri1(), null, null, null, null); assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToFirst()); assertTrue(cursor.isNull(cursor.getColumnIndex(OpenableColumns.SIZE))); String filename = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); assertEquals("John Doe.vcf", filename); cursor.close(); } { Cursor cursor = mResolver.query(contacts.getUri2(), null, null, null, null); assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToFirst()); assertTrue(cursor.isNull(cursor.getColumnIndex(OpenableColumns.SIZE))); String filename = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); assertEquals("Jane Doh.vcf", filename); cursor.close(); } } public void testQueryFileProfileVCard() { createBasicProfileContact(new ContentValues()); Cursor cursor = mResolver.query(Profile.CONTENT_VCARD_URI, null, null, null, null); assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToFirst()); assertTrue(cursor.isNull(cursor.getColumnIndex(OpenableColumns.SIZE))); String filename = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); assertEquals("Mia Prophyl.vcf", filename); cursor.close(); } public void testOpenAssetFileMultiVCard() throws IOException { final VCardTestUriCreator contacts = createVCardTestContacts(); final AssetFileDescriptor descriptor = mResolver.openAssetFileDescriptor(contacts.getCombinedUri(), "r"); final FileInputStream inputStream = descriptor.createInputStream(); String data = readToEnd(inputStream); inputStream.close(); descriptor.close(); // Ensure that the resulting VCard has both contacts assertTrue(data.contains("N:Doe;John;;;")); assertTrue(data.contains("N:Doh;Jane;;;")); } public void testOpenAssetFileSingleVCard() throws IOException { final VCardTestUriCreator contacts = createVCardTestContacts(); // Ensure that the right VCard is being created in each case { final AssetFileDescriptor descriptor = mResolver.openAssetFileDescriptor(contacts.getUri1(), "r"); final FileInputStream inputStream = descriptor.createInputStream(); final String data = readToEnd(inputStream); inputStream.close(); descriptor.close(); assertTrue(data.contains("N:Doe;John;;;")); assertFalse(data.contains("N:Doh;Jane;;;")); } { final AssetFileDescriptor descriptor = mResolver.openAssetFileDescriptor(contacts.getUri2(), "r"); final FileInputStream inputStream = descriptor.createInputStream(); final String data = readToEnd(inputStream); inputStream.close(); descriptor.close(); assertFalse(data.contains("N:Doe;John;;;")); assertTrue(data.contains("N:Doh;Jane;;;")); } } public void testAutoGroupMembership() { long g1 = createGroup(mAccount, "g1", "t1", 0, true /* autoAdd */, false /* favorite */); long g2 = createGroup(mAccount, "g2", "t2", 0, false /* autoAdd */, false /* favorite */); long g3 = createGroup(mAccountTwo, "g3", "t3", 0, true /* autoAdd */, false /* favorite */); long g4 = createGroup(mAccountTwo, "g4", "t4", 0, false /* autoAdd */, false/* favorite */); long r1 = RawContactUtil.createRawContact(mResolver, mAccount); long r2 = RawContactUtil.createRawContact(mResolver, mAccountTwo); long r3 = RawContactUtil.createRawContact(mResolver, null); Cursor c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } c = queryGroupMemberships(mAccountTwo); try { assertTrue(c.moveToNext()); assertEquals(g3, c.getLong(0)); assertEquals(r2, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } } public void testNoAutoAddMembershipAfterGroupCreation() { long r1 = RawContactUtil.createRawContact(mResolver, mAccount); long r2 = RawContactUtil.createRawContact(mResolver, mAccount); long r3 = RawContactUtil.createRawContact(mResolver, mAccount); long r4 = RawContactUtil.createRawContact(mResolver, mAccountTwo); long r5 = RawContactUtil.createRawContact(mResolver, mAccountTwo); long r6 = RawContactUtil.createRawContact(mResolver, null); assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); long g1 = createGroup(mAccount, "g1", "t1", 0, true /* autoAdd */, false /* favorite */); long g2 = createGroup(mAccount, "g2", "t2", 0, false /* autoAdd */, false /* favorite */); long g3 = createGroup(mAccountTwo, "g3", "t3", 0, true /* autoAdd */, false/* favorite */); assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); } // create some starred and non-starred contacts, some associated with account, some not // favorites group created // the starred contacts should be added to group // favorites group removed // no change to starred status public void testFavoritesMembershipAfterGroupCreation() { long r1 = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.STARRED, "1"); long r2 = RawContactUtil.createRawContact(mResolver, mAccount); long r3 = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.STARRED, "1"); long r4 = RawContactUtil.createRawContact(mResolver, mAccountTwo, RawContacts.STARRED, "1"); long r5 = RawContactUtil.createRawContact(mResolver, mAccountTwo); long r6 = RawContactUtil.createRawContact(mResolver, null, RawContacts.STARRED, "1"); long r7 = RawContactUtil.createRawContact(mResolver, null); assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); long g1 = createGroup(mAccount, "g1", "t1", 0, false /* autoAdd */, true /* favorite */); long g2 = createGroup(mAccount, "g2", "t2", 0, false /* autoAdd */, false /* favorite */); long g3 = createGroup(mAccountTwo, "g3", "t3", 0, false /* autoAdd */, false/* favorite */); assertTrue(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertTrue(queryRawContactIsStarred(r3)); assertTrue(queryRawContactIsStarred(r4)); assertFalse(queryRawContactIsStarred(r5)); assertTrue(queryRawContactIsStarred(r6)); assertFalse(queryRawContactIsStarred(r7)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); Cursor c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r3, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } updateItem(RawContacts.CONTENT_URI, r6, RawContacts.ACCOUNT_NAME, mAccount.name, RawContacts.ACCOUNT_TYPE, mAccount.type); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r3, c.getLong(1)); assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r6, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } mResolver.delete(ContentUris.withAppendedId(Groups.CONTENT_URI, g1), null, null); assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); assertTrue(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertTrue(queryRawContactIsStarred(r3)); assertTrue(queryRawContactIsStarred(r4)); assertFalse(queryRawContactIsStarred(r5)); assertTrue(queryRawContactIsStarred(r6)); assertFalse(queryRawContactIsStarred(r7)); } public void testFavoritesGroupMembershipChangeAfterStarChange() { long g1 = createGroup(mAccount, "g1", "t1", 0, false /* autoAdd */, true /* favorite */); long g2 = createGroup(mAccount, "g2", "t2", 0, false /* autoAdd */, false/* favorite */); long g4 = createGroup(mAccountTwo, "g4", "t4", 0, false /* autoAdd */, true /* favorite */); long g5 = createGroup(mAccountTwo, "g5", "t5", 0, false /* autoAdd */, false/* favorite */); long r1 = RawContactUtil.createRawContact(mResolver, mAccount, RawContacts.STARRED, "1"); long r2 = RawContactUtil.createRawContact(mResolver, mAccount); long r3 = RawContactUtil.createRawContact(mResolver, mAccountTwo); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); Cursor c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } // remove the star from r1 assertEquals(1, updateItem(RawContacts.CONTENT_URI, r1, RawContacts.STARRED, "0")); // Since no raw contacts are starred, there should be no group memberships. assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); // mark r1 as starred assertEquals(1, updateItem(RawContacts.CONTENT_URI, r1, RawContacts.STARRED, "1")); // Now that r1 is starred it should have a membership in the one groups from mAccount // that is marked as a favorite. // There should be no memberships in mAccountTwo since it has no starred raw contacts. assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } // remove the star from r1 assertEquals(1, updateItem(RawContacts.CONTENT_URI, r1, RawContacts.STARRED, "0")); // Since no raw contacts are starred, there should be no group memberships. assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, queryContactId(r1)); assertNotNull(contactUri); // mark r1 as starred via its contact lookup uri assertEquals(1, updateItem(contactUri, Contacts.STARRED, "1")); // Now that r1 is starred it should have a membership in the one groups from mAccount // that is marked as a favorite. // There should be no memberships in mAccountTwo since it has no starred raw contacts. assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } // remove the star from r1 updateItem(contactUri, Contacts.STARRED, "0"); // Since no raw contacts are starred, there should be no group memberships. assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); } public void testStarChangedAfterGroupMembershipChange() { long g1 = createGroup(mAccount, "g1", "t1", 0, false /* autoAdd */, true /* favorite */); long g2 = createGroup(mAccount, "g2", "t2", 0, false /* autoAdd */, false/* favorite */); long g4 = createGroup(mAccountTwo, "g4", "t4", 0, false /* autoAdd */, true /* favorite */); long g5 = createGroup(mAccountTwo, "g5", "t5", 0, false /* autoAdd */, false/* favorite */); long r1 = RawContactUtil.createRawContact(mResolver, mAccount); long r2 = RawContactUtil.createRawContact(mResolver, mAccount); long r3 = RawContactUtil.createRawContact(mResolver, mAccountTwo); assertFalse(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertFalse(queryRawContactIsStarred(r3)); Cursor c; // add r1 to one favorites group // r1's star should automatically be set // r1 should automatically be added to the other favorites group Uri urir1g1 = insertGroupMembership(r1, g1); assertTrue(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertFalse(queryRawContactIsStarred(r3)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); c = queryGroupMemberships(mAccount); try { assertTrue(c.moveToNext()); assertEquals(g1, c.getLong(0)); assertEquals(r1, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } // remove r1 from one favorites group mResolver.delete(urir1g1, null, null); // r1's star should no longer be set assertFalse(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertFalse(queryRawContactIsStarred(r3)); // there should be no membership rows assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); // add r3 to the one favorites group for that account // r3's star should automatically be set Uri urir3g4 = insertGroupMembership(r3, g4); assertFalse(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertTrue(queryRawContactIsStarred(r3)); assertNoRowsAndClose(queryGroupMemberships(mAccount)); c = queryGroupMemberships(mAccountTwo); try { assertTrue(c.moveToNext()); assertEquals(g4, c.getLong(0)); assertEquals(r3, c.getLong(1)); assertFalse(c.moveToNext()); } finally { c.close(); } // remove r3 from the favorites group mResolver.delete(urir3g4, null, null); // r3's star should automatically be cleared assertFalse(queryRawContactIsStarred(r1)); assertFalse(queryRawContactIsStarred(r2)); assertFalse(queryRawContactIsStarred(r3)); assertNoRowsAndClose(queryGroupMemberships(mAccount)); assertNoRowsAndClose(queryGroupMemberships(mAccountTwo)); } public void testReadOnlyRawContact() { long rawContactId = RawContactUtil.createRawContact(mResolver); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); storeValue(rawContactUri, RawContacts.CUSTOM_RINGTONE, "first"); storeValue(rawContactUri, RawContacts.RAW_CONTACT_IS_READ_ONLY, 1); storeValue(rawContactUri, RawContacts.CUSTOM_RINGTONE, "second"); assertStoredValue(rawContactUri, RawContacts.CUSTOM_RINGTONE, "first"); Uri syncAdapterUri = rawContactUri.buildUpon() .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "1") .build(); storeValue(syncAdapterUri, RawContacts.CUSTOM_RINGTONE, "third"); assertStoredValue(rawContactUri, RawContacts.CUSTOM_RINGTONE, "third"); } public void testReadOnlyDataRow() { long rawContactId = RawContactUtil.createRawContact(mResolver); Uri emailUri = insertEmail(rawContactId, "email"); Uri phoneUri = insertPhoneNumber(rawContactId, "555-1111"); storeValue(emailUri, Data.IS_READ_ONLY, "1"); storeValue(emailUri, Email.ADDRESS, "changed"); storeValue(phoneUri, Phone.NUMBER, "555-2222"); assertStoredValue(emailUri, Email.ADDRESS, "email"); assertStoredValue(phoneUri, Phone.NUMBER, "555-2222"); Uri syncAdapterUri = emailUri.buildUpon() .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "1") .build(); storeValue(syncAdapterUri, Email.ADDRESS, "changed"); assertStoredValue(emailUri, Email.ADDRESS, "changed"); } public void testContactWithReadOnlyRawContact() { long rawContactId1 = RawContactUtil.createRawContact(mResolver); Uri rawContactUri1 = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId1); storeValue(rawContactUri1, RawContacts.CUSTOM_RINGTONE, "first"); long rawContactId2 = RawContactUtil.createRawContact(mResolver); Uri rawContactUri2 = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId2); storeValue(rawContactUri2, RawContacts.CUSTOM_RINGTONE, "second"); storeValue(rawContactUri2, RawContacts.RAW_CONTACT_IS_READ_ONLY, 1); setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rawContactId1, rawContactId2); long contactId = queryContactId(rawContactId1); Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); storeValue(contactUri, Contacts.CUSTOM_RINGTONE, "rt"); assertStoredValue(contactUri, Contacts.CUSTOM_RINGTONE, "rt"); assertStoredValue(rawContactUri1, RawContacts.CUSTOM_RINGTONE, "rt"); assertStoredValue(rawContactUri2, RawContacts.CUSTOM_RINGTONE, "second"); } public void testNameParsingQuery() { Uri uri = ContactsContract.AUTHORITY_URI.buildUpon().appendPath("complete_name") .appendQueryParameter(StructuredName.DISPLAY_NAME, "Mr. John Q. Doe Jr.").build(); Cursor cursor = mResolver.query(uri, null, null, null, null); ContentValues values = new ContentValues(); values.put(StructuredName.DISPLAY_NAME, "Mr. John Q. Doe Jr."); values.put(StructuredName.PREFIX, "Mr."); values.put(StructuredName.GIVEN_NAME, "John"); values.put(StructuredName.MIDDLE_NAME, "Q."); values.put(StructuredName.FAMILY_NAME, "Doe"); values.put(StructuredName.SUFFIX, "Jr."); values.put(StructuredName.FULL_NAME_STYLE, FullNameStyle.WESTERN); assertTrue(cursor.moveToFirst()); assertCursorValues(cursor, values); cursor.close(); } public void testNameConcatenationQuery() { Uri uri = ContactsContract.AUTHORITY_URI.buildUpon().appendPath("complete_name") .appendQueryParameter(StructuredName.PREFIX, "Mr") .appendQueryParameter(StructuredName.GIVEN_NAME, "John") .appendQueryParameter(StructuredName.MIDDLE_NAME, "Q.") .appendQueryParameter(StructuredName.FAMILY_NAME, "Doe") .appendQueryParameter(StructuredName.SUFFIX, "Jr.") .build(); Cursor cursor = mResolver.query(uri, null, null, null, null); ContentValues values = new ContentValues(); values.put(StructuredName.DISPLAY_NAME, "Mr John Q. Doe, Jr."); values.put(StructuredName.PREFIX, "Mr"); values.put(StructuredName.GIVEN_NAME, "John"); values.put(StructuredName.MIDDLE_NAME, "Q."); values.put(StructuredName.FAMILY_NAME, "Doe"); values.put(StructuredName.SUFFIX, "Jr."); values.put(StructuredName.FULL_NAME_STYLE, FullNameStyle.WESTERN); assertTrue(cursor.moveToFirst()); assertCursorValues(cursor, values); cursor.close(); } public void testBuildSingleRowResult() { checkBuildSingleRowResult( new String[] {"b"}, new String[] {"a", "b"}, new Integer[] {1, 2}, new Integer[] {2} ); checkBuildSingleRowResult( new String[] {"b", "a", "b"}, new String[] {"a", "b"}, new Integer[] {1, 2}, new Integer[] {2, 1, 2} ); checkBuildSingleRowResult( null, // all columns new String[] {"a", "b"}, new Integer[] {1, 2}, new Integer[] {1, 2} ); try { // Access non-existent column ContactsProvider2.buildSingleRowResult(new String[] {"a"}, new String[] {"b"}, new Object[] {1}); fail(); } catch (IllegalArgumentException expected) { } } private void checkBuildSingleRowResult(String[] projection, String[] availableColumns, Object[] data, Integer[] expectedValues) { final Cursor c = ContactsProvider2.buildSingleRowResult(projection, availableColumns, data); try { assertTrue(c.moveToFirst()); assertEquals(1, c.getCount()); assertEquals(expectedValues.length, c.getColumnCount()); for (int i = 0; i < expectedValues.length; i++) { assertEquals("column " + i, expectedValues[i], (Integer) c.getInt(i)); } } finally { c.close(); } } public void testDataUsageFeedbackAndDelete() { sMockClock.install(); final long startTime = sMockClock.currentTimeMillis(); final long rid1 = RawContactUtil.createRawContactWithName(mResolver, "contact", "a"); final long did1a = ContentUris.parseId(insertEmail(rid1, "[email protected]")); final long did1b = ContentUris.parseId(insertEmail(rid1, "[email protected]")); final long did1p = ContentUris.parseId(insertPhoneNumber(rid1, "555-555-5555")); final long rid2 = RawContactUtil.createRawContactWithName(mResolver, "contact", "b"); final long did2a = ContentUris.parseId(insertEmail(rid2, "[email protected]")); final long did2p = ContentUris.parseId(insertPhoneNumber(rid2, "555-555-5556")); // Aggregate 1 and 2 setAggregationException(AggregationExceptions.TYPE_KEEP_TOGETHER, rid1, rid2); final long rid3 = RawContactUtil.createRawContactWithName(mResolver, "contact", "c"); final long did3a = ContentUris.parseId(insertEmail(rid3, "[email protected]")); final long did3p = ContentUris.parseId(insertPhoneNumber(rid3, "555-3333")); final long rid4 = RawContactUtil.createRawContactWithName(mResolver, "contact", "d"); final long did4p = ContentUris.parseId(insertPhoneNumber(rid4, "555-4444")); final long cid1 = queryContactId(rid1); final long cid3 = queryContactId(rid3); final long cid4 = queryContactId(rid4); // Make sure 1+2, 3 and 4 aren't aggregated MoreAsserts.assertNotEqual(cid1, cid3); MoreAsserts.assertNotEqual(cid1, cid4); MoreAsserts.assertNotEqual(cid3, cid4); // time = startTime // First, there's no frequent. (We use strequent here only because frequent is hidden // and may be removed someday.) assertRowCount(0, Contacts.CONTENT_STREQUENT_URI, null, null); // Test 1. touch data 1a updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_LONG_TEXT, did1a); // Now, there's a single frequent. (contact 1) assertRowCount(1, Contacts.CONTENT_STREQUENT_URI, null, null); // time = startTime + 1 sMockClock.advance(); // Test 2. touch data 1a, 2a and 3a updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_LONG_TEXT, did1a, did2a, did3a); // Now, contact 1 and 3 are in frequent. assertRowCount(2, Contacts.CONTENT_STREQUENT_URI, null, null); // time = startTime + 2 sMockClock.advance(); // Test 2. touch data 2p (call) updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_CALL, did2p); // There're still two frequent. assertRowCount(2, Contacts.CONTENT_STREQUENT_URI, null, null); // time = startTime + 3 sMockClock.advance(); // Test 3. touch data 2p and 3p (short text) updateDataUsageFeedback(DataUsageFeedback.USAGE_TYPE_SHORT_TEXT, did2p, did3p); // Let's check the tables. // Fist, check the data_usage_stat table, which has no public URI. assertStoredValuesDb("SELECT " + DataUsageStatColumns.DATA_ID + "," + DataUsageStatColumns.USAGE_TYPE_INT + "," + DataUsageStatColumns.TIMES_USED + "," + DataUsageStatColumns.LAST_TIME_USED + " FROM " + Tables.DATA_USAGE_STAT, null, cv(DataUsageStatColumns.DATA_ID, did1a, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT, DataUsageStatColumns.TIMES_USED, 2, DataUsageStatColumns.LAST_TIME_USED, startTime + 1 ), cv(DataUsageStatColumns.DATA_ID, did2a, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT, DataUsageStatColumns.TIMES_USED, 1, DataUsageStatColumns.LAST_TIME_USED, startTime + 1 ), cv(DataUsageStatColumns.DATA_ID, did3a, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT, DataUsageStatColumns.TIMES_USED, 1, DataUsageStatColumns.LAST_TIME_USED, startTime + 1 ), cv(DataUsageStatColumns.DATA_ID, did2p, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_CALL, DataUsageStatColumns.TIMES_USED, 1, DataUsageStatColumns.LAST_TIME_USED, startTime + 2 ), cv(DataUsageStatColumns.DATA_ID, did2p, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_SHORT_TEXT, DataUsageStatColumns.TIMES_USED, 1, DataUsageStatColumns.LAST_TIME_USED, startTime + 3 ), cv(DataUsageStatColumns.DATA_ID, did3p, DataUsageStatColumns.USAGE_TYPE_INT, DataUsageStatColumns.USAGE_TYPE_INT_SHORT_TEXT, DataUsageStatColumns.TIMES_USED, 1, DataUsageStatColumns.LAST_TIME_USED, startTime + 3 ) ); // Next, check the raw_contacts table assertStoredValuesWithProjection(RawContacts.CONTENT_URI, cv(RawContacts._ID, rid1, RawContacts.TIMES_CONTACTED, 2, RawContacts.LAST_TIME_CONTACTED, startTime + 1 ), cv(RawContacts._ID, rid2, RawContacts.TIMES_CONTACTED, 3, RawContacts.LAST_TIME_CONTACTED, startTime + 3 ), cv(RawContacts._ID, rid3, RawContacts.TIMES_CONTACTED, 2, RawContacts.LAST_TIME_CONTACTED, startTime + 3 ), cv(RawContacts._ID, rid4, RawContacts.TIMES_CONTACTED, 0, RawContacts.LAST_TIME_CONTACTED, null // 4 wasn't touched. ) ); // Lastly, check the contacts table. // Note contact1.TIMES_CONTACTED = 4, even though raw_contact1.TIMES_CONTACTED + // raw_contact1.TIMES_CONTACTED = 5, because in test 2, data 1a and data 2a were touched // at once. assertStoredValuesWithProjection(Contacts.CONTENT_URI, cv(Contacts._ID, cid1, Contacts.TIMES_CONTACTED, 4, Contacts.LAST_TIME_CONTACTED, startTime + 3 ), cv(Contacts._ID, cid3, Contacts.TIMES_CONTACTED, 2, Contacts.LAST_TIME_CONTACTED, startTime + 3 ), cv(Contacts._ID, cid4, Contacts.TIMES_CONTACTED, 0, Contacts.LAST_TIME_CONTACTED, 0 // For contacts, the default is 0, not null. ) ); // Let's test the delete too. assertTrue(mResolver.delete(DataUsageFeedback.DELETE_USAGE_URI, null, null) > 0); // Now there's no frequent. assertRowCount(0, Contacts.CONTENT_STREQUENT_URI, null, null); // No rows in the stats table. assertStoredValuesDb("SELECT " + DataUsageStatColumns.DATA_ID + " FROM " + Tables.DATA_USAGE_STAT, null, new ContentValues[0]); // The following values should all be 0 or null. assertRowCount(0, Contacts.CONTENT_URI, Contacts.TIMES_CONTACTED + ">0", null); assertRowCount(0, Contacts.CONTENT_URI, Contacts.LAST_TIME_CONTACTED + ">0", null); assertRowCount(0, RawContacts.CONTENT_URI, RawContacts.TIMES_CONTACTED + ">0", null); assertRowCount(0, RawContacts.CONTENT_URI, RawContacts.LAST_TIME_CONTACTED + ">0", null); // Calling it when there's no usage stats will still return a positive value. assertTrue(mResolver.delete(DataUsageFeedback.DELETE_USAGE_URI, null, null) > 0); } /******************************************************* * Delta api tests. */ public void testContactDelete_hasDeleteLog() { sMockClock.install(); long start = sMockClock.currentTimeMillis(); DatabaseAsserts.ContactIdPair ids = assertContactCreateDelete(); DatabaseAsserts.assertHasDeleteLogGreaterThan(mResolver, ids.mContactId, start); // Clean up. Must also remove raw contact. RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testContactDelete_marksRawContactsForDeletion() { DatabaseAsserts.ContactIdPair ids = assertContactCreateDelete(); String[] projection = new String[]{ContactsContract.RawContacts.DIRTY, ContactsContract.RawContacts.DELETED}; List<String[]> records = RawContactUtil.queryByContactId(mResolver, ids.mContactId, projection); for (String[] arr : records) { assertEquals("1", arr[0]); assertEquals("1", arr[1]); } // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testContactUpdate_updatesContactUpdatedTimestamp() { sMockClock.install(); DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); ContentValues values = new ContentValues(); values.put(ContactsContract.Contacts.STARRED, 1); sMockClock.advance(); ContactUtil.update(mResolver, ids.mContactId, values); long newTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); assertTrue(newTime > baseTime); // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } // This implicitly tests the Contact create case. public void testRawContactCreate_updatesContactUpdatedTimestamp() { long startTime = System.currentTimeMillis(); long rawContactId = RawContactUtil.createRawContactWithName(mResolver); long lastUpdated = getContactLastUpdatedTimestampByRawContactId(mResolver, rawContactId); assertTrue(lastUpdated > startTime); // Clean up RawContactUtil.delete(mResolver, rawContactId, true); } public void testRawContactUpdate_updatesContactUpdatedTimestamp() { DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); ContentValues values = new ContentValues(); values.put(ContactsContract.RawContacts.STARRED, 1); RawContactUtil.update(mResolver, ids.mRawContactId, values); long newTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); assertTrue(newTime > baseTime); // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testRawContactPsuedoDelete_hasDeleteLogForContact() { DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); RawContactUtil.delete(mResolver, ids.mRawContactId, false); DatabaseAsserts.assertHasDeleteLogGreaterThan(mResolver, ids.mContactId, baseTime); // clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testRawContactDelete_hasDeleteLogForContact() { DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); RawContactUtil.delete(mResolver, ids.mRawContactId, true); DatabaseAsserts.assertHasDeleteLogGreaterThan(mResolver, ids.mContactId, baseTime); // already clean } private long getContactLastUpdatedTimestampByRawContactId(ContentResolver resolver, long rawContactId) { long contactId = RawContactUtil.queryContactIdByRawContactId(mResolver, rawContactId); MoreAsserts.assertNotEqual(CommonDatabaseUtils.NOT_FOUND, contactId); return ContactUtil.queryContactLastUpdatedTimestamp(mResolver, contactId); } public void testDataInsert_updatesContactLastUpdatedTimestamp() { sMockClock.install(); DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); sMockClock.advance(); insertPhoneNumberAndReturnDataId(ids.mRawContactId); long newTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); assertTrue(newTime > baseTime); // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testDataDelete_updatesContactLastUpdatedTimestamp() { sMockClock.install(); DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long dataId = insertPhoneNumberAndReturnDataId(ids.mRawContactId); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); sMockClock.advance(); DataUtil.delete(mResolver, dataId); long newTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); assertTrue(newTime > baseTime); // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } public void testDataUpdate_updatesContactLastUpdatedTimestamp() { sMockClock.install(); DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); long dataId = insertPhoneNumberAndReturnDataId(ids.mRawContactId); long baseTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); sMockClock.advance(); ContentValues values = new ContentValues(); values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, "555-5555"); DataUtil.update(mResolver, dataId, values); long newTime = ContactUtil.queryContactLastUpdatedTimestamp(mResolver, ids.mContactId); assertTrue(newTime > baseTime); // Clean up RawContactUtil.delete(mResolver, ids.mRawContactId, true); } private long insertPhoneNumberAndReturnDataId(long rawContactId) { Uri uri = insertPhoneNumber(rawContactId, "1-800-GOOG-411"); return ContentUris.parseId(uri); } public void testDeletedContactsDelete_isUnsupported() { final Uri URI = ContactsContract.DeletedContacts.CONTENT_URI; DatabaseAsserts.assertDeleteIsUnsupported(mResolver, URI); Uri uri = ContentUris.withAppendedId(URI, 1L); DatabaseAsserts.assertDeleteIsUnsupported(mResolver, uri); } public void testDeletedContactsInsert_isUnsupported() { final Uri URI = ContactsContract.DeletedContacts.CONTENT_URI; DatabaseAsserts.assertInsertIsUnsupported(mResolver, URI); } public void testQueryDeletedContactsByContactId() { DatabaseAsserts.ContactIdPair ids = assertContactCreateDelete(); MoreAsserts.assertNotEqual(CommonDatabaseUtils.NOT_FOUND, DeletedContactUtil.queryDeletedTimestampForContactId(mResolver, ids.mContactId)); } public void testQueryDeletedContactsAll() { final int numDeletes = 10; // Since we cannot clean out delete log from previous tests, we need to account for that // by querying for the count first. final long startCount = DeletedContactUtil.getCount(mResolver); for (int i = 0; i < numDeletes; i++) { assertContactCreateDelete(); } final long endCount = DeletedContactUtil.getCount(mResolver); assertEquals(numDeletes, endCount - startCount); } public void testQueryDeletedContactsSinceTimestamp() { sMockClock.install(); // Before final HashSet<Long> beforeIds = new HashSet<Long>(); beforeIds.add(assertContactCreateDelete().mContactId); beforeIds.add(assertContactCreateDelete().mContactId); final long start = sMockClock.currentTimeMillis(); // After final HashSet<Long> afterIds = new HashSet<Long>(); afterIds.add(assertContactCreateDelete().mContactId); afterIds.add(assertContactCreateDelete().mContactId); afterIds.add(assertContactCreateDelete().mContactId); final String[] projection = new String[]{ ContactsContract.DeletedContacts.CONTACT_ID, ContactsContract.DeletedContacts.CONTACT_DELETED_TIMESTAMP }; final List<String[]> records = DeletedContactUtil.querySinceTimestamp(mResolver, projection, start); for (String[] record : records) { // Check ids to make sure we only have the ones that came after the time. final long contactId = Long.parseLong(record[0]); assertFalse(beforeIds.contains(contactId)); assertTrue(afterIds.contains(contactId)); // Check times to make sure they came after assertTrue(Long.parseLong(record[1]) > start); } } /** * Create a contact. Assert it's not present in the delete log. Delete it. * And assert that the contact record is no longer present. * * @return The contact id and raw contact id that was created. */ private DatabaseAsserts.ContactIdPair assertContactCreateDelete() { DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver); assertEquals(CommonDatabaseUtils.NOT_FOUND, DeletedContactUtil.queryDeletedTimestampForContactId(mResolver, ids.mContactId)); sMockClock.advance(); ContactUtil.delete(mResolver, ids.mContactId); assertFalse(ContactUtil.recordExistsForContactId(mResolver, ids.mContactId)); return ids; } /** * End delta api tests. ******************************************************/ private Cursor queryGroupMemberships(Account account) { Cursor c = mResolver.query(TestUtil.maybeAddAccountQueryParameters(Data.CONTENT_URI, account), new String[]{GroupMembership.GROUP_ROW_ID, GroupMembership.RAW_CONTACT_ID}, Data.MIMETYPE + "=?", new String[]{GroupMembership.CONTENT_ITEM_TYPE}, GroupMembership.GROUP_SOURCE_ID); return c; } private String readToEnd(FileInputStream inputStream) { try { System.out.println("DECLARED INPUT STREAM LENGTH: " + inputStream.available()); int ch; StringBuilder stringBuilder = new StringBuilder(); int index = 0; while (true) { ch = inputStream.read(); System.out.println("READ CHARACTER: " + index + " " + ch); if (ch == -1) { break; } stringBuilder.append((char)ch); index++; } return stringBuilder.toString(); } catch (IOException e) { return null; } } private void assertQueryParameter(String uriString, String parameter, String expectedValue) { assertEquals(expectedValue, ContactsProvider2.getQueryParameter( Uri.parse(uriString), parameter)); } private long createContact(ContentValues values, String firstName, String givenName, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode) { return createContact(values, firstName, givenName, phoneNumber, email, presenceStatus, timesContacted, starred, groupId, chatMode, false); } private long createContact(ContentValues values, String firstName, String givenName, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode, boolean isUserProfile) { return queryContactId(createRawContact(values, firstName, givenName, phoneNumber, email, presenceStatus, timesContacted, starred, groupId, chatMode, isUserProfile)); } private long createRawContact(ContentValues values, String firstName, String givenName, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode) { long rawContactId = createRawContact(values, phoneNumber, email, presenceStatus, timesContacted, starred, groupId, chatMode); DataUtil.insertStructuredName(mResolver, rawContactId, firstName, givenName); return rawContactId; } private long createRawContact(ContentValues values, String firstName, String givenName, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode, boolean isUserProfile) { long rawContactId = createRawContact(values, phoneNumber, email, presenceStatus, timesContacted, starred, groupId, chatMode, isUserProfile); DataUtil.insertStructuredName(mResolver, rawContactId, firstName, givenName); return rawContactId; } private long createRawContact(ContentValues values, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode) { return createRawContact(values, phoneNumber, email, presenceStatus, timesContacted, starred, groupId, chatMode, false); } private long createRawContact(ContentValues values, String phoneNumber, String email, int presenceStatus, int timesContacted, int starred, long groupId, int chatMode, boolean isUserProfile) { values.put(RawContacts.STARRED, starred); values.put(RawContacts.SEND_TO_VOICEMAIL, 1); values.put(RawContacts.CUSTOM_RINGTONE, "beethoven5"); values.put(RawContacts.TIMES_CONTACTED, timesContacted); Uri insertionUri = isUserProfile ? Profile.CONTENT_RAW_CONTACTS_URI : RawContacts.CONTENT_URI; Uri rawContactUri = mResolver.insert(insertionUri, values); long rawContactId = ContentUris.parseId(rawContactUri); Uri photoUri = insertPhoto(rawContactId); long photoId = ContentUris.parseId(photoUri); values.put(Contacts.PHOTO_ID, photoId); if (!TextUtils.isEmpty(phoneNumber)) { insertPhoneNumber(rawContactId, phoneNumber); } if (!TextUtils.isEmpty(email)) { insertEmail(rawContactId, email); } insertStatusUpdate(Im.PROTOCOL_GOOGLE_TALK, null, email, presenceStatus, "hacking", chatMode, isUserProfile); if (groupId != 0) { insertGroupMembership(rawContactId, groupId); } return rawContactId; } /** * Creates a raw contact with pre-set values under the user's profile. * @param profileValues Values to be used to create the entry (common values will be * automatically populated in createRawContact()). * @return the raw contact ID that was created. */ private long createBasicProfileContact(ContentValues profileValues) { long profileRawContactId = createRawContact(profileValues, "Mia", "Prophyl", "18005554411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_CAMERA, true); profileValues.put(Contacts.DISPLAY_NAME, "Mia Prophyl"); return profileRawContactId; } /** * Creates a raw contact with pre-set values that is not under the user's profile. * @param nonProfileValues Values to be used to create the entry (common values will be * automatically populated in createRawContact()). * @return the raw contact ID that was created. */ private long createBasicNonProfileContact(ContentValues nonProfileValues) { long nonProfileRawContactId = createRawContact(nonProfileValues, "John", "Doe", "18004664411", "[email protected]", StatusUpdates.INVISIBLE, 4, 1, 0, StatusUpdates.CAPABILITY_HAS_CAMERA, false); nonProfileValues.put(Contacts.DISPLAY_NAME, "John Doe"); return nonProfileRawContactId; } private void putDataValues(ContentValues values, long rawContactId) { values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, "testmimetype"); values.put(Data.RES_PACKAGE, "oldpackage"); values.put(Data.IS_PRIMARY, 1); values.put(Data.IS_SUPER_PRIMARY, 1); values.put(Data.DATA1, "one"); values.put(Data.DATA2, "two"); values.put(Data.DATA3, "three"); values.put(Data.DATA4, "four"); values.put(Data.DATA5, "five"); values.put(Data.DATA6, "six"); values.put(Data.DATA7, "seven"); values.put(Data.DATA8, "eight"); values.put(Data.DATA9, "nine"); values.put(Data.DATA10, "ten"); values.put(Data.DATA11, "eleven"); values.put(Data.DATA12, "twelve"); values.put(Data.DATA13, "thirteen"); values.put(Data.DATA14, "fourteen"); values.put(Data.DATA15, "fifteen"); values.put(Data.SYNC1, "sync1"); values.put(Data.SYNC2, "sync2"); values.put(Data.SYNC3, "sync3"); values.put(Data.SYNC4, "sync4"); } /** * @param data1 email address or phone number * @param usageType One of {@link DataUsageFeedback#USAGE_TYPE} * @param values ContentValues for this feedback. Useful for incrementing * {Contacts#TIMES_CONTACTED} in the ContentValue. Can be null. */ private void sendFeedback(String data1, String usageType, ContentValues values) { final long dataId = getStoredLongValue(Data.CONTENT_URI, Data.DATA1 + "=?", new String[] { data1 }, Data._ID); MoreAsserts.assertNotEqual(0, updateDataUsageFeedback(usageType, dataId)); if (values != null && values.containsKey(Contacts.TIMES_CONTACTED)) { values.put(Contacts.TIMES_CONTACTED, values.getAsInteger(Contacts.TIMES_CONTACTED) + 1); } } private void updateDataUsageFeedback(String usageType, Uri resultUri) { final long id = ContentUris.parseId(resultUri); final boolean successful = updateDataUsageFeedback(usageType, id) > 0; assertTrue(successful); } private int updateDataUsageFeedback(String usageType, long... ids) { final StringBuilder idList = new StringBuilder(); for (long id : ids) { if (idList.length() > 0) idList.append(","); idList.append(id); } return mResolver.update(DataUsageFeedback.FEEDBACK_URI.buildUpon() .appendPath(idList.toString()) .appendQueryParameter(DataUsageFeedback.USAGE_TYPE, usageType) .build(), new ContentValues(), null, null); } private boolean hasChineseCollator() { final Locale locale[] = Collator.getAvailableLocales(); for (int i = 0; i < locale.length; i++) { if (locale[i].equals(Locale.CHINA)) { return true; } } return false; } private boolean hasJapaneseCollator() { final Locale locale[] = Collator.getAvailableLocales(); for (int i = 0; i < locale.length; i++) { if (locale[i].equals(Locale.JAPAN)) { return true; } } return false; } private boolean hasGermanCollator() { final Locale locale[] = Collator.getAvailableLocales(); for (int i = 0; i < locale.length; i++) { if (locale[i].equals(Locale.GERMANY)) { return true; } } return false; } }
diff --git a/src/org/mozilla/javascript/Interpreter.java b/src/org/mozilla/javascript/Interpreter.java index c90eff92..453bd71a 100644 --- a/src/org/mozilla/javascript/Interpreter.java +++ b/src/org/mozilla/javascript/Interpreter.java @@ -1,3086 +1,3086 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * The contents of this file are subject to the Netscape 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/NPL/ * * 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 Netscape are * Copyright (C) 1997-2000 Netscape Communications Corporation. All * Rights Reserved. * * Contributor(s): * Patrick Beard * Norris Boyd * Igor Bukanov * Roger Lawrence * * Alternatively, the contents of this file may be used under the * terms of the GNU Public License (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 NPL, indicate your decision by * deleting the provisions above and replace 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 NPL or the GPL. */ package org.mozilla.javascript; import java.io.*; import org.mozilla.javascript.debug.*; public class Interpreter { // Additional interpreter-specific codes private static final int BASE_ICODE = Token.LAST_BYTECODE_TOKEN; private static final int Icode_DUP = BASE_ICODE + 1, // various types of ++/-- Icode_NAMEINC = BASE_ICODE + 2, Icode_PROPINC = BASE_ICODE + 3, Icode_ELEMINC = BASE_ICODE + 4, Icode_VARINC = BASE_ICODE + 5, Icode_NAMEDEC = BASE_ICODE + 6, Icode_PROPDEC = BASE_ICODE + 7, Icode_ELEMDEC = BASE_ICODE + 8, Icode_VARDEC = BASE_ICODE + 9, // helper codes to deal with activation Icode_SCOPE = BASE_ICODE + 10, Icode_TYPEOFNAME = BASE_ICODE + 11, // Access to parent scope and prototype Icode_GETPROTO = BASE_ICODE + 12, Icode_GETPARENT = BASE_ICODE + 13, Icode_GETSCOPEPARENT = BASE_ICODE + 14, Icode_SETPROTO = BASE_ICODE + 15, Icode_SETPARENT = BASE_ICODE + 16, // Create closure object for nested functions Icode_CLOSURE = BASE_ICODE + 17, // Special calls Icode_CALLSPECIAL = BASE_ICODE + 18, // To return undefined value Icode_RETUNDEF = BASE_ICODE + 19, // Exception handling implementation Icode_CATCH = BASE_ICODE + 20, Icode_GOSUB = BASE_ICODE + 21, Icode_RETSUB = BASE_ICODE + 22, // To indicating a line number change in icodes. Icode_LINE = BASE_ICODE + 23, // To store shorts and ints inline Icode_SHORTNUMBER = BASE_ICODE + 24, Icode_INTNUMBER = BASE_ICODE + 25, // Last icode Icode_END = BASE_ICODE + 26; public IRFactory createIRFactory(Context cx, TokenStream ts) { return new IRFactory(this, ts); } public FunctionNode createFunctionNode(IRFactory irFactory, String name) { return new FunctionNode(name); } public ScriptOrFnNode transform(Context cx, IRFactory irFactory, ScriptOrFnNode tree) { (new NodeTransformer(irFactory)).transform(tree); return tree; } public Object compile(Context cx, Scriptable scope, ScriptOrFnNode tree, SecurityController securityController, Object securityDomain, String encodedSource) { scriptOrFn = tree; itsData = new InterpreterData(securityDomain, cx.getLanguageVersion()); itsData.itsSourceFile = scriptOrFn.getSourceName(); itsData.encodedSource = encodedSource; itsData.topLevel = true; if (tree instanceof FunctionNode) { generateFunctionICode(cx); return createFunction(cx, scope, itsData, false); } else { generateICodeFromTree(cx, scriptOrFn); return new InterpretedScript(itsData); } } public void notifyDebuggerCompilationDone(Context cx, Object scriptOrFunction, String debugSource) { InterpreterData idata; if (scriptOrFunction instanceof InterpretedScript) { idata = ((InterpretedScript)scriptOrFunction).itsData; } else { idata = ((InterpretedFunction)scriptOrFunction).itsData; } notifyDebugger_r(cx, idata, debugSource); } private static void notifyDebugger_r(Context cx, InterpreterData idata, String debugSource) { cx.debugger.handleCompilationDone(cx, idata, debugSource); if (idata.itsNestedFunctions != null) { for (int i = 0; i != idata.itsNestedFunctions.length; ++i) { notifyDebugger_r(cx, idata.itsNestedFunctions[i], debugSource); } } } private void generateFunctionICode(Context cx) { FunctionNode theFunction = (FunctionNode)scriptOrFn; itsData.itsFunctionType = theFunction.getFunctionType(); itsData.itsNeedsActivation = theFunction.requiresActivation(); itsData.itsName = theFunction.getFunctionName(); if (!theFunction.getIgnoreDynamicScope()) { if (cx.hasCompileFunctionsWithDynamicScope()) { itsData.useDynamicScope = true; } } generateICodeFromTree(cx, theFunction.getLastChild()); } private void generateICodeFromTree(Context cx, Node tree) { generateNestedFunctions(cx); generateRegExpLiterals(cx); int theICodeTop = 0; theICodeTop = generateICode(tree, theICodeTop); itsLabels.fixLabelGotos(itsData.itsICode); // add Icode_END only to scripts as function always ends with RETURN if (itsData.itsFunctionType == 0) { theICodeTop = addIcode(Icode_END, theICodeTop); } // Add special CATCH to simplify Interpreter.interpret logic // and workaround lack of goto in Java theICodeTop = addIcode(Icode_CATCH, theICodeTop); itsData.itsICodeTop = theICodeTop; if (itsData.itsICode.length != theICodeTop) { // Make itsData.itsICode length exactly theICodeTop to save memory // and catch bugs with jumps beyound icode as early as possible byte[] tmp = new byte[theICodeTop]; System.arraycopy(itsData.itsICode, 0, tmp, 0, theICodeTop); itsData.itsICode = tmp; } if (itsStrings.size() == 0) { itsData.itsStringTable = null; } else { itsData.itsStringTable = new String[itsStrings.size()]; ObjToIntMap.Iterator iter = itsStrings.newIterator(); for (iter.start(); !iter.done(); iter.next()) { String str = (String)iter.getKey(); int index = iter.getValue(); if (itsData.itsStringTable[index] != null) Context.codeBug(); itsData.itsStringTable[index] = str; } } if (itsDoubleTableTop == 0) { itsData.itsDoubleTable = null; } else if (itsData.itsDoubleTable.length != itsDoubleTableTop) { double[] tmp = new double[itsDoubleTableTop]; System.arraycopy(itsData.itsDoubleTable, 0, tmp, 0, itsDoubleTableTop); itsData.itsDoubleTable = tmp; } if (itsExceptionTableTop != 0 && itsData.itsExceptionTable.length != itsExceptionTableTop) { int[] tmp = new int[itsExceptionTableTop]; System.arraycopy(itsData.itsExceptionTable, 0, tmp, 0, itsExceptionTableTop); itsData.itsExceptionTable = tmp; } itsData.itsMaxVars = scriptOrFn.getParamAndVarCount(); // itsMaxFrameArray: interpret method needs this amount for its // stack and sDbl arrays itsData.itsMaxFrameArray = itsData.itsMaxVars + itsData.itsMaxLocals + itsData.itsMaxStack; itsData.argNames = scriptOrFn.getParamAndVarNames(); itsData.argCount = scriptOrFn.getParamCount(); itsData.encodedSourceStart = scriptOrFn.getEncodedSourceStart(); itsData.encodedSourceEnd = scriptOrFn.getEncodedSourceEnd(); if (Token.printICode) dumpICode(itsData); } private void generateNestedFunctions(Context cx) { int functionCount = scriptOrFn.getFunctionCount(); if (functionCount == 0) return; InterpreterData[] array = new InterpreterData[functionCount]; for (int i = 0; i != functionCount; i++) { FunctionNode def = scriptOrFn.getFunctionNode(i); Interpreter jsi = new Interpreter(); jsi.scriptOrFn = def; jsi.itsData = new InterpreterData(itsData.securityDomain, itsData.languageVersion); jsi.itsData.parentData = itsData; jsi.itsData.itsSourceFile = itsData.itsSourceFile; jsi.itsData.encodedSource = itsData.encodedSource; jsi.itsData.itsCheckThis = def.getCheckThis(); jsi.itsInFunctionFlag = true; jsi.generateFunctionICode(cx); array[i] = jsi.itsData; } itsData.itsNestedFunctions = array; } private void generateRegExpLiterals(Context cx) { int N = scriptOrFn.getRegexpCount(); if (N == 0) return; RegExpProxy rep = ScriptRuntime.checkRegExpProxy(cx); Object[] array = new Object[N]; for (int i = 0; i != N; i++) { String string = scriptOrFn.getRegexpString(i); String flags = scriptOrFn.getRegexpFlags(i); array[i] = rep.compileRegExp(cx, string, flags); } itsData.itsRegExpLiterals = array; } private int updateLineNumber(Node node, int iCodeTop) { int lineno = node.getLineno(); if (lineno != itsLineNumber && lineno >= 0) { itsLineNumber = lineno; iCodeTop = addIcode(Icode_LINE, iCodeTop); iCodeTop = addShort(lineno, iCodeTop); } return iCodeTop; } private void badTree(Node node) { throw new RuntimeException("Un-handled node: "+node.toString()); } private int generateICode(Node node, int iCodeTop) { int type = node.getType(); Node child = node.getFirstChild(); Node firstChild = child; switch (type) { case Token.FUNCTION : { int fnIndex = node.getExistingIntProp(Node.FUNCTION_PROP); FunctionNode fn = scriptOrFn.getFunctionNode(fnIndex); if (fn.getFunctionType() != FunctionNode.FUNCTION_STATEMENT) { // Only function expressions or function expression // statements needs closure code creating new function // object on stack as function statements are initialized // at script/function start iCodeTop = addIcode(Icode_CLOSURE, iCodeTop); iCodeTop = addIndex(fnIndex, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; } break; } case Token.SCRIPT : iCodeTop = updateLineNumber(node, iCodeTop); while (child != null) { if (child.getType() != Token.FUNCTION) iCodeTop = generateICode(child, iCodeTop); child = child.getNext(); } break; case Token.CASE : iCodeTop = updateLineNumber(node, iCodeTop); child = child.getNext(); while (child != null) { iCodeTop = generateICode(child, iCodeTop); child = child.getNext(); } break; case Token.LABEL : case Token.LOOP : case Token.DEFAULT : case Token.BLOCK : case Token.EMPTY : case Token.NOP : iCodeTop = updateLineNumber(node, iCodeTop); while (child != null) { iCodeTop = generateICode(child, iCodeTop); child = child.getNext(); } break; case Token.WITH : ++itsWithDepth; iCodeTop = updateLineNumber(node, iCodeTop); while (child != null) { iCodeTop = generateICode(child, iCodeTop); child = child.getNext(); } --itsWithDepth; break; case Token.COMMA : iCodeTop = generateICode(child, iCodeTop); while (null != (child = child.getNext())) { iCodeTop = addToken(Token.POP, iCodeTop); itsStackDepth--; iCodeTop = generateICode(child, iCodeTop); } break; case Token.SWITCH : { Node.Jump switchNode = (Node.Jump)node; iCodeTop = updateLineNumber(switchNode, iCodeTop); iCodeTop = generateICode(child, iCodeTop); int theLocalSlot = allocateLocal(); iCodeTop = addToken(Token.NEWTEMP, iCodeTop); iCodeTop = addByte(theLocalSlot, iCodeTop); iCodeTop = addToken(Token.POP, iCodeTop); itsStackDepth--; ObjArray cases = (ObjArray) switchNode.getProp(Node.CASES_PROP); for (int i = 0; i < cases.size(); i++) { Node thisCase = (Node)cases.get(i); Node first = thisCase.getFirstChild(); // the case expression is the firstmost child // the rest will be generated when the case // statements are encountered as siblings of // the switch statement. iCodeTop = generateICode(first, iCodeTop); iCodeTop = addToken(Token.USETEMP, iCodeTop); iCodeTop = addByte(theLocalSlot, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; iCodeTop = addToken(Token.SHEQ, iCodeTop); itsStackDepth--; Node.Target target = new Node.Target(); thisCase.addChildAfter(target, first); iCodeTop = addGoto(target, Token.IFEQ, iCodeTop); } Node defaultNode = (Node) switchNode.getProp(Node.DEFAULT_PROP); if (defaultNode != null) { Node.Target defaultTarget = new Node.Target(); defaultNode.getFirstChild(). addChildToFront(defaultTarget); iCodeTop = addGoto(defaultTarget, Token.GOTO, iCodeTop); } Node.Target breakTarget = switchNode.target; iCodeTop = addGoto(breakTarget, Token.GOTO, iCodeTop); break; } case Token.TARGET : markTargetLabel((Node.Target)node, iCodeTop); break; case Token.NEW : case Token.CALL : { int childCount = 0; String functionName = null; while (child != null) { iCodeTop = generateICode(child, iCodeTop); if (functionName == null) { int childType = child.getType(); if (childType == Token.NAME || childType == Token.GETPROP) { functionName = lastAddString; } } child = child.getNext(); childCount++; } int callType = node.getIntProp(Node.SPECIALCALL_PROP, Node.NON_SPECIALCALL); if (callType != Node.NON_SPECIALCALL) { // embed line number and source filename iCodeTop = addIcode(Icode_CALLSPECIAL, iCodeTop); iCodeTop = addByte(callType, iCodeTop); iCodeTop = addByte(type == Token.NEW ? 1 : 0, iCodeTop); iCodeTop = addShort(itsLineNumber, iCodeTop); } else { iCodeTop = addToken(type, iCodeTop); iCodeTop = addString(functionName, iCodeTop); } itsStackDepth -= (childCount - 1); // always a result value // subtract from child count to account for [thisObj &] fun if (type == Token.NEW) { childCount -= 1; } else { childCount -= 2; } iCodeTop = addIndex(childCount, iCodeTop); if (childCount > itsData.itsMaxCalleeArgs) itsData.itsMaxCalleeArgs = childCount; break; } case Token.NEWLOCAL : case Token.NEWTEMP : { iCodeTop = generateICode(child, iCodeTop); iCodeTop = addToken(Token.NEWTEMP, iCodeTop); iCodeTop = addLocalRef(node, iCodeTop); break; } case Token.USELOCAL : { iCodeTop = addToken(Token.USETEMP, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; Node temp = (Node) node.getProp(Node.LOCAL_PROP); iCodeTop = addLocalRef(temp, iCodeTop); break; } case Token.USETEMP : { iCodeTop = addToken(Token.USETEMP, iCodeTop); Node temp = (Node) node.getProp(Node.TEMP_PROP); iCodeTop = addLocalRef(temp, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; break; } case Token.IFEQ : case Token.IFNE : iCodeTop = generateICode(child, iCodeTop); itsStackDepth--; // after the conditional GOTO, really // fall thru... case Token.GOTO : { Node.Target target = ((Node.Jump)node).target; iCodeTop = addGoto(target, (byte) type, iCodeTop); break; } case Token.JSR : { Node.Target target = ((Node.Jump)node).target; iCodeTop = addGoto(target, Icode_GOSUB, iCodeTop); break; } case Token.FINALLY : { int finallyRegister = allocateLocal(); iCodeTop = addToken(Token.NEWTEMP, iCodeTop); iCodeTop = addByte(finallyRegister, iCodeTop); iCodeTop = addToken(Token.POP, iCodeTop); itsStackDepth--; while (child != null) { iCodeTop = generateICode(child, iCodeTop); child = child.getNext(); } iCodeTop = addIcode(Icode_RETSUB, iCodeTop); iCodeTop = addByte(finallyRegister, iCodeTop); releaseLocal(finallyRegister); break; } case Token.AND : { iCodeTop = generateICode(child, iCodeTop); iCodeTop = addIcode(Icode_DUP, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; int falseJumpStart = iCodeTop; iCodeTop = addForwardGoto(Token.IFNE, iCodeTop); iCodeTop = addToken(Token.POP, iCodeTop); itsStackDepth--; child = child.getNext(); iCodeTop = generateICode(child, iCodeTop); resolveForwardGoto(falseJumpStart, iCodeTop); break; } case Token.OR : { iCodeTop = generateICode(child, iCodeTop); iCodeTop = addIcode(Icode_DUP, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; int trueJumpStart = iCodeTop; iCodeTop = addForwardGoto(Token.IFEQ, iCodeTop); iCodeTop = addToken(Token.POP, iCodeTop); itsStackDepth--; child = child.getNext(); iCodeTop = generateICode(child, iCodeTop); resolveForwardGoto(trueJumpStart, iCodeTop); break; } case Token.GETPROP : { iCodeTop = generateICode(child, iCodeTop); String s = (String) node.getProp(Node.SPECIAL_PROP_PROP); if (s != null) { if (s.equals("__proto__")) { iCodeTop = addIcode(Icode_GETPROTO, iCodeTop); } else if (s.equals("__parent__")) { iCodeTop = addIcode(Icode_GETSCOPEPARENT, iCodeTop); } else { badTree(node); } } else { child = child.getNext(); iCodeTop = generateICode(child, iCodeTop); iCodeTop = addToken(Token.GETPROP, iCodeTop); itsStackDepth--; } break; } case Token.DELPROP : case Token.BITAND : case Token.BITOR : case Token.BITXOR : case Token.LSH : case Token.RSH : case Token.URSH : case Token.ADD : case Token.SUB : case Token.MOD : case Token.DIV : case Token.MUL : case Token.GETELEM : case Token.EQ: case Token.NE: case Token.SHEQ: case Token.SHNE: case Token.IN : case Token.INSTANCEOF : case Token.LE : case Token.LT : case Token.GE : case Token.GT : iCodeTop = generateICode(child, iCodeTop); child = child.getNext(); iCodeTop = generateICode(child, iCodeTop); iCodeTop = addToken(type, iCodeTop); itsStackDepth--; break; case Token.POS : case Token.NEG : case Token.NOT : case Token.BITNOT : case Token.TYPEOF : case Token.VOID : iCodeTop = generateICode(child, iCodeTop); if (type == Token.VOID) { iCodeTop = addToken(Token.POP, iCodeTop); iCodeTop = addToken(Token.UNDEFINED, iCodeTop); } else { iCodeTop = addToken(type, iCodeTop); } break; case Token.SETPROP : { iCodeTop = generateICode(child, iCodeTop); child = child.getNext(); iCodeTop = generateICode(child, iCodeTop); String s = (String) node.getProp(Node.SPECIAL_PROP_PROP); if (s != null) { if (s.equals("__proto__")) { iCodeTop = addIcode(Icode_SETPROTO, iCodeTop); } else if (s.equals("__parent__")) { iCodeTop = addIcode(Icode_SETPARENT, iCodeTop); } else { badTree(node); } } else { child = child.getNext(); iCodeTop = generateICode(child, iCodeTop); iCodeTop = addToken(Token.SETPROP, iCodeTop); itsStackDepth -= 2; } break; } case Token.SETELEM : iCodeTop = generateICode(child, iCodeTop); child = child.getNext(); iCodeTop = generateICode(child, iCodeTop); child = child.getNext(); iCodeTop = generateICode(child, iCodeTop); iCodeTop = addToken(Token.SETELEM, iCodeTop); itsStackDepth -= 2; break; case Token.SETNAME : iCodeTop = generateICode(child, iCodeTop); child = child.getNext(); iCodeTop = generateICode(child, iCodeTop); iCodeTop = addToken(Token.SETNAME, iCodeTop); iCodeTop = addString(firstChild.getString(), iCodeTop); itsStackDepth--; break; case Token.TYPEOFNAME : { String name = node.getString(); int index = -1; // use typeofname if an activation frame exists // since the vars all exist there instead of in jregs if (itsInFunctionFlag && !itsData.itsNeedsActivation) index = scriptOrFn.getParamOrVarIndex(name); if (index == -1) { iCodeTop = addIcode(Icode_TYPEOFNAME, iCodeTop); iCodeTop = addString(name, iCodeTop); } else { iCodeTop = addToken(Token.GETVAR, iCodeTop); iCodeTop = addByte(index, iCodeTop); iCodeTop = addToken(Token.TYPEOF, iCodeTop); } itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; break; } case Token.PARENT : iCodeTop = generateICode(child, iCodeTop); iCodeTop = addIcode(Icode_GETPARENT, iCodeTop); break; case Token.GETBASE : case Token.BINDNAME : case Token.NAME : case Token.STRING : iCodeTop = addToken(type, iCodeTop); iCodeTop = addString(node.getString(), iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; break; case Token.INC : case Token.DEC : { int childType = child.getType(); switch (childType) { case Token.GETVAR : { String name = child.getString(); if (itsData.itsNeedsActivation) { iCodeTop = addIcode(Icode_SCOPE, iCodeTop); iCodeTop = addToken(Token.STRING, iCodeTop); iCodeTop = addString(name, iCodeTop); itsStackDepth += 2; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; iCodeTop = addIcode(type == Token.INC ? Icode_PROPINC : Icode_PROPDEC, iCodeTop); itsStackDepth--; } else { int i = scriptOrFn.getParamOrVarIndex(name); iCodeTop = addIcode(type == Token.INC ? Icode_VARINC : Icode_VARDEC, iCodeTop); iCodeTop = addByte(i, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; } break; } case Token.GETPROP : case Token.GETELEM : { Node getPropChild = child.getFirstChild(); iCodeTop = generateICode(getPropChild, iCodeTop); getPropChild = getPropChild.getNext(); iCodeTop = generateICode(getPropChild, iCodeTop); int icode; if (childType == Token.GETPROP) { icode = (type == Token.INC) ? Icode_PROPINC : Icode_PROPDEC; } else { icode = (type == Token.INC) ? Icode_ELEMINC : Icode_ELEMDEC; } iCodeTop = addIcode(icode, iCodeTop); itsStackDepth--; break; } default : { iCodeTop = addIcode(type == Token.INC ? Icode_NAMEINC : Icode_NAMEDEC, iCodeTop); iCodeTop = addString(child.getString(), iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; break; } } break; } case Token.NUMBER : { double num = node.getDouble(); int inum = (int)num; if (inum == num) { if (inum == 0) { iCodeTop = addToken(Token.ZERO, iCodeTop); } else if (inum == 1) { iCodeTop = addToken(Token.ONE, iCodeTop); } else if ((short)inum == inum) { iCodeTop = addIcode(Icode_SHORTNUMBER, iCodeTop); iCodeTop = addShort(inum, iCodeTop); } else { iCodeTop = addIcode(Icode_INTNUMBER, iCodeTop); iCodeTop = addInt(inum, iCodeTop); } } else { iCodeTop = addToken(Token.NUMBER, iCodeTop); iCodeTop = addDouble(num, iCodeTop); } itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; break; } case Token.POP : case Token.POPV : iCodeTop = updateLineNumber(node, iCodeTop); iCodeTop = generateICode(child, iCodeTop); iCodeTop = addToken(type, iCodeTop); itsStackDepth--; break; case Token.ENTERWITH : iCodeTop = generateICode(child, iCodeTop); iCodeTop = addToken(Token.ENTERWITH, iCodeTop); itsStackDepth--; break; case Token.GETTHIS : iCodeTop = generateICode(child, iCodeTop); iCodeTop = addToken(Token.GETTHIS, iCodeTop); break; case Token.NEWSCOPE : iCodeTop = addToken(Token.NEWSCOPE, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; break; case Token.LEAVEWITH : iCodeTop = addToken(Token.LEAVEWITH, iCodeTop); break; case Token.TRY : { Node.Jump tryNode = (Node.Jump)node; Node catchTarget = tryNode.target; Node finallyTarget = tryNode.getFinally(); int tryStart = iCodeTop; int tryEnd = -1; int catchStart = -1; int finallyStart = -1; while (child != null) { boolean generated = false; if (child == catchTarget) { if (tryEnd >= 0) Context.codeBug(); tryEnd = iCodeTop; catchStart = iCodeTop; markTargetLabel((Node.Target)child, iCodeTop); generated = true; // Catch code has exception object on the stack itsStackDepth = 1; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; } else if (child == finallyTarget) { if (tryEnd < 0) { tryEnd = iCodeTop; } finallyStart = iCodeTop; markTargetLabel((Node.Target)child, iCodeTop); generated = true; // Adjust stack for finally code: on the top of the // stack it has either a PC value when called from // GOSUB or exception object to rethrow when called // from exception handler itsStackDepth = 1; if (itsStackDepth > itsData.itsMaxStack) { itsData.itsMaxStack = itsStackDepth; } } if (!generated) { iCodeTop = generateICode(child, iCodeTop); } child = child.getNext(); } itsStackDepth = 0; // [tryStart, tryEnd) contains GOSUB to call finally when it // presents at the end of try code and before return, break // continue that transfer control outside try. // After finally is executed the control will be // transfered back into [tryStart, tryEnd) and exception // handling assumes that the only code executed after // finally returns will be a jump outside try which could not // trigger exceptions. // It does not hold if instruction observer throws during // goto. Currently it may lead to double execution of finally. addExceptionHandler(tryStart, tryEnd, catchStart, finallyStart, itsWithDepth); break; } case Token.THROW : iCodeTop = updateLineNumber(node, iCodeTop); iCodeTop = generateICode(child, iCodeTop); iCodeTop = addToken(Token.THROW, iCodeTop); iCodeTop = addShort(itsLineNumber, iCodeTop); itsStackDepth--; break; case Token.RETURN : iCodeTop = updateLineNumber(node, iCodeTop); if (child != null) { iCodeTop = generateICode(child, iCodeTop); iCodeTop = addToken(Token.RETURN, iCodeTop); itsStackDepth--; } else { iCodeTop = addIcode(Icode_RETUNDEF, iCodeTop); } break; case Token.GETVAR : { String name = node.getString(); if (itsData.itsNeedsActivation) { // SETVAR handled this by turning into a SETPROP, but // we can't do that to a GETVAR without manufacturing // bogus children. Instead we use a special op to // push the current scope. iCodeTop = addIcode(Icode_SCOPE, iCodeTop); iCodeTop = addToken(Token.STRING, iCodeTop); iCodeTop = addString(name, iCodeTop); itsStackDepth += 2; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; iCodeTop = addToken(Token.GETPROP, iCodeTop); itsStackDepth--; } else { int index = scriptOrFn.getParamOrVarIndex(name); iCodeTop = addToken(Token.GETVAR, iCodeTop); iCodeTop = addByte(index, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; } break; } case Token.SETVAR : { if (itsData.itsNeedsActivation) { child.setType(Token.BINDNAME); node.setType(Token.SETNAME); iCodeTop = generateICode(node, iCodeTop); } else { String name = child.getString(); child = child.getNext(); iCodeTop = generateICode(child, iCodeTop); int index = scriptOrFn.getParamOrVarIndex(name); iCodeTop = addToken(Token.SETVAR, iCodeTop); iCodeTop = addByte(index, iCodeTop); } break; } case Token.NULL: case Token.THIS: case Token.THISFN: case Token.FALSE: case Token.TRUE: case Token.UNDEFINED: iCodeTop = addToken(type, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; break; case Token.ENUMINIT : iCodeTop = generateICode(child, iCodeTop); iCodeTop = addToken(Token.ENUMINIT, iCodeTop); iCodeTop = addLocalRef(node, iCodeTop); itsStackDepth--; break; case Token.ENUMNEXT : { iCodeTop = addToken(Token.ENUMNEXT, iCodeTop); Node init = (Node)node.getProp(Node.ENUM_PROP); iCodeTop = addLocalRef(init, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; break; } case Token.ENUMDONE : // could release the local here?? break; case Token.REGEXP : { int index = node.getExistingIntProp(Node.REGEXP_PROP); iCodeTop = addToken(Token.REGEXP, iCodeTop); iCodeTop = addIndex(index, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; break; } default : badTree(node); break; } return iCodeTop; } private int addLocalRef(Node node, int iCodeTop) { int theLocalSlot = node.getIntProp(Node.LOCAL_PROP, -1); if (theLocalSlot == -1) { theLocalSlot = allocateLocal(); node.putIntProp(Node.LOCAL_PROP, theLocalSlot); } iCodeTop = addByte(theLocalSlot, iCodeTop); return iCodeTop; } private int allocateLocal() { return itsData.itsMaxLocals++; } private void releaseLocal(int local) { } private int getTargetLabel(Node.Target target) { int targetLabel = target.labelId; if (targetLabel == -1) { targetLabel = itsLabels.acquireLabel(); target.labelId = targetLabel; } return targetLabel; } private void markTargetLabel(Node.Target target, int iCodeTop) { int label = getTargetLabel(target); itsLabels.markLabel(label, iCodeTop); } private int addGoto(Node.Target target, int gotoOp, int iCodeTop) { int targetLabel = getTargetLabel(target); int gotoPC = iCodeTop; if (gotoOp > BASE_ICODE) { iCodeTop = addIcode(gotoOp, iCodeTop); } else { iCodeTop = addToken(gotoOp, iCodeTop); } iCodeTop = addShort(0, iCodeTop); int targetPC = itsLabels.getLabelPC(targetLabel); if (targetPC != -1) { recordJumpOffset(gotoPC + 1, targetPC - gotoPC); } else { itsLabels.addLabelFixup(targetLabel, gotoPC + 1); } return iCodeTop; } private int addForwardGoto(int gotoOp, int iCodeTop) { iCodeTop = addToken(gotoOp, iCodeTop); iCodeTop = addShort(0, iCodeTop); return iCodeTop; } private void resolveForwardGoto(int jumpStart, int iCodeTop) { if (jumpStart + 3 > iCodeTop) Context.codeBug(); int offset = iCodeTop - jumpStart; // +1 to write after jump icode recordJumpOffset(jumpStart + 1, offset); } private void recordJumpOffset(int pos, int offset) { if (offset != (short)offset) { throw Context.reportRuntimeError0("msg.too.big.jump"); } itsData.itsICode[pos] = (byte)(offset >> 8); itsData.itsICode[pos + 1] = (byte)offset; } private int addByte(int b, int iCodeTop) { byte[] array = itsData.itsICode; if (iCodeTop == array.length) { array = increaseICodeCapasity(iCodeTop, 1); } array[iCodeTop++] = (byte)b; return iCodeTop; } private int addToken(int token, int iCodeTop) { if (!(Token.FIRST_BYTECODE_TOKEN <= token && token <= Token.LAST_BYTECODE_TOKEN)) { Context.codeBug(); } return addByte(token, iCodeTop); } private int addIcode(int icode, int iCodeTop) { if (!(BASE_ICODE < icode && icode <= Icode_END)) Context.codeBug(); return addByte(icode, iCodeTop); } private int addShort(int s, int iCodeTop) { byte[] array = itsData.itsICode; if (iCodeTop + 2 > array.length) { array = increaseICodeCapasity(iCodeTop, 2); } array[iCodeTop] = (byte)(s >>> 8); array[iCodeTop + 1] = (byte)s; return iCodeTop + 2; } private int addIndex(int index, int iCodeTop) { if (index < 0) Context.codeBug(); if (index > 0xFFFF) { throw Context.reportRuntimeError0("msg.too.big.index"); } byte[] array = itsData.itsICode; if (iCodeTop + 2 > array.length) { array = increaseICodeCapasity(iCodeTop, 2); } array[iCodeTop] = (byte)(index >>> 8); array[iCodeTop + 1] = (byte)index; return iCodeTop + 2; } private int addInt(int i, int iCodeTop) { byte[] array = itsData.itsICode; if (iCodeTop + 4 > array.length) { array = increaseICodeCapasity(iCodeTop, 4); } array[iCodeTop] = (byte)(i >>> 24); array[iCodeTop + 1] = (byte)(i >>> 16); array[iCodeTop + 2] = (byte)(i >>> 8); array[iCodeTop + 3] = (byte)i; return iCodeTop + 4; } private int addDouble(double num, int iCodeTop) { int index = itsDoubleTableTop; if (index == 0) { itsData.itsDoubleTable = new double[64]; } else if (itsData.itsDoubleTable.length == index) { double[] na = new double[index * 2]; System.arraycopy(itsData.itsDoubleTable, 0, na, 0, index); itsData.itsDoubleTable = na; } itsData.itsDoubleTable[index] = num; itsDoubleTableTop = index + 1; iCodeTop = addIndex(index, iCodeTop); return iCodeTop; } private int addString(String str, int iCodeTop) { int index = itsStrings.get(str, -1); if (index == -1) { index = itsStrings.size(); itsStrings.put(str, index); } iCodeTop = addIndex(index, iCodeTop); lastAddString = str; return iCodeTop; } private void addExceptionHandler(int icodeStart, int icodeEnd, int catchStart, int finallyStart, int withDepth) { int top = itsExceptionTableTop; int[] table = itsData.itsExceptionTable; if (table == null) { if (top != 0) Context.codeBug(); table = new int[EXCEPTION_SLOT_SIZE * 2]; itsData.itsExceptionTable = table; } else if (table.length == top) { table = new int[table.length * 2]; System.arraycopy(itsData.itsExceptionTable, 0, table, 0, top); itsData.itsExceptionTable = table; } table[top + EXCEPTION_TRY_START_SLOT] = icodeStart; table[top + EXCEPTION_TRY_END_SLOT] = icodeEnd; table[top + EXCEPTION_CATCH_SLOT] = catchStart; table[top + EXCEPTION_FINALLY_SLOT] = finallyStart; table[top + EXCEPTION_WITH_DEPTH_SLOT] = withDepth; itsExceptionTableTop = top + EXCEPTION_SLOT_SIZE; } private byte[] increaseICodeCapasity(int iCodeTop, int extraSize) { int capacity = itsData.itsICode.length; if (iCodeTop + extraSize <= capacity) Context.codeBug(); capacity *= 2; if (iCodeTop + extraSize > capacity) { capacity = iCodeTop + extraSize; } byte[] array = new byte[capacity]; System.arraycopy(itsData.itsICode, 0, array, 0, iCodeTop); itsData.itsICode = array; return array; } private static int getShort(byte[] iCode, int pc) { return (iCode[pc] << 8) | (iCode[pc + 1] & 0xFF); } private static int getIndex(byte[] iCode, int pc) { return ((iCode[pc] & 0xFF) << 8) | (iCode[pc + 1] & 0xFF); } private static int getInt(byte[] iCode, int pc) { return (iCode[pc] << 24) | ((iCode[pc + 1] & 0xFF) << 16) | ((iCode[pc + 2] & 0xFF) << 8) | (iCode[pc + 3] & 0xFF); } private static int getTarget(byte[] iCode, int pc) { int displacement = getShort(iCode, pc); return pc - 1 + displacement; } private static int getExceptionHandler(int[] exceptionTable, int pc) { // OPT: use binary search if (exceptionTable == null) { return -1; } int best = -1, bestStart = 0, bestEnd = 0; for (int i = 0; i != exceptionTable.length; i += EXCEPTION_SLOT_SIZE) { int start = exceptionTable[i + EXCEPTION_TRY_START_SLOT]; int end = exceptionTable[i + EXCEPTION_TRY_END_SLOT]; if (start <= pc && pc < end) { if (best < 0 || bestStart <= start) { // Check handlers are nested if (best >= 0 && bestEnd < end) Context.codeBug(); best = i; bestStart = start; bestEnd = end; } } } return best; } private static String icodeToName(int icode) { if (Token.printICode) { if (icode <= Token.LAST_BYTECODE_TOKEN) { return Token.name(icode); } else { switch (icode) { case Icode_DUP: return "dup"; case Icode_NAMEINC: return "nameinc"; case Icode_PROPINC: return "propinc"; case Icode_ELEMINC: return "eleminc"; case Icode_VARINC: return "varinc"; case Icode_NAMEDEC: return "namedec"; case Icode_PROPDEC: return "propdec"; case Icode_ELEMDEC: return "elemdec"; case Icode_VARDEC: return "vardec"; case Icode_SCOPE: return "scope"; case Icode_TYPEOFNAME: return "typeofname"; case Icode_GETPROTO: return "getproto"; case Icode_GETPARENT: return "getparent"; case Icode_GETSCOPEPARENT: return "getscopeparent"; case Icode_SETPROTO: return "setproto"; case Icode_SETPARENT: return "setparent"; case Icode_CLOSURE: return "closure"; case Icode_CALLSPECIAL: return "callspecial"; case Icode_RETUNDEF: return "retundef"; case Icode_CATCH: return "catch"; case Icode_GOSUB: return "gosub"; case Icode_RETSUB: return "retsub"; case Icode_LINE: return "line"; case Icode_SHORTNUMBER: return "shortnumber"; case Icode_INTNUMBER: return "intnumber"; case Icode_END: return "end"; } } return "<UNKNOWN ICODE: "+icode+">"; } return ""; } private static void dumpICode(InterpreterData idata) { if (Token.printICode) { int iCodeLength = idata.itsICodeTop; byte iCode[] = idata.itsICode; String[] strings = idata.itsStringTable; PrintStream out = System.out; out.println("ICode dump, for " + idata.itsName + ", length = " + iCodeLength); out.println("MaxStack = " + idata.itsMaxStack); for (int pc = 0; pc < iCodeLength; ) { out.flush(); out.print(" [" + pc + "] "); int token = iCode[pc] & 0xff; String tname = icodeToName(token); int old_pc = pc; ++pc; int icodeLength = icodeTokenLength(token); switch (token) { default: if (icodeLength != 1) Context.codeBug(); out.println(tname); break; case Icode_GOSUB : case Token.GOTO : case Token.IFEQ : case Token.IFNE : { int newPC = getTarget(iCode, pc); out.println(tname + " " + newPC); pc += 2; break; } case Icode_RETSUB : case Token.ENUMINIT : case Token.ENUMNEXT : case Icode_VARINC : case Icode_VARDEC : case Token.GETVAR : case Token.SETVAR : case Token.NEWTEMP : case Token.USETEMP : { int slot = (iCode[pc] & 0xFF); out.println(tname + " " + slot); pc++; break; } case Icode_CALLSPECIAL : { int callType = iCode[pc] & 0xFF; boolean isNew = (iCode[pc + 1] != 0); int line = getShort(iCode, pc+2); int count = getIndex(iCode, pc + 4); out.println(tname+" "+callType+" "+isNew +" "+count+" "+line); pc += 8; break; } case Token.REGEXP : { int i = getIndex(iCode, pc); Object regexp = idata.itsRegExpLiterals[i]; out.println(tname + " " + regexp); pc += 2; break; } case Icode_CLOSURE : { int i = getIndex(iCode, pc); InterpreterData data2 = idata.itsNestedFunctions[i]; out.println(tname + " " + data2); pc += 2; break; } case Token.NEW : case Token.CALL : { int count = getIndex(iCode, pc + 2); String name = strings[getIndex(iCode, pc)]; out.println(tname+' '+count+" \""+name+'"'); pc += 4; break; } case Icode_SHORTNUMBER : { int value = getShort(iCode, pc); out.println(tname + " " + value); pc += 2; break; } case Icode_INTNUMBER : { int value = getInt(iCode, pc); out.println(tname + " " + value); pc += 4; break; } case Token.NUMBER : { int index = getIndex(iCode, pc); double value = idata.itsDoubleTable[index]; out.println(tname + " " + value); pc += 2; break; } case Icode_TYPEOFNAME : case Token.GETBASE : case Token.BINDNAME : case Token.SETNAME : case Token.NAME : case Icode_NAMEINC : case Icode_NAMEDEC : case Token.STRING : { String str = strings[getIndex(iCode, pc)]; out.println(tname + " \"" + str + '"'); pc += 2; break; } case Icode_LINE : { int line = getShort(iCode, pc); out.println(tname + " : " + line); pc += 2; break; } } if (old_pc + icodeLength != pc) Context.codeBug(); } int[] table = idata.itsExceptionTable; if (table != null) { out.println("Exception handlers: " +table.length / EXCEPTION_SLOT_SIZE); for (int i = 0; i != table.length; i += EXCEPTION_SLOT_SIZE) { int tryStart = table[i + EXCEPTION_TRY_START_SLOT]; int tryEnd = table[i + EXCEPTION_TRY_END_SLOT]; int catchStart = table[i + EXCEPTION_CATCH_SLOT]; int finallyStart = table[i + EXCEPTION_FINALLY_SLOT]; int withDepth = table[i + EXCEPTION_WITH_DEPTH_SLOT]; out.println(" "+tryStart+"\t "+tryEnd+"\t " +catchStart+"\t "+finallyStart +"\t "+withDepth); } } out.flush(); } } private static int icodeTokenLength(int icodeToken) { switch (icodeToken) { case Icode_SCOPE : case Icode_GETPROTO : case Icode_GETPARENT : case Icode_GETSCOPEPARENT : case Icode_SETPROTO : case Icode_SETPARENT : case Token.DELPROP : case Token.TYPEOF : case Token.NEWSCOPE : case Token.ENTERWITH : case Token.LEAVEWITH : case Token.RETURN : case Token.GETTHIS : case Token.SETELEM : case Token.GETELEM : case Token.SETPROP : case Token.GETPROP : case Icode_PROPINC : case Icode_PROPDEC : case Icode_ELEMINC : case Icode_ELEMDEC : case Token.BITNOT : case Token.BITAND : case Token.BITOR : case Token.BITXOR : case Token.LSH : case Token.RSH : case Token.URSH : case Token.NOT : case Token.POS : case Token.NEG : case Token.SUB : case Token.MUL : case Token.DIV : case Token.MOD : case Token.ADD : case Token.POPV : case Token.POP : case Icode_DUP : case Token.LT : case Token.GT : case Token.LE : case Token.GE : case Token.IN : case Token.INSTANCEOF : case Token.EQ : case Token.NE : case Token.SHEQ : case Token.SHNE : case Token.ZERO : case Token.ONE : case Token.NULL : case Token.THIS : case Token.THISFN : case Token.FALSE : case Token.TRUE : case Token.UNDEFINED : case Icode_CATCH: case Icode_RETUNDEF: case Icode_END: return 1; case Token.THROW : // source line return 1 + 2; case Icode_GOSUB : case Token.GOTO : case Token.IFEQ : case Token.IFNE : // target pc offset return 1 + 2; case Icode_RETSUB : case Token.ENUMINIT : case Token.ENUMNEXT : case Icode_VARINC : case Icode_VARDEC : case Token.GETVAR : case Token.SETVAR : case Token.NEWTEMP : case Token.USETEMP : // slot index return 1 + 1; case Icode_CALLSPECIAL : // call type // is new // line number // arg count return 1 + 1 + 1 + 2 + 2; case Token.REGEXP : // regexp index return 1 + 2; case Icode_CLOSURE : // index of closure master copy return 1 + 2; case Token.NEW : case Token.CALL : // name string index // arg count return 1 + 2 + 2; case Icode_SHORTNUMBER : // short number return 1 + 2; case Icode_INTNUMBER : // int number return 1 + 4; case Token.NUMBER : // index of double number return 1 + 2; case Icode_TYPEOFNAME : case Token.GETBASE : case Token.BINDNAME : case Token.SETNAME : case Token.NAME : case Icode_NAMEINC : case Icode_NAMEDEC : case Token.STRING : // string index return 1 + 2; case Icode_LINE : // line number return 1 + 2; default: Context.codeBug(); // Bad icodeToken return 0; } } static int[] getLineNumbers(InterpreterData data) { UintMap presentLines = new UintMap(); int iCodeLength = data.itsICodeTop; byte[] iCode = data.itsICode; for (int pc = 0; pc != iCodeLength;) { int icodeToken = iCode[pc] & 0xff; int icodeLength = icodeTokenLength(icodeToken); if (icodeToken == Icode_LINE) { if (icodeLength != 3) Context.codeBug(); int line = getShort(iCode, pc + 1); presentLines.put(line, 0); } pc += icodeLength; } return presentLines.getKeys(); } static String getSourcePositionFromStack(Context cx, int[] linep) { InterpreterData idata = cx.interpreterData; linep[0] = getShort(idata.itsICode, cx.interpreterLineIndex); return idata.itsSourceFile; } static Object getEncodedSource(InterpreterData idata) { if (idata.encodedSource == null) { return null; } return idata.encodedSource.substring(idata.encodedSourceStart, idata.encodedSourceEnd); } private static Scriptable[] wrapRegExps(Context cx, Scriptable scope, InterpreterData idata) { if (idata.itsRegExpLiterals == null) Context.codeBug(); RegExpProxy rep = ScriptRuntime.checkRegExpProxy(cx); int N = idata.itsRegExpLiterals.length; Scriptable[] array = new Scriptable[N]; for (int i = 0; i != N; ++i) { array[i] = rep.wrapRegExp(cx, scope, idata.itsRegExpLiterals[i]); } return array; } private static InterpretedFunction createFunction(Context cx, Scriptable scope, InterpreterData idata, boolean fromEvalCode) { InterpretedFunction fn = new InterpretedFunction(idata); if (idata.itsRegExpLiterals != null) { fn.itsRegExps = wrapRegExps(cx, scope, idata); } ScriptRuntime.initFunction(cx, scope, fn, idata.itsFunctionType, fromEvalCode); return fn; } static Object interpret(Context cx, Scriptable scope, Scriptable thisObj, Object[] args, double[] argsDbl, int argShift, int argCount, NativeFunction fnOrScript, InterpreterData idata) throws JavaScriptException { if (cx.interpreterSecurityDomain != idata.securityDomain) { return execWithNewDomain(cx, scope, thisObj, args, argsDbl, argShift, argCount, fnOrScript, idata); } final Object DBL_MRK = Interpreter.DBL_MRK; final Scriptable undefined = Undefined.instance; final int VAR_SHFT = 0; final int maxVars = idata.itsMaxVars; final int LOCAL_SHFT = VAR_SHFT + maxVars; final int STACK_SHFT = LOCAL_SHFT + idata.itsMaxLocals; // stack[VAR_SHFT <= i < LOCAL_SHFT]: variables // stack[LOCAL_SHFT <= i < TRY_STACK_SHFT]: used for newtemp/usetemp // stack[STACK_SHFT <= i < STACK_SHFT + idata.itsMaxStack]: stack data // sDbl[i]: if stack[i] is DBL_MRK, sDbl[i] holds the number value int maxFrameArray = idata.itsMaxFrameArray; if (maxFrameArray != STACK_SHFT + idata.itsMaxStack) Context.codeBug(); Object[] stack = new Object[maxFrameArray]; double[] sDbl = new double[maxFrameArray]; int stackTop = STACK_SHFT - 1; int withDepth = 0; int definedArgs = fnOrScript.argCount; if (definedArgs > argCount) { definedArgs = argCount; } for (int i = 0; i != definedArgs; ++i) { Object arg = args[argShift + i]; stack[VAR_SHFT + i] = arg; if (arg == DBL_MRK) { sDbl[VAR_SHFT + i] = argsDbl[argShift + i]; } } for (int i = definedArgs; i != maxVars; ++i) { stack[VAR_SHFT + i] = undefined; } DebugFrame debuggerFrame = null; if (cx.debugger != null) { debuggerFrame = cx.debugger.getFrame(cx, idata); } if (idata.itsFunctionType != 0) { InterpretedFunction f = (InterpretedFunction)fnOrScript; if (!idata.useDynamicScope) { scope = fnOrScript.getParentScope(); } if (idata.itsCheckThis) { thisObj = ScriptRuntime.getThis(thisObj); } if (idata.itsNeedsActivation) { if (argsDbl != null) { args = getArgsArray(args, argsDbl, argShift, argCount); argShift = 0; argsDbl = null; } scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript, thisObj, args); } } else { ScriptRuntime.initScript(cx, scope, fnOrScript, thisObj, idata.itsFromEvalCode); } if (idata.itsNestedFunctions != null) { if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) Context.codeBug(); for (int i = 0; i < idata.itsNestedFunctions.length; i++) { InterpreterData fdata = idata.itsNestedFunctions[i]; if (fdata.itsFunctionType == FunctionNode.FUNCTION_STATEMENT) { createFunction(cx, scope, fdata, idata.itsFromEvalCode); } } } // Wrapped regexps for functions are stored in InterpretedFunction // but for script which should not contain references to scope // the regexps re-wrapped during each script execution Scriptable[] scriptRegExps = null; boolean useActivationVars = false; if (debuggerFrame != null) { if (argsDbl != null) { args = getArgsArray(args, argsDbl, argShift, argCount); argShift = 0; argsDbl = null; } if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) { useActivationVars = true; scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript, thisObj, args); } debuggerFrame.onEnter(cx, scope, thisObj, args); } InterpreterData savedData = cx.interpreterData; cx.interpreterData = idata; Object result = undefined; // If javaException != null on exit, it will be throw instead of // normal return Throwable javaException = null; int exceptionPC = -1; byte[] iCode = idata.itsICode; String[] strings = idata.itsStringTable; int pc = 0; int pcPrevBranch = pc; final int instructionThreshold = cx.instructionThreshold; // During function call this will be set to -1 so catch can properly // adjust it int instructionCount = cx.instructionCount; // arbitrary number to add to instructionCount when calling // other functions final int INVOCATION_COST = 100; Loop: for (;;) { try { switch (iCode[pc] & 0xff) { // Back indent to ease imlementation reading case Icode_CATCH: { // The following code should be executed inside try/catch inside main // loop, not in the loop catch block itself to deal withnexceptions // from observeInstructionCount. A special bytecode is used only to // simplify logic. if (javaException == null) Context.codeBug(); int pcNew = -1; boolean doCatch = false; int handlerOffset = getExceptionHandler(idata.itsExceptionTable, exceptionPC); if (handlerOffset >= 0) { final int SCRIPT_CAN_CATCH = 0, ONLY_FINALLY = 1, OTHER = 2; int exType; if (javaException instanceof JavaScriptException) { exType = SCRIPT_CAN_CATCH; } else if (javaException instanceof EcmaError) { // an offical ECMA error object, exType = SCRIPT_CAN_CATCH; } else if (javaException instanceof WrappedException) { exType = SCRIPT_CAN_CATCH; } else if (javaException instanceof RuntimeException) { exType = ONLY_FINALLY; } else { // Error instance exType = OTHER; } if (exType != OTHER) { // Do not allow for JS to interfere with Error instances // (exType == OTHER), as they can be used to terminate // long running script if (exType == SCRIPT_CAN_CATCH) { // Allow JS to catch only JavaScriptException and // EcmaError pcNew = idata.itsExceptionTable[handlerOffset + EXCEPTION_CATCH_SLOT]; if (pcNew >= 0) { // Has catch block doCatch = true; } } if (pcNew < 0) { pcNew = idata.itsExceptionTable[handlerOffset + EXCEPTION_FINALLY_SLOT]; } } } if (debuggerFrame != null && !(javaException instanceof Error)) { debuggerFrame.onExceptionThrown(cx, javaException); } if (pcNew < 0) { break Loop; } // We caught an exception // restore scope at try point int tryWithDepth = idata.itsExceptionTable[ handlerOffset + EXCEPTION_WITH_DEPTH_SLOT]; while (tryWithDepth != withDepth) { if (scope == null) Context.codeBug(); scope = ScriptRuntime.leaveWith(scope); --withDepth; } // make stack to contain single exception object stackTop = STACK_SHFT; if (doCatch) { stack[stackTop] = ScriptRuntime.getCatchObject(cx, scope, javaException); } else { // Call finally handler with javaException on stack top to // distinguish from normal invocation through GOSUB // which would contain DBL_MRK on the stack stack[stackTop] = javaException; } // clear exception javaException = null; // Notify instruction observer if necessary // and point pc and pcPrevBranch to start of catch/finally block if (instructionThreshold != 0) { if (instructionCount > instructionThreshold) { // Note: this can throw Error cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = pcNew; continue Loop; } case Token.THROW: { Object value = stack[stackTop]; if (value == DBL_MRK) value = doubleWrap(sDbl[stackTop]); --stackTop; int sourceLine = getShort(iCode, pc + 1); javaException = new JavaScriptException(value, idata.itsSourceFile, sourceLine); exceptionPC = pc; if (instructionThreshold != 0) { instructionCount += pc + 1 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getJavaCatchPC(iCode); continue Loop; } case Token.GE : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; if (rhs == DBL_MRK || lhs == DBL_MRK) { double rDbl = stack_double(stack, sDbl, stackTop + 1); double lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && rDbl <= lDbl); } else { valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.LE : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; if (rhs == DBL_MRK || lhs == DBL_MRK) { double rDbl = stack_double(stack, sDbl, stackTop + 1); double lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && lDbl <= rDbl); } else { valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.GT : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; if (rhs == DBL_MRK || lhs == DBL_MRK) { double rDbl = stack_double(stack, sDbl, stackTop + 1); double lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && rDbl < lDbl); } else { valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.LT : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; if (rhs == DBL_MRK || lhs == DBL_MRK) { double rDbl = stack_double(stack, sDbl, stackTop + 1); double lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && lDbl < rDbl); } else { valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.IN : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); boolean valBln = ScriptRuntime.in(lhs, rhs, scope); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.INSTANCEOF : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); boolean valBln = ScriptRuntime.instanceOf(lhs, rhs, scope); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.EQ : { --stackTop; boolean valBln = do_eq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.NE : { --stackTop; boolean valBln = !do_eq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.SHEQ : { --stackTop; boolean valBln = do_sheq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.SHNE : { --stackTop; boolean valBln = !do_sheq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.IFNE : { boolean valBln = stack_boolean(stack, sDbl, stackTop); --stackTop; if (!valBln) { if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop; } pc += 2; break; } case Token.IFEQ : { boolean valBln = stack_boolean(stack, sDbl, stackTop); --stackTop; if (valBln) { if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop; } pc += 2; break; } case Token.GOTO : if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop; case Icode_GOSUB : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = pc + 3; if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop; case Icode_RETSUB : { int slot = (iCode[pc + 1] & 0xFF); if (instructionThreshold != 0) { instructionCount += pc + 2 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } int newPC; Object value = stack[LOCAL_SHFT + slot]; if (value != DBL_MRK) { // Invocation from exception handler, restore object to rethrow javaException = (Throwable)value; exceptionPC = pc; newPC = getJavaCatchPC(iCode); } else { // Normal return from GOSUB newPC = (int)sDbl[LOCAL_SHFT + slot]; } pcPrevBranch = pc = newPC; continue Loop; } case Token.POP : stack[stackTop] = null; stackTop--; break; case Icode_DUP : stack[stackTop + 1] = stack[stackTop]; sDbl[stackTop + 1] = sDbl[stackTop]; stackTop++; break; case Token.POPV : result = stack[stackTop]; if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]); stack[stackTop] = null; --stackTop; break; case Token.RETURN : result = stack[stackTop]; if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]); --stackTop; break Loop; case Icode_RETUNDEF : result = undefined; break Loop; case Icode_END: break Loop; case Token.BITNOT : { int rIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ~rIntValue; break; } case Token.BITAND : { int rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; int lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue & rIntValue; break; } case Token.BITOR : { int rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; int lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue | rIntValue; break; } case Token.BITXOR : { int rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; int lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue ^ rIntValue; break; } case Token.LSH : { int rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; int lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue << rIntValue; break; } case Token.RSH : { int rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; int lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue >> rIntValue; break; } case Token.URSH : { int rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F; --stackTop; double lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue; break; } case Token.ADD : --stackTop; do_add(stack, sDbl, stackTop); break; case Token.SUB : { double rDbl = stack_double(stack, sDbl, stackTop); --stackTop; double lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl - rDbl; break; } case Token.NEG : { double rDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = -rDbl; break; } case Token.POS : { double rDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = rDbl; break; } case Token.MUL : { double rDbl = stack_double(stack, sDbl, stackTop); --stackTop; double lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl * rDbl; break; } case Token.DIV : { double rDbl = stack_double(stack, sDbl, stackTop); --stackTop; double lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; // Detect the divide by zero or let Java do it ? sDbl[stackTop] = lDbl / rDbl; break; } case Token.MOD : { double rDbl = stack_double(stack, sDbl, stackTop); --stackTop; double lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl % rDbl; break; } case Token.NOT : { stack[stackTop] = stack_boolean(stack, sDbl, stackTop) ? Boolean.FALSE : Boolean.TRUE; break; } case Token.BINDNAME : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.bind(scope, name); pc += 2; break; } case Token.GETBASE : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.getBase(scope, name); pc += 2; break; } case Token.SETNAME : { String name = strings[getIndex(iCode, pc + 1)]; Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; // what about class cast exception here for lhs? Scriptable lhs = (Scriptable)stack[stackTop]; stack[stackTop] = ScriptRuntime.setName(lhs, rhs, scope, name); pc += 2; break; } case Token.DELPROP : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.delete(cx, scope, lhs, rhs); break; } case Token.GETPROP : { String name = (String)stack[stackTop]; --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getProp(lhs, name, scope); break; } case Token.SETPROP : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; String name = (String)stack[stackTop]; --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setProp(lhs, name, rhs, scope); break; } case Token.GETELEM : do_getElem(cx, stack, sDbl, stackTop, scope); --stackTop; break; case Token.SETELEM : do_setElem(cx, stack, sDbl, stackTop, scope); stackTop -= 2; break; case Icode_PROPINC : { String name = (String)stack[stackTop]; --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postIncrement(lhs, name, scope); break; } case Icode_PROPDEC : { String name = (String)stack[stackTop]; --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postDecrement(lhs, name, scope); break; } case Icode_ELEMINC : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postIncrementElem(lhs, rhs, scope); break; } case Icode_ELEMDEC : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postDecrementElem(lhs, rhs, scope); break; } case Token.GETTHIS : { Scriptable lhs = (Scriptable)stack[stackTop]; stack[stackTop] = ScriptRuntime.getThis(lhs); break; } case Token.NEWTEMP : { int slot = (iCode[++pc] & 0xFF); stack[LOCAL_SHFT + slot] = stack[stackTop]; sDbl[LOCAL_SHFT + slot] = sDbl[stackTop]; break; } case Token.USETEMP : { int slot = (iCode[++pc] & 0xFF); ++stackTop; stack[stackTop] = stack[LOCAL_SHFT + slot]; sDbl[stackTop] = sDbl[LOCAL_SHFT + slot]; break; } case Icode_CALLSPECIAL : { if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } int callType = iCode[pc + 1] & 0xFF; boolean isNew = (iCode[pc + 2] != 0); int sourceLine = getShort(iCode, pc + 3); int count = getIndex(iCode, pc + 5); stackTop -= count; Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, count); Object functionThis; if (isNew) { functionThis = null; } else { functionThis = stack[stackTop]; if (functionThis == DBL_MRK) { functionThis = doubleWrap(sDbl[stackTop]); } --stackTop; } Object function = stack[stackTop]; if (function == DBL_MRK) function = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.callSpecial( cx, function, isNew, functionThis, outArgs, scope, thisObj, callType, idata.itsSourceFile, sourceLine); pc += 6; instructionCount = cx.instructionCount; break; } case Token.CALL : { if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } int count = getIndex(iCode, pc + 3); stackTop -= count; int calleeArgShft = stackTop + 1; Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; Scriptable calleeScope = scope; if (idata.itsNeedsActivation) { calleeScope = ScriptableObject.getTopLevelScope(scope); } Scriptable calleeThis; if (rhs instanceof Scriptable || rhs == null) { calleeThis = (Scriptable)rhs; } else { calleeThis = ScriptRuntime.toObject(cx, calleeScope, rhs); } if (lhs instanceof InterpretedFunction) { // Inlining of InterpretedFunction.call not to create // argument array InterpretedFunction f = (InterpretedFunction)lhs; stack[stackTop] = interpret(cx, calleeScope, calleeThis, stack, sDbl, calleeArgShft, count, f, f.itsData); } else if (lhs instanceof Function) { Function f = (Function)lhs; Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count); stack[stackTop] = f.call(cx, calleeScope, calleeThis, outArgs); } else { if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); else if (lhs == undefined) { // special code for better error message for call // to undefined lhs = strings[getIndex(iCode, pc + 1)]; if (lhs == null) lhs = undefined; } throw ScriptRuntime.typeError1("msg.isnt.function", ScriptRuntime.toString(lhs)); } pc += 4; instructionCount = cx.instructionCount; break; } case Token.NEW : { if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } int count = getIndex(iCode, pc + 3); stackTop -= count; int calleeArgShft = stackTop + 1; Object lhs = stack[stackTop]; if (lhs instanceof InterpretedFunction) { // Inlining of InterpretedFunction.construct not to create // argument array InterpretedFunction f = (InterpretedFunction)lhs; Scriptable newInstance = f.createObject(cx, scope); Object callResult = interpret(cx, scope, newInstance, stack, sDbl, calleeArgShft, count, f, f.itsData); if (callResult instanceof Scriptable && callResult != undefined) { stack[stackTop] = callResult; } else { stack[stackTop] = newInstance; } } else if (lhs instanceof Function) { Function f = (Function)lhs; Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count); stack[stackTop] = f.construct(cx, scope, outArgs); } else { if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); else if (lhs == undefined) { // special code for better error message for call // to undefined lhs = strings[getIndex(iCode, pc + 1)]; if (lhs == null) lhs = undefined; } throw ScriptRuntime.typeError1("msg.isnt.function", ScriptRuntime.toString(lhs)); } pc += 4; instructionCount = cx.instructionCount; break; } case Token.TYPEOF : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.typeof(lhs); break; } case Icode_TYPEOFNAME : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.typeofName(scope, name); pc += 2; break; } case Token.STRING : stack[++stackTop] = strings[getIndex(iCode, pc + 1)]; pc += 2; break; case Icode_SHORTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getShort(iCode, pc + 1); pc += 2; break; case Icode_INTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getInt(iCode, pc + 1); pc += 4; break; case Token.NUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = idata.itsDoubleTable[getIndex(iCode, pc + 1)]; pc += 2; break; case Token.NAME : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.name(scope, name); pc += 2; break; } case Icode_NAMEINC : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.postIncrement(scope, name); pc += 2; break; } case Icode_NAMEDEC : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.postDecrement(scope, name); pc += 2; break; } case Token.SETVAR : { int slot = (iCode[++pc] & 0xFF); if (!useActivationVars) { stack[VAR_SHFT + slot] = stack[stackTop]; sDbl[VAR_SHFT + slot] = sDbl[stackTop]; } else { Object val = stack[stackTop]; if (val == DBL_MRK) val = doubleWrap(sDbl[stackTop]); activationPut(fnOrScript, scope, slot, val); } break; } case Token.GETVAR : { int slot = (iCode[++pc] & 0xFF); ++stackTop; if (!useActivationVars) { stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; } else { stack[stackTop] = activationGet(fnOrScript, scope, slot); } break; } case Icode_VARINC : { int slot = (iCode[++pc] & 0xFF); ++stackTop; if (!useActivationVars) { stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; stack[VAR_SHFT + slot] = DBL_MRK; sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) + 1.0; } else { Object val = activationGet(fnOrScript, scope, slot); stack[stackTop] = val; val = doubleWrap(ScriptRuntime.toNumber(val) + 1.0); activationPut(fnOrScript, scope, slot, val); } break; } case Icode_VARDEC : { int slot = (iCode[++pc] & 0xFF); ++stackTop; if (!useActivationVars) { stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; stack[VAR_SHFT + slot] = DBL_MRK; sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) - 1.0; } else { Object val = activationGet(fnOrScript, scope, slot); stack[stackTop] = val; val = doubleWrap(ScriptRuntime.toNumber(val) - 1.0); activationPut(fnOrScript, scope, slot, val); } break; } case Token.ZERO : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 0; break; case Token.ONE : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 1; break; case Token.NULL : stack[++stackTop] = null; break; case Token.THIS : stack[++stackTop] = thisObj; break; case Token.THISFN : stack[++stackTop] = fnOrScript; break; case Token.FALSE : stack[++stackTop] = Boolean.FALSE; break; case Token.TRUE : stack[++stackTop] = Boolean.TRUE; break; case Token.UNDEFINED : stack[++stackTop] = Undefined.instance; break; case Token.ENTERWITH : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); --stackTop; scope = ScriptRuntime.enterWith(lhs, scope); ++withDepth; break; } case Token.LEAVEWITH : scope = ScriptRuntime.leaveWith(scope); --withDepth; break; case Token.NEWSCOPE : stack[++stackTop] = ScriptRuntime.newScope(); break; case Token.ENUMINIT : { int slot = (iCode[++pc] & 0xFF); Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); --stackTop; stack[LOCAL_SHFT + slot] = ScriptRuntime.initEnum(lhs, scope); break; } case Token.ENUMNEXT : { int slot = (iCode[++pc] & 0xFF); Object val = stack[LOCAL_SHFT + slot]; ++stackTop; stack[stackTop] = ScriptRuntime.nextEnum(val); break; } case Icode_GETPROTO : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getProto(lhs, scope); break; } case Icode_GETPARENT : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getParent(lhs); break; } case Icode_GETSCOPEPARENT : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getParent(lhs, scope); break; } case Icode_SETPROTO : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setProto(lhs, rhs, scope); break; } case Icode_SETPARENT : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setParent(lhs, rhs, scope); break; } case Icode_SCOPE : stack[++stackTop] = scope; break; case Icode_CLOSURE : { int i = getIndex(iCode, pc + 1); InterpreterData closureData = idata.itsNestedFunctions[i]; stack[++stackTop] = createFunction(cx, scope, closureData, idata.itsFromEvalCode); pc += 2; break; } case Token.REGEXP : { int i = getIndex(iCode, pc + 1); Scriptable regexp; if (idata.itsFunctionType != 0) { regexp = ((InterpretedFunction)fnOrScript).itsRegExps[i]; } else { if (scriptRegExps == null) { scriptRegExps = wrapRegExps(cx, scope, idata); } regexp = scriptRegExps[i]; } stack[++stackTop] = regexp; pc += 2; break; } case Icode_LINE : { cx.interpreterLineIndex = pc + 1; if (debuggerFrame != null) { int line = getShort(iCode, pc + 1); debuggerFrame.onLineChange(cx, line); } pc += 2; break; } default : { dumpICode(idata); throw new RuntimeException ("Unknown icode : "+(iCode[pc] & 0xff)+" @ pc : "+pc); } // end of interpreter switch } pc++; } catch (Throwable ex) { if (instructionThreshold != 0) { if (instructionCount < 0) { // throw during function call instructionCount = cx.instructionCount; } else { // throw during any other operation instructionCount += pc - pcPrevBranch; cx.instructionCount = instructionCount; } } javaException = ex; exceptionPC = pc; pc = getJavaCatchPC(iCode); continue Loop; } } cx.interpreterData = savedData; if (debuggerFrame != null) { if (javaException != null) { debuggerFrame.onExit(cx, true, javaException); } else { debuggerFrame.onExit(cx, false, result); } } - if (idata.itsNeedsActivation) { + if (idata.itsNeedsActivation || debuggerFrame != null) { ScriptRuntime.popActivation(cx); } if (instructionThreshold != 0) { if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } cx.instructionCount = instructionCount; } if (javaException != null) { if (javaException instanceof JavaScriptException) { throw (JavaScriptException)javaException; } else if (javaException instanceof RuntimeException) { throw (RuntimeException)javaException; } else { // Must be instance of Error or code bug throw (Error)javaException; } } return result; } private static Object doubleWrap(double x) { return new Double(x); } private static int stack_int32(Object[] stack, double[] stackDbl, int i) { Object x = stack[i]; return (x != DBL_MRK) ? ScriptRuntime.toInt32(x) : ScriptRuntime.toInt32(stackDbl[i]); } private static double stack_double(Object[] stack, double[] stackDbl, int i) { Object x = stack[i]; return (x != DBL_MRK) ? ScriptRuntime.toNumber(x) : stackDbl[i]; } private static boolean stack_boolean(Object[] stack, double[] stackDbl, int i) { Object x = stack[i]; if (x == DBL_MRK) { double d = stackDbl[i]; return d == d && d != 0.0; } else if (x instanceof Boolean) { return ((Boolean)x).booleanValue(); } else if (x == null || x == Undefined.instance) { return false; } else if (x instanceof Number) { double d = ((Number)x).doubleValue(); return (d == d && d != 0.0); } else { return ScriptRuntime.toBoolean(x); } } private static void do_add(Object[] stack, double[] stackDbl, int stackTop) { Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; if (rhs == DBL_MRK) { double rDbl = stackDbl[stackTop + 1]; if (lhs == DBL_MRK) { stackDbl[stackTop] += rDbl; } else { do_add(lhs, rDbl, stack, stackDbl, stackTop, true); } } else if (lhs == DBL_MRK) { do_add(rhs, stackDbl[stackTop], stack, stackDbl, stackTop, false); } else { if (lhs instanceof Scriptable) lhs = ((Scriptable) lhs).getDefaultValue(null); if (rhs instanceof Scriptable) rhs = ((Scriptable) rhs).getDefaultValue(null); if (lhs instanceof String) { String lstr = (String)lhs; String rstr = ScriptRuntime.toString(rhs); stack[stackTop] = lstr.concat(rstr); } else if (rhs instanceof String) { String lstr = ScriptRuntime.toString(lhs); String rstr = (String)rhs; stack[stackTop] = lstr.concat(rstr); } else { double lDbl = (lhs instanceof Number) ? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs); double rDbl = (rhs instanceof Number) ? ((Number)rhs).doubleValue() : ScriptRuntime.toNumber(rhs); stack[stackTop] = DBL_MRK; stackDbl[stackTop] = lDbl + rDbl; } } } // x + y when x is Number private static void do_add (Object lhs, double rDbl, Object[] stack, double[] stackDbl, int stackTop, boolean left_right_order) { if (lhs instanceof Scriptable) { if (lhs == Undefined.instance) { lhs = ScriptRuntime.NaNobj; } else { lhs = ((Scriptable)lhs).getDefaultValue(null); } } if (lhs instanceof String) { String lstr = (String)lhs; String rstr = ScriptRuntime.toString(rDbl); if (left_right_order) { stack[stackTop] = lstr.concat(rstr); } else { stack[stackTop] = rstr.concat(lstr); } } else { double lDbl = (lhs instanceof Number) ? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs); stack[stackTop] = DBL_MRK; stackDbl[stackTop] = lDbl + rDbl; } } private static boolean do_eq(Object[] stack, double[] stackDbl, int stackTop) { boolean result; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; if (rhs == DBL_MRK) { if (lhs == DBL_MRK) { result = (stackDbl[stackTop] == stackDbl[stackTop + 1]); } else { result = do_eq(stackDbl[stackTop + 1], lhs); } } else { if (lhs == DBL_MRK) { result = do_eq(stackDbl[stackTop], rhs); } else { result = ScriptRuntime.eq(lhs, rhs); } } return result; } // Optimized version of ScriptRuntime.eq if x is a Number private static boolean do_eq(double x, Object y) { for (;;) { if (y instanceof Number) { return x == ((Number) y).doubleValue(); } if (y instanceof String) { return x == ScriptRuntime.toNumber((String)y); } if (y instanceof Boolean) { return x == (((Boolean)y).booleanValue() ? 1 : 0); } if (y instanceof Scriptable) { if (y == Undefined.instance) { return false; } y = ScriptRuntime.toPrimitive(y); continue; } return false; } } private static boolean do_sheq(Object[] stack, double[] stackDbl, int stackTop) { boolean result; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; if (rhs == DBL_MRK) { double rDbl = stackDbl[stackTop + 1]; if (lhs == DBL_MRK) { result = (stackDbl[stackTop] == rDbl); } else { result = (lhs instanceof Number); if (result) { result = (((Number)lhs).doubleValue() == rDbl); } } } else if (rhs instanceof Number) { double rDbl = ((Number)rhs).doubleValue(); if (lhs == DBL_MRK) { result = (stackDbl[stackTop] == rDbl); } else { result = (lhs instanceof Number); if (result) { result = (((Number)lhs).doubleValue() == rDbl); } } } else { result = ScriptRuntime.shallowEq(lhs, rhs); } return result; } private static void do_getElem(Context cx, Object[] stack, double[] stackDbl, int stackTop, Scriptable scope) { Object lhs = stack[stackTop - 1]; if (lhs == DBL_MRK) lhs = doubleWrap(stackDbl[stackTop - 1]); Object result; Object id = stack[stackTop]; if (id != DBL_MRK) { result = ScriptRuntime.getElem(lhs, id, scope); } else { double val = stackDbl[stackTop]; if (lhs == null || lhs == Undefined.instance) { throw ScriptRuntime.undefReadError( lhs, ScriptRuntime.toString(val)); } Scriptable obj = (lhs instanceof Scriptable) ? (Scriptable)lhs : ScriptRuntime.toObject(cx, scope, lhs); int index = (int)val; if (index == val) { result = ScriptRuntime.getElem(obj, index); } else { String s = ScriptRuntime.toString(val); result = ScriptRuntime.getStrIdElem(obj, s); } } stack[stackTop - 1] = result; } private static void do_setElem(Context cx, Object[] stack, double[] stackDbl, int stackTop, Scriptable scope) { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(stackDbl[stackTop]); Object lhs = stack[stackTop - 2]; if (lhs == DBL_MRK) lhs = doubleWrap(stackDbl[stackTop - 2]); Object result; Object id = stack[stackTop - 1]; if (id != DBL_MRK) { result = ScriptRuntime.setElem(lhs, id, rhs, scope); } else { double val = stackDbl[stackTop - 1]; if (lhs == null || lhs == Undefined.instance) { throw ScriptRuntime.undefWriteError( lhs, ScriptRuntime.toString(val), rhs); } Scriptable obj = (lhs instanceof Scriptable) ? (Scriptable)lhs : ScriptRuntime.toObject(cx, scope, lhs); int index = (int)val; if (index == val) { result = ScriptRuntime.setElem(obj, index, rhs); } else { String s = ScriptRuntime.toString(val); result = ScriptRuntime.setStrIdElem(obj, s, rhs, scope); } } stack[stackTop - 2] = result; } private static Object[] getArgsArray(Object[] stack, double[] sDbl, int shift, int count) { if (count == 0) { return ScriptRuntime.emptyArgs; } Object[] args = new Object[count]; for (int i = 0; i != count; ++i, ++shift) { Object val = stack[shift]; if (val == DBL_MRK) val = doubleWrap(sDbl[shift]); args[i] = val; } return args; } private static Object activationGet(NativeFunction f, Scriptable activation, int slot) { String name = f.argNames[slot]; Object val = activation.get(name, activation); // Activation parameter or var is permanent if (val == Scriptable.NOT_FOUND) Context.codeBug(); return val; } private static void activationPut(NativeFunction f, Scriptable activation, int slot, Object value) { String name = f.argNames[slot]; activation.put(name, activation, value); } private static Object execWithNewDomain(Context cx, Scriptable scope, final Scriptable thisObj, final Object[] args, final double[] argsDbl, final int argShift, final int argCount, final NativeFunction fnOrScript, final InterpreterData idata) throws JavaScriptException { if (cx.interpreterSecurityDomain == idata.securityDomain) Context.codeBug(); Script code = new Script() { public Object exec(Context cx, Scriptable scope) throws JavaScriptException { return interpret(cx, scope, thisObj, args, argsDbl, argShift, argCount, fnOrScript, idata); } }; Object savedDomain = cx.interpreterSecurityDomain; cx.interpreterSecurityDomain = idata.securityDomain; try { return cx.getSecurityController(). execWithDomain(cx, scope, code, idata.securityDomain); } finally { cx.interpreterSecurityDomain = savedDomain; } } private static int getJavaCatchPC(byte[] iCode) { int pc = iCode.length - 1; if ((iCode[pc] & 0xFF) != Icode_CATCH) Context.codeBug(); return pc; } private boolean itsInFunctionFlag; private InterpreterData itsData; private ScriptOrFnNode scriptOrFn; private int itsStackDepth = 0; private int itsWithDepth = 0; private int itsLineNumber = 0; private LabelTable itsLabels = new LabelTable(); private int itsDoubleTableTop; private ObjToIntMap itsStrings = new ObjToIntMap(20); private String lastAddString; private int itsExceptionTableTop = 0; // 5 = space for try start/end, catch begin, finally begin and with depth private static final int EXCEPTION_SLOT_SIZE = 5; private static final int EXCEPTION_TRY_START_SLOT = 0; private static final int EXCEPTION_TRY_END_SLOT = 1; private static final int EXCEPTION_CATCH_SLOT = 2; private static final int EXCEPTION_FINALLY_SLOT = 3; private static final int EXCEPTION_WITH_DEPTH_SLOT = 4; private static final Object DBL_MRK = new Object(); }
true
true
static Object interpret(Context cx, Scriptable scope, Scriptable thisObj, Object[] args, double[] argsDbl, int argShift, int argCount, NativeFunction fnOrScript, InterpreterData idata) throws JavaScriptException { if (cx.interpreterSecurityDomain != idata.securityDomain) { return execWithNewDomain(cx, scope, thisObj, args, argsDbl, argShift, argCount, fnOrScript, idata); } final Object DBL_MRK = Interpreter.DBL_MRK; final Scriptable undefined = Undefined.instance; final int VAR_SHFT = 0; final int maxVars = idata.itsMaxVars; final int LOCAL_SHFT = VAR_SHFT + maxVars; final int STACK_SHFT = LOCAL_SHFT + idata.itsMaxLocals; // stack[VAR_SHFT <= i < LOCAL_SHFT]: variables // stack[LOCAL_SHFT <= i < TRY_STACK_SHFT]: used for newtemp/usetemp // stack[STACK_SHFT <= i < STACK_SHFT + idata.itsMaxStack]: stack data // sDbl[i]: if stack[i] is DBL_MRK, sDbl[i] holds the number value int maxFrameArray = idata.itsMaxFrameArray; if (maxFrameArray != STACK_SHFT + idata.itsMaxStack) Context.codeBug(); Object[] stack = new Object[maxFrameArray]; double[] sDbl = new double[maxFrameArray]; int stackTop = STACK_SHFT - 1; int withDepth = 0; int definedArgs = fnOrScript.argCount; if (definedArgs > argCount) { definedArgs = argCount; } for (int i = 0; i != definedArgs; ++i) { Object arg = args[argShift + i]; stack[VAR_SHFT + i] = arg; if (arg == DBL_MRK) { sDbl[VAR_SHFT + i] = argsDbl[argShift + i]; } } for (int i = definedArgs; i != maxVars; ++i) { stack[VAR_SHFT + i] = undefined; } DebugFrame debuggerFrame = null; if (cx.debugger != null) { debuggerFrame = cx.debugger.getFrame(cx, idata); } if (idata.itsFunctionType != 0) { InterpretedFunction f = (InterpretedFunction)fnOrScript; if (!idata.useDynamicScope) { scope = fnOrScript.getParentScope(); } if (idata.itsCheckThis) { thisObj = ScriptRuntime.getThis(thisObj); } if (idata.itsNeedsActivation) { if (argsDbl != null) { args = getArgsArray(args, argsDbl, argShift, argCount); argShift = 0; argsDbl = null; } scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript, thisObj, args); } } else { ScriptRuntime.initScript(cx, scope, fnOrScript, thisObj, idata.itsFromEvalCode); } if (idata.itsNestedFunctions != null) { if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) Context.codeBug(); for (int i = 0; i < idata.itsNestedFunctions.length; i++) { InterpreterData fdata = idata.itsNestedFunctions[i]; if (fdata.itsFunctionType == FunctionNode.FUNCTION_STATEMENT) { createFunction(cx, scope, fdata, idata.itsFromEvalCode); } } } // Wrapped regexps for functions are stored in InterpretedFunction // but for script which should not contain references to scope // the regexps re-wrapped during each script execution Scriptable[] scriptRegExps = null; boolean useActivationVars = false; if (debuggerFrame != null) { if (argsDbl != null) { args = getArgsArray(args, argsDbl, argShift, argCount); argShift = 0; argsDbl = null; } if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) { useActivationVars = true; scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript, thisObj, args); } debuggerFrame.onEnter(cx, scope, thisObj, args); } InterpreterData savedData = cx.interpreterData; cx.interpreterData = idata; Object result = undefined; // If javaException != null on exit, it will be throw instead of // normal return Throwable javaException = null; int exceptionPC = -1; byte[] iCode = idata.itsICode; String[] strings = idata.itsStringTable; int pc = 0; int pcPrevBranch = pc; final int instructionThreshold = cx.instructionThreshold; // During function call this will be set to -1 so catch can properly // adjust it int instructionCount = cx.instructionCount; // arbitrary number to add to instructionCount when calling // other functions final int INVOCATION_COST = 100; Loop: for (;;) { try { switch (iCode[pc] & 0xff) { // Back indent to ease imlementation reading case Icode_CATCH: { // The following code should be executed inside try/catch inside main // loop, not in the loop catch block itself to deal withnexceptions // from observeInstructionCount. A special bytecode is used only to // simplify logic. if (javaException == null) Context.codeBug(); int pcNew = -1; boolean doCatch = false; int handlerOffset = getExceptionHandler(idata.itsExceptionTable, exceptionPC); if (handlerOffset >= 0) { final int SCRIPT_CAN_CATCH = 0, ONLY_FINALLY = 1, OTHER = 2; int exType; if (javaException instanceof JavaScriptException) { exType = SCRIPT_CAN_CATCH; } else if (javaException instanceof EcmaError) { // an offical ECMA error object, exType = SCRIPT_CAN_CATCH; } else if (javaException instanceof WrappedException) { exType = SCRIPT_CAN_CATCH; } else if (javaException instanceof RuntimeException) { exType = ONLY_FINALLY; } else { // Error instance exType = OTHER; } if (exType != OTHER) { // Do not allow for JS to interfere with Error instances // (exType == OTHER), as they can be used to terminate // long running script if (exType == SCRIPT_CAN_CATCH) { // Allow JS to catch only JavaScriptException and // EcmaError pcNew = idata.itsExceptionTable[handlerOffset + EXCEPTION_CATCH_SLOT]; if (pcNew >= 0) { // Has catch block doCatch = true; } } if (pcNew < 0) { pcNew = idata.itsExceptionTable[handlerOffset + EXCEPTION_FINALLY_SLOT]; } } } if (debuggerFrame != null && !(javaException instanceof Error)) { debuggerFrame.onExceptionThrown(cx, javaException); } if (pcNew < 0) { break Loop; } // We caught an exception // restore scope at try point int tryWithDepth = idata.itsExceptionTable[ handlerOffset + EXCEPTION_WITH_DEPTH_SLOT]; while (tryWithDepth != withDepth) { if (scope == null) Context.codeBug(); scope = ScriptRuntime.leaveWith(scope); --withDepth; } // make stack to contain single exception object stackTop = STACK_SHFT; if (doCatch) { stack[stackTop] = ScriptRuntime.getCatchObject(cx, scope, javaException); } else { // Call finally handler with javaException on stack top to // distinguish from normal invocation through GOSUB // which would contain DBL_MRK on the stack stack[stackTop] = javaException; } // clear exception javaException = null; // Notify instruction observer if necessary // and point pc and pcPrevBranch to start of catch/finally block if (instructionThreshold != 0) { if (instructionCount > instructionThreshold) { // Note: this can throw Error cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = pcNew; continue Loop; } case Token.THROW: { Object value = stack[stackTop]; if (value == DBL_MRK) value = doubleWrap(sDbl[stackTop]); --stackTop; int sourceLine = getShort(iCode, pc + 1); javaException = new JavaScriptException(value, idata.itsSourceFile, sourceLine); exceptionPC = pc; if (instructionThreshold != 0) { instructionCount += pc + 1 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getJavaCatchPC(iCode); continue Loop; } case Token.GE : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; if (rhs == DBL_MRK || lhs == DBL_MRK) { double rDbl = stack_double(stack, sDbl, stackTop + 1); double lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && rDbl <= lDbl); } else { valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.LE : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; if (rhs == DBL_MRK || lhs == DBL_MRK) { double rDbl = stack_double(stack, sDbl, stackTop + 1); double lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && lDbl <= rDbl); } else { valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.GT : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; if (rhs == DBL_MRK || lhs == DBL_MRK) { double rDbl = stack_double(stack, sDbl, stackTop + 1); double lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && rDbl < lDbl); } else { valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.LT : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; if (rhs == DBL_MRK || lhs == DBL_MRK) { double rDbl = stack_double(stack, sDbl, stackTop + 1); double lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && lDbl < rDbl); } else { valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.IN : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); boolean valBln = ScriptRuntime.in(lhs, rhs, scope); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.INSTANCEOF : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); boolean valBln = ScriptRuntime.instanceOf(lhs, rhs, scope); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.EQ : { --stackTop; boolean valBln = do_eq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.NE : { --stackTop; boolean valBln = !do_eq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.SHEQ : { --stackTop; boolean valBln = do_sheq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.SHNE : { --stackTop; boolean valBln = !do_sheq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.IFNE : { boolean valBln = stack_boolean(stack, sDbl, stackTop); --stackTop; if (!valBln) { if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop; } pc += 2; break; } case Token.IFEQ : { boolean valBln = stack_boolean(stack, sDbl, stackTop); --stackTop; if (valBln) { if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop; } pc += 2; break; } case Token.GOTO : if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop; case Icode_GOSUB : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = pc + 3; if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop; case Icode_RETSUB : { int slot = (iCode[pc + 1] & 0xFF); if (instructionThreshold != 0) { instructionCount += pc + 2 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } int newPC; Object value = stack[LOCAL_SHFT + slot]; if (value != DBL_MRK) { // Invocation from exception handler, restore object to rethrow javaException = (Throwable)value; exceptionPC = pc; newPC = getJavaCatchPC(iCode); } else { // Normal return from GOSUB newPC = (int)sDbl[LOCAL_SHFT + slot]; } pcPrevBranch = pc = newPC; continue Loop; } case Token.POP : stack[stackTop] = null; stackTop--; break; case Icode_DUP : stack[stackTop + 1] = stack[stackTop]; sDbl[stackTop + 1] = sDbl[stackTop]; stackTop++; break; case Token.POPV : result = stack[stackTop]; if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]); stack[stackTop] = null; --stackTop; break; case Token.RETURN : result = stack[stackTop]; if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]); --stackTop; break Loop; case Icode_RETUNDEF : result = undefined; break Loop; case Icode_END: break Loop; case Token.BITNOT : { int rIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ~rIntValue; break; } case Token.BITAND : { int rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; int lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue & rIntValue; break; } case Token.BITOR : { int rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; int lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue | rIntValue; break; } case Token.BITXOR : { int rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; int lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue ^ rIntValue; break; } case Token.LSH : { int rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; int lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue << rIntValue; break; } case Token.RSH : { int rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; int lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue >> rIntValue; break; } case Token.URSH : { int rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F; --stackTop; double lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue; break; } case Token.ADD : --stackTop; do_add(stack, sDbl, stackTop); break; case Token.SUB : { double rDbl = stack_double(stack, sDbl, stackTop); --stackTop; double lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl - rDbl; break; } case Token.NEG : { double rDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = -rDbl; break; } case Token.POS : { double rDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = rDbl; break; } case Token.MUL : { double rDbl = stack_double(stack, sDbl, stackTop); --stackTop; double lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl * rDbl; break; } case Token.DIV : { double rDbl = stack_double(stack, sDbl, stackTop); --stackTop; double lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; // Detect the divide by zero or let Java do it ? sDbl[stackTop] = lDbl / rDbl; break; } case Token.MOD : { double rDbl = stack_double(stack, sDbl, stackTop); --stackTop; double lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl % rDbl; break; } case Token.NOT : { stack[stackTop] = stack_boolean(stack, sDbl, stackTop) ? Boolean.FALSE : Boolean.TRUE; break; } case Token.BINDNAME : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.bind(scope, name); pc += 2; break; } case Token.GETBASE : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.getBase(scope, name); pc += 2; break; } case Token.SETNAME : { String name = strings[getIndex(iCode, pc + 1)]; Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; // what about class cast exception here for lhs? Scriptable lhs = (Scriptable)stack[stackTop]; stack[stackTop] = ScriptRuntime.setName(lhs, rhs, scope, name); pc += 2; break; } case Token.DELPROP : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.delete(cx, scope, lhs, rhs); break; } case Token.GETPROP : { String name = (String)stack[stackTop]; --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getProp(lhs, name, scope); break; } case Token.SETPROP : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; String name = (String)stack[stackTop]; --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setProp(lhs, name, rhs, scope); break; } case Token.GETELEM : do_getElem(cx, stack, sDbl, stackTop, scope); --stackTop; break; case Token.SETELEM : do_setElem(cx, stack, sDbl, stackTop, scope); stackTop -= 2; break; case Icode_PROPINC : { String name = (String)stack[stackTop]; --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postIncrement(lhs, name, scope); break; } case Icode_PROPDEC : { String name = (String)stack[stackTop]; --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postDecrement(lhs, name, scope); break; } case Icode_ELEMINC : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postIncrementElem(lhs, rhs, scope); break; } case Icode_ELEMDEC : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postDecrementElem(lhs, rhs, scope); break; } case Token.GETTHIS : { Scriptable lhs = (Scriptable)stack[stackTop]; stack[stackTop] = ScriptRuntime.getThis(lhs); break; } case Token.NEWTEMP : { int slot = (iCode[++pc] & 0xFF); stack[LOCAL_SHFT + slot] = stack[stackTop]; sDbl[LOCAL_SHFT + slot] = sDbl[stackTop]; break; } case Token.USETEMP : { int slot = (iCode[++pc] & 0xFF); ++stackTop; stack[stackTop] = stack[LOCAL_SHFT + slot]; sDbl[stackTop] = sDbl[LOCAL_SHFT + slot]; break; } case Icode_CALLSPECIAL : { if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } int callType = iCode[pc + 1] & 0xFF; boolean isNew = (iCode[pc + 2] != 0); int sourceLine = getShort(iCode, pc + 3); int count = getIndex(iCode, pc + 5); stackTop -= count; Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, count); Object functionThis; if (isNew) { functionThis = null; } else { functionThis = stack[stackTop]; if (functionThis == DBL_MRK) { functionThis = doubleWrap(sDbl[stackTop]); } --stackTop; } Object function = stack[stackTop]; if (function == DBL_MRK) function = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.callSpecial( cx, function, isNew, functionThis, outArgs, scope, thisObj, callType, idata.itsSourceFile, sourceLine); pc += 6; instructionCount = cx.instructionCount; break; } case Token.CALL : { if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } int count = getIndex(iCode, pc + 3); stackTop -= count; int calleeArgShft = stackTop + 1; Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; Scriptable calleeScope = scope; if (idata.itsNeedsActivation) { calleeScope = ScriptableObject.getTopLevelScope(scope); } Scriptable calleeThis; if (rhs instanceof Scriptable || rhs == null) { calleeThis = (Scriptable)rhs; } else { calleeThis = ScriptRuntime.toObject(cx, calleeScope, rhs); } if (lhs instanceof InterpretedFunction) { // Inlining of InterpretedFunction.call not to create // argument array InterpretedFunction f = (InterpretedFunction)lhs; stack[stackTop] = interpret(cx, calleeScope, calleeThis, stack, sDbl, calleeArgShft, count, f, f.itsData); } else if (lhs instanceof Function) { Function f = (Function)lhs; Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count); stack[stackTop] = f.call(cx, calleeScope, calleeThis, outArgs); } else { if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); else if (lhs == undefined) { // special code for better error message for call // to undefined lhs = strings[getIndex(iCode, pc + 1)]; if (lhs == null) lhs = undefined; } throw ScriptRuntime.typeError1("msg.isnt.function", ScriptRuntime.toString(lhs)); } pc += 4; instructionCount = cx.instructionCount; break; } case Token.NEW : { if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } int count = getIndex(iCode, pc + 3); stackTop -= count; int calleeArgShft = stackTop + 1; Object lhs = stack[stackTop]; if (lhs instanceof InterpretedFunction) { // Inlining of InterpretedFunction.construct not to create // argument array InterpretedFunction f = (InterpretedFunction)lhs; Scriptable newInstance = f.createObject(cx, scope); Object callResult = interpret(cx, scope, newInstance, stack, sDbl, calleeArgShft, count, f, f.itsData); if (callResult instanceof Scriptable && callResult != undefined) { stack[stackTop] = callResult; } else { stack[stackTop] = newInstance; } } else if (lhs instanceof Function) { Function f = (Function)lhs; Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count); stack[stackTop] = f.construct(cx, scope, outArgs); } else { if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); else if (lhs == undefined) { // special code for better error message for call // to undefined lhs = strings[getIndex(iCode, pc + 1)]; if (lhs == null) lhs = undefined; } throw ScriptRuntime.typeError1("msg.isnt.function", ScriptRuntime.toString(lhs)); } pc += 4; instructionCount = cx.instructionCount; break; } case Token.TYPEOF : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.typeof(lhs); break; } case Icode_TYPEOFNAME : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.typeofName(scope, name); pc += 2; break; } case Token.STRING : stack[++stackTop] = strings[getIndex(iCode, pc + 1)]; pc += 2; break; case Icode_SHORTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getShort(iCode, pc + 1); pc += 2; break; case Icode_INTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getInt(iCode, pc + 1); pc += 4; break; case Token.NUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = idata.itsDoubleTable[getIndex(iCode, pc + 1)]; pc += 2; break; case Token.NAME : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.name(scope, name); pc += 2; break; } case Icode_NAMEINC : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.postIncrement(scope, name); pc += 2; break; } case Icode_NAMEDEC : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.postDecrement(scope, name); pc += 2; break; } case Token.SETVAR : { int slot = (iCode[++pc] & 0xFF); if (!useActivationVars) { stack[VAR_SHFT + slot] = stack[stackTop]; sDbl[VAR_SHFT + slot] = sDbl[stackTop]; } else { Object val = stack[stackTop]; if (val == DBL_MRK) val = doubleWrap(sDbl[stackTop]); activationPut(fnOrScript, scope, slot, val); } break; } case Token.GETVAR : { int slot = (iCode[++pc] & 0xFF); ++stackTop; if (!useActivationVars) { stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; } else { stack[stackTop] = activationGet(fnOrScript, scope, slot); } break; } case Icode_VARINC : { int slot = (iCode[++pc] & 0xFF); ++stackTop; if (!useActivationVars) { stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; stack[VAR_SHFT + slot] = DBL_MRK; sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) + 1.0; } else { Object val = activationGet(fnOrScript, scope, slot); stack[stackTop] = val; val = doubleWrap(ScriptRuntime.toNumber(val) + 1.0); activationPut(fnOrScript, scope, slot, val); } break; } case Icode_VARDEC : { int slot = (iCode[++pc] & 0xFF); ++stackTop; if (!useActivationVars) { stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; stack[VAR_SHFT + slot] = DBL_MRK; sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) - 1.0; } else { Object val = activationGet(fnOrScript, scope, slot); stack[stackTop] = val; val = doubleWrap(ScriptRuntime.toNumber(val) - 1.0); activationPut(fnOrScript, scope, slot, val); } break; } case Token.ZERO : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 0; break; case Token.ONE : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 1; break; case Token.NULL : stack[++stackTop] = null; break; case Token.THIS : stack[++stackTop] = thisObj; break; case Token.THISFN : stack[++stackTop] = fnOrScript; break; case Token.FALSE : stack[++stackTop] = Boolean.FALSE; break; case Token.TRUE : stack[++stackTop] = Boolean.TRUE; break; case Token.UNDEFINED : stack[++stackTop] = Undefined.instance; break; case Token.ENTERWITH : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); --stackTop; scope = ScriptRuntime.enterWith(lhs, scope); ++withDepth; break; } case Token.LEAVEWITH : scope = ScriptRuntime.leaveWith(scope); --withDepth; break; case Token.NEWSCOPE : stack[++stackTop] = ScriptRuntime.newScope(); break; case Token.ENUMINIT : { int slot = (iCode[++pc] & 0xFF); Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); --stackTop; stack[LOCAL_SHFT + slot] = ScriptRuntime.initEnum(lhs, scope); break; } case Token.ENUMNEXT : { int slot = (iCode[++pc] & 0xFF); Object val = stack[LOCAL_SHFT + slot]; ++stackTop; stack[stackTop] = ScriptRuntime.nextEnum(val); break; } case Icode_GETPROTO : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getProto(lhs, scope); break; } case Icode_GETPARENT : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getParent(lhs); break; } case Icode_GETSCOPEPARENT : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getParent(lhs, scope); break; } case Icode_SETPROTO : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setProto(lhs, rhs, scope); break; } case Icode_SETPARENT : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setParent(lhs, rhs, scope); break; } case Icode_SCOPE : stack[++stackTop] = scope; break; case Icode_CLOSURE : { int i = getIndex(iCode, pc + 1); InterpreterData closureData = idata.itsNestedFunctions[i]; stack[++stackTop] = createFunction(cx, scope, closureData, idata.itsFromEvalCode); pc += 2; break; } case Token.REGEXP : { int i = getIndex(iCode, pc + 1); Scriptable regexp; if (idata.itsFunctionType != 0) { regexp = ((InterpretedFunction)fnOrScript).itsRegExps[i]; } else { if (scriptRegExps == null) { scriptRegExps = wrapRegExps(cx, scope, idata); } regexp = scriptRegExps[i]; } stack[++stackTop] = regexp; pc += 2; break; } case Icode_LINE : { cx.interpreterLineIndex = pc + 1; if (debuggerFrame != null) { int line = getShort(iCode, pc + 1); debuggerFrame.onLineChange(cx, line); } pc += 2; break; } default : { dumpICode(idata); throw new RuntimeException ("Unknown icode : "+(iCode[pc] & 0xff)+" @ pc : "+pc); } // end of interpreter switch } pc++; } catch (Throwable ex) { if (instructionThreshold != 0) { if (instructionCount < 0) { // throw during function call instructionCount = cx.instructionCount; } else { // throw during any other operation instructionCount += pc - pcPrevBranch; cx.instructionCount = instructionCount; } } javaException = ex; exceptionPC = pc; pc = getJavaCatchPC(iCode); continue Loop; } } cx.interpreterData = savedData; if (debuggerFrame != null) { if (javaException != null) { debuggerFrame.onExit(cx, true, javaException); } else { debuggerFrame.onExit(cx, false, result); } } if (idata.itsNeedsActivation) { ScriptRuntime.popActivation(cx); } if (instructionThreshold != 0) { if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } cx.instructionCount = instructionCount; } if (javaException != null) { if (javaException instanceof JavaScriptException) { throw (JavaScriptException)javaException; } else if (javaException instanceof RuntimeException) { throw (RuntimeException)javaException; } else { // Must be instance of Error or code bug throw (Error)javaException; } } return result; }
static Object interpret(Context cx, Scriptable scope, Scriptable thisObj, Object[] args, double[] argsDbl, int argShift, int argCount, NativeFunction fnOrScript, InterpreterData idata) throws JavaScriptException { if (cx.interpreterSecurityDomain != idata.securityDomain) { return execWithNewDomain(cx, scope, thisObj, args, argsDbl, argShift, argCount, fnOrScript, idata); } final Object DBL_MRK = Interpreter.DBL_MRK; final Scriptable undefined = Undefined.instance; final int VAR_SHFT = 0; final int maxVars = idata.itsMaxVars; final int LOCAL_SHFT = VAR_SHFT + maxVars; final int STACK_SHFT = LOCAL_SHFT + idata.itsMaxLocals; // stack[VAR_SHFT <= i < LOCAL_SHFT]: variables // stack[LOCAL_SHFT <= i < TRY_STACK_SHFT]: used for newtemp/usetemp // stack[STACK_SHFT <= i < STACK_SHFT + idata.itsMaxStack]: stack data // sDbl[i]: if stack[i] is DBL_MRK, sDbl[i] holds the number value int maxFrameArray = idata.itsMaxFrameArray; if (maxFrameArray != STACK_SHFT + idata.itsMaxStack) Context.codeBug(); Object[] stack = new Object[maxFrameArray]; double[] sDbl = new double[maxFrameArray]; int stackTop = STACK_SHFT - 1; int withDepth = 0; int definedArgs = fnOrScript.argCount; if (definedArgs > argCount) { definedArgs = argCount; } for (int i = 0; i != definedArgs; ++i) { Object arg = args[argShift + i]; stack[VAR_SHFT + i] = arg; if (arg == DBL_MRK) { sDbl[VAR_SHFT + i] = argsDbl[argShift + i]; } } for (int i = definedArgs; i != maxVars; ++i) { stack[VAR_SHFT + i] = undefined; } DebugFrame debuggerFrame = null; if (cx.debugger != null) { debuggerFrame = cx.debugger.getFrame(cx, idata); } if (idata.itsFunctionType != 0) { InterpretedFunction f = (InterpretedFunction)fnOrScript; if (!idata.useDynamicScope) { scope = fnOrScript.getParentScope(); } if (idata.itsCheckThis) { thisObj = ScriptRuntime.getThis(thisObj); } if (idata.itsNeedsActivation) { if (argsDbl != null) { args = getArgsArray(args, argsDbl, argShift, argCount); argShift = 0; argsDbl = null; } scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript, thisObj, args); } } else { ScriptRuntime.initScript(cx, scope, fnOrScript, thisObj, idata.itsFromEvalCode); } if (idata.itsNestedFunctions != null) { if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) Context.codeBug(); for (int i = 0; i < idata.itsNestedFunctions.length; i++) { InterpreterData fdata = idata.itsNestedFunctions[i]; if (fdata.itsFunctionType == FunctionNode.FUNCTION_STATEMENT) { createFunction(cx, scope, fdata, idata.itsFromEvalCode); } } } // Wrapped regexps for functions are stored in InterpretedFunction // but for script which should not contain references to scope // the regexps re-wrapped during each script execution Scriptable[] scriptRegExps = null; boolean useActivationVars = false; if (debuggerFrame != null) { if (argsDbl != null) { args = getArgsArray(args, argsDbl, argShift, argCount); argShift = 0; argsDbl = null; } if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) { useActivationVars = true; scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript, thisObj, args); } debuggerFrame.onEnter(cx, scope, thisObj, args); } InterpreterData savedData = cx.interpreterData; cx.interpreterData = idata; Object result = undefined; // If javaException != null on exit, it will be throw instead of // normal return Throwable javaException = null; int exceptionPC = -1; byte[] iCode = idata.itsICode; String[] strings = idata.itsStringTable; int pc = 0; int pcPrevBranch = pc; final int instructionThreshold = cx.instructionThreshold; // During function call this will be set to -1 so catch can properly // adjust it int instructionCount = cx.instructionCount; // arbitrary number to add to instructionCount when calling // other functions final int INVOCATION_COST = 100; Loop: for (;;) { try { switch (iCode[pc] & 0xff) { // Back indent to ease imlementation reading case Icode_CATCH: { // The following code should be executed inside try/catch inside main // loop, not in the loop catch block itself to deal withnexceptions // from observeInstructionCount. A special bytecode is used only to // simplify logic. if (javaException == null) Context.codeBug(); int pcNew = -1; boolean doCatch = false; int handlerOffset = getExceptionHandler(idata.itsExceptionTable, exceptionPC); if (handlerOffset >= 0) { final int SCRIPT_CAN_CATCH = 0, ONLY_FINALLY = 1, OTHER = 2; int exType; if (javaException instanceof JavaScriptException) { exType = SCRIPT_CAN_CATCH; } else if (javaException instanceof EcmaError) { // an offical ECMA error object, exType = SCRIPT_CAN_CATCH; } else if (javaException instanceof WrappedException) { exType = SCRIPT_CAN_CATCH; } else if (javaException instanceof RuntimeException) { exType = ONLY_FINALLY; } else { // Error instance exType = OTHER; } if (exType != OTHER) { // Do not allow for JS to interfere with Error instances // (exType == OTHER), as they can be used to terminate // long running script if (exType == SCRIPT_CAN_CATCH) { // Allow JS to catch only JavaScriptException and // EcmaError pcNew = idata.itsExceptionTable[handlerOffset + EXCEPTION_CATCH_SLOT]; if (pcNew >= 0) { // Has catch block doCatch = true; } } if (pcNew < 0) { pcNew = idata.itsExceptionTable[handlerOffset + EXCEPTION_FINALLY_SLOT]; } } } if (debuggerFrame != null && !(javaException instanceof Error)) { debuggerFrame.onExceptionThrown(cx, javaException); } if (pcNew < 0) { break Loop; } // We caught an exception // restore scope at try point int tryWithDepth = idata.itsExceptionTable[ handlerOffset + EXCEPTION_WITH_DEPTH_SLOT]; while (tryWithDepth != withDepth) { if (scope == null) Context.codeBug(); scope = ScriptRuntime.leaveWith(scope); --withDepth; } // make stack to contain single exception object stackTop = STACK_SHFT; if (doCatch) { stack[stackTop] = ScriptRuntime.getCatchObject(cx, scope, javaException); } else { // Call finally handler with javaException on stack top to // distinguish from normal invocation through GOSUB // which would contain DBL_MRK on the stack stack[stackTop] = javaException; } // clear exception javaException = null; // Notify instruction observer if necessary // and point pc and pcPrevBranch to start of catch/finally block if (instructionThreshold != 0) { if (instructionCount > instructionThreshold) { // Note: this can throw Error cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = pcNew; continue Loop; } case Token.THROW: { Object value = stack[stackTop]; if (value == DBL_MRK) value = doubleWrap(sDbl[stackTop]); --stackTop; int sourceLine = getShort(iCode, pc + 1); javaException = new JavaScriptException(value, idata.itsSourceFile, sourceLine); exceptionPC = pc; if (instructionThreshold != 0) { instructionCount += pc + 1 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getJavaCatchPC(iCode); continue Loop; } case Token.GE : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; if (rhs == DBL_MRK || lhs == DBL_MRK) { double rDbl = stack_double(stack, sDbl, stackTop + 1); double lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && rDbl <= lDbl); } else { valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.LE : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; if (rhs == DBL_MRK || lhs == DBL_MRK) { double rDbl = stack_double(stack, sDbl, stackTop + 1); double lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && lDbl <= rDbl); } else { valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.GT : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; if (rhs == DBL_MRK || lhs == DBL_MRK) { double rDbl = stack_double(stack, sDbl, stackTop + 1); double lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && rDbl < lDbl); } else { valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.LT : { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; if (rhs == DBL_MRK || lhs == DBL_MRK) { double rDbl = stack_double(stack, sDbl, stackTop + 1); double lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && lDbl < rDbl); } else { valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.IN : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); boolean valBln = ScriptRuntime.in(lhs, rhs, scope); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.INSTANCEOF : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); boolean valBln = ScriptRuntime.instanceOf(lhs, rhs, scope); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.EQ : { --stackTop; boolean valBln = do_eq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.NE : { --stackTop; boolean valBln = !do_eq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.SHEQ : { --stackTop; boolean valBln = do_sheq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.SHNE : { --stackTop; boolean valBln = !do_sheq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; } case Token.IFNE : { boolean valBln = stack_boolean(stack, sDbl, stackTop); --stackTop; if (!valBln) { if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop; } pc += 2; break; } case Token.IFEQ : { boolean valBln = stack_boolean(stack, sDbl, stackTop); --stackTop; if (valBln) { if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop; } pc += 2; break; } case Token.GOTO : if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop; case Icode_GOSUB : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = pc + 3; if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop; case Icode_RETSUB : { int slot = (iCode[pc + 1] & 0xFF); if (instructionThreshold != 0) { instructionCount += pc + 2 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } int newPC; Object value = stack[LOCAL_SHFT + slot]; if (value != DBL_MRK) { // Invocation from exception handler, restore object to rethrow javaException = (Throwable)value; exceptionPC = pc; newPC = getJavaCatchPC(iCode); } else { // Normal return from GOSUB newPC = (int)sDbl[LOCAL_SHFT + slot]; } pcPrevBranch = pc = newPC; continue Loop; } case Token.POP : stack[stackTop] = null; stackTop--; break; case Icode_DUP : stack[stackTop + 1] = stack[stackTop]; sDbl[stackTop + 1] = sDbl[stackTop]; stackTop++; break; case Token.POPV : result = stack[stackTop]; if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]); stack[stackTop] = null; --stackTop; break; case Token.RETURN : result = stack[stackTop]; if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]); --stackTop; break Loop; case Icode_RETUNDEF : result = undefined; break Loop; case Icode_END: break Loop; case Token.BITNOT : { int rIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ~rIntValue; break; } case Token.BITAND : { int rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; int lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue & rIntValue; break; } case Token.BITOR : { int rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; int lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue | rIntValue; break; } case Token.BITXOR : { int rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; int lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue ^ rIntValue; break; } case Token.LSH : { int rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; int lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue << rIntValue; break; } case Token.RSH : { int rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; int lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue >> rIntValue; break; } case Token.URSH : { int rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F; --stackTop; double lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue; break; } case Token.ADD : --stackTop; do_add(stack, sDbl, stackTop); break; case Token.SUB : { double rDbl = stack_double(stack, sDbl, stackTop); --stackTop; double lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl - rDbl; break; } case Token.NEG : { double rDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = -rDbl; break; } case Token.POS : { double rDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = rDbl; break; } case Token.MUL : { double rDbl = stack_double(stack, sDbl, stackTop); --stackTop; double lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl * rDbl; break; } case Token.DIV : { double rDbl = stack_double(stack, sDbl, stackTop); --stackTop; double lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; // Detect the divide by zero or let Java do it ? sDbl[stackTop] = lDbl / rDbl; break; } case Token.MOD : { double rDbl = stack_double(stack, sDbl, stackTop); --stackTop; double lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl % rDbl; break; } case Token.NOT : { stack[stackTop] = stack_boolean(stack, sDbl, stackTop) ? Boolean.FALSE : Boolean.TRUE; break; } case Token.BINDNAME : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.bind(scope, name); pc += 2; break; } case Token.GETBASE : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.getBase(scope, name); pc += 2; break; } case Token.SETNAME : { String name = strings[getIndex(iCode, pc + 1)]; Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; // what about class cast exception here for lhs? Scriptable lhs = (Scriptable)stack[stackTop]; stack[stackTop] = ScriptRuntime.setName(lhs, rhs, scope, name); pc += 2; break; } case Token.DELPROP : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.delete(cx, scope, lhs, rhs); break; } case Token.GETPROP : { String name = (String)stack[stackTop]; --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getProp(lhs, name, scope); break; } case Token.SETPROP : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; String name = (String)stack[stackTop]; --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setProp(lhs, name, rhs, scope); break; } case Token.GETELEM : do_getElem(cx, stack, sDbl, stackTop, scope); --stackTop; break; case Token.SETELEM : do_setElem(cx, stack, sDbl, stackTop, scope); stackTop -= 2; break; case Icode_PROPINC : { String name = (String)stack[stackTop]; --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postIncrement(lhs, name, scope); break; } case Icode_PROPDEC : { String name = (String)stack[stackTop]; --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postDecrement(lhs, name, scope); break; } case Icode_ELEMINC : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postIncrementElem(lhs, rhs, scope); break; } case Icode_ELEMDEC : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postDecrementElem(lhs, rhs, scope); break; } case Token.GETTHIS : { Scriptable lhs = (Scriptable)stack[stackTop]; stack[stackTop] = ScriptRuntime.getThis(lhs); break; } case Token.NEWTEMP : { int slot = (iCode[++pc] & 0xFF); stack[LOCAL_SHFT + slot] = stack[stackTop]; sDbl[LOCAL_SHFT + slot] = sDbl[stackTop]; break; } case Token.USETEMP : { int slot = (iCode[++pc] & 0xFF); ++stackTop; stack[stackTop] = stack[LOCAL_SHFT + slot]; sDbl[stackTop] = sDbl[LOCAL_SHFT + slot]; break; } case Icode_CALLSPECIAL : { if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } int callType = iCode[pc + 1] & 0xFF; boolean isNew = (iCode[pc + 2] != 0); int sourceLine = getShort(iCode, pc + 3); int count = getIndex(iCode, pc + 5); stackTop -= count; Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, count); Object functionThis; if (isNew) { functionThis = null; } else { functionThis = stack[stackTop]; if (functionThis == DBL_MRK) { functionThis = doubleWrap(sDbl[stackTop]); } --stackTop; } Object function = stack[stackTop]; if (function == DBL_MRK) function = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.callSpecial( cx, function, isNew, functionThis, outArgs, scope, thisObj, callType, idata.itsSourceFile, sourceLine); pc += 6; instructionCount = cx.instructionCount; break; } case Token.CALL : { if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } int count = getIndex(iCode, pc + 3); stackTop -= count; int calleeArgShft = stackTop + 1; Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; Scriptable calleeScope = scope; if (idata.itsNeedsActivation) { calleeScope = ScriptableObject.getTopLevelScope(scope); } Scriptable calleeThis; if (rhs instanceof Scriptable || rhs == null) { calleeThis = (Scriptable)rhs; } else { calleeThis = ScriptRuntime.toObject(cx, calleeScope, rhs); } if (lhs instanceof InterpretedFunction) { // Inlining of InterpretedFunction.call not to create // argument array InterpretedFunction f = (InterpretedFunction)lhs; stack[stackTop] = interpret(cx, calleeScope, calleeThis, stack, sDbl, calleeArgShft, count, f, f.itsData); } else if (lhs instanceof Function) { Function f = (Function)lhs; Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count); stack[stackTop] = f.call(cx, calleeScope, calleeThis, outArgs); } else { if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); else if (lhs == undefined) { // special code for better error message for call // to undefined lhs = strings[getIndex(iCode, pc + 1)]; if (lhs == null) lhs = undefined; } throw ScriptRuntime.typeError1("msg.isnt.function", ScriptRuntime.toString(lhs)); } pc += 4; instructionCount = cx.instructionCount; break; } case Token.NEW : { if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } int count = getIndex(iCode, pc + 3); stackTop -= count; int calleeArgShft = stackTop + 1; Object lhs = stack[stackTop]; if (lhs instanceof InterpretedFunction) { // Inlining of InterpretedFunction.construct not to create // argument array InterpretedFunction f = (InterpretedFunction)lhs; Scriptable newInstance = f.createObject(cx, scope); Object callResult = interpret(cx, scope, newInstance, stack, sDbl, calleeArgShft, count, f, f.itsData); if (callResult instanceof Scriptable && callResult != undefined) { stack[stackTop] = callResult; } else { stack[stackTop] = newInstance; } } else if (lhs instanceof Function) { Function f = (Function)lhs; Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count); stack[stackTop] = f.construct(cx, scope, outArgs); } else { if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); else if (lhs == undefined) { // special code for better error message for call // to undefined lhs = strings[getIndex(iCode, pc + 1)]; if (lhs == null) lhs = undefined; } throw ScriptRuntime.typeError1("msg.isnt.function", ScriptRuntime.toString(lhs)); } pc += 4; instructionCount = cx.instructionCount; break; } case Token.TYPEOF : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.typeof(lhs); break; } case Icode_TYPEOFNAME : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.typeofName(scope, name); pc += 2; break; } case Token.STRING : stack[++stackTop] = strings[getIndex(iCode, pc + 1)]; pc += 2; break; case Icode_SHORTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getShort(iCode, pc + 1); pc += 2; break; case Icode_INTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getInt(iCode, pc + 1); pc += 4; break; case Token.NUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = idata.itsDoubleTable[getIndex(iCode, pc + 1)]; pc += 2; break; case Token.NAME : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.name(scope, name); pc += 2; break; } case Icode_NAMEINC : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.postIncrement(scope, name); pc += 2; break; } case Icode_NAMEDEC : { String name = strings[getIndex(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.postDecrement(scope, name); pc += 2; break; } case Token.SETVAR : { int slot = (iCode[++pc] & 0xFF); if (!useActivationVars) { stack[VAR_SHFT + slot] = stack[stackTop]; sDbl[VAR_SHFT + slot] = sDbl[stackTop]; } else { Object val = stack[stackTop]; if (val == DBL_MRK) val = doubleWrap(sDbl[stackTop]); activationPut(fnOrScript, scope, slot, val); } break; } case Token.GETVAR : { int slot = (iCode[++pc] & 0xFF); ++stackTop; if (!useActivationVars) { stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; } else { stack[stackTop] = activationGet(fnOrScript, scope, slot); } break; } case Icode_VARINC : { int slot = (iCode[++pc] & 0xFF); ++stackTop; if (!useActivationVars) { stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; stack[VAR_SHFT + slot] = DBL_MRK; sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) + 1.0; } else { Object val = activationGet(fnOrScript, scope, slot); stack[stackTop] = val; val = doubleWrap(ScriptRuntime.toNumber(val) + 1.0); activationPut(fnOrScript, scope, slot, val); } break; } case Icode_VARDEC : { int slot = (iCode[++pc] & 0xFF); ++stackTop; if (!useActivationVars) { stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; stack[VAR_SHFT + slot] = DBL_MRK; sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) - 1.0; } else { Object val = activationGet(fnOrScript, scope, slot); stack[stackTop] = val; val = doubleWrap(ScriptRuntime.toNumber(val) - 1.0); activationPut(fnOrScript, scope, slot, val); } break; } case Token.ZERO : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 0; break; case Token.ONE : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 1; break; case Token.NULL : stack[++stackTop] = null; break; case Token.THIS : stack[++stackTop] = thisObj; break; case Token.THISFN : stack[++stackTop] = fnOrScript; break; case Token.FALSE : stack[++stackTop] = Boolean.FALSE; break; case Token.TRUE : stack[++stackTop] = Boolean.TRUE; break; case Token.UNDEFINED : stack[++stackTop] = Undefined.instance; break; case Token.ENTERWITH : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); --stackTop; scope = ScriptRuntime.enterWith(lhs, scope); ++withDepth; break; } case Token.LEAVEWITH : scope = ScriptRuntime.leaveWith(scope); --withDepth; break; case Token.NEWSCOPE : stack[++stackTop] = ScriptRuntime.newScope(); break; case Token.ENUMINIT : { int slot = (iCode[++pc] & 0xFF); Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); --stackTop; stack[LOCAL_SHFT + slot] = ScriptRuntime.initEnum(lhs, scope); break; } case Token.ENUMNEXT : { int slot = (iCode[++pc] & 0xFF); Object val = stack[LOCAL_SHFT + slot]; ++stackTop; stack[stackTop] = ScriptRuntime.nextEnum(val); break; } case Icode_GETPROTO : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getProto(lhs, scope); break; } case Icode_GETPARENT : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getParent(lhs); break; } case Icode_GETSCOPEPARENT : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getParent(lhs, scope); break; } case Icode_SETPROTO : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setProto(lhs, rhs, scope); break; } case Icode_SETPARENT : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setParent(lhs, rhs, scope); break; } case Icode_SCOPE : stack[++stackTop] = scope; break; case Icode_CLOSURE : { int i = getIndex(iCode, pc + 1); InterpreterData closureData = idata.itsNestedFunctions[i]; stack[++stackTop] = createFunction(cx, scope, closureData, idata.itsFromEvalCode); pc += 2; break; } case Token.REGEXP : { int i = getIndex(iCode, pc + 1); Scriptable regexp; if (idata.itsFunctionType != 0) { regexp = ((InterpretedFunction)fnOrScript).itsRegExps[i]; } else { if (scriptRegExps == null) { scriptRegExps = wrapRegExps(cx, scope, idata); } regexp = scriptRegExps[i]; } stack[++stackTop] = regexp; pc += 2; break; } case Icode_LINE : { cx.interpreterLineIndex = pc + 1; if (debuggerFrame != null) { int line = getShort(iCode, pc + 1); debuggerFrame.onLineChange(cx, line); } pc += 2; break; } default : { dumpICode(idata); throw new RuntimeException ("Unknown icode : "+(iCode[pc] & 0xff)+" @ pc : "+pc); } // end of interpreter switch } pc++; } catch (Throwable ex) { if (instructionThreshold != 0) { if (instructionCount < 0) { // throw during function call instructionCount = cx.instructionCount; } else { // throw during any other operation instructionCount += pc - pcPrevBranch; cx.instructionCount = instructionCount; } } javaException = ex; exceptionPC = pc; pc = getJavaCatchPC(iCode); continue Loop; } } cx.interpreterData = savedData; if (debuggerFrame != null) { if (javaException != null) { debuggerFrame.onExit(cx, true, javaException); } else { debuggerFrame.onExit(cx, false, result); } } if (idata.itsNeedsActivation || debuggerFrame != null) { ScriptRuntime.popActivation(cx); } if (instructionThreshold != 0) { if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } cx.instructionCount = instructionCount; } if (javaException != null) { if (javaException instanceof JavaScriptException) { throw (JavaScriptException)javaException; } else if (javaException instanceof RuntimeException) { throw (RuntimeException)javaException; } else { // Must be instance of Error or code bug throw (Error)javaException; } } return result; }
diff --git a/freeplane/src/org/freeplane/features/styles/mindmapmode/NewUserStyleAction.java b/freeplane/src/org/freeplane/features/styles/mindmapmode/NewUserStyleAction.java index 9dce83aa1..65a60d001 100644 --- a/freeplane/src/org/freeplane/features/styles/mindmapmode/NewUserStyleAction.java +++ b/freeplane/src/org/freeplane/features/styles/mindmapmode/NewUserStyleAction.java @@ -1,109 +1,109 @@ /* * Freeplane - mind map editor * Copyright (C) 2009 Dimitry * * This file author is Dimitry * * 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, see <http://www.gnu.org/licenses/>. */ package org.freeplane.features.styles.mindmapmode; import java.awt.event.ActionEvent; import java.util.ArrayList; import javax.swing.JOptionPane; import org.freeplane.core.ui.AFreeplaneAction; import org.freeplane.core.ui.components.UITools; import org.freeplane.core.undo.IActor; import org.freeplane.core.util.TextUtils; import org.freeplane.features.icon.mindmapmode.MIconController.Keys; import org.freeplane.features.map.MapModel; import org.freeplane.features.map.NodeModel; import org.freeplane.features.map.mindmapmode.MMapController; import org.freeplane.features.mode.Controller; import org.freeplane.features.styles.IStyle; import org.freeplane.features.styles.LogicalStyleController; import org.freeplane.features.styles.LogicalStyleKeys; import org.freeplane.features.styles.MapStyleModel; import org.freeplane.features.styles.StyleFactory; /** * @author Dimitry Polivaev * 02.10.2009 */ public class NewUserStyleAction extends AFreeplaneAction { public NewUserStyleAction() { super("NewUserStyleAction"); } /** * */ private static final long serialVersionUID = 1L; public void actionPerformed(final ActionEvent e) { final String styleName = JOptionPane.showInputDialog(TextUtils.getText("enter_new_style_name")); if (styleName == null) { return; } final Controller controller = Controller.getCurrentController(); final NodeModel selectedNode = controller.getSelection().getSelected(); final MapModel map = controller.getMap(); final MapStyleModel styleModel = MapStyleModel.getExtension(map); final MapModel styleMap = styleModel.getStyleMap(); final IStyle newStyle = StyleFactory.create(styleName); if (null != styleModel.getStyleNode(newStyle)) { UITools.errorMessage(TextUtils.getText("style_already_exists")); return; } final MMapController mapController = (MMapController) Controller.getCurrentModeController().getMapController(); final NodeModel newNode = new NodeModel(styleMap); newNode.setUserObject(newStyle); final LogicalStyleController styleController = LogicalStyleController.getController(); final ArrayList<IStyle> styles = new ArrayList<IStyle>(styleController.getStyles(selectedNode)); for(int i = styles.size() - 1; i >= 0; i--){ IStyle style = styles.get(i); if(MapStyleModel.DEFAULT_STYLE.equals(style)){ continue; } final NodeModel styleNode = styleModel.getStyleNode(style); - Controller.getCurrentModeController().copyExtensions(LogicalStyleKeys.NODE_STYLE, styleNode, newNode); if(styleNode == null){ continue; } + Controller.getCurrentModeController().copyExtensions(LogicalStyleKeys.NODE_STYLE, styleNode, newNode); } Controller.getCurrentModeController().copyExtensions(LogicalStyleKeys.NODE_STYLE, selectedNode, newNode); Controller.getCurrentModeController().copyExtensions(Keys.ICONS, selectedNode, newNode); mapController.insertNode(newNode, styleModel.getUserStyleParentNode(styleMap), false, false, true); mapController.select(newNode); final IActor actor = new IActor() { public void undo() { styleModel.removeStyleNode(newNode); styleController.refreshMap(map); } public String getDescription() { return "NewStyle"; } public void act() { styleModel.addStyleNode(newNode); styleController.refreshMap(map); } }; Controller.getCurrentModeController().execute(actor, styleMap); } }
false
true
public void actionPerformed(final ActionEvent e) { final String styleName = JOptionPane.showInputDialog(TextUtils.getText("enter_new_style_name")); if (styleName == null) { return; } final Controller controller = Controller.getCurrentController(); final NodeModel selectedNode = controller.getSelection().getSelected(); final MapModel map = controller.getMap(); final MapStyleModel styleModel = MapStyleModel.getExtension(map); final MapModel styleMap = styleModel.getStyleMap(); final IStyle newStyle = StyleFactory.create(styleName); if (null != styleModel.getStyleNode(newStyle)) { UITools.errorMessage(TextUtils.getText("style_already_exists")); return; } final MMapController mapController = (MMapController) Controller.getCurrentModeController().getMapController(); final NodeModel newNode = new NodeModel(styleMap); newNode.setUserObject(newStyle); final LogicalStyleController styleController = LogicalStyleController.getController(); final ArrayList<IStyle> styles = new ArrayList<IStyle>(styleController.getStyles(selectedNode)); for(int i = styles.size() - 1; i >= 0; i--){ IStyle style = styles.get(i); if(MapStyleModel.DEFAULT_STYLE.equals(style)){ continue; } final NodeModel styleNode = styleModel.getStyleNode(style); Controller.getCurrentModeController().copyExtensions(LogicalStyleKeys.NODE_STYLE, styleNode, newNode); if(styleNode == null){ continue; } } Controller.getCurrentModeController().copyExtensions(LogicalStyleKeys.NODE_STYLE, selectedNode, newNode); Controller.getCurrentModeController().copyExtensions(Keys.ICONS, selectedNode, newNode); mapController.insertNode(newNode, styleModel.getUserStyleParentNode(styleMap), false, false, true); mapController.select(newNode); final IActor actor = new IActor() { public void undo() { styleModel.removeStyleNode(newNode); styleController.refreshMap(map); } public String getDescription() { return "NewStyle"; } public void act() { styleModel.addStyleNode(newNode); styleController.refreshMap(map); } }; Controller.getCurrentModeController().execute(actor, styleMap); }
public void actionPerformed(final ActionEvent e) { final String styleName = JOptionPane.showInputDialog(TextUtils.getText("enter_new_style_name")); if (styleName == null) { return; } final Controller controller = Controller.getCurrentController(); final NodeModel selectedNode = controller.getSelection().getSelected(); final MapModel map = controller.getMap(); final MapStyleModel styleModel = MapStyleModel.getExtension(map); final MapModel styleMap = styleModel.getStyleMap(); final IStyle newStyle = StyleFactory.create(styleName); if (null != styleModel.getStyleNode(newStyle)) { UITools.errorMessage(TextUtils.getText("style_already_exists")); return; } final MMapController mapController = (MMapController) Controller.getCurrentModeController().getMapController(); final NodeModel newNode = new NodeModel(styleMap); newNode.setUserObject(newStyle); final LogicalStyleController styleController = LogicalStyleController.getController(); final ArrayList<IStyle> styles = new ArrayList<IStyle>(styleController.getStyles(selectedNode)); for(int i = styles.size() - 1; i >= 0; i--){ IStyle style = styles.get(i); if(MapStyleModel.DEFAULT_STYLE.equals(style)){ continue; } final NodeModel styleNode = styleModel.getStyleNode(style); if(styleNode == null){ continue; } Controller.getCurrentModeController().copyExtensions(LogicalStyleKeys.NODE_STYLE, styleNode, newNode); } Controller.getCurrentModeController().copyExtensions(LogicalStyleKeys.NODE_STYLE, selectedNode, newNode); Controller.getCurrentModeController().copyExtensions(Keys.ICONS, selectedNode, newNode); mapController.insertNode(newNode, styleModel.getUserStyleParentNode(styleMap), false, false, true); mapController.select(newNode); final IActor actor = new IActor() { public void undo() { styleModel.removeStyleNode(newNode); styleController.refreshMap(map); } public String getDescription() { return "NewStyle"; } public void act() { styleModel.addStyleNode(newNode); styleController.refreshMap(map); } }; Controller.getCurrentModeController().execute(actor, styleMap); }
diff --git a/access/access-download/src/test/java/com/bhle/access/download/convert/CompleteDerivativesTest.java b/access/access-download/src/test/java/com/bhle/access/download/convert/CompleteDerivativesTest.java index d760159e..1663b2a1 100644 --- a/access/access-download/src/test/java/com/bhle/access/download/convert/CompleteDerivativesTest.java +++ b/access/access-download/src/test/java/com/bhle/access/download/convert/CompleteDerivativesTest.java @@ -1,62 +1,62 @@ package com.bhle.access.download.convert; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import com.bhle.access.BaseTest; import com.bhle.access.util.FedoraURI; import com.bhle.access.util.StaticURI; @ContextConfiguration public class CompleteDerivativesTest extends BaseTest { private static final Logger logger = LoggerFactory .getLogger(CompleteDerivativesTest.class); @Test public void testPostIngestDerivatives() throws InterruptedException { - Thread.sleep(10000); + Thread.sleep(15000); try { testPdfGeneration(); testJpegGeneration(); testOcrGeneration(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void testPdfGeneration() throws MalformedURLException, IOException { FedoraURI fedoraURI = FedoraURI.getFedoraUri("a000test", "full_pdf"); URI uri = StaticURI.toStaticFileUri(fedoraURI); InputStream in = uri.toURL().openStream(); Assert.assertTrue(in.available() > 0); in.close(); } private void testJpegGeneration() throws MalformedURLException, IOException { FedoraURI fedoraURI = FedoraURI.getFedoraUri("a000test", "full_jpeg"); URI uri = StaticURI.toStaticFileUri(fedoraURI); InputStream in = uri.toURL().openStream(); Assert.assertTrue(in.available() > 0); in.close(); } private void testOcrGeneration() throws MalformedURLException, IOException { FedoraURI fedoraURI = FedoraURI.getFedoraUri("a000test", "full_ocr"); URI uri = StaticURI.toStaticFileUri(fedoraURI); InputStream in = uri.toURL().openStream(); Assert.assertTrue(in.available() > 0); in.close(); } }
true
true
public void testPostIngestDerivatives() throws InterruptedException { Thread.sleep(10000); try { testPdfGeneration(); testJpegGeneration(); testOcrGeneration(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public void testPostIngestDerivatives() throws InterruptedException { Thread.sleep(15000); try { testPdfGeneration(); testJpegGeneration(); testOcrGeneration(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
diff --git a/src/com/martinbrook/tesseractuhc/notification/DamageNotification.java b/src/com/martinbrook/tesseractuhc/notification/DamageNotification.java index dacc519..aa1cf82 100644 --- a/src/com/martinbrook/tesseractuhc/notification/DamageNotification.java +++ b/src/com/martinbrook/tesseractuhc/notification/DamageNotification.java @@ -1,95 +1,96 @@ package com.martinbrook.tesseractuhc.notification; import org.bukkit.entity.AnimalTamer; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.entity.Wolf; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import com.martinbrook.tesseractuhc.UhcPlayer; public class DamageNotification extends UhcNotification { private UhcPlayer damaged; private int damageAmount; private DamageCause cause; private Entity damager; public DamageNotification(UhcPlayer damaged, int damageAmount, DamageCause cause, Entity damager) { super(); this.damaged = damaged; this.damageAmount = damageAmount; this.cause = cause; this.damager = damager; } public DamageNotification(UhcPlayer damaged, int damageAmount, DamageCause cause) { super(); this.damaged = damaged; this.damageAmount = damageAmount; this.cause = cause; this.damager = null; } @Override public String formatForPlayers() { if (damager != null) { if (damager instanceof Player) { // PVP damage if (cause == DamageCause.ENTITY_ATTACK) return damaged.getName() + " was hurt by " + ((Player) damager).getDisplayName() + " (" + (damageAmount / 2.0) + " hearts)!"; if (cause == DamageCause.PROJECTILE) return damaged.getName() + " was shot at by " + ((Player) damager).getDisplayName() + " (" + (damageAmount / 2.0) + " hearts)!"; } else { // Mob damage String type = "an unknown entity"; if (damager.getType() == EntityType.BLAZE) type = "a blaze"; else if (damager.getType() == EntityType.CAVE_SPIDER) type = "a cave spider"; else if (damager.getType() == EntityType.CREEPER) type = "a creeper"; else if (damager.getType() == EntityType.ENDER_DRAGON) type = "the dragon"; else if (damager.getType() == EntityType.ENDERMAN) type = "an enderman"; else if (damager.getType() == EntityType.GHAST) type = "a ghast"; else if (damager.getType() == EntityType.IRON_GOLEM) type = "an iron golem"; else if (damager.getType() == EntityType.MAGMA_CUBE) type = "a magma cube"; else if (damager.getType() == EntityType.PIG_ZOMBIE) type = "a zombie pigman"; else if (damager.getType() == EntityType.SILVERFISH) type = "a silverfish"; else if (damager.getType() == EntityType.SKELETON) type = "a skeleton"; else if (damager.getType() == EntityType.SLIME) type = "a slime"; else if (damager.getType() == EntityType.WITCH) type = "a witch"; else if (damager.getType() == EntityType.WITHER) type = "a wither"; else if (damager.getType() == EntityType.WITHER_SKULL) type = "a wither skull"; else if (damager.getType() == EntityType.ZOMBIE) type = "a zombie"; else if (damager.getType() == EntityType.WOLF) { AnimalTamer owner = ((Wolf) damager).getOwner(); if (owner != null) type = owner.getName() + "'s wolf"; else type = "a wolf"; } return damaged.getName() + " took " + (damageAmount/2.0) + " hearts of damage from " + type; } } // Environmental damage String type = "unknown"; if (cause == DamageCause.BLOCK_EXPLOSION) type = "TNT"; else if (cause == DamageCause.CONTACT) type = "cactus"; else if (cause == DamageCause.DROWNING) type = "drowning"; else if (cause == DamageCause.FALL) type = "fall"; - else if (cause == DamageCause.FIRE || cause == DamageCause.FIRE_TICK) type = "burning"; + else if (cause == DamageCause.FIRE) return null; + else if (cause == DamageCause.FIRE_TICK) type = "burning"; else if (cause == DamageCause.LAVA) type = "lava"; else if (cause == DamageCause.LIGHTNING) type = "lightning"; else if (cause == DamageCause.MAGIC) type = "magic"; else if (cause == DamageCause.POISON) type = "poison"; else if (cause == DamageCause.STARVATION) type = "starvation"; else if (cause == DamageCause.SUFFOCATION) type = "suffocation"; else if (cause == DamageCause.VOID) type = "void"; else if (cause == DamageCause.WITHER) type = "wither"; return damaged.getName() + " took " + (damageAmount/2.0) + " hearts of " + type + " damage!"; } }
true
true
public String formatForPlayers() { if (damager != null) { if (damager instanceof Player) { // PVP damage if (cause == DamageCause.ENTITY_ATTACK) return damaged.getName() + " was hurt by " + ((Player) damager).getDisplayName() + " (" + (damageAmount / 2.0) + " hearts)!"; if (cause == DamageCause.PROJECTILE) return damaged.getName() + " was shot at by " + ((Player) damager).getDisplayName() + " (" + (damageAmount / 2.0) + " hearts)!"; } else { // Mob damage String type = "an unknown entity"; if (damager.getType() == EntityType.BLAZE) type = "a blaze"; else if (damager.getType() == EntityType.CAVE_SPIDER) type = "a cave spider"; else if (damager.getType() == EntityType.CREEPER) type = "a creeper"; else if (damager.getType() == EntityType.ENDER_DRAGON) type = "the dragon"; else if (damager.getType() == EntityType.ENDERMAN) type = "an enderman"; else if (damager.getType() == EntityType.GHAST) type = "a ghast"; else if (damager.getType() == EntityType.IRON_GOLEM) type = "an iron golem"; else if (damager.getType() == EntityType.MAGMA_CUBE) type = "a magma cube"; else if (damager.getType() == EntityType.PIG_ZOMBIE) type = "a zombie pigman"; else if (damager.getType() == EntityType.SILVERFISH) type = "a silverfish"; else if (damager.getType() == EntityType.SKELETON) type = "a skeleton"; else if (damager.getType() == EntityType.SLIME) type = "a slime"; else if (damager.getType() == EntityType.WITCH) type = "a witch"; else if (damager.getType() == EntityType.WITHER) type = "a wither"; else if (damager.getType() == EntityType.WITHER_SKULL) type = "a wither skull"; else if (damager.getType() == EntityType.ZOMBIE) type = "a zombie"; else if (damager.getType() == EntityType.WOLF) { AnimalTamer owner = ((Wolf) damager).getOwner(); if (owner != null) type = owner.getName() + "'s wolf"; else type = "a wolf"; } return damaged.getName() + " took " + (damageAmount/2.0) + " hearts of damage from " + type; } } // Environmental damage String type = "unknown"; if (cause == DamageCause.BLOCK_EXPLOSION) type = "TNT"; else if (cause == DamageCause.CONTACT) type = "cactus"; else if (cause == DamageCause.DROWNING) type = "drowning"; else if (cause == DamageCause.FALL) type = "fall"; else if (cause == DamageCause.FIRE || cause == DamageCause.FIRE_TICK) type = "burning"; else if (cause == DamageCause.LAVA) type = "lava"; else if (cause == DamageCause.LIGHTNING) type = "lightning"; else if (cause == DamageCause.MAGIC) type = "magic"; else if (cause == DamageCause.POISON) type = "poison"; else if (cause == DamageCause.STARVATION) type = "starvation"; else if (cause == DamageCause.SUFFOCATION) type = "suffocation"; else if (cause == DamageCause.VOID) type = "void"; else if (cause == DamageCause.WITHER) type = "wither"; return damaged.getName() + " took " + (damageAmount/2.0) + " hearts of " + type + " damage!"; }
public String formatForPlayers() { if (damager != null) { if (damager instanceof Player) { // PVP damage if (cause == DamageCause.ENTITY_ATTACK) return damaged.getName() + " was hurt by " + ((Player) damager).getDisplayName() + " (" + (damageAmount / 2.0) + " hearts)!"; if (cause == DamageCause.PROJECTILE) return damaged.getName() + " was shot at by " + ((Player) damager).getDisplayName() + " (" + (damageAmount / 2.0) + " hearts)!"; } else { // Mob damage String type = "an unknown entity"; if (damager.getType() == EntityType.BLAZE) type = "a blaze"; else if (damager.getType() == EntityType.CAVE_SPIDER) type = "a cave spider"; else if (damager.getType() == EntityType.CREEPER) type = "a creeper"; else if (damager.getType() == EntityType.ENDER_DRAGON) type = "the dragon"; else if (damager.getType() == EntityType.ENDERMAN) type = "an enderman"; else if (damager.getType() == EntityType.GHAST) type = "a ghast"; else if (damager.getType() == EntityType.IRON_GOLEM) type = "an iron golem"; else if (damager.getType() == EntityType.MAGMA_CUBE) type = "a magma cube"; else if (damager.getType() == EntityType.PIG_ZOMBIE) type = "a zombie pigman"; else if (damager.getType() == EntityType.SILVERFISH) type = "a silverfish"; else if (damager.getType() == EntityType.SKELETON) type = "a skeleton"; else if (damager.getType() == EntityType.SLIME) type = "a slime"; else if (damager.getType() == EntityType.WITCH) type = "a witch"; else if (damager.getType() == EntityType.WITHER) type = "a wither"; else if (damager.getType() == EntityType.WITHER_SKULL) type = "a wither skull"; else if (damager.getType() == EntityType.ZOMBIE) type = "a zombie"; else if (damager.getType() == EntityType.WOLF) { AnimalTamer owner = ((Wolf) damager).getOwner(); if (owner != null) type = owner.getName() + "'s wolf"; else type = "a wolf"; } return damaged.getName() + " took " + (damageAmount/2.0) + " hearts of damage from " + type; } } // Environmental damage String type = "unknown"; if (cause == DamageCause.BLOCK_EXPLOSION) type = "TNT"; else if (cause == DamageCause.CONTACT) type = "cactus"; else if (cause == DamageCause.DROWNING) type = "drowning"; else if (cause == DamageCause.FALL) type = "fall"; else if (cause == DamageCause.FIRE) return null; else if (cause == DamageCause.FIRE_TICK) type = "burning"; else if (cause == DamageCause.LAVA) type = "lava"; else if (cause == DamageCause.LIGHTNING) type = "lightning"; else if (cause == DamageCause.MAGIC) type = "magic"; else if (cause == DamageCause.POISON) type = "poison"; else if (cause == DamageCause.STARVATION) type = "starvation"; else if (cause == DamageCause.SUFFOCATION) type = "suffocation"; else if (cause == DamageCause.VOID) type = "void"; else if (cause == DamageCause.WITHER) type = "wither"; return damaged.getName() + " took " + (damageAmount/2.0) + " hearts of " + type + " damage!"; }
diff --git a/src/main/java/com/photon/phresco/impl/EnvironmentsParameterImpl.java b/src/main/java/com/photon/phresco/impl/EnvironmentsParameterImpl.java index 10cfa75..d8bd851 100644 --- a/src/main/java/com/photon/phresco/impl/EnvironmentsParameterImpl.java +++ b/src/main/java/com/photon/phresco/impl/EnvironmentsParameterImpl.java @@ -1,97 +1,97 @@ package com.photon.phresco.impl; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.lang.StringUtils; import org.xml.sax.SAXException; import com.photon.phresco.api.ConfigManager; import com.photon.phresco.api.DynamicParameter; import com.photon.phresco.commons.model.ApplicationInfo; import com.photon.phresco.configuration.Environment; import com.photon.phresco.exception.ConfigurationException; import com.photon.phresco.exception.PhrescoException; import com.photon.phresco.plugins.model.Mojos.Mojo.Configuration.Parameters.Parameter; import com.photon.phresco.plugins.model.Mojos.Mojo.Configuration.Parameters.Parameter.PossibleValues; import com.photon.phresco.plugins.model.Mojos.Mojo.Configuration.Parameters.Parameter.PossibleValues.Value; import com.photon.phresco.plugins.util.MojoProcessor; import com.photon.phresco.util.Constants; import com.photon.phresco.util.Utility; public class EnvironmentsParameterImpl implements DynamicParameter, Constants { private static final long serialVersionUID = 1L; @Override public PossibleValues getValues(Map<String, Object> paramsMap) throws IOException, ParserConfigurationException, SAXException, ConfigurationException, PhrescoException { PossibleValues possibleValues = new PossibleValues(); ApplicationInfo applicationInfo = (ApplicationInfo) paramsMap.get(KEY_APP_INFO); String customer = (String) paramsMap.get(KEY_CUSTOMER_ID); MojoProcessor mojo = (MojoProcessor) paramsMap.get(KEY_MOJO); String goal = (String) paramsMap.get(KEY_GOAL); Parameter parameter = mojo.getParameter(goal, KEY_ENVIRONMENT); String updateDefaultEnv = ""; if (paramsMap != null) { String showSettings = (String) paramsMap.get(KEY_SHOW_SETTINGS); if (Boolean.parseBoolean(showSettings)) { String techId = applicationInfo.getTechInfo().getId(); String settingsPath = getSettingsPath(customer); ConfigManager configManager = new ConfigManagerImpl(new File(settingsPath)); List<Environment> environments = configManager.getEnvironments(); for (Environment environment : environments) { List<String> appliesTos = environment.getAppliesTo(); Value value = new Value(); for (String appliesTo : appliesTos) { if(appliesTo.equals(techId)) { value.setValue(environment.getName()); possibleValues.getValue().add(value); if(environment.isDefaultEnv()) { updateDefaultEnv = environment.getName(); } } } } } } String projectDirectory = applicationInfo.getAppDirName(); String configPath = getConfigurationPath(projectDirectory).toString(); ConfigManager configManager = new ConfigManagerImpl(new File(configPath)); List<Environment> environments = configManager.getEnvironments(); for (Environment environment : environments) { Value value = new Value(); value.setValue(environment.getName()); possibleValues.getValue().add(value); if(environment.isDefaultEnv()) { updateDefaultEnv = environment.getName(); } } - if (parameter != null && StringUtils.isEmpty(parameter.getValue())) { + if (parameter != null) { parameter.setValue(updateDefaultEnv); mojo.save(); } return possibleValues; } private StringBuilder getConfigurationPath(String projectDirectory) { StringBuilder builder = new StringBuilder(Utility.getProjectHome()); builder.append(projectDirectory); builder.append(File.separator); builder.append(DOT_PHRESCO_FOLDER); builder.append(File.separator); builder.append(CONFIGURATION_INFO_FILE); return builder; } private String getSettingsPath(String customer) { return Utility.getProjectHome() + customer +"-settings.xml"; } }
true
true
public PossibleValues getValues(Map<String, Object> paramsMap) throws IOException, ParserConfigurationException, SAXException, ConfigurationException, PhrescoException { PossibleValues possibleValues = new PossibleValues(); ApplicationInfo applicationInfo = (ApplicationInfo) paramsMap.get(KEY_APP_INFO); String customer = (String) paramsMap.get(KEY_CUSTOMER_ID); MojoProcessor mojo = (MojoProcessor) paramsMap.get(KEY_MOJO); String goal = (String) paramsMap.get(KEY_GOAL); Parameter parameter = mojo.getParameter(goal, KEY_ENVIRONMENT); String updateDefaultEnv = ""; if (paramsMap != null) { String showSettings = (String) paramsMap.get(KEY_SHOW_SETTINGS); if (Boolean.parseBoolean(showSettings)) { String techId = applicationInfo.getTechInfo().getId(); String settingsPath = getSettingsPath(customer); ConfigManager configManager = new ConfigManagerImpl(new File(settingsPath)); List<Environment> environments = configManager.getEnvironments(); for (Environment environment : environments) { List<String> appliesTos = environment.getAppliesTo(); Value value = new Value(); for (String appliesTo : appliesTos) { if(appliesTo.equals(techId)) { value.setValue(environment.getName()); possibleValues.getValue().add(value); if(environment.isDefaultEnv()) { updateDefaultEnv = environment.getName(); } } } } } } String projectDirectory = applicationInfo.getAppDirName(); String configPath = getConfigurationPath(projectDirectory).toString(); ConfigManager configManager = new ConfigManagerImpl(new File(configPath)); List<Environment> environments = configManager.getEnvironments(); for (Environment environment : environments) { Value value = new Value(); value.setValue(environment.getName()); possibleValues.getValue().add(value); if(environment.isDefaultEnv()) { updateDefaultEnv = environment.getName(); } } if (parameter != null && StringUtils.isEmpty(parameter.getValue())) { parameter.setValue(updateDefaultEnv); mojo.save(); } return possibleValues; }
public PossibleValues getValues(Map<String, Object> paramsMap) throws IOException, ParserConfigurationException, SAXException, ConfigurationException, PhrescoException { PossibleValues possibleValues = new PossibleValues(); ApplicationInfo applicationInfo = (ApplicationInfo) paramsMap.get(KEY_APP_INFO); String customer = (String) paramsMap.get(KEY_CUSTOMER_ID); MojoProcessor mojo = (MojoProcessor) paramsMap.get(KEY_MOJO); String goal = (String) paramsMap.get(KEY_GOAL); Parameter parameter = mojo.getParameter(goal, KEY_ENVIRONMENT); String updateDefaultEnv = ""; if (paramsMap != null) { String showSettings = (String) paramsMap.get(KEY_SHOW_SETTINGS); if (Boolean.parseBoolean(showSettings)) { String techId = applicationInfo.getTechInfo().getId(); String settingsPath = getSettingsPath(customer); ConfigManager configManager = new ConfigManagerImpl(new File(settingsPath)); List<Environment> environments = configManager.getEnvironments(); for (Environment environment : environments) { List<String> appliesTos = environment.getAppliesTo(); Value value = new Value(); for (String appliesTo : appliesTos) { if(appliesTo.equals(techId)) { value.setValue(environment.getName()); possibleValues.getValue().add(value); if(environment.isDefaultEnv()) { updateDefaultEnv = environment.getName(); } } } } } } String projectDirectory = applicationInfo.getAppDirName(); String configPath = getConfigurationPath(projectDirectory).toString(); ConfigManager configManager = new ConfigManagerImpl(new File(configPath)); List<Environment> environments = configManager.getEnvironments(); for (Environment environment : environments) { Value value = new Value(); value.setValue(environment.getName()); possibleValues.getValue().add(value); if(environment.isDefaultEnv()) { updateDefaultEnv = environment.getName(); } } if (parameter != null) { parameter.setValue(updateDefaultEnv); mojo.save(); } return possibleValues; }
diff --git a/src/com/darwinsys/lang/GetOpt.java b/src/com/darwinsys/lang/GetOpt.java index 5d0ea26..1e1bf21 100644 --- a/src/com/darwinsys/lang/GetOpt.java +++ b/src/com/darwinsys/lang/GetOpt.java @@ -1,60 +1,62 @@ /** A class to implement UNIX-style (single-character) command arguments * @author Ian F. Darwin, [email protected] * based on the standard UNIX getopt(3) program. * @version $Id$ */ public class GetOpt { /** The set of characters to look for */ protected String pattern; /** Where we are in the options */ protected int optind = 0; /** Retreive the option index */ public int optind() { return optind; } /** The option argument, if there is one. */ protected String optarg; /** Retreive the option argument */ public String optarg() { return optarg; } /** Whether we are done all the options */ protected boolean done = false; /* Construct a GetOpt object, storing the set of option characters. */ public GetOpt(String patt) { pattern = patt; optind = 0; rewind(); } public void rewind() { done = false; } /** Return one argument. */ public char getopt(String argv[]) { + if (optind == (argv.length)) + done = true; if (done) return 0; String thisArg = argv[optind++]; optarg = null; for (int i=0; i<pattern.length(); i++) { char c = pattern.charAt(i); if (thisArg.startsWith("-")) { if (thisArg.equals("-"+c)) { if (i+1 < pattern.length() && pattern.charAt((i++)+1)==':') optarg = argv[optind++]; return c; } } else { done = true; return 0; } } // Still no match, and not used all args, so must be error. return '?'; } }
true
true
public char getopt(String argv[]) { if (done) return 0; String thisArg = argv[optind++]; optarg = null; for (int i=0; i<pattern.length(); i++) { char c = pattern.charAt(i); if (thisArg.startsWith("-")) { if (thisArg.equals("-"+c)) { if (i+1 < pattern.length() && pattern.charAt((i++)+1)==':') optarg = argv[optind++]; return c; } } else { done = true; return 0; } } // Still no match, and not used all args, so must be error. return '?'; }
public char getopt(String argv[]) { if (optind == (argv.length)) done = true; if (done) return 0; String thisArg = argv[optind++]; optarg = null; for (int i=0; i<pattern.length(); i++) { char c = pattern.charAt(i); if (thisArg.startsWith("-")) { if (thisArg.equals("-"+c)) { if (i+1 < pattern.length() && pattern.charAt((i++)+1)==':') optarg = argv[optind++]; return c; } } else { done = true; return 0; } } // Still no match, and not used all args, so must be error. return '?'; }
diff --git a/v4/java/android/support/v4/view/ViewPager.java b/v4/java/android/support/v4/view/ViewPager.java index 88740969d..429390a73 100644 --- a/v4/java/android/support/v4/view/ViewPager.java +++ b/v4/java/android/support/v4/view/ViewPager.java @@ -1,2865 +1,2866 @@ /* * Copyright (C) 2011 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 android.support.v4.view; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.os.SystemClock; import android.support.v4.os.ParcelableCompat; import android.support.v4.os.ParcelableCompatCreatorCallbacks; import android.support.v4.view.accessibility.AccessibilityEventCompat; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.support.v4.view.accessibility.AccessibilityRecordCompat; import android.support.v4.widget.EdgeEffectCompat; import android.util.AttributeSet; import android.util.Log; import android.view.FocusFinder; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SoundEffectConstants; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; import android.view.animation.Interpolator; import android.widget.Scroller; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; /** * Layout manager that allows the user to flip left and right * through pages of data. You supply an implementation of a * {@link PagerAdapter} to generate the pages that the view shows. * * <p>Note this class is currently under early design and * development. The API will likely change in later updates of * the compatibility library, requiring changes to the source code * of apps when they are compiled against the newer version.</p> * * <p>ViewPager is most often used in conjunction with {@link android.app.Fragment}, * which is a convenient way to supply and manage the lifecycle of each page. * There are standard adapters implemented for using fragments with the ViewPager, * which cover the most common use cases. These are * {@link android.support.v4.app.FragmentPagerAdapter} and * {@link android.support.v4.app.FragmentStatePagerAdapter}; each of these * classes have simple code showing how to build a full user interface * with them. * * <p>Here is a more complicated example of ViewPager, using it in conjuction * with {@link android.app.ActionBar} tabs. You can find other examples of using * ViewPager in the API 4+ Support Demos and API 13+ Support Demos sample code. * * {@sample development/samples/Support13Demos/src/com/example/android/supportv13/app/ActionBarTabsPager.java * complete} */ public class ViewPager extends ViewGroup { private static final String TAG = "ViewPager"; private static final boolean DEBUG = false; private static final boolean USE_CACHE = false; private static final int DEFAULT_OFFSCREEN_PAGES = 1; private static final int MAX_SETTLE_DURATION = 600; // ms private static final int MIN_DISTANCE_FOR_FLING = 25; // dips private static final int DEFAULT_GUTTER_SIZE = 16; // dips private static final int MIN_FLING_VELOCITY = 400; // dips private static final int[] LAYOUT_ATTRS = new int[] { android.R.attr.layout_gravity }; /** * Used to track what the expected number of items in the adapter should be. * If the app changes this when we don't expect it, we'll throw a big obnoxious exception. */ private int mExpectedAdapterCount; static class ItemInfo { Object object; int position; boolean scrolling; float widthFactor; float offset; } private static final Comparator<ItemInfo> COMPARATOR = new Comparator<ItemInfo>(){ @Override public int compare(ItemInfo lhs, ItemInfo rhs) { return lhs.position - rhs.position; } }; private static final Interpolator sInterpolator = new Interpolator() { public float getInterpolation(float t) { t -= 1.0f; return t * t * t * t * t + 1.0f; } }; private final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>(); private final ItemInfo mTempItem = new ItemInfo(); private final Rect mTempRect = new Rect(); private PagerAdapter mAdapter; private int mCurItem; // Index of currently displayed page. private int mRestoredCurItem = -1; private Parcelable mRestoredAdapterState = null; private ClassLoader mRestoredClassLoader = null; private Scroller mScroller; private PagerObserver mObserver; private int mPageMargin; private Drawable mMarginDrawable; private int mTopPageBounds; private int mBottomPageBounds; // Offsets of the first and last items, if known. // Set during population, used to determine if we are at the beginning // or end of the pager data set during touch scrolling. private float mFirstOffset = -Float.MAX_VALUE; private float mLastOffset = Float.MAX_VALUE; private int mChildWidthMeasureSpec; private int mChildHeightMeasureSpec; private boolean mInLayout; private boolean mScrollingCacheEnabled; private boolean mPopulatePending; private int mOffscreenPageLimit = DEFAULT_OFFSCREEN_PAGES; private boolean mIsBeingDragged; private boolean mIsUnableToDrag; private boolean mIgnoreGutter; private int mDefaultGutterSize; private int mGutterSize; private int mTouchSlop; /** * Position of the last motion event. */ private float mLastMotionX; private float mLastMotionY; private float mInitialMotionX; private float mInitialMotionY; /** * ID of the active pointer. This is used to retain consistency during * drags/flings if multiple pointers are used. */ private int mActivePointerId = INVALID_POINTER; /** * Sentinel value for no current active pointer. * Used by {@link #mActivePointerId}. */ private static final int INVALID_POINTER = -1; /** * Determines speed during touch scrolling */ private VelocityTracker mVelocityTracker; private int mMinimumVelocity; private int mMaximumVelocity; private int mFlingDistance; private int mCloseEnough; // If the pager is at least this close to its final position, complete the scroll // on touch down and let the user interact with the content inside instead of // "catching" the flinging pager. private static final int CLOSE_ENOUGH = 2; // dp private boolean mFakeDragging; private long mFakeDragBeginTime; private EdgeEffectCompat mLeftEdge; private EdgeEffectCompat mRightEdge; private boolean mFirstLayout = true; private boolean mNeedCalculatePageOffsets = false; private boolean mCalledSuper; private int mDecorChildCount; private OnPageChangeListener mOnPageChangeListener; private OnPageChangeListener mInternalPageChangeListener; private OnAdapterChangeListener mAdapterChangeListener; private PageTransformer mPageTransformer; private Method mSetChildrenDrawingOrderEnabled; private static final int DRAW_ORDER_DEFAULT = 0; private static final int DRAW_ORDER_FORWARD = 1; private static final int DRAW_ORDER_REVERSE = 2; private int mDrawingOrder; private ArrayList<View> mDrawingOrderedChildren; private static final ViewPositionComparator sPositionComparator = new ViewPositionComparator(); /** * Indicates that the pager is in an idle, settled state. The current page * is fully in view and no animation is in progress. */ public static final int SCROLL_STATE_IDLE = 0; /** * Indicates that the pager is currently being dragged by the user. */ public static final int SCROLL_STATE_DRAGGING = 1; /** * Indicates that the pager is in the process of settling to a final position. */ public static final int SCROLL_STATE_SETTLING = 2; private final Runnable mEndScrollRunnable = new Runnable() { public void run() { setScrollState(SCROLL_STATE_IDLE); populate(); } }; private int mScrollState = SCROLL_STATE_IDLE; /** * Callback interface for responding to changing state of the selected page. */ public interface OnPageChangeListener { /** * This method will be invoked when the current page is scrolled, either as part * of a programmatically initiated smooth scroll or a user initiated touch scroll. * * @param position Position index of the first page currently being displayed. * Page position+1 will be visible if positionOffset is nonzero. * @param positionOffset Value from [0, 1) indicating the offset from the page at position. * @param positionOffsetPixels Value in pixels indicating the offset from position. */ public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels); /** * This method will be invoked when a new page becomes selected. Animation is not * necessarily complete. * * @param position Position index of the new selected page. */ public void onPageSelected(int position); /** * Called when the scroll state changes. Useful for discovering when the user * begins dragging, when the pager is automatically settling to the current page, * or when it is fully stopped/idle. * * @param state The new scroll state. * @see ViewPager#SCROLL_STATE_IDLE * @see ViewPager#SCROLL_STATE_DRAGGING * @see ViewPager#SCROLL_STATE_SETTLING */ public void onPageScrollStateChanged(int state); } /** * Simple implementation of the {@link OnPageChangeListener} interface with stub * implementations of each method. Extend this if you do not intend to override * every method of {@link OnPageChangeListener}. */ public static class SimpleOnPageChangeListener implements OnPageChangeListener { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // This space for rent } @Override public void onPageSelected(int position) { // This space for rent } @Override public void onPageScrollStateChanged(int state) { // This space for rent } } /** * A PageTransformer is invoked whenever a visible/attached page is scrolled. * This offers an opportunity for the application to apply a custom transformation * to the page views using animation properties. * * <p>As property animation is only supported as of Android 3.0 and forward, * setting a PageTransformer on a ViewPager on earlier platform versions will * be ignored.</p> */ public interface PageTransformer { /** * Apply a property transformation to the given page. * * @param page Apply the transformation to this page * @param position Position of page relative to the current front-and-center * position of the pager. 0 is front and center. 1 is one full * page position to the right, and -1 is one page position to the left. */ public void transformPage(View page, float position); } /** * Used internally to monitor when adapters are switched. */ interface OnAdapterChangeListener { public void onAdapterChanged(PagerAdapter oldAdapter, PagerAdapter newAdapter); } /** * Used internally to tag special types of child views that should be added as * pager decorations by default. */ interface Decor {} public ViewPager(Context context) { super(context); initViewPager(); } public ViewPager(Context context, AttributeSet attrs) { super(context, attrs); initViewPager(); } void initViewPager() { setWillNotDraw(false); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); setFocusable(true); final Context context = getContext(); mScroller = new Scroller(context, sInterpolator); final ViewConfiguration configuration = ViewConfiguration.get(context); final float density = context.getResources().getDisplayMetrics().density; mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration); mMinimumVelocity = (int) (MIN_FLING_VELOCITY * density); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); mLeftEdge = new EdgeEffectCompat(context); mRightEdge = new EdgeEffectCompat(context); mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density); mCloseEnough = (int) (CLOSE_ENOUGH * density); mDefaultGutterSize = (int) (DEFAULT_GUTTER_SIZE * density); ViewCompat.setAccessibilityDelegate(this, new MyAccessibilityDelegate()); if (ViewCompat.getImportantForAccessibility(this) == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); } } @Override protected void onDetachedFromWindow() { removeCallbacks(mEndScrollRunnable); super.onDetachedFromWindow(); } private void setScrollState(int newState) { if (mScrollState == newState) { return; } mScrollState = newState; if (mPageTransformer != null) { // PageTransformers can do complex things that benefit from hardware layers. enableLayers(newState != SCROLL_STATE_IDLE); } if (mOnPageChangeListener != null) { mOnPageChangeListener.onPageScrollStateChanged(newState); } } /** * Set a PagerAdapter that will supply views for this pager as needed. * * @param adapter Adapter to use */ public void setAdapter(PagerAdapter adapter) { if (mAdapter != null) { mAdapter.unregisterDataSetObserver(mObserver); mAdapter.startUpdate(this); for (int i = 0; i < mItems.size(); i++) { final ItemInfo ii = mItems.get(i); mAdapter.destroyItem(this, ii.position, ii.object); } mAdapter.finishUpdate(this); mItems.clear(); removeNonDecorViews(); mCurItem = 0; scrollTo(0, 0); } final PagerAdapter oldAdapter = mAdapter; mAdapter = adapter; mExpectedAdapterCount = 0; if (mAdapter != null) { if (mObserver == null) { mObserver = new PagerObserver(); } mAdapter.registerDataSetObserver(mObserver); mPopulatePending = false; final boolean wasFirstLayout = mFirstLayout; mFirstLayout = true; mExpectedAdapterCount = mAdapter.getCount(); if (mRestoredCurItem >= 0) { mAdapter.restoreState(mRestoredAdapterState, mRestoredClassLoader); setCurrentItemInternal(mRestoredCurItem, false, true); mRestoredCurItem = -1; mRestoredAdapterState = null; mRestoredClassLoader = null; } else if (!wasFirstLayout) { populate(); } else { requestLayout(); } } if (mAdapterChangeListener != null && oldAdapter != adapter) { mAdapterChangeListener.onAdapterChanged(oldAdapter, adapter); } } private void removeNonDecorViews() { for (int i = 0; i < getChildCount(); i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (!lp.isDecor) { removeViewAt(i); i--; } } } /** * Retrieve the current adapter supplying pages. * * @return The currently registered PagerAdapter */ public PagerAdapter getAdapter() { return mAdapter; } void setOnAdapterChangeListener(OnAdapterChangeListener listener) { mAdapterChangeListener = listener; } private int getClientWidth() { return getMeasuredWidth() - getPaddingLeft() - getPaddingRight(); } /** * Set the currently selected page. If the ViewPager has already been through its first * layout with its current adapter there will be a smooth animated transition between * the current item and the specified item. * * @param item Item index to select */ public void setCurrentItem(int item) { mPopulatePending = false; setCurrentItemInternal(item, !mFirstLayout, false); } /** * Set the currently selected page. * * @param item Item index to select * @param smoothScroll True to smoothly scroll to the new item, false to transition immediately */ public void setCurrentItem(int item, boolean smoothScroll) { mPopulatePending = false; setCurrentItemInternal(item, smoothScroll, false); } public int getCurrentItem() { return mCurItem; } void setCurrentItemInternal(int item, boolean smoothScroll, boolean always) { setCurrentItemInternal(item, smoothScroll, always, 0); } void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) { if (mAdapter == null || mAdapter.getCount() <= 0) { setScrollingCacheEnabled(false); return; } if (!always && mCurItem == item && mItems.size() != 0) { setScrollingCacheEnabled(false); return; } if (item < 0) { item = 0; } else if (item >= mAdapter.getCount()) { item = mAdapter.getCount() - 1; } final int pageLimit = mOffscreenPageLimit; if (item > (mCurItem + pageLimit) || item < (mCurItem - pageLimit)) { // We are doing a jump by more than one page. To avoid // glitches, we want to keep all current pages in the view // until the scroll ends. for (int i=0; i<mItems.size(); i++) { mItems.get(i).scrolling = true; } } final boolean dispatchSelected = mCurItem != item; if (mFirstLayout) { // We don't have any idea how big we are yet and shouldn't have any pages either. // Just set things up and let the pending layout handle things. mCurItem = item; if (dispatchSelected && mOnPageChangeListener != null) { mOnPageChangeListener.onPageSelected(item); } if (dispatchSelected && mInternalPageChangeListener != null) { mInternalPageChangeListener.onPageSelected(item); } requestLayout(); } else { populate(item); scrollToItem(item, smoothScroll, velocity, dispatchSelected); } } private void scrollToItem(int item, boolean smoothScroll, int velocity, boolean dispatchSelected) { final ItemInfo curInfo = infoForPosition(item); int destX = 0; if (curInfo != null) { final int width = getClientWidth(); destX = (int) (width * Math.max(mFirstOffset, Math.min(curInfo.offset, mLastOffset))); } if (smoothScroll) { smoothScrollTo(destX, 0, velocity); if (dispatchSelected && mOnPageChangeListener != null) { mOnPageChangeListener.onPageSelected(item); } if (dispatchSelected && mInternalPageChangeListener != null) { mInternalPageChangeListener.onPageSelected(item); } } else { if (dispatchSelected && mOnPageChangeListener != null) { mOnPageChangeListener.onPageSelected(item); } if (dispatchSelected && mInternalPageChangeListener != null) { mInternalPageChangeListener.onPageSelected(item); } completeScroll(false); scrollTo(destX, 0); } } /** * Set a listener that will be invoked whenever the page changes or is incrementally * scrolled. See {@link OnPageChangeListener}. * * @param listener Listener to set */ public void setOnPageChangeListener(OnPageChangeListener listener) { mOnPageChangeListener = listener; } /** * Set a {@link PageTransformer} that will be called for each attached page whenever * the scroll position is changed. This allows the application to apply custom property * transformations to each page, overriding the default sliding look and feel. * * <p><em>Note:</em> Prior to Android 3.0 the property animation APIs did not exist. * As a result, setting a PageTransformer prior to Android 3.0 (API 11) will have no effect.</p> * * @param reverseDrawingOrder true if the supplied PageTransformer requires page views * to be drawn from last to first instead of first to last. * @param transformer PageTransformer that will modify each page's animation properties */ public void setPageTransformer(boolean reverseDrawingOrder, PageTransformer transformer) { if (Build.VERSION.SDK_INT >= 11) { final boolean hasTransformer = transformer != null; final boolean needsPopulate = hasTransformer != (mPageTransformer != null); mPageTransformer = transformer; setChildrenDrawingOrderEnabledCompat(hasTransformer); if (hasTransformer) { mDrawingOrder = reverseDrawingOrder ? DRAW_ORDER_REVERSE : DRAW_ORDER_FORWARD; } else { mDrawingOrder = DRAW_ORDER_DEFAULT; } if (needsPopulate) populate(); } } void setChildrenDrawingOrderEnabledCompat(boolean enable) { if (Build.VERSION.SDK_INT >= 7) { if (mSetChildrenDrawingOrderEnabled == null) { try { mSetChildrenDrawingOrderEnabled = ViewGroup.class.getDeclaredMethod( "setChildrenDrawingOrderEnabled", new Class[] { Boolean.TYPE }); } catch (NoSuchMethodException e) { Log.e(TAG, "Can't find setChildrenDrawingOrderEnabled", e); } } try { mSetChildrenDrawingOrderEnabled.invoke(this, enable); } catch (Exception e) { Log.e(TAG, "Error changing children drawing order", e); } } } @Override protected int getChildDrawingOrder(int childCount, int i) { final int index = mDrawingOrder == DRAW_ORDER_REVERSE ? childCount - 1 - i : i; final int result = ((LayoutParams) mDrawingOrderedChildren.get(index).getLayoutParams()).childIndex; return result; } /** * Set a separate OnPageChangeListener for internal use by the support library. * * @param listener Listener to set * @return The old listener that was set, if any. */ OnPageChangeListener setInternalPageChangeListener(OnPageChangeListener listener) { OnPageChangeListener oldListener = mInternalPageChangeListener; mInternalPageChangeListener = listener; return oldListener; } /** * Returns the number of pages that will be retained to either side of the * current page in the view hierarchy in an idle state. Defaults to 1. * * @return How many pages will be kept offscreen on either side * @see #setOffscreenPageLimit(int) */ public int getOffscreenPageLimit() { return mOffscreenPageLimit; } /** * Set the number of pages that should be retained to either side of the * current page in the view hierarchy in an idle state. Pages beyond this * limit will be recreated from the adapter when needed. * * <p>This is offered as an optimization. If you know in advance the number * of pages you will need to support or have lazy-loading mechanisms in place * on your pages, tweaking this setting can have benefits in perceived smoothness * of paging animations and interaction. If you have a small number of pages (3-4) * that you can keep active all at once, less time will be spent in layout for * newly created view subtrees as the user pages back and forth.</p> * * <p>You should keep this limit low, especially if your pages have complex layouts. * This setting defaults to 1.</p> * * @param limit How many pages will be kept offscreen in an idle state. */ public void setOffscreenPageLimit(int limit) { if (limit < DEFAULT_OFFSCREEN_PAGES) { Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " + DEFAULT_OFFSCREEN_PAGES); limit = DEFAULT_OFFSCREEN_PAGES; } if (limit != mOffscreenPageLimit) { mOffscreenPageLimit = limit; populate(); } } /** * Set the margin between pages. * * @param marginPixels Distance between adjacent pages in pixels * @see #getPageMargin() * @see #setPageMarginDrawable(Drawable) * @see #setPageMarginDrawable(int) */ public void setPageMargin(int marginPixels) { final int oldMargin = mPageMargin; mPageMargin = marginPixels; final int width = getWidth(); recomputeScrollPosition(width, width, marginPixels, oldMargin); requestLayout(); } /** * Return the margin between pages. * * @return The size of the margin in pixels */ public int getPageMargin() { return mPageMargin; } /** * Set a drawable that will be used to fill the margin between pages. * * @param d Drawable to display between pages */ public void setPageMarginDrawable(Drawable d) { mMarginDrawable = d; if (d != null) refreshDrawableState(); setWillNotDraw(d == null); invalidate(); } /** * Set a drawable that will be used to fill the margin between pages. * * @param resId Resource ID of a drawable to display between pages */ public void setPageMarginDrawable(int resId) { setPageMarginDrawable(getContext().getResources().getDrawable(resId)); } @Override protected boolean verifyDrawable(Drawable who) { return super.verifyDrawable(who) || who == mMarginDrawable; } @Override protected void drawableStateChanged() { super.drawableStateChanged(); final Drawable d = mMarginDrawable; if (d != null && d.isStateful()) { d.setState(getDrawableState()); } } // We want the duration of the page snap animation to be influenced by the distance that // the screen has to travel, however, we don't want this duration to be effected in a // purely linear fashion. Instead, we use this method to moderate the effect that the distance // of travel has on the overall snap duration. float distanceInfluenceForSnapDuration(float f) { f -= 0.5f; // center the values about 0. f *= 0.3f * Math.PI / 2.0f; return (float) Math.sin(f); } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param x the number of pixels to scroll by on the X axis * @param y the number of pixels to scroll by on the Y axis */ void smoothScrollTo(int x, int y) { smoothScrollTo(x, y, 0); } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param x the number of pixels to scroll by on the X axis * @param y the number of pixels to scroll by on the Y axis * @param velocity the velocity associated with a fling, if applicable. (0 otherwise) */ void smoothScrollTo(int x, int y, int velocity) { if (getChildCount() == 0) { // Nothing to do. setScrollingCacheEnabled(false); return; } int sx = getScrollX(); int sy = getScrollY(); int dx = x - sx; int dy = y - sy; if (dx == 0 && dy == 0) { completeScroll(false); populate(); setScrollState(SCROLL_STATE_IDLE); return; } setScrollingCacheEnabled(true); setScrollState(SCROLL_STATE_SETTLING); final int width = getClientWidth(); final int halfWidth = width / 2; final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width); final float distance = halfWidth + halfWidth * distanceInfluenceForSnapDuration(distanceRatio); int duration = 0; velocity = Math.abs(velocity); if (velocity > 0) { duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); } else { final float pageWidth = width * mAdapter.getPageWidth(mCurItem); final float pageDelta = (float) Math.abs(dx) / (pageWidth + mPageMargin); duration = (int) ((pageDelta + 1) * 100); } duration = Math.min(duration, MAX_SETTLE_DURATION); mScroller.startScroll(sx, sy, dx, dy, duration); ViewCompat.postInvalidateOnAnimation(this); } ItemInfo addNewItem(int position, int index) { ItemInfo ii = new ItemInfo(); ii.position = position; ii.object = mAdapter.instantiateItem(this, position); ii.widthFactor = mAdapter.getPageWidth(position); if (index < 0 || index >= mItems.size()) { mItems.add(ii); } else { mItems.add(index, ii); } return ii; } void dataSetChanged() { // This method only gets called if our observer is attached, so mAdapter is non-null. final int adapterCount = mAdapter.getCount(); mExpectedAdapterCount = adapterCount; boolean needPopulate = mItems.size() < mOffscreenPageLimit * 2 + 1 && mItems.size() < adapterCount; int newCurrItem = mCurItem; boolean isUpdating = false; for (int i = 0; i < mItems.size(); i++) { final ItemInfo ii = mItems.get(i); final int newPos = mAdapter.getItemPosition(ii.object); if (newPos == PagerAdapter.POSITION_UNCHANGED) { continue; } if (newPos == PagerAdapter.POSITION_NONE) { mItems.remove(i); i--; if (!isUpdating) { mAdapter.startUpdate(this); isUpdating = true; } mAdapter.destroyItem(this, ii.position, ii.object); needPopulate = true; if (mCurItem == ii.position) { // Keep the current item in the valid range newCurrItem = Math.max(0, Math.min(mCurItem, adapterCount - 1)); needPopulate = true; } continue; } if (ii.position != newPos) { if (ii.position == mCurItem) { // Our current item changed position. Follow it. newCurrItem = newPos; } ii.position = newPos; needPopulate = true; } } if (isUpdating) { mAdapter.finishUpdate(this); } Collections.sort(mItems, COMPARATOR); if (needPopulate) { // Reset our known page widths; populate will recompute them. final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (!lp.isDecor) { lp.widthFactor = 0.f; } } setCurrentItemInternal(newCurrItem, false, true); requestLayout(); } } void populate() { populate(mCurItem); } void populate(int newCurrentItem) { ItemInfo oldCurInfo = null; int focusDirection = View.FOCUS_FORWARD; if (mCurItem != newCurrentItem) { focusDirection = mCurItem < newCurrentItem ? View.FOCUS_RIGHT : View.FOCUS_LEFT; oldCurInfo = infoForPosition(mCurItem); mCurItem = newCurrentItem; } if (mAdapter == null) { sortChildDrawingOrder(); return; } // Bail now if we are waiting to populate. This is to hold off // on creating views from the time the user releases their finger to // fling to a new position until we have finished the scroll to // that position, avoiding glitches from happening at that point. if (mPopulatePending) { if (DEBUG) Log.i(TAG, "populate is pending, skipping for now..."); sortChildDrawingOrder(); return; } // Also, don't populate until we are attached to a window. This is to // avoid trying to populate before we have restored our view hierarchy // state and conflicting with what is restored. if (getWindowToken() == null) { return; } mAdapter.startUpdate(this); final int pageLimit = mOffscreenPageLimit; final int startPos = Math.max(0, mCurItem - pageLimit); final int N = mAdapter.getCount(); final int endPos = Math.min(N-1, mCurItem + pageLimit); if (N != mExpectedAdapterCount) { String resName; try { resName = getResources().getResourceName(getId()); } catch (Resources.NotFoundException e) { resName = Integer.toHexString(getId()); } throw new IllegalStateException("The application's PagerAdapter changed the adapter's" + " contents without calling PagerAdapter#notifyDataSetChanged!" + " Expected adapter item count: " + mExpectedAdapterCount + ", found: " + N + " Pager id: " + resName + " Pager class: " + getClass() + " Problematic adapter: " + mAdapter.getClass()); } // Locate the currently focused item or add it if needed. int curIndex = -1; ItemInfo curItem = null; for (curIndex = 0; curIndex < mItems.size(); curIndex++) { final ItemInfo ii = mItems.get(curIndex); if (ii.position >= mCurItem) { if (ii.position == mCurItem) curItem = ii; break; } } if (curItem == null && N > 0) { curItem = addNewItem(mCurItem, curIndex); } // Fill 3x the available width or up to the number of offscreen // pages requested to either side, whichever is larger. // If we have no current item we have no work to do. if (curItem != null) { float extraWidthLeft = 0.f; int itemIndex = curIndex - 1; ItemInfo ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; - final float leftWidthNeeded = 2.f - curItem.widthFactor + - (float) getPaddingLeft() / (float) getClientWidth(); + final int clientWidth = getClientWidth(); + final float leftWidthNeeded = clientWidth <= 0 ? 0 : + 2.f - curItem.widthFactor + (float) getPaddingLeft() / (float) clientWidth; for (int pos = mCurItem - 1; pos >= 0; pos--) { if (extraWidthLeft >= leftWidthNeeded && pos < startPos) { if (ii == null) { break; } if (pos == ii.position && !ii.scrolling) { mItems.remove(itemIndex); mAdapter.destroyItem(this, pos, ii.object); if (DEBUG) { Log.i(TAG, "populate() - destroyItem() with pos: " + pos + " view: " + ((View) ii.object)); } itemIndex--; curIndex--; ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; } } else if (ii != null && pos == ii.position) { extraWidthLeft += ii.widthFactor; itemIndex--; ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; } else { ii = addNewItem(pos, itemIndex + 1); extraWidthLeft += ii.widthFactor; curIndex++; ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; } } float extraWidthRight = curItem.widthFactor; itemIndex = curIndex + 1; if (extraWidthRight < 2.f) { ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; - final float rightWidthNeeded = (float) getPaddingRight() / (float) getClientWidth() - + 2.f; + final float rightWidthNeeded = clientWidth <= 0 ? 0 : + (float) getPaddingRight() / (float) clientWidth + 2.f; for (int pos = mCurItem + 1; pos < N; pos++) { if (extraWidthRight >= rightWidthNeeded && pos > endPos) { if (ii == null) { break; } if (pos == ii.position && !ii.scrolling) { mItems.remove(itemIndex); mAdapter.destroyItem(this, pos, ii.object); if (DEBUG) { Log.i(TAG, "populate() - destroyItem() with pos: " + pos + " view: " + ((View) ii.object)); } ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; } } else if (ii != null && pos == ii.position) { extraWidthRight += ii.widthFactor; itemIndex++; ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; } else { ii = addNewItem(pos, itemIndex); itemIndex++; extraWidthRight += ii.widthFactor; ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; } } } calculatePageOffsets(curItem, curIndex, oldCurInfo); } if (DEBUG) { Log.i(TAG, "Current page list:"); for (int i=0; i<mItems.size(); i++) { Log.i(TAG, "#" + i + ": page " + mItems.get(i).position); } } mAdapter.setPrimaryItem(this, mCurItem, curItem != null ? curItem.object : null); mAdapter.finishUpdate(this); // Check width measurement of current pages and drawing sort order. // Update LayoutParams as needed. final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); lp.childIndex = i; if (!lp.isDecor && lp.widthFactor == 0.f) { // 0 means requery the adapter for this, it doesn't have a valid width. final ItemInfo ii = infoForChild(child); if (ii != null) { lp.widthFactor = ii.widthFactor; lp.position = ii.position; } } } sortChildDrawingOrder(); if (hasFocus()) { View currentFocused = findFocus(); ItemInfo ii = currentFocused != null ? infoForAnyChild(currentFocused) : null; if (ii == null || ii.position != mCurItem) { for (int i=0; i<getChildCount(); i++) { View child = getChildAt(i); ii = infoForChild(child); if (ii != null && ii.position == mCurItem) { if (child.requestFocus(focusDirection)) { break; } } } } } } private void sortChildDrawingOrder() { if (mDrawingOrder != DRAW_ORDER_DEFAULT) { if (mDrawingOrderedChildren == null) { mDrawingOrderedChildren = new ArrayList<View>(); } else { mDrawingOrderedChildren.clear(); } final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); mDrawingOrderedChildren.add(child); } Collections.sort(mDrawingOrderedChildren, sPositionComparator); } } private void calculatePageOffsets(ItemInfo curItem, int curIndex, ItemInfo oldCurInfo) { final int N = mAdapter.getCount(); final int width = getClientWidth(); final float marginOffset = width > 0 ? (float) mPageMargin / width : 0; // Fix up offsets for later layout. if (oldCurInfo != null) { final int oldCurPosition = oldCurInfo.position; // Base offsets off of oldCurInfo. if (oldCurPosition < curItem.position) { int itemIndex = 0; ItemInfo ii = null; float offset = oldCurInfo.offset + oldCurInfo.widthFactor + marginOffset; for (int pos = oldCurPosition + 1; pos <= curItem.position && itemIndex < mItems.size(); pos++) { ii = mItems.get(itemIndex); while (pos > ii.position && itemIndex < mItems.size() - 1) { itemIndex++; ii = mItems.get(itemIndex); } while (pos < ii.position) { // We don't have an item populated for this, // ask the adapter for an offset. offset += mAdapter.getPageWidth(pos) + marginOffset; pos++; } ii.offset = offset; offset += ii.widthFactor + marginOffset; } } else if (oldCurPosition > curItem.position) { int itemIndex = mItems.size() - 1; ItemInfo ii = null; float offset = oldCurInfo.offset; for (int pos = oldCurPosition - 1; pos >= curItem.position && itemIndex >= 0; pos--) { ii = mItems.get(itemIndex); while (pos < ii.position && itemIndex > 0) { itemIndex--; ii = mItems.get(itemIndex); } while (pos > ii.position) { // We don't have an item populated for this, // ask the adapter for an offset. offset -= mAdapter.getPageWidth(pos) + marginOffset; pos--; } offset -= ii.widthFactor + marginOffset; ii.offset = offset; } } } // Base all offsets off of curItem. final int itemCount = mItems.size(); float offset = curItem.offset; int pos = curItem.position - 1; mFirstOffset = curItem.position == 0 ? curItem.offset : -Float.MAX_VALUE; mLastOffset = curItem.position == N - 1 ? curItem.offset + curItem.widthFactor - 1 : Float.MAX_VALUE; // Previous pages for (int i = curIndex - 1; i >= 0; i--, pos--) { final ItemInfo ii = mItems.get(i); while (pos > ii.position) { offset -= mAdapter.getPageWidth(pos--) + marginOffset; } offset -= ii.widthFactor + marginOffset; ii.offset = offset; if (ii.position == 0) mFirstOffset = offset; } offset = curItem.offset + curItem.widthFactor + marginOffset; pos = curItem.position + 1; // Next pages for (int i = curIndex + 1; i < itemCount; i++, pos++) { final ItemInfo ii = mItems.get(i); while (pos < ii.position) { offset += mAdapter.getPageWidth(pos++) + marginOffset; } if (ii.position == N - 1) { mLastOffset = offset + ii.widthFactor - 1; } ii.offset = offset; offset += ii.widthFactor + marginOffset; } mNeedCalculatePageOffsets = false; } /** * This is the persistent state that is saved by ViewPager. Only needed * if you are creating a sublass of ViewPager that must save its own * state, in which case it should implement a subclass of this which * contains that state. */ public static class SavedState extends BaseSavedState { int position; Parcelable adapterState; ClassLoader loader; public SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(position); out.writeParcelable(adapterState, flags); } @Override public String toString() { return "FragmentPager.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " position=" + position + "}"; } public static final Parcelable.Creator<SavedState> CREATOR = ParcelableCompat.newCreator(new ParcelableCompatCreatorCallbacks<SavedState>() { @Override public SavedState createFromParcel(Parcel in, ClassLoader loader) { return new SavedState(in, loader); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }); SavedState(Parcel in, ClassLoader loader) { super(in); if (loader == null) { loader = getClass().getClassLoader(); } position = in.readInt(); adapterState = in.readParcelable(loader); this.loader = loader; } } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.position = mCurItem; if (mAdapter != null) { ss.adapterState = mAdapter.saveState(); } return ss; } @Override public void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState)state; super.onRestoreInstanceState(ss.getSuperState()); if (mAdapter != null) { mAdapter.restoreState(ss.adapterState, ss.loader); setCurrentItemInternal(ss.position, false, true); } else { mRestoredCurItem = ss.position; mRestoredAdapterState = ss.adapterState; mRestoredClassLoader = ss.loader; } } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { if (!checkLayoutParams(params)) { params = generateLayoutParams(params); } final LayoutParams lp = (LayoutParams) params; lp.isDecor |= child instanceof Decor; if (mInLayout) { if (lp != null && lp.isDecor) { throw new IllegalStateException("Cannot add pager decor view during layout"); } lp.needsMeasure = true; addViewInLayout(child, index, params); } else { super.addView(child, index, params); } if (USE_CACHE) { if (child.getVisibility() != GONE) { child.setDrawingCacheEnabled(mScrollingCacheEnabled); } else { child.setDrawingCacheEnabled(false); } } } @Override public void removeView(View view) { if (mInLayout) { removeViewInLayout(view); } else { super.removeView(view); } } ItemInfo infoForChild(View child) { for (int i=0; i<mItems.size(); i++) { ItemInfo ii = mItems.get(i); if (mAdapter.isViewFromObject(child, ii.object)) { return ii; } } return null; } ItemInfo infoForAnyChild(View child) { ViewParent parent; while ((parent=child.getParent()) != this) { if (parent == null || !(parent instanceof View)) { return null; } child = (View)parent; } return infoForChild(child); } ItemInfo infoForPosition(int position) { for (int i = 0; i < mItems.size(); i++) { ItemInfo ii = mItems.get(i); if (ii.position == position) { return ii; } } return null; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mFirstLayout = true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // For simple implementation, our internal size is always 0. // We depend on the container to specify the layout size of // our view. We can't really know what it is since we will be // adding and removing different arbitrary views and do not // want the layout to change as this happens. setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec)); final int measuredWidth = getMeasuredWidth(); final int maxGutterSize = measuredWidth / 10; mGutterSize = Math.min(maxGutterSize, mDefaultGutterSize); // Children are just made to fill our space. int childWidthSize = measuredWidth - getPaddingLeft() - getPaddingRight(); int childHeightSize = getMeasuredHeight() - getPaddingTop() - getPaddingBottom(); /* * Make sure all children have been properly measured. Decor views first. * Right now we cheat and make this less complicated by assuming decor * views won't intersect. We will pin to edges based on gravity. */ int size = getChildCount(); for (int i = 0; i < size; ++i) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp != null && lp.isDecor) { final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK; final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK; int widthMode = MeasureSpec.AT_MOST; int heightMode = MeasureSpec.AT_MOST; boolean consumeVertical = vgrav == Gravity.TOP || vgrav == Gravity.BOTTOM; boolean consumeHorizontal = hgrav == Gravity.LEFT || hgrav == Gravity.RIGHT; if (consumeVertical) { widthMode = MeasureSpec.EXACTLY; } else if (consumeHorizontal) { heightMode = MeasureSpec.EXACTLY; } int widthSize = childWidthSize; int heightSize = childHeightSize; if (lp.width != LayoutParams.WRAP_CONTENT) { widthMode = MeasureSpec.EXACTLY; if (lp.width != LayoutParams.FILL_PARENT) { widthSize = lp.width; } } if (lp.height != LayoutParams.WRAP_CONTENT) { heightMode = MeasureSpec.EXACTLY; if (lp.height != LayoutParams.FILL_PARENT) { heightSize = lp.height; } } final int widthSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode); final int heightSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode); child.measure(widthSpec, heightSpec); if (consumeVertical) { childHeightSize -= child.getMeasuredHeight(); } else if (consumeHorizontal) { childWidthSize -= child.getMeasuredWidth(); } } } } mChildWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY); mChildHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeightSize, MeasureSpec.EXACTLY); // Make sure we have created all fragments that we need to have shown. mInLayout = true; populate(); mInLayout = false; // Page views next. size = getChildCount(); for (int i = 0; i < size; ++i) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { if (DEBUG) Log.v(TAG, "Measuring #" + i + " " + child + ": " + mChildWidthMeasureSpec); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp == null || !lp.isDecor) { final int widthSpec = MeasureSpec.makeMeasureSpec( (int) (childWidthSize * lp.widthFactor), MeasureSpec.EXACTLY); child.measure(widthSpec, mChildHeightMeasureSpec); } } } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // Make sure scroll position is set correctly. if (w != oldw) { recomputeScrollPosition(w, oldw, mPageMargin, mPageMargin); } } private void recomputeScrollPosition(int width, int oldWidth, int margin, int oldMargin) { if (oldWidth > 0 && !mItems.isEmpty()) { final int widthWithMargin = width - getPaddingLeft() - getPaddingRight() + margin; final int oldWidthWithMargin = oldWidth - getPaddingLeft() - getPaddingRight() + oldMargin; final int xpos = getScrollX(); final float pageOffset = (float) xpos / oldWidthWithMargin; final int newOffsetPixels = (int) (pageOffset * widthWithMargin); scrollTo(newOffsetPixels, getScrollY()); if (!mScroller.isFinished()) { // We now return to your regularly scheduled scroll, already in progress. final int newDuration = mScroller.getDuration() - mScroller.timePassed(); ItemInfo targetInfo = infoForPosition(mCurItem); mScroller.startScroll(newOffsetPixels, 0, (int) (targetInfo.offset * width), 0, newDuration); } } else { final ItemInfo ii = infoForPosition(mCurItem); final float scrollOffset = ii != null ? Math.min(ii.offset, mLastOffset) : 0; final int scrollPos = (int) (scrollOffset * (width - getPaddingLeft() - getPaddingRight())); if (scrollPos != getScrollX()) { completeScroll(false); scrollTo(scrollPos, getScrollY()); } } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = getChildCount(); int width = r - l; int height = b - t; int paddingLeft = getPaddingLeft(); int paddingTop = getPaddingTop(); int paddingRight = getPaddingRight(); int paddingBottom = getPaddingBottom(); final int scrollX = getScrollX(); int decorCount = 0; // First pass - decor views. We need to do this in two passes so that // we have the proper offsets for non-decor views later. for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); int childLeft = 0; int childTop = 0; if (lp.isDecor) { final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK; final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK; switch (hgrav) { default: childLeft = paddingLeft; break; case Gravity.LEFT: childLeft = paddingLeft; paddingLeft += child.getMeasuredWidth(); break; case Gravity.CENTER_HORIZONTAL: childLeft = Math.max((width - child.getMeasuredWidth()) / 2, paddingLeft); break; case Gravity.RIGHT: childLeft = width - paddingRight - child.getMeasuredWidth(); paddingRight += child.getMeasuredWidth(); break; } switch (vgrav) { default: childTop = paddingTop; break; case Gravity.TOP: childTop = paddingTop; paddingTop += child.getMeasuredHeight(); break; case Gravity.CENTER_VERTICAL: childTop = Math.max((height - child.getMeasuredHeight()) / 2, paddingTop); break; case Gravity.BOTTOM: childTop = height - paddingBottom - child.getMeasuredHeight(); paddingBottom += child.getMeasuredHeight(); break; } childLeft += scrollX; child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + child.getMeasuredHeight()); decorCount++; } } } final int childWidth = width - paddingLeft - paddingRight; // Page views. Do this once we have the right padding offsets from above. for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); ItemInfo ii; if (!lp.isDecor && (ii = infoForChild(child)) != null) { int loff = (int) (childWidth * ii.offset); int childLeft = paddingLeft + loff; int childTop = paddingTop; if (lp.needsMeasure) { // This was added during layout and needs measurement. // Do it now that we know what we're working with. lp.needsMeasure = false; final int widthSpec = MeasureSpec.makeMeasureSpec( (int) (childWidth * lp.widthFactor), MeasureSpec.EXACTLY); final int heightSpec = MeasureSpec.makeMeasureSpec( (int) (height - paddingTop - paddingBottom), MeasureSpec.EXACTLY); child.measure(widthSpec, heightSpec); } if (DEBUG) Log.v(TAG, "Positioning #" + i + " " + child + " f=" + ii.object + ":" + childLeft + "," + childTop + " " + child.getMeasuredWidth() + "x" + child.getMeasuredHeight()); child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + child.getMeasuredHeight()); } } } mTopPageBounds = paddingTop; mBottomPageBounds = height - paddingBottom; mDecorChildCount = decorCount; if (mFirstLayout) { scrollToItem(mCurItem, false, 0, false); } mFirstLayout = false; } @Override public void computeScroll() { if (!mScroller.isFinished() && mScroller.computeScrollOffset()) { int oldX = getScrollX(); int oldY = getScrollY(); int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); if (oldX != x || oldY != y) { scrollTo(x, y); if (!pageScrolled(x)) { mScroller.abortAnimation(); scrollTo(0, y); } } // Keep on drawing until the animation has finished. ViewCompat.postInvalidateOnAnimation(this); return; } // Done with scroll, clean up state. completeScroll(true); } private boolean pageScrolled(int xpos) { if (mItems.size() == 0) { mCalledSuper = false; onPageScrolled(0, 0, 0); if (!mCalledSuper) { throw new IllegalStateException( "onPageScrolled did not call superclass implementation"); } return false; } final ItemInfo ii = infoForCurrentScrollPosition(); final int width = getClientWidth(); final int widthWithMargin = width + mPageMargin; final float marginOffset = (float) mPageMargin / width; final int currentPage = ii.position; final float pageOffset = (((float) xpos / width) - ii.offset) / (ii.widthFactor + marginOffset); final int offsetPixels = (int) (pageOffset * widthWithMargin); mCalledSuper = false; onPageScrolled(currentPage, pageOffset, offsetPixels); if (!mCalledSuper) { throw new IllegalStateException( "onPageScrolled did not call superclass implementation"); } return true; } /** * This method will be invoked when the current page is scrolled, either as part * of a programmatically initiated smooth scroll or a user initiated touch scroll. * If you override this method you must call through to the superclass implementation * (e.g. super.onPageScrolled(position, offset, offsetPixels)) before onPageScrolled * returns. * * @param position Position index of the first page currently being displayed. * Page position+1 will be visible if positionOffset is nonzero. * @param offset Value from [0, 1) indicating the offset from the page at position. * @param offsetPixels Value in pixels indicating the offset from position. */ protected void onPageScrolled(int position, float offset, int offsetPixels) { // Offset any decor views if needed - keep them on-screen at all times. if (mDecorChildCount > 0) { final int scrollX = getScrollX(); int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); final int width = getWidth(); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (!lp.isDecor) continue; final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK; int childLeft = 0; switch (hgrav) { default: childLeft = paddingLeft; break; case Gravity.LEFT: childLeft = paddingLeft; paddingLeft += child.getWidth(); break; case Gravity.CENTER_HORIZONTAL: childLeft = Math.max((width - child.getMeasuredWidth()) / 2, paddingLeft); break; case Gravity.RIGHT: childLeft = width - paddingRight - child.getMeasuredWidth(); paddingRight += child.getMeasuredWidth(); break; } childLeft += scrollX; final int childOffset = childLeft - child.getLeft(); if (childOffset != 0) { child.offsetLeftAndRight(childOffset); } } } if (mOnPageChangeListener != null) { mOnPageChangeListener.onPageScrolled(position, offset, offsetPixels); } if (mInternalPageChangeListener != null) { mInternalPageChangeListener.onPageScrolled(position, offset, offsetPixels); } if (mPageTransformer != null) { final int scrollX = getScrollX(); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.isDecor) continue; final float transformPos = (float) (child.getLeft() - scrollX) / getClientWidth(); mPageTransformer.transformPage(child, transformPos); } } mCalledSuper = true; } private void completeScroll(boolean postEvents) { boolean needPopulate = mScrollState == SCROLL_STATE_SETTLING; if (needPopulate) { // Done with scroll, no longer want to cache view drawing. setScrollingCacheEnabled(false); mScroller.abortAnimation(); int oldX = getScrollX(); int oldY = getScrollY(); int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); if (oldX != x || oldY != y) { scrollTo(x, y); } } mPopulatePending = false; for (int i=0; i<mItems.size(); i++) { ItemInfo ii = mItems.get(i); if (ii.scrolling) { needPopulate = true; ii.scrolling = false; } } if (needPopulate) { if (postEvents) { ViewCompat.postOnAnimation(this, mEndScrollRunnable); } else { mEndScrollRunnable.run(); } } } private boolean isGutterDrag(float x, float dx) { return (x < mGutterSize && dx > 0) || (x > getWidth() - mGutterSize && dx < 0); } private void enableLayers(boolean enable) { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final int layerType = enable ? ViewCompat.LAYER_TYPE_HARDWARE : ViewCompat.LAYER_TYPE_NONE; ViewCompat.setLayerType(getChildAt(i), layerType, null); } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { /* * This method JUST determines whether we want to intercept the motion. * If we return true, onMotionEvent will be called and we do the actual * scrolling there. */ final int action = ev.getAction() & MotionEventCompat.ACTION_MASK; // Always take care of the touch gesture being complete. if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { // Release the drag. if (DEBUG) Log.v(TAG, "Intercept done!"); mIsBeingDragged = false; mIsUnableToDrag = false; mActivePointerId = INVALID_POINTER; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } return false; } // Nothing more to do here if we have decided whether or not we // are dragging. if (action != MotionEvent.ACTION_DOWN) { if (mIsBeingDragged) { if (DEBUG) Log.v(TAG, "Intercept returning true!"); return true; } if (mIsUnableToDrag) { if (DEBUG) Log.v(TAG, "Intercept returning false!"); return false; } } switch (action) { case MotionEvent.ACTION_MOVE: { /* * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check * whether the user has moved far enough from his original down touch. */ /* * Locally do absolute value. mLastMotionY is set to the y value * of the down event. */ final int activePointerId = mActivePointerId; if (activePointerId == INVALID_POINTER) { // If we don't have a valid id, the touch down wasn't on content. break; } final int pointerIndex = MotionEventCompat.findPointerIndex(ev, activePointerId); final float x = MotionEventCompat.getX(ev, pointerIndex); final float dx = x - mLastMotionX; final float xDiff = Math.abs(dx); final float y = MotionEventCompat.getY(ev, pointerIndex); final float yDiff = Math.abs(y - mInitialMotionY); if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff); if (dx != 0 && !isGutterDrag(mLastMotionX, dx) && canScroll(this, false, (int) dx, (int) x, (int) y)) { // Nested view has scrollable area under this point. Let it be handled there. mLastMotionX = x; mLastMotionY = y; mIsUnableToDrag = true; return false; } if (xDiff > mTouchSlop && xDiff * 0.5f > yDiff) { if (DEBUG) Log.v(TAG, "Starting drag!"); mIsBeingDragged = true; setScrollState(SCROLL_STATE_DRAGGING); mLastMotionX = dx > 0 ? mInitialMotionX + mTouchSlop : mInitialMotionX - mTouchSlop; mLastMotionY = y; setScrollingCacheEnabled(true); } else if (yDiff > mTouchSlop) { // The finger has moved enough in the vertical // direction to be counted as a drag... abort // any attempt to drag horizontally, to work correctly // with children that have scrolling containers. if (DEBUG) Log.v(TAG, "Starting unable to drag!"); mIsUnableToDrag = true; } if (mIsBeingDragged) { // Scroll to follow the motion event if (performDrag(x)) { ViewCompat.postInvalidateOnAnimation(this); } } break; } case MotionEvent.ACTION_DOWN: { /* * Remember location of down touch. * ACTION_DOWN always refers to pointer index 0. */ mLastMotionX = mInitialMotionX = ev.getX(); mLastMotionY = mInitialMotionY = ev.getY(); mActivePointerId = MotionEventCompat.getPointerId(ev, 0); mIsUnableToDrag = false; mScroller.computeScrollOffset(); if (mScrollState == SCROLL_STATE_SETTLING && Math.abs(mScroller.getFinalX() - mScroller.getCurrX()) > mCloseEnough) { // Let the user 'catch' the pager as it animates. mScroller.abortAnimation(); mPopulatePending = false; populate(); mIsBeingDragged = true; setScrollState(SCROLL_STATE_DRAGGING); } else { completeScroll(false); mIsBeingDragged = false; } if (DEBUG) Log.v(TAG, "Down at " + mLastMotionX + "," + mLastMotionY + " mIsBeingDragged=" + mIsBeingDragged + "mIsUnableToDrag=" + mIsUnableToDrag); break; } case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); /* * The only time we want to intercept motion events is if we are in the * drag mode. */ return mIsBeingDragged; } @Override public boolean onTouchEvent(MotionEvent ev) { if (mFakeDragging) { // A fake drag is in progress already, ignore this real one // but still eat the touch events. // (It is likely that the user is multi-touching the screen.) return true; } if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) { // Don't handle edge touches immediately -- they may actually belong to one of our // descendants. return false; } if (mAdapter == null || mAdapter.getCount() == 0) { // Nothing to present or scroll; nothing to touch. return false; } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); final int action = ev.getAction(); boolean needsInvalidate = false; switch (action & MotionEventCompat.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { mScroller.abortAnimation(); mPopulatePending = false; populate(); mIsBeingDragged = true; setScrollState(SCROLL_STATE_DRAGGING); // Remember where the motion event started mLastMotionX = mInitialMotionX = ev.getX(); mLastMotionY = mInitialMotionY = ev.getY(); mActivePointerId = MotionEventCompat.getPointerId(ev, 0); break; } case MotionEvent.ACTION_MOVE: if (!mIsBeingDragged) { final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, pointerIndex); final float xDiff = Math.abs(x - mLastMotionX); final float y = MotionEventCompat.getY(ev, pointerIndex); final float yDiff = Math.abs(y - mLastMotionY); if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff); if (xDiff > mTouchSlop && xDiff > yDiff) { if (DEBUG) Log.v(TAG, "Starting drag!"); mIsBeingDragged = true; mLastMotionX = x - mInitialMotionX > 0 ? mInitialMotionX + mTouchSlop : mInitialMotionX - mTouchSlop; mLastMotionY = y; setScrollState(SCROLL_STATE_DRAGGING); setScrollingCacheEnabled(true); } } // Not else! Note that mIsBeingDragged can be set above. if (mIsBeingDragged) { // Scroll to follow the motion event final int activePointerIndex = MotionEventCompat.findPointerIndex( ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, activePointerIndex); needsInvalidate |= performDrag(x); } break; case MotionEvent.ACTION_UP: if (mIsBeingDragged) { final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int initialVelocity = (int) VelocityTrackerCompat.getXVelocity( velocityTracker, mActivePointerId); mPopulatePending = true; final int width = getClientWidth(); final int scrollX = getScrollX(); final ItemInfo ii = infoForCurrentScrollPosition(); final int currentPage = ii.position; final float pageOffset = (((float) scrollX / width) - ii.offset) / ii.widthFactor; final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, activePointerIndex); final int totalDelta = (int) (x - mInitialMotionX); int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity, totalDelta); setCurrentItemInternal(nextPage, true, true, initialVelocity); mActivePointerId = INVALID_POINTER; endDrag(); needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease(); } break; case MotionEvent.ACTION_CANCEL: if (mIsBeingDragged) { scrollToItem(mCurItem, true, 0, false); mActivePointerId = INVALID_POINTER; endDrag(); needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease(); } break; case MotionEventCompat.ACTION_POINTER_DOWN: { final int index = MotionEventCompat.getActionIndex(ev); final float x = MotionEventCompat.getX(ev, index); mLastMotionX = x; mActivePointerId = MotionEventCompat.getPointerId(ev, index); break; } case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId)); break; } if (needsInvalidate) { ViewCompat.postInvalidateOnAnimation(this); } return true; } private boolean performDrag(float x) { boolean needsInvalidate = false; final float deltaX = mLastMotionX - x; mLastMotionX = x; float oldScrollX = getScrollX(); float scrollX = oldScrollX + deltaX; final int width = getClientWidth(); float leftBound = width * mFirstOffset; float rightBound = width * mLastOffset; boolean leftAbsolute = true; boolean rightAbsolute = true; final ItemInfo firstItem = mItems.get(0); final ItemInfo lastItem = mItems.get(mItems.size() - 1); if (firstItem.position != 0) { leftAbsolute = false; leftBound = firstItem.offset * width; } if (lastItem.position != mAdapter.getCount() - 1) { rightAbsolute = false; rightBound = lastItem.offset * width; } if (scrollX < leftBound) { if (leftAbsolute) { float over = leftBound - scrollX; needsInvalidate = mLeftEdge.onPull(Math.abs(over) / width); } scrollX = leftBound; } else if (scrollX > rightBound) { if (rightAbsolute) { float over = scrollX - rightBound; needsInvalidate = mRightEdge.onPull(Math.abs(over) / width); } scrollX = rightBound; } // Don't lose the rounded component mLastMotionX += scrollX - (int) scrollX; scrollTo((int) scrollX, getScrollY()); pageScrolled((int) scrollX); return needsInvalidate; } /** * @return Info about the page at the current scroll position. * This can be synthetic for a missing middle page; the 'object' field can be null. */ private ItemInfo infoForCurrentScrollPosition() { final int width = getClientWidth(); final float scrollOffset = width > 0 ? (float) getScrollX() / width : 0; final float marginOffset = width > 0 ? (float) mPageMargin / width : 0; int lastPos = -1; float lastOffset = 0.f; float lastWidth = 0.f; boolean first = true; ItemInfo lastItem = null; for (int i = 0; i < mItems.size(); i++) { ItemInfo ii = mItems.get(i); float offset; if (!first && ii.position != lastPos + 1) { // Create a synthetic item for a missing page. ii = mTempItem; ii.offset = lastOffset + lastWidth + marginOffset; ii.position = lastPos + 1; ii.widthFactor = mAdapter.getPageWidth(ii.position); i--; } offset = ii.offset; final float leftBound = offset; final float rightBound = offset + ii.widthFactor + marginOffset; if (first || scrollOffset >= leftBound) { if (scrollOffset < rightBound || i == mItems.size() - 1) { return ii; } } else { return lastItem; } first = false; lastPos = ii.position; lastOffset = offset; lastWidth = ii.widthFactor; lastItem = ii; } return lastItem; } private int determineTargetPage(int currentPage, float pageOffset, int velocity, int deltaX) { int targetPage; if (Math.abs(deltaX) > mFlingDistance && Math.abs(velocity) > mMinimumVelocity) { targetPage = velocity > 0 ? currentPage : currentPage + 1; } else { final float truncator = currentPage >= mCurItem ? 0.4f : 0.6f; targetPage = (int) (currentPage + pageOffset + truncator); } if (mItems.size() > 0) { final ItemInfo firstItem = mItems.get(0); final ItemInfo lastItem = mItems.get(mItems.size() - 1); // Only let the user target pages we have items for targetPage = Math.max(firstItem.position, Math.min(targetPage, lastItem.position)); } return targetPage; } @Override public void draw(Canvas canvas) { super.draw(canvas); boolean needsInvalidate = false; final int overScrollMode = ViewCompat.getOverScrollMode(this); if (overScrollMode == ViewCompat.OVER_SCROLL_ALWAYS || (overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS && mAdapter != null && mAdapter.getCount() > 1)) { if (!mLeftEdge.isFinished()) { final int restoreCount = canvas.save(); final int height = getHeight() - getPaddingTop() - getPaddingBottom(); final int width = getWidth(); canvas.rotate(270); canvas.translate(-height + getPaddingTop(), mFirstOffset * width); mLeftEdge.setSize(height, width); needsInvalidate |= mLeftEdge.draw(canvas); canvas.restoreToCount(restoreCount); } if (!mRightEdge.isFinished()) { final int restoreCount = canvas.save(); final int width = getWidth(); final int height = getHeight() - getPaddingTop() - getPaddingBottom(); canvas.rotate(90); canvas.translate(-getPaddingTop(), -(mLastOffset + 1) * width); mRightEdge.setSize(height, width); needsInvalidate |= mRightEdge.draw(canvas); canvas.restoreToCount(restoreCount); } } else { mLeftEdge.finish(); mRightEdge.finish(); } if (needsInvalidate) { // Keep animating ViewCompat.postInvalidateOnAnimation(this); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // Draw the margin drawable between pages if needed. if (mPageMargin > 0 && mMarginDrawable != null && mItems.size() > 0 && mAdapter != null) { final int scrollX = getScrollX(); final int width = getWidth(); final float marginOffset = (float) mPageMargin / width; int itemIndex = 0; ItemInfo ii = mItems.get(0); float offset = ii.offset; final int itemCount = mItems.size(); final int firstPos = ii.position; final int lastPos = mItems.get(itemCount - 1).position; for (int pos = firstPos; pos < lastPos; pos++) { while (pos > ii.position && itemIndex < itemCount) { ii = mItems.get(++itemIndex); } float drawAt; if (pos == ii.position) { drawAt = (ii.offset + ii.widthFactor) * width; offset = ii.offset + ii.widthFactor + marginOffset; } else { float widthFactor = mAdapter.getPageWidth(pos); drawAt = (offset + widthFactor) * width; offset += widthFactor + marginOffset; } if (drawAt + mPageMargin > scrollX) { mMarginDrawable.setBounds((int) drawAt, mTopPageBounds, (int) (drawAt + mPageMargin + 0.5f), mBottomPageBounds); mMarginDrawable.draw(canvas); } if (drawAt > scrollX + width) { break; // No more visible, no sense in continuing } } } } /** * Start a fake drag of the pager. * * <p>A fake drag can be useful if you want to synchronize the motion of the ViewPager * with the touch scrolling of another view, while still letting the ViewPager * control the snapping motion and fling behavior. (e.g. parallax-scrolling tabs.) * Call {@link #fakeDragBy(float)} to simulate the actual drag motion. Call * {@link #endFakeDrag()} to complete the fake drag and fling as necessary. * * <p>During a fake drag the ViewPager will ignore all touch events. If a real drag * is already in progress, this method will return false. * * @return true if the fake drag began successfully, false if it could not be started. * * @see #fakeDragBy(float) * @see #endFakeDrag() */ public boolean beginFakeDrag() { if (mIsBeingDragged) { return false; } mFakeDragging = true; setScrollState(SCROLL_STATE_DRAGGING); mInitialMotionX = mLastMotionX = 0; if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } else { mVelocityTracker.clear(); } final long time = SystemClock.uptimeMillis(); final MotionEvent ev = MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN, 0, 0, 0); mVelocityTracker.addMovement(ev); ev.recycle(); mFakeDragBeginTime = time; return true; } /** * End a fake drag of the pager. * * @see #beginFakeDrag() * @see #fakeDragBy(float) */ public void endFakeDrag() { if (!mFakeDragging) { throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first."); } final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int initialVelocity = (int) VelocityTrackerCompat.getXVelocity( velocityTracker, mActivePointerId); mPopulatePending = true; final int width = getClientWidth(); final int scrollX = getScrollX(); final ItemInfo ii = infoForCurrentScrollPosition(); final int currentPage = ii.position; final float pageOffset = (((float) scrollX / width) - ii.offset) / ii.widthFactor; final int totalDelta = (int) (mLastMotionX - mInitialMotionX); int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity, totalDelta); setCurrentItemInternal(nextPage, true, true, initialVelocity); endDrag(); mFakeDragging = false; } /** * Fake drag by an offset in pixels. You must have called {@link #beginFakeDrag()} first. * * @param xOffset Offset in pixels to drag by. * @see #beginFakeDrag() * @see #endFakeDrag() */ public void fakeDragBy(float xOffset) { if (!mFakeDragging) { throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first."); } mLastMotionX += xOffset; float oldScrollX = getScrollX(); float scrollX = oldScrollX - xOffset; final int width = getClientWidth(); float leftBound = width * mFirstOffset; float rightBound = width * mLastOffset; final ItemInfo firstItem = mItems.get(0); final ItemInfo lastItem = mItems.get(mItems.size() - 1); if (firstItem.position != 0) { leftBound = firstItem.offset * width; } if (lastItem.position != mAdapter.getCount() - 1) { rightBound = lastItem.offset * width; } if (scrollX < leftBound) { scrollX = leftBound; } else if (scrollX > rightBound) { scrollX = rightBound; } // Don't lose the rounded component mLastMotionX += scrollX - (int) scrollX; scrollTo((int) scrollX, getScrollY()); pageScrolled((int) scrollX); // Synthesize an event for the VelocityTracker. final long time = SystemClock.uptimeMillis(); final MotionEvent ev = MotionEvent.obtain(mFakeDragBeginTime, time, MotionEvent.ACTION_MOVE, mLastMotionX, 0, 0); mVelocityTracker.addMovement(ev); ev.recycle(); } /** * Returns true if a fake drag is in progress. * * @return true if currently in a fake drag, false otherwise. * * @see #beginFakeDrag() * @see #fakeDragBy(float) * @see #endFakeDrag() */ public boolean isFakeDragging() { return mFakeDragging; } private void onSecondaryPointerUp(MotionEvent ev) { final int pointerIndex = MotionEventCompat.getActionIndex(ev); final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex); mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } private void endDrag() { mIsBeingDragged = false; mIsUnableToDrag = false; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } } private void setScrollingCacheEnabled(boolean enabled) { if (mScrollingCacheEnabled != enabled) { mScrollingCacheEnabled = enabled; if (USE_CACHE) { final int size = getChildCount(); for (int i = 0; i < size; ++i) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { child.setDrawingCacheEnabled(enabled); } } } } } /** * Tests scrollability within child views of v given a delta of dx. * * @param v View to test for horizontal scrollability * @param checkV Whether the view v passed should itself be checked for scrollability (true), * or just its children (false). * @param dx Delta scrolled in pixels * @param x X coordinate of the active touch point * @param y Y coordinate of the active touch point * @return true if child views of v can be scrolled by delta of dx. */ protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) { if (v instanceof ViewGroup) { final ViewGroup group = (ViewGroup) v; final int scrollX = v.getScrollX(); final int scrollY = v.getScrollY(); final int count = group.getChildCount(); // Count backwards - let topmost views consume scroll distance first. for (int i = count - 1; i >= 0; i--) { // TODO: Add versioned support here for transformed views. // This will not work for transformed views in Honeycomb+ final View child = group.getChildAt(i); if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() && y + scrollY >= child.getTop() && y + scrollY < child.getBottom() && canScroll(child, true, dx, x + scrollX - child.getLeft(), y + scrollY - child.getTop())) { return true; } } } return checkV && ViewCompat.canScrollHorizontally(v, -dx); } @Override public boolean dispatchKeyEvent(KeyEvent event) { // Let the focused view and/or our descendants get the key first return super.dispatchKeyEvent(event) || executeKeyEvent(event); } /** * You can call this function yourself to have the scroll view perform * scrolling from a key event, just as if the event had been dispatched to * it by the view hierarchy. * * @param event The key event to execute. * @return Return true if the event was handled, else false. */ public boolean executeKeyEvent(KeyEvent event) { boolean handled = false; if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_LEFT: handled = arrowScroll(FOCUS_LEFT); break; case KeyEvent.KEYCODE_DPAD_RIGHT: handled = arrowScroll(FOCUS_RIGHT); break; case KeyEvent.KEYCODE_TAB: if (Build.VERSION.SDK_INT >= 11) { // The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD // before Android 3.0. Ignore the tab key on those devices. if (KeyEventCompat.hasNoModifiers(event)) { handled = arrowScroll(FOCUS_FORWARD); } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) { handled = arrowScroll(FOCUS_BACKWARD); } } break; } } return handled; } public boolean arrowScroll(int direction) { View currentFocused = findFocus(); if (currentFocused == this) { currentFocused = null; } else if (currentFocused != null) { boolean isChild = false; for (ViewParent parent = currentFocused.getParent(); parent instanceof ViewGroup; parent = parent.getParent()) { if (parent == this) { isChild = true; break; } } if (!isChild) { // This would cause the focus search down below to fail in fun ways. final StringBuilder sb = new StringBuilder(); sb.append(currentFocused.getClass().getSimpleName()); for (ViewParent parent = currentFocused.getParent(); parent instanceof ViewGroup; parent = parent.getParent()) { sb.append(" => ").append(parent.getClass().getSimpleName()); } Log.e(TAG, "arrowScroll tried to find focus based on non-child " + "current focused view " + sb.toString()); currentFocused = null; } } boolean handled = false; View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); if (nextFocused != null && nextFocused != currentFocused) { if (direction == View.FOCUS_LEFT) { // If there is nothing to the left, or this is causing us to // jump to the right, then what we really want to do is page left. final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left; final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left; if (currentFocused != null && nextLeft >= currLeft) { handled = pageLeft(); } else { handled = nextFocused.requestFocus(); } } else if (direction == View.FOCUS_RIGHT) { // If there is nothing to the right, or this is causing us to // jump to the left, then what we really want to do is page right. final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left; final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left; if (currentFocused != null && nextLeft <= currLeft) { handled = pageRight(); } else { handled = nextFocused.requestFocus(); } } } else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) { // Trying to move left and nothing there; try to page. handled = pageLeft(); } else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) { // Trying to move right and nothing there; try to page. handled = pageRight(); } if (handled) { playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction)); } return handled; } private Rect getChildRectInPagerCoordinates(Rect outRect, View child) { if (outRect == null) { outRect = new Rect(); } if (child == null) { outRect.set(0, 0, 0, 0); return outRect; } outRect.left = child.getLeft(); outRect.right = child.getRight(); outRect.top = child.getTop(); outRect.bottom = child.getBottom(); ViewParent parent = child.getParent(); while (parent instanceof ViewGroup && parent != this) { final ViewGroup group = (ViewGroup) parent; outRect.left += group.getLeft(); outRect.right += group.getRight(); outRect.top += group.getTop(); outRect.bottom += group.getBottom(); parent = group.getParent(); } return outRect; } boolean pageLeft() { if (mCurItem > 0) { setCurrentItem(mCurItem-1, true); return true; } return false; } boolean pageRight() { if (mAdapter != null && mCurItem < (mAdapter.getCount()-1)) { setCurrentItem(mCurItem+1, true); return true; } return false; } /** * We only want the current page that is being shown to be focusable. */ @Override public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { final int focusableCount = views.size(); final int descendantFocusability = getDescendantFocusability(); if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) { for (int i = 0; i < getChildCount(); i++) { final View child = getChildAt(i); if (child.getVisibility() == VISIBLE) { ItemInfo ii = infoForChild(child); if (ii != null && ii.position == mCurItem) { child.addFocusables(views, direction, focusableMode); } } } } // we add ourselves (if focusable) in all cases except for when we are // FOCUS_AFTER_DESCENDANTS and there are some descendants focusable. this is // to avoid the focus search finding layouts when a more precise search // among the focusable children would be more interesting. if ( descendantFocusability != FOCUS_AFTER_DESCENDANTS || // No focusable descendants (focusableCount == views.size())) { // Note that we can't call the superclass here, because it will // add all views in. So we need to do the same thing View does. if (!isFocusable()) { return; } if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && isInTouchMode() && !isFocusableInTouchMode()) { return; } if (views != null) { views.add(this); } } } /** * We only want the current page that is being shown to be touchable. */ @Override public void addTouchables(ArrayList<View> views) { // Note that we don't call super.addTouchables(), which means that // we don't call View.addTouchables(). This is okay because a ViewPager // is itself not touchable. for (int i = 0; i < getChildCount(); i++) { final View child = getChildAt(i); if (child.getVisibility() == VISIBLE) { ItemInfo ii = infoForChild(child); if (ii != null && ii.position == mCurItem) { child.addTouchables(views); } } } } /** * We only want the current page that is being shown to be focusable. */ @Override protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { int index; int increment; int end; int count = getChildCount(); if ((direction & FOCUS_FORWARD) != 0) { index = 0; increment = 1; end = count; } else { index = count - 1; increment = -1; end = -1; } for (int i = index; i != end; i += increment) { View child = getChildAt(i); if (child.getVisibility() == VISIBLE) { ItemInfo ii = infoForChild(child); if (ii != null && ii.position == mCurItem) { if (child.requestFocus(direction, previouslyFocusedRect)) { return true; } } } } return false; } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { // Dispatch scroll events from this ViewPager. if (event.getEventType() == AccessibilityEventCompat.TYPE_VIEW_SCROLLED) { return super.dispatchPopulateAccessibilityEvent(event); } // Dispatch all other accessibility events from the current page. final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() == VISIBLE) { final ItemInfo ii = infoForChild(child); if (ii != null && ii.position == mCurItem && child.dispatchPopulateAccessibilityEvent(event)) { return true; } } } return false; } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(); } @Override protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return generateDefaultLayoutParams(); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof LayoutParams && super.checkLayoutParams(p); } @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } class MyAccessibilityDelegate extends AccessibilityDelegateCompat { @Override public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { super.onInitializeAccessibilityEvent(host, event); event.setClassName(ViewPager.class.getName()); final AccessibilityRecordCompat recordCompat = AccessibilityRecordCompat.obtain(); recordCompat.setScrollable(canScroll()); if (event.getEventType() == AccessibilityEventCompat.TYPE_VIEW_SCROLLED) { recordCompat.setItemCount(mAdapter.getCount()); recordCompat.setFromIndex(mCurItem); recordCompat.setToIndex(mCurItem); } } @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) { super.onInitializeAccessibilityNodeInfo(host, info); info.setClassName(ViewPager.class.getName()); info.setScrollable(canScroll()); if (canScrollForward()) { info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD); } if (canScrollBackward()) { info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD); } } @Override public boolean performAccessibilityAction(View host, int action, Bundle args) { if (super.performAccessibilityAction(host, action, args)) { return true; } switch (action) { case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD: { if (canScrollForward()) { setCurrentItem(mCurItem + 1); return true; } } return false; case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD: { if (canScrollBackward()) { setCurrentItem(mCurItem - 1); return true; } } return false; } return false; } private boolean canScroll() { return (mAdapter != null) && (mAdapter.getCount() > 1); } private boolean canScrollForward() { return (mAdapter != null) && (mCurItem >= 0) && (mCurItem < (mAdapter.getCount() - 1)); } private boolean canScrollBackward() { return (mAdapter != null) && (mCurItem > 0) && (mCurItem < mAdapter.getCount()); } } private class PagerObserver extends DataSetObserver { @Override public void onChanged() { dataSetChanged(); } @Override public void onInvalidated() { dataSetChanged(); } } /** * Layout parameters that should be supplied for views added to a * ViewPager. */ public static class LayoutParams extends ViewGroup.LayoutParams { /** * true if this view is a decoration on the pager itself and not * a view supplied by the adapter. */ public boolean isDecor; /** * Gravity setting for use on decor views only: * Where to position the view page within the overall ViewPager * container; constants are defined in {@link android.view.Gravity}. */ public int gravity; /** * Width as a 0-1 multiplier of the measured pager width */ float widthFactor = 0.f; /** * true if this view was added during layout and needs to be measured * before being positioned. */ boolean needsMeasure; /** * Adapter position this view is for if !isDecor */ int position; /** * Current child index within the ViewPager that this view occupies */ int childIndex; public LayoutParams() { super(FILL_PARENT, FILL_PARENT); } public LayoutParams(Context context, AttributeSet attrs) { super(context, attrs); final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS); gravity = a.getInteger(0, Gravity.TOP); a.recycle(); } } static class ViewPositionComparator implements Comparator<View> { @Override public int compare(View lhs, View rhs) { final LayoutParams llp = (LayoutParams) lhs.getLayoutParams(); final LayoutParams rlp = (LayoutParams) rhs.getLayoutParams(); if (llp.isDecor != rlp.isDecor) { return llp.isDecor ? 1 : -1; } return llp.position - rlp.position; } } }
false
true
void populate(int newCurrentItem) { ItemInfo oldCurInfo = null; int focusDirection = View.FOCUS_FORWARD; if (mCurItem != newCurrentItem) { focusDirection = mCurItem < newCurrentItem ? View.FOCUS_RIGHT : View.FOCUS_LEFT; oldCurInfo = infoForPosition(mCurItem); mCurItem = newCurrentItem; } if (mAdapter == null) { sortChildDrawingOrder(); return; } // Bail now if we are waiting to populate. This is to hold off // on creating views from the time the user releases their finger to // fling to a new position until we have finished the scroll to // that position, avoiding glitches from happening at that point. if (mPopulatePending) { if (DEBUG) Log.i(TAG, "populate is pending, skipping for now..."); sortChildDrawingOrder(); return; } // Also, don't populate until we are attached to a window. This is to // avoid trying to populate before we have restored our view hierarchy // state and conflicting with what is restored. if (getWindowToken() == null) { return; } mAdapter.startUpdate(this); final int pageLimit = mOffscreenPageLimit; final int startPos = Math.max(0, mCurItem - pageLimit); final int N = mAdapter.getCount(); final int endPos = Math.min(N-1, mCurItem + pageLimit); if (N != mExpectedAdapterCount) { String resName; try { resName = getResources().getResourceName(getId()); } catch (Resources.NotFoundException e) { resName = Integer.toHexString(getId()); } throw new IllegalStateException("The application's PagerAdapter changed the adapter's" + " contents without calling PagerAdapter#notifyDataSetChanged!" + " Expected adapter item count: " + mExpectedAdapterCount + ", found: " + N + " Pager id: " + resName + " Pager class: " + getClass() + " Problematic adapter: " + mAdapter.getClass()); } // Locate the currently focused item or add it if needed. int curIndex = -1; ItemInfo curItem = null; for (curIndex = 0; curIndex < mItems.size(); curIndex++) { final ItemInfo ii = mItems.get(curIndex); if (ii.position >= mCurItem) { if (ii.position == mCurItem) curItem = ii; break; } } if (curItem == null && N > 0) { curItem = addNewItem(mCurItem, curIndex); } // Fill 3x the available width or up to the number of offscreen // pages requested to either side, whichever is larger. // If we have no current item we have no work to do. if (curItem != null) { float extraWidthLeft = 0.f; int itemIndex = curIndex - 1; ItemInfo ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; final float leftWidthNeeded = 2.f - curItem.widthFactor + (float) getPaddingLeft() / (float) getClientWidth(); for (int pos = mCurItem - 1; pos >= 0; pos--) { if (extraWidthLeft >= leftWidthNeeded && pos < startPos) { if (ii == null) { break; } if (pos == ii.position && !ii.scrolling) { mItems.remove(itemIndex); mAdapter.destroyItem(this, pos, ii.object); if (DEBUG) { Log.i(TAG, "populate() - destroyItem() with pos: " + pos + " view: " + ((View) ii.object)); } itemIndex--; curIndex--; ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; } } else if (ii != null && pos == ii.position) { extraWidthLeft += ii.widthFactor; itemIndex--; ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; } else { ii = addNewItem(pos, itemIndex + 1); extraWidthLeft += ii.widthFactor; curIndex++; ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; } } float extraWidthRight = curItem.widthFactor; itemIndex = curIndex + 1; if (extraWidthRight < 2.f) { ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; final float rightWidthNeeded = (float) getPaddingRight() / (float) getClientWidth() + 2.f; for (int pos = mCurItem + 1; pos < N; pos++) { if (extraWidthRight >= rightWidthNeeded && pos > endPos) { if (ii == null) { break; } if (pos == ii.position && !ii.scrolling) { mItems.remove(itemIndex); mAdapter.destroyItem(this, pos, ii.object); if (DEBUG) { Log.i(TAG, "populate() - destroyItem() with pos: " + pos + " view: " + ((View) ii.object)); } ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; } } else if (ii != null && pos == ii.position) { extraWidthRight += ii.widthFactor; itemIndex++; ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; } else { ii = addNewItem(pos, itemIndex); itemIndex++; extraWidthRight += ii.widthFactor; ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; } } } calculatePageOffsets(curItem, curIndex, oldCurInfo); } if (DEBUG) { Log.i(TAG, "Current page list:"); for (int i=0; i<mItems.size(); i++) { Log.i(TAG, "#" + i + ": page " + mItems.get(i).position); } } mAdapter.setPrimaryItem(this, mCurItem, curItem != null ? curItem.object : null); mAdapter.finishUpdate(this); // Check width measurement of current pages and drawing sort order. // Update LayoutParams as needed. final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); lp.childIndex = i; if (!lp.isDecor && lp.widthFactor == 0.f) { // 0 means requery the adapter for this, it doesn't have a valid width. final ItemInfo ii = infoForChild(child); if (ii != null) { lp.widthFactor = ii.widthFactor; lp.position = ii.position; } } } sortChildDrawingOrder(); if (hasFocus()) { View currentFocused = findFocus(); ItemInfo ii = currentFocused != null ? infoForAnyChild(currentFocused) : null; if (ii == null || ii.position != mCurItem) { for (int i=0; i<getChildCount(); i++) { View child = getChildAt(i); ii = infoForChild(child); if (ii != null && ii.position == mCurItem) { if (child.requestFocus(focusDirection)) { break; } } } } } }
void populate(int newCurrentItem) { ItemInfo oldCurInfo = null; int focusDirection = View.FOCUS_FORWARD; if (mCurItem != newCurrentItem) { focusDirection = mCurItem < newCurrentItem ? View.FOCUS_RIGHT : View.FOCUS_LEFT; oldCurInfo = infoForPosition(mCurItem); mCurItem = newCurrentItem; } if (mAdapter == null) { sortChildDrawingOrder(); return; } // Bail now if we are waiting to populate. This is to hold off // on creating views from the time the user releases their finger to // fling to a new position until we have finished the scroll to // that position, avoiding glitches from happening at that point. if (mPopulatePending) { if (DEBUG) Log.i(TAG, "populate is pending, skipping for now..."); sortChildDrawingOrder(); return; } // Also, don't populate until we are attached to a window. This is to // avoid trying to populate before we have restored our view hierarchy // state and conflicting with what is restored. if (getWindowToken() == null) { return; } mAdapter.startUpdate(this); final int pageLimit = mOffscreenPageLimit; final int startPos = Math.max(0, mCurItem - pageLimit); final int N = mAdapter.getCount(); final int endPos = Math.min(N-1, mCurItem + pageLimit); if (N != mExpectedAdapterCount) { String resName; try { resName = getResources().getResourceName(getId()); } catch (Resources.NotFoundException e) { resName = Integer.toHexString(getId()); } throw new IllegalStateException("The application's PagerAdapter changed the adapter's" + " contents without calling PagerAdapter#notifyDataSetChanged!" + " Expected adapter item count: " + mExpectedAdapterCount + ", found: " + N + " Pager id: " + resName + " Pager class: " + getClass() + " Problematic adapter: " + mAdapter.getClass()); } // Locate the currently focused item or add it if needed. int curIndex = -1; ItemInfo curItem = null; for (curIndex = 0; curIndex < mItems.size(); curIndex++) { final ItemInfo ii = mItems.get(curIndex); if (ii.position >= mCurItem) { if (ii.position == mCurItem) curItem = ii; break; } } if (curItem == null && N > 0) { curItem = addNewItem(mCurItem, curIndex); } // Fill 3x the available width or up to the number of offscreen // pages requested to either side, whichever is larger. // If we have no current item we have no work to do. if (curItem != null) { float extraWidthLeft = 0.f; int itemIndex = curIndex - 1; ItemInfo ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; final int clientWidth = getClientWidth(); final float leftWidthNeeded = clientWidth <= 0 ? 0 : 2.f - curItem.widthFactor + (float) getPaddingLeft() / (float) clientWidth; for (int pos = mCurItem - 1; pos >= 0; pos--) { if (extraWidthLeft >= leftWidthNeeded && pos < startPos) { if (ii == null) { break; } if (pos == ii.position && !ii.scrolling) { mItems.remove(itemIndex); mAdapter.destroyItem(this, pos, ii.object); if (DEBUG) { Log.i(TAG, "populate() - destroyItem() with pos: " + pos + " view: " + ((View) ii.object)); } itemIndex--; curIndex--; ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; } } else if (ii != null && pos == ii.position) { extraWidthLeft += ii.widthFactor; itemIndex--; ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; } else { ii = addNewItem(pos, itemIndex + 1); extraWidthLeft += ii.widthFactor; curIndex++; ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; } } float extraWidthRight = curItem.widthFactor; itemIndex = curIndex + 1; if (extraWidthRight < 2.f) { ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; final float rightWidthNeeded = clientWidth <= 0 ? 0 : (float) getPaddingRight() / (float) clientWidth + 2.f; for (int pos = mCurItem + 1; pos < N; pos++) { if (extraWidthRight >= rightWidthNeeded && pos > endPos) { if (ii == null) { break; } if (pos == ii.position && !ii.scrolling) { mItems.remove(itemIndex); mAdapter.destroyItem(this, pos, ii.object); if (DEBUG) { Log.i(TAG, "populate() - destroyItem() with pos: " + pos + " view: " + ((View) ii.object)); } ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; } } else if (ii != null && pos == ii.position) { extraWidthRight += ii.widthFactor; itemIndex++; ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; } else { ii = addNewItem(pos, itemIndex); itemIndex++; extraWidthRight += ii.widthFactor; ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; } } } calculatePageOffsets(curItem, curIndex, oldCurInfo); } if (DEBUG) { Log.i(TAG, "Current page list:"); for (int i=0; i<mItems.size(); i++) { Log.i(TAG, "#" + i + ": page " + mItems.get(i).position); } } mAdapter.setPrimaryItem(this, mCurItem, curItem != null ? curItem.object : null); mAdapter.finishUpdate(this); // Check width measurement of current pages and drawing sort order. // Update LayoutParams as needed. final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); lp.childIndex = i; if (!lp.isDecor && lp.widthFactor == 0.f) { // 0 means requery the adapter for this, it doesn't have a valid width. final ItemInfo ii = infoForChild(child); if (ii != null) { lp.widthFactor = ii.widthFactor; lp.position = ii.position; } } } sortChildDrawingOrder(); if (hasFocus()) { View currentFocused = findFocus(); ItemInfo ii = currentFocused != null ? infoForAnyChild(currentFocused) : null; if (ii == null || ii.position != mCurItem) { for (int i=0; i<getChildCount(); i++) { View child = getChildAt(i); ii = infoForChild(child); if (ii != null && ii.position == mCurItem) { if (child.requestFocus(focusDirection)) { break; } } } } } }
diff --git a/src/main/java/org/andrill/conop4j/mutation/ConstrainedMutator.java b/src/main/java/org/andrill/conop4j/mutation/ConstrainedMutator.java index c74093d..04c96b6 100644 --- a/src/main/java/org/andrill/conop4j/mutation/ConstrainedMutator.java +++ b/src/main/java/org/andrill/conop4j/mutation/ConstrainedMutator.java @@ -1,32 +1,32 @@ package org.andrill.conop4j.mutation; import java.util.List; import java.util.Random; import org.andrill.conop4j.Event; import org.andrill.conop4j.Solution; import com.google.common.collect.Lists; /** * Moves a random event within its before and after constraints. * * @author Josh Reed ([email protected]) */ public class ConstrainedMutator implements MutationStrategy { protected Random random = new Random(); @Override public Solution mutate(final Solution solution) { List<Event> events = Lists.newArrayList(solution.getEvents()); // pick a random event and calculate the valid position range Event e = events.remove(random.nextInt(events.size())); - int min = e.getAfterConstraint() == null ? 0 : solution.getPosition(e.getAfterConstraint()) + 1; - int max = e.getBeforeConstraint() == null ? events.size() : solution.getPosition(e.getBeforeConstraint()) + 1; + int min = e.getAfterConstraint() == null ? 0 : solution.getPosition(e.getAfterConstraint()); + int max = e.getBeforeConstraint() == null ? events.size() : solution.getPosition(e.getBeforeConstraint()); // add in the event at a random valid position events.add(min + random.nextInt(max - min), e); return new Solution(solution.getRun(), events); } }
true
true
public Solution mutate(final Solution solution) { List<Event> events = Lists.newArrayList(solution.getEvents()); // pick a random event and calculate the valid position range Event e = events.remove(random.nextInt(events.size())); int min = e.getAfterConstraint() == null ? 0 : solution.getPosition(e.getAfterConstraint()) + 1; int max = e.getBeforeConstraint() == null ? events.size() : solution.getPosition(e.getBeforeConstraint()) + 1; // add in the event at a random valid position events.add(min + random.nextInt(max - min), e); return new Solution(solution.getRun(), events); }
public Solution mutate(final Solution solution) { List<Event> events = Lists.newArrayList(solution.getEvents()); // pick a random event and calculate the valid position range Event e = events.remove(random.nextInt(events.size())); int min = e.getAfterConstraint() == null ? 0 : solution.getPosition(e.getAfterConstraint()); int max = e.getBeforeConstraint() == null ? events.size() : solution.getPosition(e.getBeforeConstraint()); // add in the event at a random valid position events.add(min + random.nextInt(max - min), e); return new Solution(solution.getRun(), events); }
diff --git a/tm/mymemory/src/main/java/net/sf/okapi/tm/mymemory/MyMemoryTMConnector.java b/tm/mymemory/src/main/java/net/sf/okapi/tm/mymemory/MyMemoryTMConnector.java index 347da2e7d..3f47acca4 100644 --- a/tm/mymemory/src/main/java/net/sf/okapi/tm/mymemory/MyMemoryTMConnector.java +++ b/tm/mymemory/src/main/java/net/sf/okapi/tm/mymemory/MyMemoryTMConnector.java @@ -1,193 +1,193 @@ /*=========================================================================== Copyright (C) 2009 by the Okapi Framework contributors ----------------------------------------------------------------------------- This library 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 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. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html ===========================================================================*/ package net.sf.okapi.tm.mymemory; import java.net.MalformedURLException; import java.net.URL; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.List; import org.apache.axis.AxisFault; import org.tempuri.GetResponse; import org.tempuri.Match; import org.tempuri.OtmsSoapStub; import org.tempuri.Query; import net.sf.okapi.common.IParameters; import net.sf.okapi.common.exceptions.OkapiNotImplementedException; import net.sf.okapi.common.resource.TextFragment; import net.sf.okapi.lib.translation.ITMQuery; import net.sf.okapi.lib.translation.QueryResult; public class MyMemoryTMConnector implements ITMQuery { private String srcLang; private String trgLang; private List<QueryResult> results; private int current = -1; private int maxHits = 25; private int threshold = 75; private Parameters params; private OtmsSoapStub otms; public MyMemoryTMConnector () { params = new Parameters(); } public String getName () { return "MyMemory-TM"; } public void close () { } public void export (String outputPath) { throw new OkapiNotImplementedException("The export() method is not supported."); } public String getSourceLanguage () { return toISOCode(srcLang); } public String getTargetLanguage () { return toISOCode(trgLang); } public boolean hasNext () { if ( results == null ) return false; if ( current >= results.size() ) { current = -1; } return (current > -1); } public QueryResult next () { if ( results == null ) return null; if (( current > -1 ) && ( current < results.size() )) { current++; return results.get(current-1); } current = -1; return null; } public void open () { try { results = new ArrayList<QueryResult>(); URL url = new URL("http://mymemory.translated.net/otms/"); otms = new OtmsSoapStub(url, null); } catch ( AxisFault e ) { throw new RuntimeException("Error creating the GlobalSight Web services.", e); } catch ( MalformedURLException e ) { throw new RuntimeException("Invalid server URL.", e); } } public int query (String text) { results.clear(); try { Query query = new Query(text, srcLang, trgLang, null); GetResponse gresp = otms.otmsGet(params.key, query); if ( gresp.isSuccess() ) { QueryResult res; Match[] matches = gresp.getMatches(); int i = 0; for ( Match match : matches ) { if ( ++i > maxHits ) break; // Maximum reached res = new QueryResult(); res.source = new TextFragment(match.getSegment()); res.target = new TextFragment(match.getTranslation()); - res.score = match.getQuality(); + res.score = match.getScore(); // Score not working yet. if ( res.score < getThreshold() ) break; results.add(res); } } } catch ( RemoteException e ) { throw new RuntimeException("Error querying TM.", e); } if ( results.size() > 0 ) current = 0; return results.size(); } public int query (TextFragment frag) { return query(frag.toString()); } public void removeAttribute (String name) { //TODO: use domain } public void setAttribute (String name, String value) { //TODO: use domain } public void setLanguages (String sourceLang, String targetLang) { srcLang = toInternalCode(sourceLang); trgLang = toInternalCode(targetLang); } private String toInternalCode (String standardCode) { //TODO: Check return standardCode; } private String toISOCode (String internalCode) { //TODO: Check return internalCode; } /** * Sets the maximum number of hits to return. */ public void setMaximumHits (int max) { if ( max < 1 ) maxHits = 1; else maxHits = max; } public void setThreshold (int threshold) { this.threshold = threshold; } public int getMaximumHits () { return maxHits; } public int getThreshold () { return threshold; } public IParameters getParameters () { return params; } public void setParameters (IParameters params) { params = (Parameters)params; } }
true
true
public int query (String text) { results.clear(); try { Query query = new Query(text, srcLang, trgLang, null); GetResponse gresp = otms.otmsGet(params.key, query); if ( gresp.isSuccess() ) { QueryResult res; Match[] matches = gresp.getMatches(); int i = 0; for ( Match match : matches ) { if ( ++i > maxHits ) break; // Maximum reached res = new QueryResult(); res.source = new TextFragment(match.getSegment()); res.target = new TextFragment(match.getTranslation()); res.score = match.getQuality(); // Score not working yet. if ( res.score < getThreshold() ) break; results.add(res); } } } catch ( RemoteException e ) { throw new RuntimeException("Error querying TM.", e); } if ( results.size() > 0 ) current = 0; return results.size(); }
public int query (String text) { results.clear(); try { Query query = new Query(text, srcLang, trgLang, null); GetResponse gresp = otms.otmsGet(params.key, query); if ( gresp.isSuccess() ) { QueryResult res; Match[] matches = gresp.getMatches(); int i = 0; for ( Match match : matches ) { if ( ++i > maxHits ) break; // Maximum reached res = new QueryResult(); res.source = new TextFragment(match.getSegment()); res.target = new TextFragment(match.getTranslation()); res.score = match.getScore(); // Score not working yet. if ( res.score < getThreshold() ) break; results.add(res); } } } catch ( RemoteException e ) { throw new RuntimeException("Error querying TM.", e); } if ( results.size() > 0 ) current = 0; return results.size(); }
diff --git a/src/java/org/apache/jcs/auxiliary/disk/jdbc/mysql/MySQLTableOptimizer.java b/src/java/org/apache/jcs/auxiliary/disk/jdbc/mysql/MySQLTableOptimizer.java index 0fed6e4c..1dfbce2d 100644 --- a/src/java/org/apache/jcs/auxiliary/disk/jdbc/mysql/MySQLTableOptimizer.java +++ b/src/java/org/apache/jcs/auxiliary/disk/jdbc/mysql/MySQLTableOptimizer.java @@ -1,332 +1,336 @@ package org.apache.jcs.auxiliary.disk.jdbc.mysql; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.jcs.auxiliary.disk.jdbc.JDBCDiskCacheAttributes; import org.apache.jcs.auxiliary.disk.jdbc.JDBCDiskCachePoolAccess; import org.apache.jcs.auxiliary.disk.jdbc.TableState; /** * The MySQL Table Optimizer can optimize MySQL tables. It knows how to optimize * for MySQL datbases in particular and how to repari the table if it is * corrupted in the process. * <p> * We will probably be able to abstract out a generic optimizer interface from * this class in the future. * <p> * @author Aaron Smuts */ public class MySQLTableOptimizer { private final static Log log = LogFactory.getLog( MySQLTableOptimizer.class ); private JDBCDiskCachePoolAccess poolAccess = null; private String tableName = null; private TableState tableState; /** * This constructs an optimizer with the disk cacn properties. * <p> * @param attributes * @param tableState * We mark the table status as optimizing when this is happening. */ public MySQLTableOptimizer( MySQLDiskCacheAttributes attributes, TableState tableState ) { setTableName( attributes.getTableName() ); this.tableState = tableState; /** * This initializes the pool access. */ initializePoolAccess( attributes ); } /** * Register the driver and create a pool. * <p> * @param cattr */ protected void initializePoolAccess( JDBCDiskCacheAttributes cattr ) { try { try { // org.gjt.mm.mysql.Driver Class.forName( cattr.getDriverClassName() ); } catch ( ClassNotFoundException e ) { log.error( "Couldn't find class for driver [" + cattr.getDriverClassName() + "]", e ); } poolAccess = new JDBCDiskCachePoolAccess( cattr.getName() ); poolAccess.setupDriver( cattr.getUrl() + cattr.getDatabase(), cattr.getUserName(), cattr.getPassword(), cattr.getMaxActive() ); } catch ( Exception e ) { log.error( "Problem getting connection.", e ); } } /** * A scheduler will call this method. When it is called the table state is * marked as optimizing. TODO we need to verify that no deletions are * running before we call optimize. We should wait if a deletion is in * progress. * <p> * This restores when there is an optimization error. The error output looks * like this: * * <pre> * mysql&gt; optimize table JCS_STORE_FLIGHT_OPTION_ITINERARY; * +---------------------------------------------+----------+----------+---------------------+ * | Table | Op | Msg_type | Msg_text | * +---------------------------------------------+----------+----------+---------------------+ * | jcs_cache.JCS_STORE_FLIGHT_OPTION_ITINERARY | optimize | error | 2 when fixing table | * | jcs_cache.JCS_STORE_FLIGHT_OPTION_ITINERARY | optimize | status | Operation failed | * +---------------------------------------------+----------+----------+---------------------+ * 2 rows in set (51.78 sec) * </pre> * * A successful repair response looks like this: * * <pre> * mysql&gt; REPAIR TABLE JCS_STORE_FLIGHT_OPTION_ITINERARY; * +---------------------------------------------+--------+----------+----------------------------------------------+ * | Table | Op | Msg_type | Msg_text | * +---------------------------------------------+--------+----------+----------------------------------------------+ * | jcs_cache.JCS_STORE_FLIGHT_OPTION_ITINERARY | repair | error | 2 when fixing table | * | jcs_cache.JCS_STORE_FLIGHT_OPTION_ITINERARY | repair | warning | Number of rows changed from 131276 to 260461 | * | jcs_cache.JCS_STORE_FLIGHT_OPTION_ITINERARY | repair | status | OK | * +---------------------------------------------+--------+----------+----------------------------------------------+ * 3 rows in set (3 min 5.94 sec) * </pre> * * A successful optimization looks like this: * * <pre> * mysql&gt; optimize table JCS_STORE_DEFAULT; * +-----------------------------+----------+----------+----------+ * | Table | Op | Msg_type | Msg_text | * +-----------------------------+----------+----------+----------+ * | jcs_cache.JCS_STORE_DEFAULT | optimize | status | OK | * +-----------------------------+----------+----------+----------+ * 1 row in set (1.10 sec) * </pre> * * @return */ public boolean optimizeTable() { long start = System.currentTimeMillis(); boolean success = false; if ( tableState.getState() == TableState.OPTIMIZATION_RUNNING ) { log .warn( "Skipping optimization. Optimize was called, but the table state indicates that an optimization is currently running." ); return false; } try { tableState.setState( TableState.OPTIMIZATION_RUNNING ); if ( log.isInfoEnabled() ) { log.debug( "Optimizing table [" + this.getTableName() + "]" ); } Connection con; try { con = poolAccess.getConnection(); } catch ( SQLException e ) { log.error( "Problem getting connection.", e ); return false; } try { // TEST Statement sStatement = null; try { sStatement = con.createStatement(); ResultSet rs = sStatement.executeQuery( "optimize table " + this.getTableName() ); // first row is error, then status // if there is only one row in the result set, everything // should be fine. // This may be mysql version specific. if ( rs.next() ) { String status = rs.getString( "Msg_type" ); String message = rs.getString( "Msg_text" ); if ( log.isInfoEnabled() ) { log.info( "Message Type: " + status ); log.info( "Message: " + message ); } if ( "error".equals( status ) ) { log.warn( "Optimization was in erorr. Will attempt to repair the table. Message: " + message ); // try to repair the table. success = repairTable( sStatement ); } + else + { + success = true; + } } // log the table status String statusString = getTableStatus( sStatement ); if ( log.isInfoEnabled() ) { log.info( "Table status after optimizing table [" + this.getTableName() + "]\n" + statusString ); } } catch ( SQLException e ) { log.error( "Problem optimizing table [" + this.getTableName() + "]", e ); return false; } finally { try { sStatement.close(); } catch ( SQLException e ) { log.error( "Problem closing statement.", e ); } } } finally { try { con.close(); } catch ( SQLException e ) { log.error( "Problem closing connection.", e ); } } } finally { tableState.setState( TableState.FREE ); long end = System.currentTimeMillis(); if ( log.isInfoEnabled() ) { log.info( "Optimization of table [" + this.getTableName() + "] took " + ( end - start ) + " ms." ); } } return success; } /** * This calls show table status and returns the result as a String. * <p> * @param sStatement * @return String * @throws SQLException */ protected String getTableStatus( Statement sStatement ) throws SQLException { ResultSet statusResultSet = sStatement.executeQuery( "show table status" ); StringBuffer statusString = new StringBuffer(); int numColumns = statusResultSet.getMetaData().getColumnCount(); while ( statusResultSet.next() ) { statusString.append( "\n" ); for ( int i = 1; i <= numColumns; i++ ) { statusString.append( statusResultSet.getMetaData().getColumnLabel( i ) + " [" + statusResultSet.getString( i ) + "] | " ); } } return statusString.toString(); } /** * This is called if the optimizatio is in error. * <p> * It looks for "OK" in response. If it find "OK" as a message in any result * set row, it returns true. Otherwise we assume that the repair failed. * <p> * @param sStatement * @return true if successful * @throws SQLException */ protected boolean repairTable( Statement sStatement ) throws SQLException { boolean success = false; // if( message != null && message.indexOf( ) ) ResultSet repairResult = sStatement.executeQuery( "repair table " + this.getTableName() ); StringBuffer repairString = new StringBuffer(); int numColumns = repairResult.getMetaData().getColumnCount(); while ( repairResult.next() ) { for ( int i = 1; i <= numColumns; i++ ) { repairString.append( repairResult.getMetaData().getColumnLabel( i ) + " [" + repairResult.getString( i ) + "] | " ); } String message = repairResult.getString( "Msg_text" ); if ( "OK".equals( message ) ) { success = true; } } if ( log.isInfoEnabled() ) { log.info( repairString ); } if ( !success ) { log.warn( "Failed to repair the table. " + repairString ); } return success; } /** * @param tableName * The tableName to set. */ public void setTableName( String tableName ) { this.tableName = tableName; } /** * @return Returns the tableName. */ public String getTableName() { return tableName; } }
true
true
public boolean optimizeTable() { long start = System.currentTimeMillis(); boolean success = false; if ( tableState.getState() == TableState.OPTIMIZATION_RUNNING ) { log .warn( "Skipping optimization. Optimize was called, but the table state indicates that an optimization is currently running." ); return false; } try { tableState.setState( TableState.OPTIMIZATION_RUNNING ); if ( log.isInfoEnabled() ) { log.debug( "Optimizing table [" + this.getTableName() + "]" ); } Connection con; try { con = poolAccess.getConnection(); } catch ( SQLException e ) { log.error( "Problem getting connection.", e ); return false; } try { // TEST Statement sStatement = null; try { sStatement = con.createStatement(); ResultSet rs = sStatement.executeQuery( "optimize table " + this.getTableName() ); // first row is error, then status // if there is only one row in the result set, everything // should be fine. // This may be mysql version specific. if ( rs.next() ) { String status = rs.getString( "Msg_type" ); String message = rs.getString( "Msg_text" ); if ( log.isInfoEnabled() ) { log.info( "Message Type: " + status ); log.info( "Message: " + message ); } if ( "error".equals( status ) ) { log.warn( "Optimization was in erorr. Will attempt to repair the table. Message: " + message ); // try to repair the table. success = repairTable( sStatement ); } } // log the table status String statusString = getTableStatus( sStatement ); if ( log.isInfoEnabled() ) { log.info( "Table status after optimizing table [" + this.getTableName() + "]\n" + statusString ); } } catch ( SQLException e ) { log.error( "Problem optimizing table [" + this.getTableName() + "]", e ); return false; } finally { try { sStatement.close(); } catch ( SQLException e ) { log.error( "Problem closing statement.", e ); } } } finally { try { con.close(); } catch ( SQLException e ) { log.error( "Problem closing connection.", e ); } } } finally { tableState.setState( TableState.FREE ); long end = System.currentTimeMillis(); if ( log.isInfoEnabled() ) { log.info( "Optimization of table [" + this.getTableName() + "] took " + ( end - start ) + " ms." ); } } return success; }
public boolean optimizeTable() { long start = System.currentTimeMillis(); boolean success = false; if ( tableState.getState() == TableState.OPTIMIZATION_RUNNING ) { log .warn( "Skipping optimization. Optimize was called, but the table state indicates that an optimization is currently running." ); return false; } try { tableState.setState( TableState.OPTIMIZATION_RUNNING ); if ( log.isInfoEnabled() ) { log.debug( "Optimizing table [" + this.getTableName() + "]" ); } Connection con; try { con = poolAccess.getConnection(); } catch ( SQLException e ) { log.error( "Problem getting connection.", e ); return false; } try { // TEST Statement sStatement = null; try { sStatement = con.createStatement(); ResultSet rs = sStatement.executeQuery( "optimize table " + this.getTableName() ); // first row is error, then status // if there is only one row in the result set, everything // should be fine. // This may be mysql version specific. if ( rs.next() ) { String status = rs.getString( "Msg_type" ); String message = rs.getString( "Msg_text" ); if ( log.isInfoEnabled() ) { log.info( "Message Type: " + status ); log.info( "Message: " + message ); } if ( "error".equals( status ) ) { log.warn( "Optimization was in erorr. Will attempt to repair the table. Message: " + message ); // try to repair the table. success = repairTable( sStatement ); } else { success = true; } } // log the table status String statusString = getTableStatus( sStatement ); if ( log.isInfoEnabled() ) { log.info( "Table status after optimizing table [" + this.getTableName() + "]\n" + statusString ); } } catch ( SQLException e ) { log.error( "Problem optimizing table [" + this.getTableName() + "]", e ); return false; } finally { try { sStatement.close(); } catch ( SQLException e ) { log.error( "Problem closing statement.", e ); } } } finally { try { con.close(); } catch ( SQLException e ) { log.error( "Problem closing connection.", e ); } } } finally { tableState.setState( TableState.FREE ); long end = System.currentTimeMillis(); if ( log.isInfoEnabled() ) { log.info( "Optimization of table [" + this.getTableName() + "] took " + ( end - start ) + " ms." ); } } return success; }
diff --git a/src/edu/aau/utzon/indoor/LocatingActivity.java b/src/edu/aau/utzon/indoor/LocatingActivity.java index fbbf993..9508c00 100644 --- a/src/edu/aau/utzon/indoor/LocatingActivity.java +++ b/src/edu/aau/utzon/indoor/LocatingActivity.java @@ -1,64 +1,64 @@ package edu.aau.utzon.indoor; import java.util.ArrayList; import java.util.List; import edu.aau.utzon.R; import android.app.Activity; import android.content.Context; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class LocatingActivity extends Activity { WifiManager _wifi; TextView _textView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.location); _textView = (TextView)findViewById(R.id.textView3); String connectivity_context = Context.WIFI_SERVICE; _wifi = (WifiManager)getSystemService(connectivity_context); } public void findLocation(View view) throws InterruptedException { _textView.setText(""); if (_wifi.startScan() == true) { List<ScanResult> scanResults = _wifi.getScanResults(); ArrayList<WifiMeasureCollection> measures = WifiHelper.getWifiMeasures(this, _wifi, 10, 200); - Point p = RadioMap.FindPosition(measures, 1); + Point p = RadioMap.FindPosition(measures, 1, 1); String text = ""; text += p.getName() + "\n"; if (p == null) { text = "You are not close to any points.!"; } else { // This is just printet out for debug reasons. You can just delete it if you want... But ask lige Steffan first //for (WifiMeasure m1 : measures) { // for (WifiMeasure m2 : p.getMeasures()) { // if (m1.getName().equals(m2.getName())) { // Double temp = (double)m1.getSignal() - (double)m2.getSignal(); // text += m1.getName() + ": " + temp + "\n"; // } // } //} } _textView.setText(text); } else { _textView.setText("Could not scan networks"); } } }
true
true
public void findLocation(View view) throws InterruptedException { _textView.setText(""); if (_wifi.startScan() == true) { List<ScanResult> scanResults = _wifi.getScanResults(); ArrayList<WifiMeasureCollection> measures = WifiHelper.getWifiMeasures(this, _wifi, 10, 200); Point p = RadioMap.FindPosition(measures, 1); String text = ""; text += p.getName() + "\n"; if (p == null) { text = "You are not close to any points.!"; } else { // This is just printet out for debug reasons. You can just delete it if you want... But ask lige Steffan first //for (WifiMeasure m1 : measures) { // for (WifiMeasure m2 : p.getMeasures()) { // if (m1.getName().equals(m2.getName())) { // Double temp = (double)m1.getSignal() - (double)m2.getSignal(); // text += m1.getName() + ": " + temp + "\n"; // } // } //} } _textView.setText(text); } else { _textView.setText("Could not scan networks"); } }
public void findLocation(View view) throws InterruptedException { _textView.setText(""); if (_wifi.startScan() == true) { List<ScanResult> scanResults = _wifi.getScanResults(); ArrayList<WifiMeasureCollection> measures = WifiHelper.getWifiMeasures(this, _wifi, 10, 200); Point p = RadioMap.FindPosition(measures, 1, 1); String text = ""; text += p.getName() + "\n"; if (p == null) { text = "You are not close to any points.!"; } else { // This is just printet out for debug reasons. You can just delete it if you want... But ask lige Steffan first //for (WifiMeasure m1 : measures) { // for (WifiMeasure m2 : p.getMeasures()) { // if (m1.getName().equals(m2.getName())) { // Double temp = (double)m1.getSignal() - (double)m2.getSignal(); // text += m1.getName() + ": " + temp + "\n"; // } // } //} } _textView.setText(text); } else { _textView.setText("Could not scan networks"); } }
diff --git a/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/html/HtmlScript.java b/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/html/HtmlScript.java index c029cf007..247724227 100644 --- a/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/html/HtmlScript.java +++ b/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/html/HtmlScript.java @@ -1,515 +1,518 @@ /* * Copyright (c) 2002-2010 Gargoyle Software 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.gargoylesoftware.htmlunit.html; import java.io.PrintWriter; import java.util.Map; import net.sourceforge.htmlunit.corejs.javascript.BaseFunction; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.gargoylesoftware.htmlunit.BrowserVersion; import com.gargoylesoftware.htmlunit.BrowserVersionFeatures; import com.gargoylesoftware.htmlunit.ElementNotFoundException; import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; import com.gargoylesoftware.htmlunit.SgmlPage; import com.gargoylesoftware.htmlunit.TextUtil; import com.gargoylesoftware.htmlunit.html.HtmlPage.JavaScriptLoadResult; import com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine; import com.gargoylesoftware.htmlunit.javascript.PostponedAction; import com.gargoylesoftware.htmlunit.javascript.host.Event; import com.gargoylesoftware.htmlunit.javascript.host.EventHandler; import com.gargoylesoftware.htmlunit.javascript.host.Window; import com.gargoylesoftware.htmlunit.javascript.host.html.HTMLScriptElement; import com.gargoylesoftware.htmlunit.protocol.javascript.JavaScriptURLConnection; import com.gargoylesoftware.htmlunit.xml.XmlPage; /** * Wrapper for the HTML element "script".<br> * When a script tag references an external script (with attribute src) it gets executed when the node * is added to the DOM tree. When the script code is nested, it gets executed when the text node * containing the script is added to the HtmlScript.<br> * The ScriptFilter feature of NekoHtml can't be used because it doesn't allow immediate access to the DOM * (i.e. <code>document.write("&lt;span id='mySpan'/>"); document.getElementById("mySpan").tagName;</code> * can't work with a filter). * * @version $Revision$ * @author <a href="mailto:[email protected]">Mike Bowler</a> * @author <a href="mailto:[email protected]">Christian Sell</a> * @author Marc Guillemot * @author David K. Taylor * @author Ahmed Ashour * @author Daniel Gredler * @author Dmitri Zoubkov * @author Sudhan Moghe * @see <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one-html.html#ID-81598695">DOM Level 1</a> * @see <a href="http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html#ID-81598695">DOM Level 2</a> */ public class HtmlScript extends HtmlElement { private static final Log LOG = LogFactory.getLog(HtmlScript.class); /** The HTML tag represented by this element. */ public static final String TAG_NAME = "script"; /** Invalid source attribute which should be ignored (used by JS libraries like jQuery). */ private static final String SLASH_SLASH_COLON = "//:"; /** * Creates an instance of HtmlScript * * @param namespaceURI the URI that identifies an XML namespace * @param qualifiedName the qualified name of the element type to instantiate * @param page the HtmlPage that contains this element * @param attributes the initial attributes */ HtmlScript(final String namespaceURI, final String qualifiedName, final SgmlPage page, final Map<String, DomAttr> attributes) { super(namespaceURI, qualifiedName, page, attributes); } /** * Returns the value of the attribute "charset". Refer to the * <a href='http://www.w3.org/TR/html401/'>HTML 4.01</a> * documentation for details on the use of this attribute. * * @return the value of the attribute "charset" * or an empty string if that attribute isn't defined. */ public final String getCharsetAttribute() { return getAttribute("charset"); } /** * Returns the value of the attribute "type". Refer to the * <a href='http://www.w3.org/TR/html401/'>HTML 4.01</a> * documentation for details on the use of this attribute. * * @return the value of the attribute "type" * or an empty string if that attribute isn't defined. */ public final String getTypeAttribute() { return getAttribute("type"); } /** * Returns the value of the attribute "language". Refer to the * <a href='http://www.w3.org/TR/html401/'>HTML 4.01</a> * documentation for details on the use of this attribute. * * @return the value of the attribute "language" * or an empty string if that attribute isn't defined. */ public final String getLanguageAttribute() { return getAttribute("language"); } /** * Returns the value of the attribute "src". Refer to the * <a href='http://www.w3.org/TR/html401/'>HTML 4.01</a> * documentation for details on the use of this attribute. * * @return the value of the attribute "src" * or an empty string if that attribute isn't defined. */ public final String getSrcAttribute() { return getAttribute("src"); } /** * Returns the value of the attribute "event". * @return the value of the attribute "event" */ public final String getEventAttribute() { return getAttribute("event"); } /** * Returns the value of the attribute "for". * @return the value of the attribute "for" */ public final String getHtmlForAttribute() { return getAttribute("for"); } /** * Returns the value of the attribute "defer". Refer to the * <a href='http://www.w3.org/TR/html401/'>HTML 4.01</a> * documentation for details on the use of this attribute. * * @return the value of the attribute "defer" * or an empty string if that attribute isn't defined. */ public final String getDeferAttribute() { return getAttribute("defer"); } /** * Returns <tt>true</tt> if this script is deferred. * @return <tt>true</tt> if this script is deferred */ protected boolean isDeferred() { return getDeferAttribute() != ATTRIBUTE_NOT_DEFINED; } /** * {@inheritDoc} */ @Override public boolean mayBeDisplayed() { return false; } /** * If setting the <tt>src</tt> attribute, this method executes the new JavaScript if necessary * (behavior varies by browser version). {@inheritDoc} */ @Override public void setAttributeNS(final String namespaceURI, final String qualifiedName, final String attributeValue) { final String oldValue = getAttributeNS(namespaceURI, qualifiedName); super.setAttributeNS(namespaceURI, qualifiedName, attributeValue); boolean execute = false; if (namespaceURI == null && "src".equals(qualifiedName)) { final boolean ie = getPage().getWebClient().getBrowserVersion().hasFeature(BrowserVersionFeatures.GENERATED_5); if (ie || (oldValue.length() == 0 && getFirstChild() == null)) { // Always execute if IE; if FF, only execute if the "src" attribute // was undefined and there was no inline code. execute = true; } } if (execute) { executeScriptIfNeeded(true); } } /** * Executes the <tt>onreadystatechange</tt> handler when simulating IE, as well as executing * the script itself, if necessary. {@inheritDoc} */ @Override protected void onAllChildrenAddedToPage(final boolean postponed) { if (getOwnerDocument() instanceof XmlPage) { return; } if (LOG.isDebugEnabled()) { LOG.debug("Script node added: " + asXml()); } final PostponedAction action = new PostponedAction(getPage()) { @Override public void execute() { final boolean ie = getPage().getWebClient().getBrowserVersion().hasFeature(BrowserVersionFeatures.GENERATED_6); if (ie) { if (!isDeferred()) { if (!getSrcAttribute().equals("//:")) { setAndExecuteReadyState(READY_STATE_LOADING); executeScriptIfNeeded(true); setAndExecuteReadyState(READY_STATE_LOADED); } else { setAndExecuteReadyState(READY_STATE_COMPLETE); executeScriptIfNeeded(true); } } } else { executeScriptIfNeeded(true); } } }; if (postponed && getTextContent().length() == 0) { final JavaScriptEngine engine = getPage().getWebClient().getJavaScriptEngine(); engine.addPostponedAction(action); } else { try { action.execute(); } catch (final Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException(e); } } } /** * Executes this script node as inline script if necessary and/or possible. * * @param executeIfDeferred if <tt>false</tt>, and we are emulating IE, and the <tt>defer</tt> * attribute is defined, the script is not executed */ private void executeInlineScriptIfNeeded(final boolean executeIfDeferred) { if (!isExecutionNeeded()) { return; } final boolean ie = getPage().getWebClient().getBrowserVersion().hasFeature(BrowserVersionFeatures.GENERATED_7); if (!executeIfDeferred && isDeferred() && ie) { return; } final String src = getSrcAttribute(); if (src != HtmlElement.ATTRIBUTE_NOT_DEFINED) { return; } final DomCharacterData textNode = (DomCharacterData) getFirstChild(); final String forr = getHtmlForAttribute(); String event = getEventAttribute(); // The event name can be like "onload" or "onload()". if (event.endsWith("()")) { event = event.substring(0, event.length() - 2); } final String scriptCode = textNode.getData(); if (ie && event != ATTRIBUTE_NOT_DEFINED && forr != ATTRIBUTE_NOT_DEFINED) { if ("window".equals(forr)) { // everything fine, accepted by IE and FF final Window window = (Window) getPage().getEnclosingWindow().getScriptObject(); final BaseFunction function = new EventHandler(this, event, scriptCode); window.jsxFunction_attachEvent(event, function); } else { try { final HtmlElement elt = ((HtmlPage) getPage()).getHtmlElementById(forr); elt.setEventHandler(event, scriptCode); } catch (final ElementNotFoundException e) { LOG.warn("<script for='" + forr + "' ...>: no element found with id \"" + forr + "\". Ignoring."); } } } else if (forr == ATTRIBUTE_NOT_DEFINED || "onload".equals(event)) { final String url = getPage().getWebResponse().getWebRequest().getUrl().toExternalForm(); final int line1 = getStartLineNumber(); final int line2 = getEndLineNumber(); final int col1 = getStartColumnNumber(); final int col2 = getEndColumnNumber(); final String desc = "script in " + url + " from (" + line1 + ", " + col1 + ") to (" + line2 + ", " + col2 + ")"; ((HtmlPage) getPage()).executeJavaScriptIfPossible(scriptCode, desc, line1); } } /** * Executes this script node if necessary and/or possible. * * @param executeIfDeferred if <tt>false</tt>, and we are emulating IE, and the <tt>defer</tt> * attribute is defined, the script is not executed */ void executeScriptIfNeeded(final boolean executeIfDeferred) { if (!isExecutionNeeded()) { return; } final HtmlPage page = (HtmlPage) getPage(); final BrowserVersion browser = page.getWebClient().getBrowserVersion(); final boolean ie = browser.hasFeature(BrowserVersionFeatures.GENERATED_8); if (!executeIfDeferred && isDeferred() && ie) { return; } final String src = getSrcAttribute(); if (src.equals(SLASH_SLASH_COLON)) { return; } if (src != ATTRIBUTE_NOT_DEFINED) { if (src.startsWith(JavaScriptURLConnection.JAVASCRIPT_PREFIX)) { // <script src="javascript:'[code]'"></script> if (browser.hasFeature(BrowserVersionFeatures.HTMLSCRIPT_SRC_JAVASCRIPT)) { String code = StringUtils.removeStart(src, JavaScriptURLConnection.JAVASCRIPT_PREFIX).trim(); final int len = code.length(); if (len > 2) { if ((code.charAt(0) == '\'' && code.charAt(len - 1) == '\'') || (code.charAt(0) == '"' && code.charAt(len - 1) == '"')) { code = code.substring(1, len - 1); if (LOG.isDebugEnabled()) { LOG.debug("Executing JavaScript: " + code); } page.executeJavaScriptIfPossible(code, code, getStartLineNumber()); } } } } else { // <script src="[url]"></script> if (LOG.isDebugEnabled()) { LOG.debug("Loading external JavaScript: " + src); } try { final JavaScriptLoadResult result = page.loadExternalJavaScriptFile(src, getCharsetAttribute()); if (result == JavaScriptLoadResult.SUCCESS) { - executeEventIfBrowserHasFeature(Event.TYPE_LOAD, BrowserVersionFeatures.EVENT_ONLOAD_EXTERNAL_JAVASCRIPT); + executeEventIfBrowserHasFeature(Event.TYPE_LOAD, + BrowserVersionFeatures.EVENT_ONLOAD_EXTERNAL_JAVASCRIPT); } else if (result == JavaScriptLoadResult.DOWNLOAD_ERROR) { - executeEventIfBrowserHasFeature(Event.TYPE_ERROR, BrowserVersionFeatures.EVENT_ONERROR_EXTERNAL_JAVASCRIPT); + executeEventIfBrowserHasFeature(Event.TYPE_ERROR, + BrowserVersionFeatures.EVENT_ONERROR_EXTERNAL_JAVASCRIPT); } } catch (final FailingHttpStatusCodeException e) { - executeEventIfBrowserHasFeature(Event.TYPE_ERROR, BrowserVersionFeatures.EVENT_ONERROR_EXTERNAL_JAVASCRIPT); + executeEventIfBrowserHasFeature(Event.TYPE_ERROR, + BrowserVersionFeatures.EVENT_ONERROR_EXTERNAL_JAVASCRIPT); throw e; } } } else if (getFirstChild() != null) { // <script>[code]</script> executeInlineScriptIfNeeded(executeIfDeferred); } } private void executeEventIfBrowserHasFeature(final String type, final BrowserVersionFeatures feature) { if (getPage().getWebClient().getBrowserVersion().hasFeature(feature)) { final HTMLScriptElement script = (HTMLScriptElement) getScriptObject(); final Event event = new Event(HtmlScript.this, type); script.executeEvent(event); } } /** * Indicates if script execution is necessary and/or possible. * * @return <code>true</code> if the script should be executed */ private boolean isExecutionNeeded() { final SgmlPage page = getPage(); // If JavaScript is disabled, we don't need to execute. if (!page.getWebClient().isJavaScriptEnabled()) { return false; } //If innerHTML or outerHTML is being parsed if (page instanceof HtmlPage && ((HtmlPage) page).isParsingHtmlSnippet()) { return false; } // If the script node is nested in an iframe, a noframes, or a noscript node, we don't need to execute. for (DomNode o = this; o != null; o = o.getParentNode()) { if (o instanceof HtmlInlineFrame || o instanceof HtmlNoFrames) { return false; } } // If the underlying page no longer owns its window, the client has moved on (possibly // because another script set window.location.href), and we don't need to execute. if (page.getEnclosingWindow() != null && page.getEnclosingWindow().getEnclosedPage() != page) { return false; } // If the script language is not JavaScript, we can't execute. if (!isJavaScript(getTypeAttribute(), getLanguageAttribute())) { final String t = getTypeAttribute(); final String l = getLanguageAttribute(); LOG.warn("Script is not JavaScript (type: " + t + ", language: " + l + "). Skipping execution."); return false; } // If the script's root ancestor node is not the page, the the script is not a part of the page. // If it isn't yet part of the page, don't execute the script; it's probably just being cloned. DomNode root = this; while (root.getParentNode() != null) { root = root.getParentNode(); } if (root != getPage()) { return false; } return true; } /** * Returns true if a script with the specified type and language attributes is actually JavaScript. * According to <a href="http://www.w3.org/TR/REC-html40/types.html#h-6.7">W3C recommendation</a> * are content types case insensitive. * @param typeAttribute the type attribute specified in the script tag * @param languageAttribute the language attribute specified in the script tag * @return true if the script is JavaScript */ boolean isJavaScript(final String typeAttribute, final String languageAttribute) { final boolean isJavaScript; if (typeAttribute != null && typeAttribute.length() != 0) { isJavaScript = typeAttribute.equalsIgnoreCase("text/javascript") || (typeAttribute.equalsIgnoreCase("application/javascript") && getPage().getWebClient().getBrowserVersion() .hasFeature(BrowserVersionFeatures.HTMLSCRIPT_APPLICATION_JAVASCRIPT)); } else if (languageAttribute != null && languageAttribute.length() != 0) { isJavaScript = TextUtil.startsWithIgnoreCase(languageAttribute, "javascript"); } else { isJavaScript = true; } return isJavaScript; } /** * Sets the <tt>readyState</tt> to the specified state and executes the * <tt>onreadystatechange</tt> handler when simulating IE. * @param state this script ready state */ protected void setAndExecuteReadyState(final String state) { if (getPage().getWebClient().getBrowserVersion() .hasFeature(BrowserVersionFeatures.EVENT_ONREADY_STATE_CHANGE)) { setReadyState(state); final HTMLScriptElement script = (HTMLScriptElement) getScriptObject(); final Event event = new Event(this, Event.TYPE_READY_STATE_CHANGE); script.executeEvent(event); } } /** * @see com.gargoylesoftware.htmlunit.html.HtmlInput#asText() * @return an empty string as the content of script is not visible by itself */ // we need to preserve this method as it is there since many versions with the above documentation. @Override public String asText() { return ""; } /** * Indicates if a node without children should be written in expanded form as XML * (i.e. with closing tag rather than with "/&gt;") * @return <code>true</code> to make generated XML readable as HTML */ @Override protected boolean isEmptyXmlTagExpanded() { return true; } /** * {@inheritDoc} */ @Override protected void printChildrenAsXml(final String indent, final PrintWriter printWriter) { final DomCharacterData textNode = (DomCharacterData) getFirstChild(); if (textNode != null) { printWriter.println("//<![CDATA["); printWriter.println(textNode.getData()); printWriter.println("//]]>"); } } }
false
true
void executeScriptIfNeeded(final boolean executeIfDeferred) { if (!isExecutionNeeded()) { return; } final HtmlPage page = (HtmlPage) getPage(); final BrowserVersion browser = page.getWebClient().getBrowserVersion(); final boolean ie = browser.hasFeature(BrowserVersionFeatures.GENERATED_8); if (!executeIfDeferred && isDeferred() && ie) { return; } final String src = getSrcAttribute(); if (src.equals(SLASH_SLASH_COLON)) { return; } if (src != ATTRIBUTE_NOT_DEFINED) { if (src.startsWith(JavaScriptURLConnection.JAVASCRIPT_PREFIX)) { // <script src="javascript:'[code]'"></script> if (browser.hasFeature(BrowserVersionFeatures.HTMLSCRIPT_SRC_JAVASCRIPT)) { String code = StringUtils.removeStart(src, JavaScriptURLConnection.JAVASCRIPT_PREFIX).trim(); final int len = code.length(); if (len > 2) { if ((code.charAt(0) == '\'' && code.charAt(len - 1) == '\'') || (code.charAt(0) == '"' && code.charAt(len - 1) == '"')) { code = code.substring(1, len - 1); if (LOG.isDebugEnabled()) { LOG.debug("Executing JavaScript: " + code); } page.executeJavaScriptIfPossible(code, code, getStartLineNumber()); } } } } else { // <script src="[url]"></script> if (LOG.isDebugEnabled()) { LOG.debug("Loading external JavaScript: " + src); } try { final JavaScriptLoadResult result = page.loadExternalJavaScriptFile(src, getCharsetAttribute()); if (result == JavaScriptLoadResult.SUCCESS) { executeEventIfBrowserHasFeature(Event.TYPE_LOAD, BrowserVersionFeatures.EVENT_ONLOAD_EXTERNAL_JAVASCRIPT); } else if (result == JavaScriptLoadResult.DOWNLOAD_ERROR) { executeEventIfBrowserHasFeature(Event.TYPE_ERROR, BrowserVersionFeatures.EVENT_ONERROR_EXTERNAL_JAVASCRIPT); } } catch (final FailingHttpStatusCodeException e) { executeEventIfBrowserHasFeature(Event.TYPE_ERROR, BrowserVersionFeatures.EVENT_ONERROR_EXTERNAL_JAVASCRIPT); throw e; } } } else if (getFirstChild() != null) { // <script>[code]</script> executeInlineScriptIfNeeded(executeIfDeferred); } }
void executeScriptIfNeeded(final boolean executeIfDeferred) { if (!isExecutionNeeded()) { return; } final HtmlPage page = (HtmlPage) getPage(); final BrowserVersion browser = page.getWebClient().getBrowserVersion(); final boolean ie = browser.hasFeature(BrowserVersionFeatures.GENERATED_8); if (!executeIfDeferred && isDeferred() && ie) { return; } final String src = getSrcAttribute(); if (src.equals(SLASH_SLASH_COLON)) { return; } if (src != ATTRIBUTE_NOT_DEFINED) { if (src.startsWith(JavaScriptURLConnection.JAVASCRIPT_PREFIX)) { // <script src="javascript:'[code]'"></script> if (browser.hasFeature(BrowserVersionFeatures.HTMLSCRIPT_SRC_JAVASCRIPT)) { String code = StringUtils.removeStart(src, JavaScriptURLConnection.JAVASCRIPT_PREFIX).trim(); final int len = code.length(); if (len > 2) { if ((code.charAt(0) == '\'' && code.charAt(len - 1) == '\'') || (code.charAt(0) == '"' && code.charAt(len - 1) == '"')) { code = code.substring(1, len - 1); if (LOG.isDebugEnabled()) { LOG.debug("Executing JavaScript: " + code); } page.executeJavaScriptIfPossible(code, code, getStartLineNumber()); } } } } else { // <script src="[url]"></script> if (LOG.isDebugEnabled()) { LOG.debug("Loading external JavaScript: " + src); } try { final JavaScriptLoadResult result = page.loadExternalJavaScriptFile(src, getCharsetAttribute()); if (result == JavaScriptLoadResult.SUCCESS) { executeEventIfBrowserHasFeature(Event.TYPE_LOAD, BrowserVersionFeatures.EVENT_ONLOAD_EXTERNAL_JAVASCRIPT); } else if (result == JavaScriptLoadResult.DOWNLOAD_ERROR) { executeEventIfBrowserHasFeature(Event.TYPE_ERROR, BrowserVersionFeatures.EVENT_ONERROR_EXTERNAL_JAVASCRIPT); } } catch (final FailingHttpStatusCodeException e) { executeEventIfBrowserHasFeature(Event.TYPE_ERROR, BrowserVersionFeatures.EVENT_ONERROR_EXTERNAL_JAVASCRIPT); throw e; } } } else if (getFirstChild() != null) { // <script>[code]</script> executeInlineScriptIfNeeded(executeIfDeferred); } }
diff --git a/org.dawnsci.plotting.tools/src/org/dawnsci/plotting/tools/diffraction/NexusDiffractionMetaCreator.java b/org.dawnsci.plotting.tools/src/org/dawnsci/plotting/tools/diffraction/NexusDiffractionMetaCreator.java index b24bacfe0..45590ea6a 100644 --- a/org.dawnsci.plotting.tools/src/org/dawnsci/plotting/tools/diffraction/NexusDiffractionMetaCreator.java +++ b/org.dawnsci.plotting.tools/src/org/dawnsci/plotting/tools/diffraction/NexusDiffractionMetaCreator.java @@ -1,80 +1,80 @@ package org.dawnsci.plotting.tools.diffraction; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import org.dawnsci.plotting.tools.preference.detector.DiffractionDetectorHelper; import uk.ac.diamond.scisoft.analysis.diffraction.DiffractionCrystalEnvironment; import uk.ac.diamond.scisoft.analysis.io.DiffractionMetadata; import uk.ac.diamond.scisoft.analysis.io.IDiffractionMetadata; import uk.ac.diamond.scisoft.analysis.io.NexusDiffractionMetaReader; public class NexusDiffractionMetaCreator { NexusDiffractionMetaReader nexusDiffraction = null; public NexusDiffractionMetaCreator(String filePath) { nexusDiffraction = new NexusDiffractionMetaReader(filePath); } /** * Read the diffraction metadata from a Nexus file. * Other methods on the class can be used to determine how complete the read is * May return null * Uses NexusDiffactionMetaReader to read the data, this class just gives access to the * metadata stored in the preference file * * @param imageSize. Size of the image the diffraction metadata is associated with in pixels (can be null) */ public IDiffractionMetadata getDiffractionMetadataFromNexus(int[] imageSize) { final DetectorBean bean = DiffractionDefaultMetadata.getPersistedDetectorPropertiesBean(imageSize); final DiffractionCrystalEnvironment diffcrys = DiffractionDefaultMetadata.getPersistedDiffractionCrystalEnvironment(); double[] xyPixelSize = DiffractionDetectorHelper.getXYPixelSizeMM(imageSize); IDiffractionMetadata md = nexusDiffraction.getDiffractionMetadataFromNexus(imageSize, null, null, xyPixelSize); - if (!nexusDiffraction.anyValuesRead()) { + if (md != null && !nexusDiffraction.anyValuesRead()) { md = new DiffractionMetadata(nexusDiffraction.getFilePath(), bean.getDetectorProperties(), diffcrys); Collection<Serializable> col = new ArrayList<Serializable>(); col.add(bean.getDiffractionDetector()); ((DiffractionMetadata)md).setUserObjects(col); } if (!nexusDiffraction.isDetectorRead()) { if (md instanceof DiffractionMetadata) { Collection<Serializable> col = new ArrayList<Serializable>(); col.add(bean.getDiffractionDetector()); ((DiffractionMetadata)md).setUserObjects(col); } } return md; } /** * Have complete DetectorProperties and DiffractionCrystalEnvironment values been read */ public boolean isCompleteRead() { return nexusDiffraction.isCompleteRead(); } /** * Have enough values to perform downstream calculations been read (ie exposure time not read) */ public boolean isPartialRead() { return nexusDiffraction.isPartialRead(); } /** * Were any values read from the Nexus file */ public boolean anyValuesRead() { return nexusDiffraction.anyValuesRead(); } }
true
true
public IDiffractionMetadata getDiffractionMetadataFromNexus(int[] imageSize) { final DetectorBean bean = DiffractionDefaultMetadata.getPersistedDetectorPropertiesBean(imageSize); final DiffractionCrystalEnvironment diffcrys = DiffractionDefaultMetadata.getPersistedDiffractionCrystalEnvironment(); double[] xyPixelSize = DiffractionDetectorHelper.getXYPixelSizeMM(imageSize); IDiffractionMetadata md = nexusDiffraction.getDiffractionMetadataFromNexus(imageSize, null, null, xyPixelSize); if (!nexusDiffraction.anyValuesRead()) { md = new DiffractionMetadata(nexusDiffraction.getFilePath(), bean.getDetectorProperties(), diffcrys); Collection<Serializable> col = new ArrayList<Serializable>(); col.add(bean.getDiffractionDetector()); ((DiffractionMetadata)md).setUserObjects(col); } if (!nexusDiffraction.isDetectorRead()) { if (md instanceof DiffractionMetadata) { Collection<Serializable> col = new ArrayList<Serializable>(); col.add(bean.getDiffractionDetector()); ((DiffractionMetadata)md).setUserObjects(col); } } return md; }
public IDiffractionMetadata getDiffractionMetadataFromNexus(int[] imageSize) { final DetectorBean bean = DiffractionDefaultMetadata.getPersistedDetectorPropertiesBean(imageSize); final DiffractionCrystalEnvironment diffcrys = DiffractionDefaultMetadata.getPersistedDiffractionCrystalEnvironment(); double[] xyPixelSize = DiffractionDetectorHelper.getXYPixelSizeMM(imageSize); IDiffractionMetadata md = nexusDiffraction.getDiffractionMetadataFromNexus(imageSize, null, null, xyPixelSize); if (md != null && !nexusDiffraction.anyValuesRead()) { md = new DiffractionMetadata(nexusDiffraction.getFilePath(), bean.getDetectorProperties(), diffcrys); Collection<Serializable> col = new ArrayList<Serializable>(); col.add(bean.getDiffractionDetector()); ((DiffractionMetadata)md).setUserObjects(col); } if (!nexusDiffraction.isDetectorRead()) { if (md instanceof DiffractionMetadata) { Collection<Serializable> col = new ArrayList<Serializable>(); col.add(bean.getDiffractionDetector()); ((DiffractionMetadata)md).setUserObjects(col); } } return md; }
diff --git a/SoundStream/src/com/thelastcrusade/soundstream/components/AboutFragment.java b/SoundStream/src/com/thelastcrusade/soundstream/components/AboutFragment.java index fcc80da..1e3578b 100644 --- a/SoundStream/src/com/thelastcrusade/soundstream/components/AboutFragment.java +++ b/SoundStream/src/com/thelastcrusade/soundstream/components/AboutFragment.java @@ -1,110 +1,108 @@ /* * Copyright 2013 The Last Crusade [email protected] * * This file is part of SoundStream. * * SoundStream 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. * * SoundStream 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 SoundStream. If not, see <http://www.gnu.org/licenses/>. */ package com.thelastcrusade.soundstream.components; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.TextView; import com.thelastcrusade.soundstream.CoreActivity; import com.thelastcrusade.soundstream.R; import com.thelastcrusade.soundstream.util.ITitleable; /** * @author Elizabeth * */ public class AboutFragment extends Fragment implements ITitleable { private final String TAG = AboutFragment.class.getSimpleName(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_about, container, false); final TextView repoLinkText = (TextView)v.findViewById(R.id.repo_link), SlidingMenuLinkText = (TextView)v.findViewById(R.id.thanks_SlidingMenu), - ABSLinkText = (TextView)v.findViewById(R.id.thanks_ABS), emailLinkText = (TextView)v.findViewById(R.id.email_link); listenToHttpLink(repoLinkText, getString(R.string.repo_link)); listenToHttpLink(SlidingMenuLinkText, getString(R.string.sliding_menu_link)); - listenToHttpLink(ABSLinkText, getString(R.string.ABS_link)); emailLinkText.setOnClickListener(new AdapterView.OnClickListener() { @Override public void onClick(View v) { Intent emailIntent = new Intent( Intent.ACTION_SENDTO, Uri.fromParts("mailto", getString(R.string.email_support_address), null)); emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.email_subject_tag)); startActivity(Intent.createChooser(emailIntent, "Send email...")); } }); v.findViewById(R.id.instructions_text).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new InstructionsDialog(getActivity()).show(); } }); return v; } @Override public void onStart(){ super.onStart(); ((CoreActivity)getActivity()).getTracker().sendView(TAG); } @Override public void onResume(){ super.onResume(); getActivity().setTitle(getTitle()); } @Override public int getTitle() { return R.string.about; } public void listenToHttpLink(TextView linkText, final String url) { linkText.setOnClickListener(new AdapterView.OnClickListener() { @Override public void onClick(View arg0) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(browserIntent); } }); } }
false
true
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_about, container, false); final TextView repoLinkText = (TextView)v.findViewById(R.id.repo_link), SlidingMenuLinkText = (TextView)v.findViewById(R.id.thanks_SlidingMenu), ABSLinkText = (TextView)v.findViewById(R.id.thanks_ABS), emailLinkText = (TextView)v.findViewById(R.id.email_link); listenToHttpLink(repoLinkText, getString(R.string.repo_link)); listenToHttpLink(SlidingMenuLinkText, getString(R.string.sliding_menu_link)); listenToHttpLink(ABSLinkText, getString(R.string.ABS_link)); emailLinkText.setOnClickListener(new AdapterView.OnClickListener() { @Override public void onClick(View v) { Intent emailIntent = new Intent( Intent.ACTION_SENDTO, Uri.fromParts("mailto", getString(R.string.email_support_address), null)); emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.email_subject_tag)); startActivity(Intent.createChooser(emailIntent, "Send email...")); } }); v.findViewById(R.id.instructions_text).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new InstructionsDialog(getActivity()).show(); } }); return v; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_about, container, false); final TextView repoLinkText = (TextView)v.findViewById(R.id.repo_link), SlidingMenuLinkText = (TextView)v.findViewById(R.id.thanks_SlidingMenu), emailLinkText = (TextView)v.findViewById(R.id.email_link); listenToHttpLink(repoLinkText, getString(R.string.repo_link)); listenToHttpLink(SlidingMenuLinkText, getString(R.string.sliding_menu_link)); emailLinkText.setOnClickListener(new AdapterView.OnClickListener() { @Override public void onClick(View v) { Intent emailIntent = new Intent( Intent.ACTION_SENDTO, Uri.fromParts("mailto", getString(R.string.email_support_address), null)); emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.email_subject_tag)); startActivity(Intent.createChooser(emailIntent, "Send email...")); } }); v.findViewById(R.id.instructions_text).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new InstructionsDialog(getActivity()).show(); } }); return v; }
diff --git a/test/src/org/broad/igv/tools/CoverageCounterTest.java b/test/src/org/broad/igv/tools/CoverageCounterTest.java index e70cb789..0b10698b 100644 --- a/test/src/org/broad/igv/tools/CoverageCounterTest.java +++ b/test/src/org/broad/igv/tools/CoverageCounterTest.java @@ -1,84 +1,84 @@ /* * Copyright (c) 2007-2011 by The Broad Institute, Inc. and the Massachusetts Institute of * Technology. All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR * WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER * OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE * TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES * OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, * ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER * THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT * SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING. */ package org.broad.igv.tools; import org.broad.igv.tools.parsers.DataConsumer; import org.broad.igv.track.TrackType; import static org.junit.Assert.assertEquals; import org.junit.Test; import java.util.HashMap; import java.util.Map; /** * Created by IntelliJ IDEA. * User: jrobinso * Date: Jan 18, 2010 * Time: 11:22:21 AM * To change this template use File | Settings | File Templates. */ public class CoverageCounterTest { @Test public void testGetTotalCount() { String bamURL = "test/data/index_test.bam"; TestDataConsumer dc = new TestDataConsumer(); - CoverageCounter cc = new CoverageCounter(bamURL, dc, 25, 0, null, null, null, 1); + CoverageCounter cc = new CoverageCounter(bamURL, dc, 25, 0, null, null, null, 1, null); cc.parse(); String totalCount = dc.attributes.get("totalCount"); assertEquals("9721", totalCount); } static class TestDataConsumer implements DataConsumer { Map<String, String> attributes = new HashMap(); public void setType(String type) { //To change body of implemented methods use File | Settings | File Templates. } public void addData(String chr, int start, int end, float[] data, String name) { //To change body of implemented methods use File | Settings | File Templates. } public void parsingComplete() { //To change body of implemented methods use File | Settings | File Templates. } public void setTrackParameters(TrackType trackType, String trackLine, String[] trackNames) { //To change body of implemented methods use File | Settings | File Templates. } public void setSortTolerance(int tolerance) { //To change body of implemented methods use File | Settings | File Templates. } public void setAttribute(String key, String value) { attributes.put(key, value); } } }
true
true
public void testGetTotalCount() { String bamURL = "test/data/index_test.bam"; TestDataConsumer dc = new TestDataConsumer(); CoverageCounter cc = new CoverageCounter(bamURL, dc, 25, 0, null, null, null, 1); cc.parse(); String totalCount = dc.attributes.get("totalCount"); assertEquals("9721", totalCount); }
public void testGetTotalCount() { String bamURL = "test/data/index_test.bam"; TestDataConsumer dc = new TestDataConsumer(); CoverageCounter cc = new CoverageCounter(bamURL, dc, 25, 0, null, null, null, 1, null); cc.parse(); String totalCount = dc.attributes.get("totalCount"); assertEquals("9721", totalCount); }
diff --git a/DataBindingAndroid/src/no/ntnu/capgeminitest/binding/android/BindingActivity.java b/DataBindingAndroid/src/no/ntnu/capgeminitest/binding/android/BindingActivity.java index 8653211..aabecc7 100644 --- a/DataBindingAndroid/src/no/ntnu/capgeminitest/binding/android/BindingActivity.java +++ b/DataBindingAndroid/src/no/ntnu/capgeminitest/binding/android/BindingActivity.java @@ -1,60 +1,60 @@ package no.ntnu.capgeminitest.binding.android; import java.util.Map; import no.ntnu.capgeminitest.binding.Property; import no.ntnu.capgeminitest.binding.android.propertyprovider.PropertyProviderFactory; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public abstract class BindingActivity extends Activity { private Map<String, Property<?>> bindings; public class BindingLayoutInflater { private LayoutInflater inflater; private BindingFactory bindingFactory; public BindingLayoutInflater(LayoutInflater inflater, BindingFactory bindingFactory) { this.inflater = inflater; this.bindingFactory = bindingFactory; } public View inflate(int resource, ViewGroup root) { return inflater.inflate(resource, root); } public Map<String, Property<?>> getBoundProperties() { return bindingFactory.getBoundProperties(); } } private PropertyProviderFactory propertyProviderFactory = PropertyProviderFactory.getDefaultFactory(); /** * Set content view from a layout resource. * * This is the */ public View createBoundView(int id, Map<String, Property<?>> bindings) { BindingLayoutInflater inflater = getBindingLayoutInflater(); View v = inflater.inflate(id, null); bindings.putAll(inflater.getBoundProperties()); return v; } public void setBoundContentView(int id, Map<String, Property<?>> bindings) { setContentView(createBoundView(id, bindings)); } private BindingLayoutInflater getBindingLayoutInflater() { LayoutInflater inflater = getLayoutInflater().cloneInContext(this); BindingFactory factory = new BindingFactory(propertyProviderFactory, inflater); inflater.setFactory(factory); - return inflater; + return new BindingLayoutInflater(inflater, factory); } }
true
true
private BindingLayoutInflater getBindingLayoutInflater() { LayoutInflater inflater = getLayoutInflater().cloneInContext(this); BindingFactory factory = new BindingFactory(propertyProviderFactory, inflater); inflater.setFactory(factory); return inflater; }
private BindingLayoutInflater getBindingLayoutInflater() { LayoutInflater inflater = getLayoutInflater().cloneInContext(this); BindingFactory factory = new BindingFactory(propertyProviderFactory, inflater); inflater.setFactory(factory); return new BindingLayoutInflater(inflater, factory); }
diff --git a/src/java/com/linuxbox/enkive/web/MessageAttachmentDetailServlet.java b/src/java/com/linuxbox/enkive/web/MessageAttachmentDetailServlet.java index a63de0a..1f02542 100644 --- a/src/java/com/linuxbox/enkive/web/MessageAttachmentDetailServlet.java +++ b/src/java/com/linuxbox/enkive/web/MessageAttachmentDetailServlet.java @@ -1,113 +1,113 @@ /******************************************************************************* * Copyright 2012 The Linux Box Corporation. * * This file is part of Enkive CE (Community Edition). * * Enkive CE 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. * * Enkive CE 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 Enkive CE. If not, see * <http://www.gnu.org/licenses/>. *******************************************************************************/ package com.linuxbox.enkive.web; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.linuxbox.enkive.exception.CannotRetrieveException; import com.linuxbox.enkive.message.AttachmentSummary; import com.linuxbox.enkive.message.Message; import com.linuxbox.enkive.retriever.MessageRetrieverService; public class MessageAttachmentDetailServlet extends EnkiveServlet { private static final long serialVersionUID = 7489338160172966335L; protected static final String KEY_UUID = "UUID"; protected static final String KEY_FILE_NAME = "filename"; protected static final String KEY_MIME_TYPE = "mimeType"; protected static final String PARAM_MSG_ID = "message_id"; @Override public void init(ServletConfig config) throws ServletException { super.init(config); } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { final String messageId = req.getParameter(PARAM_MSG_ID); final MessageRetrieverService retriever = getMessageRetrieverService(); try { final Message message = retriever.retrieve(messageId); JSONArray attachments = new JSONArray(); for (AttachmentSummary attachment : message.getContentHeader() .getAttachmentSummaries()) { JSONObject attachmentObject = new JSONObject(); String filename = attachment.getFileName(); if (filename == null || filename.isEmpty()) { final String positionString = attachment .getPositionString(); // TODO: revisit this logic; best to assume first attachment // is body? - if (positionString.equals("1")) { + if (positionString.isEmpty() || positionString.equals("1")) { filename = "Message-Body"; } else { filename = "attachment-" + positionString; } } String mimeType = attachment.getMimeType(); if (mimeType == null) { mimeType = ""; } attachmentObject.put(KEY_UUID, attachment.getUuid()); attachmentObject.put(KEY_FILE_NAME, filename); attachmentObject.put(KEY_MIME_TYPE, mimeType); attachments.put(attachmentObject); } try { JSONObject jObject = new JSONObject(); jObject.put(WebConstants.DATA_TAG, attachments); String jsonString = jObject.toString(); resp.getWriter().write(jsonString); } catch (JSONException e) { respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp); throw new CannotRetrieveException( "could not create JSON for message attachment", e); } } catch (CannotRetrieveException e) { respondError(HttpServletResponse.SC_UNAUTHORIZED, null, resp); if (LOGGER.isErrorEnabled()) { LOGGER.error("Could not retrieve attachment"); } } catch (JSONException e) { respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp); if (LOGGER.isErrorEnabled()) { LOGGER.error("Could not retrieve attachment"); } } } }
true
true
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { final String messageId = req.getParameter(PARAM_MSG_ID); final MessageRetrieverService retriever = getMessageRetrieverService(); try { final Message message = retriever.retrieve(messageId); JSONArray attachments = new JSONArray(); for (AttachmentSummary attachment : message.getContentHeader() .getAttachmentSummaries()) { JSONObject attachmentObject = new JSONObject(); String filename = attachment.getFileName(); if (filename == null || filename.isEmpty()) { final String positionString = attachment .getPositionString(); // TODO: revisit this logic; best to assume first attachment // is body? if (positionString.equals("1")) { filename = "Message-Body"; } else { filename = "attachment-" + positionString; } } String mimeType = attachment.getMimeType(); if (mimeType == null) { mimeType = ""; } attachmentObject.put(KEY_UUID, attachment.getUuid()); attachmentObject.put(KEY_FILE_NAME, filename); attachmentObject.put(KEY_MIME_TYPE, mimeType); attachments.put(attachmentObject); } try { JSONObject jObject = new JSONObject(); jObject.put(WebConstants.DATA_TAG, attachments); String jsonString = jObject.toString(); resp.getWriter().write(jsonString); } catch (JSONException e) { respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp); throw new CannotRetrieveException( "could not create JSON for message attachment", e); } } catch (CannotRetrieveException e) { respondError(HttpServletResponse.SC_UNAUTHORIZED, null, resp); if (LOGGER.isErrorEnabled()) { LOGGER.error("Could not retrieve attachment"); } } catch (JSONException e) { respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp); if (LOGGER.isErrorEnabled()) { LOGGER.error("Could not retrieve attachment"); } } }
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { final String messageId = req.getParameter(PARAM_MSG_ID); final MessageRetrieverService retriever = getMessageRetrieverService(); try { final Message message = retriever.retrieve(messageId); JSONArray attachments = new JSONArray(); for (AttachmentSummary attachment : message.getContentHeader() .getAttachmentSummaries()) { JSONObject attachmentObject = new JSONObject(); String filename = attachment.getFileName(); if (filename == null || filename.isEmpty()) { final String positionString = attachment .getPositionString(); // TODO: revisit this logic; best to assume first attachment // is body? if (positionString.isEmpty() || positionString.equals("1")) { filename = "Message-Body"; } else { filename = "attachment-" + positionString; } } String mimeType = attachment.getMimeType(); if (mimeType == null) { mimeType = ""; } attachmentObject.put(KEY_UUID, attachment.getUuid()); attachmentObject.put(KEY_FILE_NAME, filename); attachmentObject.put(KEY_MIME_TYPE, mimeType); attachments.put(attachmentObject); } try { JSONObject jObject = new JSONObject(); jObject.put(WebConstants.DATA_TAG, attachments); String jsonString = jObject.toString(); resp.getWriter().write(jsonString); } catch (JSONException e) { respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp); throw new CannotRetrieveException( "could not create JSON for message attachment", e); } } catch (CannotRetrieveException e) { respondError(HttpServletResponse.SC_UNAUTHORIZED, null, resp); if (LOGGER.isErrorEnabled()) { LOGGER.error("Could not retrieve attachment"); } } catch (JSONException e) { respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp); if (LOGGER.isErrorEnabled()) { LOGGER.error("Could not retrieve attachment"); } } }
diff --git a/src/gui/view/ApplicationWindow.java b/src/gui/view/ApplicationWindow.java index da48510..8b46e32 100644 --- a/src/gui/view/ApplicationWindow.java +++ b/src/gui/view/ApplicationWindow.java @@ -1,1225 +1,1226 @@ package gui.view; import networking.ProxyLog; import networking.ProxyServer; import networking.HttpFilter; import networking.HttpResponseFilters; import networking.CustomHttpResponseFilter; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.custom.SashForm; import java.awt.Frame; import org.eclipse.swt.accessibility.Accessible; import org.eclipse.swt.awt.SWT_AWT; import java.awt.Color; import java.awt.Panel; import java.awt.BorderLayout; import java.awt.event.FocusEvent; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JRootPane; import javax.swing.JScrollPane; import javax.swing.JTextField; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.GridData; import javax.swing.JTextArea; import javax.swing.border.Border; import org.eclipse.swt.widgets.List; import swing2swt.layout.FlowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Tree; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.ListViewer; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.group.ChannelGroupFuture; import org.jboss.netty.channel.group.DefaultChannelGroup; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import storage.*; import org.eclipse.swt.custom.StyledText; import org.eclipse.jface.text.TextViewer; import org.eclipse.swt.widgets.Text; public class ApplicationWindow{ //final static variables final static String EXPORT = "Export"; final static String IMPORT = "Import"; final static String CREATE = "Create"; final static String EDIT = "Edit"; //Constructor variables protected Shell shlButterfly; protected Display display; private ProxyServer server; private Account account; private Accounts accounts; private JFrame frame; private final FormToolkit formToolkit = new FormToolkit(Display.getDefault()); private ListViewer filterInactiveListViewer; private ListViewer filterActiveListViewer; private ListViewer AccountListViewer; private Button btnCreate, btnDelete, btnEdit; // Status Menu Components private JTextArea textAreaDialog; private JTextArea textAreaConnectionList; private Text textPort; private Text textConnectionCount; /** * Launches Login window * @param shell * @return boolean */ private boolean authenticate(Shell shell) { LoginShell login = new LoginShell(shell); login.open(this); return true; } /** * Create the filter editing window. * @param s type of window (create/edit) * @return boolean true upon close */ private boolean filterEdit(String s, Filter editFilter) { Display display = Display.getDefault(); FilterShell filterEdit = new FilterShell(display, s, account, accounts); filterEdit.setFilter(editFilter); filterEdit.open(); return true; } /** * Call the edit shell with account edit permissions * @param a * @return */ private boolean editUserAccount(Account a){ Display display = Display.getDefault(); EditShell eShell = new EditShell(display, a,account, accounts); //Disable the main window shlButterfly.setEnabled(false); // open new window eShell.open(); //Re-Enable and make the window active shlButterfly.setEnabled(true); shlButterfly.setActive(); return true; } /** * Call the edit shell with edit user group permissions * @param g * @return */ private boolean editUserGroup(Group g){ Display display = Display.getDefault(); EditShell eShell = new EditShell(display, g, accounts); //Disable the main window shlButterfly.setEnabled(false); // open new window eShell.open(); //Re-Enable and make the window active if(account.getPermissions().contains(Permission.CREATEFILTER)) btnCreate.setEnabled(true); else btnCreate.setEnabled(false); if(account.getPermissions().contains(Permission.EDITFILTER)) btnEdit.setEnabled(true); else btnEdit.setEnabled(false); if(account.getPermissions().contains(Permission.DELETEFILTER)) btnDelete.setEnabled(true); else btnDelete.setEnabled(false); shlButterfly.setEnabled(true); shlButterfly.setActive(); return true; } /** * Open filter import/export * @return */ private boolean impExpShell(Account a, String s){ Display display = Display.getDefault(); EditShell eShell = new EditShell(display, a, s, accounts); //Disable the main window shlButterfly.setEnabled(false); // open new window eShell.open(); //Re-Enable and make the window active shlButterfly.setEnabled(true); shlButterfly.setActive(); accounts.loadAccounts(); List filterInactiveList = filterInactiveListViewer.getList(); filterInactiveList.removeAll(); java.util.List<Filter> fml = account.getInactiveFilters(); for(Filter fia: fml){ filterInactiveList.add(fia.toString()); } List filteractiveList = filterActiveListViewer.getList(); filteractiveList.removeAll(); java.util.List<Filter> fma = account.getActiveFilters(); for(Filter fia: fma){ filteractiveList.add(fia.toString()); } return true; } /** * Open the Account shell using the change password constructs. * @param shell * @param accName * @param group * @return */ private boolean changePassword(Shell shell, String accName, Group group) { AccountShell aShell = new AccountShell(shell, accName, group); //Disable the main window shlButterfly.setEnabled(false); aShell.open(this); //Re-Enable and make the window active shlButterfly.setEnabled(true); shlButterfly.setActive(); return true; } /** * Launches Create Account window * @param shell * @return */ private boolean accountShell(Shell shell){ AccountShell aShell = new AccountShell(shell); shlButterfly.setEnabled(false); aShell.open(this); List AccountList = AccountListViewer.getList(); AccountList.removeAll(); AccountList.add("Administrator"); AccountList.add("Power"); AccountList.add("Standard"); accounts.loadAccounts(); for(Account ac: accounts){ AccountList.add(ac.getName()); } shlButterfly.setEnabled(true); shlButterfly.setActive(); return true; } /** * * @param a */ public void setAccount(Account a){ account = a; } /** * Open the window. * @wbp.parser.entryPoint */ public void open() { Display display = Display.getDefault(); final Shell shell = new Shell(display); authenticate(shell); createContents(); shlButterfly.open(); shlButterfly.layout(); while (!shlButterfly.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } if (!shlButterfly.isDisposed()) { shlButterfly.dispose(); } display.dispose(); System.exit(0); } /** * Create contents of the window. */ protected void createContents() { shlButterfly = new Shell(SWT.ON_TOP | SWT.CLOSE | SWT.TITLE | SWT.MIN); shlButterfly.setSize(800, 600); shlButterfly.setText("Butterfly - Logged in as "+ account.getName()); shlButterfly.setLayout(new FillLayout(SWT.HORIZONTAL)); CTabFolder tabFolder = new CTabFolder(shlButterfly, SWT.BORDER); tabFolder.setSelectionBackground(Display.getCurrent().getSystemColor(SWT.COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT)); Border border; border = BorderFactory.createLineBorder(Color.black); //----------------------------------------------------------------- // Status Menu Item //----------------------------------------------------------------- CTabItem tbtmStatus = new CTabItem(tabFolder, SWT.NONE); tbtmStatus.setText("Status"); Composite statusComposite = new Composite(tabFolder, SWT.NONE); tbtmStatus.setControl(statusComposite); statusComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); Composite statusCompositeLeft = new Composite(statusComposite, SWT.NONE); formToolkit.adapt(statusCompositeLeft); formToolkit.paintBordersFor(statusCompositeLeft); statusCompositeLeft.setLayout(new GridLayout(1, false)); Composite composite_1 = new Composite(statusCompositeLeft, SWT.BORDER); composite_1.setLayout(new GridLayout(1, false)); GridData gd_composite_1 = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_composite_1.heightHint = 453; gd_composite_1.widthHint = 469; composite_1.setLayoutData(gd_composite_1); formToolkit.adapt(composite_1); formToolkit.paintBordersFor(composite_1); //Connection List label Label lblConnectionList = new Label(composite_1, SWT.NONE); lblConnectionList.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblConnectionList, true, true); lblConnectionList.setText("Connection List"); //Tons of stuff for putting jtext areas in swt applications Composite composite_4 = new Composite(composite_1, SWT.NONE); composite_4.setLayout(new FillLayout(SWT.HORIZONTAL)); GridData gd_composite_4 = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_composite_4.heightHint = 431; gd_composite_4.widthHint = 386; composite_4.setLayoutData(gd_composite_4); formToolkit.adapt(composite_4); formToolkit.paintBordersFor(composite_4); Composite composite_5 = new Composite(composite_4, SWT.EMBEDDED); formToolkit.adapt(composite_5); formToolkit.paintBordersFor(composite_5); Frame frame_2 = SWT_AWT.new_Frame(composite_5); Panel panel_1 = new Panel(); frame_2.add(panel_1); panel_1.setLayout(new BorderLayout(0, 0)); JRootPane rootPane_1 = new JRootPane(); panel_1.add(rootPane_1); rootPane_1.getContentPane().setLayout(new java.awt.GridLayout(1, 0, 0, 0)); // Initialize text area connection list textAreaConnectionList = new JTextArea(); //rootPane_1.getContentPane().add(textAreaConnectionList); textAreaConnectionList.setEditable(false); textAreaConnectionList.setBorder(border); JScrollPane sbConnectionList = new JScrollPane(textAreaConnectionList); rootPane_1.getContentPane().add(sbConnectionList); Composite composite = new Composite(statusCompositeLeft, SWT.BORDER); GridData gd_composite = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1); gd_composite.widthHint = 385; composite.setLayoutData(gd_composite); composite.setLayout(new GridLayout(3, false)); //composite.setBorder(border); formToolkit.adapt(composite); formToolkit.paintBordersFor(composite); //Port Label Label lblPort = new Label(composite, SWT.NONE); formToolkit.adapt(lblPort, true, true); lblPort.setText("Port:"); // Initialize Port Text Field textPort = new Text(composite, SWT.BORDER); textPort.setText(Integer.toString(accounts.getPortNumber())); GridData gd_textPort = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1); gd_textPort.widthHint = 262; textPort.setLayoutData(gd_textPort); formToolkit.adapt(textPort, true, true); if (!account.getPermissions().contains(Permission.SETPORT)) { textPort.setEditable(false); } // Initialize Listen Button for the port final Button btnListen = new Button(composite, SWT.NONE); GridData gd_btnListen = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 2); gd_btnListen.heightHint = 50; gd_btnListen.widthHint = 70; btnListen.setLayoutData(gd_btnListen); btnListen.setSelection(true); formToolkit.adapt(btnListen, true, true); btnListen.setText("Listen"); //Listen Button listener btnListen.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch(e.type){ case SWT.Selection: if(server != null && server.isRunning()) { server.stop(); btnListen.setText("Listen"); } else { accounts.setPortNumber(Integer.parseInt(textPort.getText())); server = new ProxyServer(accounts.getPortNumber(), new HttpResponseFilters() { public HttpFilter getFilter(String hostAndPort) { return new CustomHttpResponseFilter(account.getActiveFilters()); }}, null); server.start(); btnListen.setText("Stop"); } accounts.saveAccounts(); } } }); // Connection Count Label Label lblConnections = new Label(composite, SWT.NONE); lblConnections.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblConnections, true, true); lblConnections.setText("Connection Count:"); // Initialize connection count text field + //TODO change to JTextArea not Text textConnectionCount = new Text(composite, SWT.BORDER); textConnectionCount.setText("0"); GridData gd_textConnectionCount = new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1); gd_textConnectionCount.widthHint = 266; textConnectionCount.setLayoutData(gd_textConnectionCount); formToolkit.adapt(textConnectionCount, true, true); //disable the fields textConnectionCount.setEnabled(false); - ProxyLog.setCountText(textConnectionCount); + //ProxyLog.setCountText(textConnectionCount); Composite statusCompositeRight = new Composite(statusComposite, SWT.NONE); formToolkit.adapt(statusCompositeRight); formToolkit.paintBordersFor(statusCompositeRight); statusCompositeRight.setLayout(new GridLayout(1, false)); Composite composite_2 = new Composite(statusCompositeRight, SWT.BORDER); composite_2.setLayout(new GridLayout(1, false)); GridData gd_composite_2 = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_composite_2.heightHint = 529; gd_composite_2.widthHint = 390; composite_2.setLayoutData(gd_composite_2); formToolkit.adapt(composite_2); formToolkit.paintBordersFor(composite_2); //Dialog label Label lblNewLabel_2 = new Label(composite_2, SWT.NONE); lblNewLabel_2.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblNewLabel_2, true, true); lblNewLabel_2.setText("Dialog"); //Tons of stuff for the dialog text area Composite composite_3 = new Composite(composite_2, SWT.EMBEDDED); composite_3.setLayout(new FillLayout(SWT.HORIZONTAL)); GridData gd_composite_3 = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_composite_3.heightHint = 523; gd_composite_3.widthHint = 407; composite_3.setLayoutData(gd_composite_3); formToolkit.adapt(composite_3); formToolkit.paintBordersFor(composite_3); Frame frame_1 = SWT_AWT.new_Frame(composite_3); Panel panel = new Panel(); frame_1.add(panel); panel.setLayout(new BorderLayout(0, 0)); JRootPane rootPane = new JRootPane(); panel.add(rootPane); rootPane.getContentPane().setLayout(new java.awt.GridLayout(1, 0, 0, 0)); // Initialize Text Area for Dialog textAreaDialog= new JTextArea(); textAreaDialog.setLineWrap(true); //rootPane.getContentPane().add(textAreaDialog); textAreaDialog.setBorder(border); //set border textAreaDialog.setEditable(false); // meddling in my text area JScrollPane sbDialog = new JScrollPane(textAreaDialog); rootPane.getContentPane().add(sbDialog); //----------------------------------------------------------------- // Filters menu item //----------------------------------------------------------------- CTabItem tbtmNewItem = new CTabItem(tabFolder, SWT.NONE); tbtmNewItem.setText("Filters"); Composite filterComposite = new Composite(tabFolder, SWT.NONE); tbtmNewItem.setControl(filterComposite); formToolkit.paintBordersFor(filterComposite); filterComposite.setLayout(new GridLayout(1, false)); Composite filterComposite_1 = new Composite(filterComposite, SWT.NONE); GridData gd_filterComposite_1 = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_filterComposite_1.widthHint = 768; gd_filterComposite_1.heightHint = 474; filterComposite_1.setLayoutData(gd_filterComposite_1); formToolkit.adapt(filterComposite_1); formToolkit.paintBordersFor(filterComposite_1); filterComposite_1.setLayout(new GridLayout(3, false)); Label lblActiveFilters = new Label(filterComposite_1, SWT.NONE); lblActiveFilters.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblActiveFilters, true, true); lblActiveFilters.setText("Active Filters"); new Label(filterComposite_1, SWT.NONE); Label lblInactiveFilters = new Label(filterComposite_1, SWT.NONE); lblInactiveFilters.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblInactiveFilters, true, true); lblInactiveFilters.setText("Inactive Filters"); //Active Filter composite Composite filterActiveComposite = new Composite(filterComposite_1, SWT.NONE); GridData gd_filterActiveComposite = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_filterActiveComposite.heightHint = 465; gd_filterActiveComposite.widthHint = 333; filterActiveComposite.setLayoutData(gd_filterActiveComposite); formToolkit.adapt(filterActiveComposite); formToolkit.paintBordersFor(filterActiveComposite); filterActiveComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); // Active filter list viewer filterActiveListViewer = new ListViewer(filterActiveComposite, SWT.BORDER | SWT.V_SCROLL); List filterActiveList = filterActiveListViewer.getList(); java.util.List<Filter> f = account.getActiveFilters(); for(Filter fil: f){ filterActiveList.add(fil.toString()); } if(account.getGroup()!= Group.STANDARD){ f = account.getDefaultFilters(); for(Filter fil : f){ filterActiveList.add(fil.toString()); } } //Filter middle button bar Composite filterBtnComposite = new Composite(filterComposite_1, SWT.NONE); filterBtnComposite.setLayout(new FillLayout(SWT.VERTICAL)); GridData gd_filterBtnComposite = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_filterBtnComposite.heightHint = 465; gd_filterBtnComposite.widthHint = 85; filterBtnComposite.setLayoutData(gd_filterBtnComposite); formToolkit.adapt(filterBtnComposite); formToolkit.paintBordersFor(filterBtnComposite); Composite filterBtnComposite_NORTH = new Composite(filterBtnComposite, SWT.NONE); formToolkit.adapt(filterBtnComposite_NORTH); formToolkit.paintBordersFor(filterBtnComposite_NORTH); Composite filterBtnComposite_CENTER = new Composite(filterBtnComposite, SWT.NONE); formToolkit.adapt(filterBtnComposite_CENTER); formToolkit.paintBordersFor(filterBtnComposite_CENTER); filterBtnComposite_CENTER.setLayout(new FillLayout(SWT.HORIZONTAL)); //Add from inactive to active Button btnAdd = new Button(filterBtnComposite_CENTER, SWT.NONE); formToolkit.adapt(btnAdd, true, true); btnAdd.setText("<"); //Remove from active to inactive Button btnRemove = new Button(filterBtnComposite_CENTER, SWT.NONE); formToolkit.adapt(btnRemove, true, true); btnRemove.setText(">"); Composite filterBtnComposite_SOUTH = new Composite(filterBtnComposite, SWT.NONE); formToolkit.adapt(filterBtnComposite_SOUTH); formToolkit.paintBordersFor(filterBtnComposite_SOUTH); //Inactive filter composite Composite filterInactiveComposite = new Composite(filterComposite_1, SWT.NONE); GridData gd_filterInactiveComposite = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_filterInactiveComposite.heightHint = 465; gd_filterInactiveComposite.widthHint = 333; filterInactiveComposite.setLayoutData(gd_filterInactiveComposite); formToolkit.adapt(filterInactiveComposite); formToolkit.paintBordersFor(filterInactiveComposite); filterInactiveComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); //Inactive List viewer filterInactiveListViewer = new ListViewer(filterInactiveComposite, SWT.BORDER | SWT.V_SCROLL); List filterInactiveList = filterInactiveListViewer.getList(); java.util.List<Filter> fml = account.getInactiveFilters(); for(Filter fil: fml){ filterInactiveList.add(fil.toString()); } //Filter Button Bar Composite filterBtnBarComposite = new Composite(filterComposite, SWT.NONE); filterBtnBarComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); GridData gd_filterBtnBarComposite = new GridData(SWT.LEFT, SWT.BOTTOM, true, true, 1, 1); gd_filterBtnBarComposite.widthHint = 771; gd_filterBtnBarComposite.heightHint = 28; filterBtnBarComposite.setLayoutData(gd_filterBtnBarComposite); formToolkit.adapt(filterBtnBarComposite); formToolkit.paintBordersFor(filterBtnBarComposite); //Create filter btnCreate = new Button(filterBtnBarComposite, SWT.NONE); formToolkit.adapt(btnCreate, true, true); btnCreate.setText(CREATE); //Create filter button listener. Open blank text area. btnCreate.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: btnCreateHandleEvent(); } } } ); if(!account.getPermissions().contains(Permission.CREATEFILTER)){ btnCreate.setEnabled(false); } //Add Filter from inactive to active list btnAdd.addListener(SWT.Selection, new Listener(){ @Override public void handleEvent(Event event) { switch(event.type){ case SWT.Selection: btnAddHandleEvent(); } } }); btnRemove.addListener(SWT.Selection, new Listener(){ @Override public void handleEvent(Event event) { switch(event.type){ case SWT.Selection: btnRemoveHandleEvent(); } } }); //Edit filter btnEdit = new Button(filterBtnBarComposite, SWT.NONE); formToolkit.adapt(btnEdit, true, true); btnEdit.setText(EDIT); //Create filter button listener. Open text area with highlighted filters text. btnEdit.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: btnEditHandleEvent(); } } } ); if(!account.getPermissions().contains(Permission.EDITFILTER)){ btnEdit.setEnabled(false); } //Delete filter btnDelete = new Button(filterBtnBarComposite, SWT.NONE); formToolkit.adapt(btnDelete, true, true); btnDelete.setText("Delete"); btnDelete.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch(e.type){ case SWT.Selection: btnDeleteHandleEvent(); } } }); if(!account.getPermissions().contains(Permission.DELETEFILTER)){ btnDelete.setEnabled(false); } //----------------------------------------------------------------- //Administrator Tab //----------------------------------------------------------------- if(account.getGroup()==Group.ADMINISTRATOR){ CTabItem tbtmAdministrator = new CTabItem(tabFolder, SWT.NONE); tbtmAdministrator.setText("Administrator"); Composite admComposite = new Composite(tabFolder, SWT.NONE); tbtmAdministrator.setControl(admComposite); formToolkit.paintBordersFor(admComposite); admComposite.setLayout(new GridLayout(3, false)); Label lblAccounts = new Label(admComposite, SWT.NONE); lblAccounts.setAlignment(SWT.CENTER); GridData gd_lblAccounts = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1); gd_lblAccounts.widthHint = 256; lblAccounts.setLayoutData(gd_lblAccounts); formToolkit.adapt(lblAccounts, true, true); lblAccounts.setText("Accounts"); //Active Filter label Label lblNewLabel = new Label(admComposite, SWT.NONE); lblNewLabel.setAlignment(SWT.CENTER); GridData gd_lblNewLabel = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1); gd_lblNewLabel.widthHint = 255; lblNewLabel.setLayoutData(gd_lblNewLabel); formToolkit.adapt(lblNewLabel, true, true); lblNewLabel.setText("Active Filters"); //Inactive filter label Label lblNewLabel_1 = new Label(admComposite, SWT.NONE); lblNewLabel_1.setAlignment(SWT.CENTER); lblNewLabel_1.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblNewLabel_1, true, true); lblNewLabel_1.setText("Inactive Filters"); Composite admTableTreeComposite = new Composite(admComposite, SWT.NONE); GridData gd_admTableTreeComposite = new GridData(SWT.LEFT, SWT.TOP, true, true, 3, 1); gd_admTableTreeComposite.heightHint = 484; gd_admTableTreeComposite.widthHint = 778; admTableTreeComposite.setLayoutData(gd_admTableTreeComposite); formToolkit.adapt(admTableTreeComposite); formToolkit.paintBordersFor(admTableTreeComposite); admTableTreeComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); // Account viewer AccountListViewer = new ListViewer(admTableTreeComposite, SWT.BORDER | SWT.V_SCROLL); final List AccountList = AccountListViewer.getList(); AccountList.add("Administrator"); AccountList.add("Power"); AccountList.add("Standard"); //TODO set active list to selections current active filters ListViewer activeViewer = new ListViewer(admTableTreeComposite, SWT.BORDER | SWT.V_SCROLL); final List activeList = activeViewer.getList(); //TODO set inactive list to selections current inactive filters ListViewer inactiveViewer = new ListViewer(admTableTreeComposite, SWT.BORDER | SWT.V_SCROLL); final List inactiveList = inactiveViewer.getList(); // Administrator button bar Composite admBtnBarComposite = formToolkit.createComposite(admComposite, SWT.NONE); GridData gd_admBtnBarComposite = new GridData(SWT.LEFT, SWT.TOP, true, false, 3, 1); gd_admBtnBarComposite.widthHint = 779; gd_admBtnBarComposite.heightHint = 28; admBtnBarComposite.setLayoutData(gd_admBtnBarComposite); formToolkit.paintBordersFor(admBtnBarComposite); admBtnBarComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); //Create an Account Button admBtnCreate = new Button(admBtnBarComposite, SWT.NONE); formToolkit.adapt(admBtnCreate, true, true); admBtnCreate.setText(CREATE); admBtnCreate.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: Shell accShell = new Shell(display); accountShell(accShell); } } } ); //TODO implement user group edit/accounts //Edit User Groups/Accounts Button admBtnEdit = new Button(admBtnBarComposite, SWT.NONE); formToolkit.adapt(admBtnEdit, true, true); admBtnEdit.setText(EDIT); admBtnEdit.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: Accounts acc = new Accounts(); acc.loadAccounts(); try{ String selection = AccountList.getSelection()[0].trim(); Account a =acc.getAccount(selection); if(a == null){ if(Group.valueOf(selection.toUpperCase())!= null){ editUserGroup(Group.valueOf(selection.toUpperCase())); } } else{ //editShell(a,"Administrator"); //TODO If an account is selected editUserAccount(a); } //TODO If a user group is selected //editUserGroup(group); }catch(ArrayIndexOutOfBoundsException ex){ } catch(IllegalArgumentException ex){} } } } ); //Delete User Accounts final Button admBtnDelete = new Button(admBtnBarComposite, SWT.NONE); formToolkit.adapt(admBtnDelete, true, true); admBtnDelete.setText("Delete"); admBtnDelete.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch(e.type){ case SWT.Selection: Accounts acc = new Accounts(); acc.loadAccounts(); Account a =acc.getAccount(AccountList.getSelection()[0].trim()); if(a!=null){ if(!a.getName().equals(account.getName())){ acc.removeAccount(a); acc.saveAccounts(); AccountList.removeAll(); AccountList.add("Administrator"); AccountList.add("Power"); AccountList.add("Standard"); for(Account ac: acc){ AccountList.add(ac.getName()); } } } else System.err.println("No account selected"); } } }); AccountListViewer.addSelectionChangedListener(new ISelectionChangedListener(){ @Override public void selectionChanged(SelectionChangedEvent e) { try{ String selection = AccountList.getSelection()[0].trim(); if(selection.equals("Administrator")||selection.equals("Power")||selection.equals("Standard")){ activeList.removeAll(); inactiveList.removeAll(); admBtnDelete.setEnabled(false); } else if(accounts.getAccount(selection)!=null){ Account acc = accounts.getAccount(selection); activeList.removeAll(); inactiveList.removeAll(); for(Filter f: acc.getActiveFilters()) activeList.add(f.getName()); for(Filter f: acc.getInactiveFilters()) inactiveList.add(f.getName()); if(acc.getName().equals(account.getName())) admBtnDelete.setEnabled(false); else admBtnDelete.setEnabled(true); } else admBtnDelete.setEnabled(true); }catch(ArrayIndexOutOfBoundsException ex){ } } }); Accounts a = new Accounts(); a.loadAccounts(); for(Account acc: a){ if(acc.getGroup()==Group.ADMINISTRATOR) AccountList.add("\t"+acc.getName()); } for(Account acc: a){ if(acc.getGroup()==Group.POWER) AccountList.add("\t"+acc.getName()); } for(Account acc: a){ if(acc.getGroup()==Group.STANDARD) AccountList.add("\t"+acc.getName()); } } //----------------------------------------------------------------- //Main menu bar //----------------------------------------------------------------- Menu menu = new Menu(shlButterfly, SWT.BAR); shlButterfly.setMenuBar(menu); // Menu Bar Main MenuItem mntmMain = new MenuItem(menu, SWT.CASCADE); mntmMain.setText("Main"); Menu menu_main = new Menu(mntmMain); mntmMain.setMenu(menu_main); /* commented this out because we moved it but I'm leaving this here for now //Listen if the user is not a standard user if (account.getGroup() != Group.STANDARD) { final MenuItem mntmListen = new MenuItem(menu_main, SWT.CHECK); //Set Listen to default on mntmListen.setSelection(false); mntmListen.setText("Listen"); mntmListen.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ if (mntmListen.getSelection()) { //TODO turn on the proxy System.out.println("Checked"); } else { //TODO turn off the proxy System.out.println("Uncheck"); } } }); }*/ //Import MenuItem mntmImport = new MenuItem(menu_main, SWT.NONE); mntmImport.setText(IMPORT); mntmImport.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: impExpShell(account, IMPORT); } } } ); //Export MenuItem mntmExport = new MenuItem(menu_main, SWT.NONE); mntmExport.setText(EXPORT); mntmExport.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: impExpShell(account, EXPORT); } } } ); //Logout MenuItem mntmNewItem = new MenuItem(menu_main, SWT.NONE); mntmNewItem.setText("Logout"); mntmNewItem.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: //TODO Logout, currently I (Zong) implemented this naive way of doing it. Please correct it if its wrong if (server != null && server.isRunning()) { server.stop(); } if (!shlButterfly.isDisposed()) { shlButterfly.dispose(); } open(); } } } ); //Quit MenuItem mntmQuit = new MenuItem(menu_main, SWT.NONE); mntmQuit.setText("Quit"); mntmQuit.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: if (!shlButterfly.isDisposed()) { shlButterfly.dispose(); } } } }); // Menu Bar Settings MenuItem mntmSettings = new MenuItem(menu, SWT.CASCADE); mntmSettings.setText("Settings"); Menu menu_settings = new Menu(mntmSettings); mntmSettings.setMenu(menu_settings); //Change Password MenuItem mntmChangePassword = new MenuItem(menu_settings, SWT.NONE); mntmChangePassword.setText("Change Password"); mntmChangePassword.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e) { Shell aShell = new Shell(display); changePassword(aShell, account.getName(), account.getGroup()); } }); // Initialize proxy log items to settings previously set ProxyLog.setLogEnabled(accounts.isLogEnabled()); if (accounts.isDialogEnabled()) { ProxyLog.setDialogText(textAreaDialog); } if (accounts.isConnectionListEnabled()) { ProxyLog.setConnectionText(textAreaConnectionList); } if (account.getGroup()==Group.ADMINISTRATOR || accounts.isDialogEnabled()) { MenuItem mntmLogging = new MenuItem(menu, SWT.CASCADE); mntmLogging.setText("Logging"); Menu menu_logging = new Menu(mntmLogging); mntmLogging.setMenu(menu_logging); /* * Menu Item for Clear Dialog */ final MenuItem mntmClearDialog = new MenuItem(menu_logging, SWT.NONE); mntmClearDialog.setText("Clear Dialog"); // Listener for selection of Clear Dialog mntmClearDialog.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e) { ProxyLog.clearDialog(); } }); if (account.getGroup()==Group.ADMINISTRATOR) { /* * MenuItem for Enable Log */ final MenuItem mntmEnableLogging = new MenuItem(menu_logging, SWT.CHECK); mntmEnableLogging.setText("Enable Log"); // Load default/previous setting mntmEnableLogging.setSelection(accounts.isLogEnabled()); // Listener for selection of Enable Log mntmEnableLogging.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e) { ProxyLog.setLogEnabled(mntmEnableLogging.getSelection()); accounts.setLogEnabled(mntmEnableLogging.getSelection()); accounts.saveAccounts(); } }); /* * MenuItem for Enable Dialog */ final MenuItem mntmNewCheckbox = new MenuItem(menu_logging, SWT.CHECK); mntmNewCheckbox.setText("Enable Dialog"); // Load default/previous setting mntmNewCheckbox.setSelection(accounts.isDialogEnabled()); // Listener for selection of Enable Dialog mntmNewCheckbox.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e) { if (mntmNewCheckbox.getSelection() == true) { ProxyLog.setDialogText(textAreaDialog); accounts.setDialogEnabled(true); } else { ProxyLog.setDialogText(null); accounts.setDialogEnabled(false); } accounts.saveAccounts(); } }); /* * Menu Item for Connection List */ final MenuItem mntmEnableConnectionList = new MenuItem(menu_logging, SWT.CHECK); mntmEnableConnectionList.setText("Enable Connection List"); // Load default/previous setting mntmEnableConnectionList.setSelection(accounts.isConnectionListEnabled()); // Listener for selection of Enable Connection List mntmEnableConnectionList.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e) { if (mntmEnableConnectionList.getSelection() == true) { ProxyLog.setConnectionText(textAreaConnectionList); accounts.setConnectionListEnabled(true); } else { ProxyLog.setConnectionText(null); accounts.setConnectionListEnabled(false); } accounts.saveAccounts(); } }); } } } public void setAccounts(Accounts a){ accounts = a; } private void btnDeleteHandleEvent(){ try{ List activeFilters = filterActiveListViewer.getList(); List inactiveFilters = filterInactiveListViewer.getList(); String filter; if(inactiveFilters.getSelection().length!=0) filter = inactiveFilters.getSelection()[0]; else filter = activeFilters.getSelection()[0]; String[] fil = filter.split(":"); String filterName = fil[0]; account.removeFilter(Integer.parseInt(filterName)); accounts.saveAccounts(); inactiveFilters.removeAll(); activeFilters.removeAll(); java.util.List<Filter> fml = account.getInactiveFilters(); for(Filter fia: fml){ inactiveFilters.add(fia.toString()); } fml = account.getActiveFilters(); for(Filter fia: fml){ activeFilters.add(fia.toString()); } }catch(ArrayIndexOutOfBoundsException exc){ System.err.println("Didn't select anything"); } } private void btnAddHandleEvent(){ List al = filterActiveListViewer.getList(); List il = filterInactiveListViewer.getList(); try{ String filter = il.getSelection()[0]; String[] fil = filter.split(":"); String filterName = fil[0]; Filter removedFilter = account.removeInactiveFilter(Integer.parseInt(filterName)); account.addFilter(removedFilter); accounts.saveAccounts(); il.remove(filter); al.add(filter); }catch(ArrayIndexOutOfBoundsException e){ System.err.println("Didn't select anything"); } } private void btnRemoveHandleEvent(){ try{ List al = filterActiveListViewer.getList(); List il = filterInactiveListViewer.getList(); String filter = al.getSelection()[0]; String[] fil = filter.split(":"); String filterName = fil[0]; Filter removedFilter = account.removeActiveFilter(Integer.parseInt(filterName)); account.addInactiveFilter(removedFilter); accounts.saveAccounts(); al.remove(filter); il.add(filter); }catch(ArrayIndexOutOfBoundsException e){ System.err.println("Didn't select anything"); } } private void btnCreateHandleEvent(){ filterEdit(CREATE,null); //Repopulate filter lists List filterInactiveList = filterInactiveListViewer.getList(); filterInactiveList.removeAll(); java.util.List<Filter> fml = account.getInactiveFilters(); for(Filter fia: fml){ filterInactiveList.add(fia.toString()); } List filteractiveList = filterActiveListViewer.getList(); filteractiveList.removeAll(); java.util.List<Filter> fma = account.getActiveFilters(); for(Filter fia: fma){ filteractiveList.add(fia.toString()); } } private void btnEditHandleEvent(){ List activeFilters = filterActiveListViewer.getList(); List inactiveFilters = filterInactiveListViewer.getList(); try{ String filter; if(inactiveFilters.getSelection().length!=0) filter = inactiveFilters.getSelection()[0]; else filter = activeFilters.getSelection()[0]; String[] fil = filter.split(":"); String filterName = fil[0]; Filter editFilter = account.getFilter(Integer.parseInt(filterName)); filterEdit(EDIT,editFilter); //Repopulate filter lists List filterInactiveList = filterInactiveListViewer.getList(); filterInactiveList.removeAll(); java.util.List<Filter> fml = account.getInactiveFilters(); for(Filter fia: fml){ filterInactiveList.add(fia.toString()); } List filteractiveList = filterActiveListViewer.getList(); filteractiveList.removeAll(); java.util.List<Filter> fma = account.getActiveFilters(); for(Filter fia: fma){ filteractiveList.add(fia.toString()); } }catch(ArrayIndexOutOfBoundsException exc){ System.err.println("Didn't select anything"); } } }
false
true
protected void createContents() { shlButterfly = new Shell(SWT.ON_TOP | SWT.CLOSE | SWT.TITLE | SWT.MIN); shlButterfly.setSize(800, 600); shlButterfly.setText("Butterfly - Logged in as "+ account.getName()); shlButterfly.setLayout(new FillLayout(SWT.HORIZONTAL)); CTabFolder tabFolder = new CTabFolder(shlButterfly, SWT.BORDER); tabFolder.setSelectionBackground(Display.getCurrent().getSystemColor(SWT.COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT)); Border border; border = BorderFactory.createLineBorder(Color.black); //----------------------------------------------------------------- // Status Menu Item //----------------------------------------------------------------- CTabItem tbtmStatus = new CTabItem(tabFolder, SWT.NONE); tbtmStatus.setText("Status"); Composite statusComposite = new Composite(tabFolder, SWT.NONE); tbtmStatus.setControl(statusComposite); statusComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); Composite statusCompositeLeft = new Composite(statusComposite, SWT.NONE); formToolkit.adapt(statusCompositeLeft); formToolkit.paintBordersFor(statusCompositeLeft); statusCompositeLeft.setLayout(new GridLayout(1, false)); Composite composite_1 = new Composite(statusCompositeLeft, SWT.BORDER); composite_1.setLayout(new GridLayout(1, false)); GridData gd_composite_1 = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_composite_1.heightHint = 453; gd_composite_1.widthHint = 469; composite_1.setLayoutData(gd_composite_1); formToolkit.adapt(composite_1); formToolkit.paintBordersFor(composite_1); //Connection List label Label lblConnectionList = new Label(composite_1, SWT.NONE); lblConnectionList.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblConnectionList, true, true); lblConnectionList.setText("Connection List"); //Tons of stuff for putting jtext areas in swt applications Composite composite_4 = new Composite(composite_1, SWT.NONE); composite_4.setLayout(new FillLayout(SWT.HORIZONTAL)); GridData gd_composite_4 = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_composite_4.heightHint = 431; gd_composite_4.widthHint = 386; composite_4.setLayoutData(gd_composite_4); formToolkit.adapt(composite_4); formToolkit.paintBordersFor(composite_4); Composite composite_5 = new Composite(composite_4, SWT.EMBEDDED); formToolkit.adapt(composite_5); formToolkit.paintBordersFor(composite_5); Frame frame_2 = SWT_AWT.new_Frame(composite_5); Panel panel_1 = new Panel(); frame_2.add(panel_1); panel_1.setLayout(new BorderLayout(0, 0)); JRootPane rootPane_1 = new JRootPane(); panel_1.add(rootPane_1); rootPane_1.getContentPane().setLayout(new java.awt.GridLayout(1, 0, 0, 0)); // Initialize text area connection list textAreaConnectionList = new JTextArea(); //rootPane_1.getContentPane().add(textAreaConnectionList); textAreaConnectionList.setEditable(false); textAreaConnectionList.setBorder(border); JScrollPane sbConnectionList = new JScrollPane(textAreaConnectionList); rootPane_1.getContentPane().add(sbConnectionList); Composite composite = new Composite(statusCompositeLeft, SWT.BORDER); GridData gd_composite = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1); gd_composite.widthHint = 385; composite.setLayoutData(gd_composite); composite.setLayout(new GridLayout(3, false)); //composite.setBorder(border); formToolkit.adapt(composite); formToolkit.paintBordersFor(composite); //Port Label Label lblPort = new Label(composite, SWT.NONE); formToolkit.adapt(lblPort, true, true); lblPort.setText("Port:"); // Initialize Port Text Field textPort = new Text(composite, SWT.BORDER); textPort.setText(Integer.toString(accounts.getPortNumber())); GridData gd_textPort = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1); gd_textPort.widthHint = 262; textPort.setLayoutData(gd_textPort); formToolkit.adapt(textPort, true, true); if (!account.getPermissions().contains(Permission.SETPORT)) { textPort.setEditable(false); } // Initialize Listen Button for the port final Button btnListen = new Button(composite, SWT.NONE); GridData gd_btnListen = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 2); gd_btnListen.heightHint = 50; gd_btnListen.widthHint = 70; btnListen.setLayoutData(gd_btnListen); btnListen.setSelection(true); formToolkit.adapt(btnListen, true, true); btnListen.setText("Listen"); //Listen Button listener btnListen.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch(e.type){ case SWT.Selection: if(server != null && server.isRunning()) { server.stop(); btnListen.setText("Listen"); } else { accounts.setPortNumber(Integer.parseInt(textPort.getText())); server = new ProxyServer(accounts.getPortNumber(), new HttpResponseFilters() { public HttpFilter getFilter(String hostAndPort) { return new CustomHttpResponseFilter(account.getActiveFilters()); }}, null); server.start(); btnListen.setText("Stop"); } accounts.saveAccounts(); } } }); // Connection Count Label Label lblConnections = new Label(composite, SWT.NONE); lblConnections.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblConnections, true, true); lblConnections.setText("Connection Count:"); // Initialize connection count text field textConnectionCount = new Text(composite, SWT.BORDER); textConnectionCount.setText("0"); GridData gd_textConnectionCount = new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1); gd_textConnectionCount.widthHint = 266; textConnectionCount.setLayoutData(gd_textConnectionCount); formToolkit.adapt(textConnectionCount, true, true); //disable the fields textConnectionCount.setEnabled(false); ProxyLog.setCountText(textConnectionCount); Composite statusCompositeRight = new Composite(statusComposite, SWT.NONE); formToolkit.adapt(statusCompositeRight); formToolkit.paintBordersFor(statusCompositeRight); statusCompositeRight.setLayout(new GridLayout(1, false)); Composite composite_2 = new Composite(statusCompositeRight, SWT.BORDER); composite_2.setLayout(new GridLayout(1, false)); GridData gd_composite_2 = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_composite_2.heightHint = 529; gd_composite_2.widthHint = 390; composite_2.setLayoutData(gd_composite_2); formToolkit.adapt(composite_2); formToolkit.paintBordersFor(composite_2); //Dialog label Label lblNewLabel_2 = new Label(composite_2, SWT.NONE); lblNewLabel_2.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblNewLabel_2, true, true); lblNewLabel_2.setText("Dialog"); //Tons of stuff for the dialog text area Composite composite_3 = new Composite(composite_2, SWT.EMBEDDED); composite_3.setLayout(new FillLayout(SWT.HORIZONTAL)); GridData gd_composite_3 = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_composite_3.heightHint = 523; gd_composite_3.widthHint = 407; composite_3.setLayoutData(gd_composite_3); formToolkit.adapt(composite_3); formToolkit.paintBordersFor(composite_3); Frame frame_1 = SWT_AWT.new_Frame(composite_3); Panel panel = new Panel(); frame_1.add(panel); panel.setLayout(new BorderLayout(0, 0)); JRootPane rootPane = new JRootPane(); panel.add(rootPane); rootPane.getContentPane().setLayout(new java.awt.GridLayout(1, 0, 0, 0)); // Initialize Text Area for Dialog textAreaDialog= new JTextArea(); textAreaDialog.setLineWrap(true); //rootPane.getContentPane().add(textAreaDialog); textAreaDialog.setBorder(border); //set border textAreaDialog.setEditable(false); // meddling in my text area JScrollPane sbDialog = new JScrollPane(textAreaDialog); rootPane.getContentPane().add(sbDialog); //----------------------------------------------------------------- // Filters menu item //----------------------------------------------------------------- CTabItem tbtmNewItem = new CTabItem(tabFolder, SWT.NONE); tbtmNewItem.setText("Filters"); Composite filterComposite = new Composite(tabFolder, SWT.NONE); tbtmNewItem.setControl(filterComposite); formToolkit.paintBordersFor(filterComposite); filterComposite.setLayout(new GridLayout(1, false)); Composite filterComposite_1 = new Composite(filterComposite, SWT.NONE); GridData gd_filterComposite_1 = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_filterComposite_1.widthHint = 768; gd_filterComposite_1.heightHint = 474; filterComposite_1.setLayoutData(gd_filterComposite_1); formToolkit.adapt(filterComposite_1); formToolkit.paintBordersFor(filterComposite_1); filterComposite_1.setLayout(new GridLayout(3, false)); Label lblActiveFilters = new Label(filterComposite_1, SWT.NONE); lblActiveFilters.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblActiveFilters, true, true); lblActiveFilters.setText("Active Filters"); new Label(filterComposite_1, SWT.NONE); Label lblInactiveFilters = new Label(filterComposite_1, SWT.NONE); lblInactiveFilters.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblInactiveFilters, true, true); lblInactiveFilters.setText("Inactive Filters"); //Active Filter composite Composite filterActiveComposite = new Composite(filterComposite_1, SWT.NONE); GridData gd_filterActiveComposite = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_filterActiveComposite.heightHint = 465; gd_filterActiveComposite.widthHint = 333; filterActiveComposite.setLayoutData(gd_filterActiveComposite); formToolkit.adapt(filterActiveComposite); formToolkit.paintBordersFor(filterActiveComposite); filterActiveComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); // Active filter list viewer filterActiveListViewer = new ListViewer(filterActiveComposite, SWT.BORDER | SWT.V_SCROLL); List filterActiveList = filterActiveListViewer.getList(); java.util.List<Filter> f = account.getActiveFilters(); for(Filter fil: f){ filterActiveList.add(fil.toString()); } if(account.getGroup()!= Group.STANDARD){ f = account.getDefaultFilters(); for(Filter fil : f){ filterActiveList.add(fil.toString()); } } //Filter middle button bar Composite filterBtnComposite = new Composite(filterComposite_1, SWT.NONE); filterBtnComposite.setLayout(new FillLayout(SWT.VERTICAL)); GridData gd_filterBtnComposite = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_filterBtnComposite.heightHint = 465; gd_filterBtnComposite.widthHint = 85; filterBtnComposite.setLayoutData(gd_filterBtnComposite); formToolkit.adapt(filterBtnComposite); formToolkit.paintBordersFor(filterBtnComposite); Composite filterBtnComposite_NORTH = new Composite(filterBtnComposite, SWT.NONE); formToolkit.adapt(filterBtnComposite_NORTH); formToolkit.paintBordersFor(filterBtnComposite_NORTH); Composite filterBtnComposite_CENTER = new Composite(filterBtnComposite, SWT.NONE); formToolkit.adapt(filterBtnComposite_CENTER); formToolkit.paintBordersFor(filterBtnComposite_CENTER); filterBtnComposite_CENTER.setLayout(new FillLayout(SWT.HORIZONTAL)); //Add from inactive to active Button btnAdd = new Button(filterBtnComposite_CENTER, SWT.NONE); formToolkit.adapt(btnAdd, true, true); btnAdd.setText("<"); //Remove from active to inactive Button btnRemove = new Button(filterBtnComposite_CENTER, SWT.NONE); formToolkit.adapt(btnRemove, true, true); btnRemove.setText(">"); Composite filterBtnComposite_SOUTH = new Composite(filterBtnComposite, SWT.NONE); formToolkit.adapt(filterBtnComposite_SOUTH); formToolkit.paintBordersFor(filterBtnComposite_SOUTH); //Inactive filter composite Composite filterInactiveComposite = new Composite(filterComposite_1, SWT.NONE); GridData gd_filterInactiveComposite = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_filterInactiveComposite.heightHint = 465; gd_filterInactiveComposite.widthHint = 333; filterInactiveComposite.setLayoutData(gd_filterInactiveComposite); formToolkit.adapt(filterInactiveComposite); formToolkit.paintBordersFor(filterInactiveComposite); filterInactiveComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); //Inactive List viewer filterInactiveListViewer = new ListViewer(filterInactiveComposite, SWT.BORDER | SWT.V_SCROLL); List filterInactiveList = filterInactiveListViewer.getList(); java.util.List<Filter> fml = account.getInactiveFilters(); for(Filter fil: fml){ filterInactiveList.add(fil.toString()); } //Filter Button Bar Composite filterBtnBarComposite = new Composite(filterComposite, SWT.NONE); filterBtnBarComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); GridData gd_filterBtnBarComposite = new GridData(SWT.LEFT, SWT.BOTTOM, true, true, 1, 1); gd_filterBtnBarComposite.widthHint = 771; gd_filterBtnBarComposite.heightHint = 28; filterBtnBarComposite.setLayoutData(gd_filterBtnBarComposite); formToolkit.adapt(filterBtnBarComposite); formToolkit.paintBordersFor(filterBtnBarComposite); //Create filter btnCreate = new Button(filterBtnBarComposite, SWT.NONE); formToolkit.adapt(btnCreate, true, true); btnCreate.setText(CREATE); //Create filter button listener. Open blank text area. btnCreate.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: btnCreateHandleEvent(); } } } ); if(!account.getPermissions().contains(Permission.CREATEFILTER)){ btnCreate.setEnabled(false); } //Add Filter from inactive to active list btnAdd.addListener(SWT.Selection, new Listener(){ @Override public void handleEvent(Event event) { switch(event.type){ case SWT.Selection: btnAddHandleEvent(); } } }); btnRemove.addListener(SWT.Selection, new Listener(){ @Override public void handleEvent(Event event) { switch(event.type){ case SWT.Selection: btnRemoveHandleEvent(); } } }); //Edit filter btnEdit = new Button(filterBtnBarComposite, SWT.NONE); formToolkit.adapt(btnEdit, true, true); btnEdit.setText(EDIT); //Create filter button listener. Open text area with highlighted filters text. btnEdit.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: btnEditHandleEvent(); } } } ); if(!account.getPermissions().contains(Permission.EDITFILTER)){ btnEdit.setEnabled(false); } //Delete filter btnDelete = new Button(filterBtnBarComposite, SWT.NONE); formToolkit.adapt(btnDelete, true, true); btnDelete.setText("Delete"); btnDelete.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch(e.type){ case SWT.Selection: btnDeleteHandleEvent(); } } }); if(!account.getPermissions().contains(Permission.DELETEFILTER)){ btnDelete.setEnabled(false); } //----------------------------------------------------------------- //Administrator Tab //----------------------------------------------------------------- if(account.getGroup()==Group.ADMINISTRATOR){ CTabItem tbtmAdministrator = new CTabItem(tabFolder, SWT.NONE); tbtmAdministrator.setText("Administrator"); Composite admComposite = new Composite(tabFolder, SWT.NONE); tbtmAdministrator.setControl(admComposite); formToolkit.paintBordersFor(admComposite); admComposite.setLayout(new GridLayout(3, false)); Label lblAccounts = new Label(admComposite, SWT.NONE); lblAccounts.setAlignment(SWT.CENTER); GridData gd_lblAccounts = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1); gd_lblAccounts.widthHint = 256; lblAccounts.setLayoutData(gd_lblAccounts); formToolkit.adapt(lblAccounts, true, true); lblAccounts.setText("Accounts"); //Active Filter label Label lblNewLabel = new Label(admComposite, SWT.NONE); lblNewLabel.setAlignment(SWT.CENTER); GridData gd_lblNewLabel = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1); gd_lblNewLabel.widthHint = 255; lblNewLabel.setLayoutData(gd_lblNewLabel); formToolkit.adapt(lblNewLabel, true, true); lblNewLabel.setText("Active Filters"); //Inactive filter label Label lblNewLabel_1 = new Label(admComposite, SWT.NONE); lblNewLabel_1.setAlignment(SWT.CENTER); lblNewLabel_1.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblNewLabel_1, true, true); lblNewLabel_1.setText("Inactive Filters"); Composite admTableTreeComposite = new Composite(admComposite, SWT.NONE); GridData gd_admTableTreeComposite = new GridData(SWT.LEFT, SWT.TOP, true, true, 3, 1); gd_admTableTreeComposite.heightHint = 484; gd_admTableTreeComposite.widthHint = 778; admTableTreeComposite.setLayoutData(gd_admTableTreeComposite); formToolkit.adapt(admTableTreeComposite); formToolkit.paintBordersFor(admTableTreeComposite); admTableTreeComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); // Account viewer AccountListViewer = new ListViewer(admTableTreeComposite, SWT.BORDER | SWT.V_SCROLL); final List AccountList = AccountListViewer.getList(); AccountList.add("Administrator"); AccountList.add("Power"); AccountList.add("Standard"); //TODO set active list to selections current active filters ListViewer activeViewer = new ListViewer(admTableTreeComposite, SWT.BORDER | SWT.V_SCROLL); final List activeList = activeViewer.getList(); //TODO set inactive list to selections current inactive filters ListViewer inactiveViewer = new ListViewer(admTableTreeComposite, SWT.BORDER | SWT.V_SCROLL); final List inactiveList = inactiveViewer.getList(); // Administrator button bar Composite admBtnBarComposite = formToolkit.createComposite(admComposite, SWT.NONE); GridData gd_admBtnBarComposite = new GridData(SWT.LEFT, SWT.TOP, true, false, 3, 1); gd_admBtnBarComposite.widthHint = 779; gd_admBtnBarComposite.heightHint = 28; admBtnBarComposite.setLayoutData(gd_admBtnBarComposite); formToolkit.paintBordersFor(admBtnBarComposite); admBtnBarComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); //Create an Account Button admBtnCreate = new Button(admBtnBarComposite, SWT.NONE); formToolkit.adapt(admBtnCreate, true, true); admBtnCreate.setText(CREATE); admBtnCreate.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: Shell accShell = new Shell(display); accountShell(accShell); } } } ); //TODO implement user group edit/accounts //Edit User Groups/Accounts Button admBtnEdit = new Button(admBtnBarComposite, SWT.NONE); formToolkit.adapt(admBtnEdit, true, true); admBtnEdit.setText(EDIT); admBtnEdit.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: Accounts acc = new Accounts(); acc.loadAccounts(); try{ String selection = AccountList.getSelection()[0].trim(); Account a =acc.getAccount(selection); if(a == null){ if(Group.valueOf(selection.toUpperCase())!= null){ editUserGroup(Group.valueOf(selection.toUpperCase())); } } else{ //editShell(a,"Administrator"); //TODO If an account is selected editUserAccount(a); } //TODO If a user group is selected //editUserGroup(group); }catch(ArrayIndexOutOfBoundsException ex){ } catch(IllegalArgumentException ex){} } } } ); //Delete User Accounts final Button admBtnDelete = new Button(admBtnBarComposite, SWT.NONE); formToolkit.adapt(admBtnDelete, true, true); admBtnDelete.setText("Delete"); admBtnDelete.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch(e.type){ case SWT.Selection: Accounts acc = new Accounts(); acc.loadAccounts(); Account a =acc.getAccount(AccountList.getSelection()[0].trim()); if(a!=null){ if(!a.getName().equals(account.getName())){ acc.removeAccount(a); acc.saveAccounts(); AccountList.removeAll(); AccountList.add("Administrator"); AccountList.add("Power"); AccountList.add("Standard"); for(Account ac: acc){ AccountList.add(ac.getName()); } } } else System.err.println("No account selected"); } } }); AccountListViewer.addSelectionChangedListener(new ISelectionChangedListener(){ @Override public void selectionChanged(SelectionChangedEvent e) { try{ String selection = AccountList.getSelection()[0].trim(); if(selection.equals("Administrator")||selection.equals("Power")||selection.equals("Standard")){ activeList.removeAll(); inactiveList.removeAll(); admBtnDelete.setEnabled(false); } else if(accounts.getAccount(selection)!=null){ Account acc = accounts.getAccount(selection); activeList.removeAll(); inactiveList.removeAll(); for(Filter f: acc.getActiveFilters()) activeList.add(f.getName()); for(Filter f: acc.getInactiveFilters()) inactiveList.add(f.getName()); if(acc.getName().equals(account.getName())) admBtnDelete.setEnabled(false); else admBtnDelete.setEnabled(true); } else admBtnDelete.setEnabled(true); }catch(ArrayIndexOutOfBoundsException ex){ } } }); Accounts a = new Accounts(); a.loadAccounts(); for(Account acc: a){ if(acc.getGroup()==Group.ADMINISTRATOR) AccountList.add("\t"+acc.getName()); } for(Account acc: a){ if(acc.getGroup()==Group.POWER) AccountList.add("\t"+acc.getName()); } for(Account acc: a){ if(acc.getGroup()==Group.STANDARD) AccountList.add("\t"+acc.getName()); } } //----------------------------------------------------------------- //Main menu bar //----------------------------------------------------------------- Menu menu = new Menu(shlButterfly, SWT.BAR); shlButterfly.setMenuBar(menu); // Menu Bar Main MenuItem mntmMain = new MenuItem(menu, SWT.CASCADE); mntmMain.setText("Main"); Menu menu_main = new Menu(mntmMain); mntmMain.setMenu(menu_main); /* commented this out because we moved it but I'm leaving this here for now //Listen if the user is not a standard user if (account.getGroup() != Group.STANDARD) { final MenuItem mntmListen = new MenuItem(menu_main, SWT.CHECK); //Set Listen to default on mntmListen.setSelection(false); mntmListen.setText("Listen"); mntmListen.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ if (mntmListen.getSelection()) { //TODO turn on the proxy System.out.println("Checked"); } else { //TODO turn off the proxy System.out.println("Uncheck"); } } }); }*/ //Import MenuItem mntmImport = new MenuItem(menu_main, SWT.NONE); mntmImport.setText(IMPORT); mntmImport.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: impExpShell(account, IMPORT); } } } ); //Export MenuItem mntmExport = new MenuItem(menu_main, SWT.NONE); mntmExport.setText(EXPORT); mntmExport.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: impExpShell(account, EXPORT); } } } ); //Logout MenuItem mntmNewItem = new MenuItem(menu_main, SWT.NONE); mntmNewItem.setText("Logout"); mntmNewItem.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: //TODO Logout, currently I (Zong) implemented this naive way of doing it. Please correct it if its wrong if (server != null && server.isRunning()) { server.stop(); } if (!shlButterfly.isDisposed()) { shlButterfly.dispose(); } open(); } } } ); //Quit MenuItem mntmQuit = new MenuItem(menu_main, SWT.NONE); mntmQuit.setText("Quit"); mntmQuit.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: if (!shlButterfly.isDisposed()) { shlButterfly.dispose(); } } } }); // Menu Bar Settings MenuItem mntmSettings = new MenuItem(menu, SWT.CASCADE); mntmSettings.setText("Settings"); Menu menu_settings = new Menu(mntmSettings); mntmSettings.setMenu(menu_settings); //Change Password MenuItem mntmChangePassword = new MenuItem(menu_settings, SWT.NONE); mntmChangePassword.setText("Change Password"); mntmChangePassword.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e) { Shell aShell = new Shell(display); changePassword(aShell, account.getName(), account.getGroup()); } }); // Initialize proxy log items to settings previously set ProxyLog.setLogEnabled(accounts.isLogEnabled()); if (accounts.isDialogEnabled()) { ProxyLog.setDialogText(textAreaDialog); } if (accounts.isConnectionListEnabled()) { ProxyLog.setConnectionText(textAreaConnectionList); } if (account.getGroup()==Group.ADMINISTRATOR || accounts.isDialogEnabled()) { MenuItem mntmLogging = new MenuItem(menu, SWT.CASCADE); mntmLogging.setText("Logging"); Menu menu_logging = new Menu(mntmLogging); mntmLogging.setMenu(menu_logging); /* * Menu Item for Clear Dialog */ final MenuItem mntmClearDialog = new MenuItem(menu_logging, SWT.NONE); mntmClearDialog.setText("Clear Dialog"); // Listener for selection of Clear Dialog mntmClearDialog.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e) { ProxyLog.clearDialog(); } }); if (account.getGroup()==Group.ADMINISTRATOR) { /* * MenuItem for Enable Log */ final MenuItem mntmEnableLogging = new MenuItem(menu_logging, SWT.CHECK); mntmEnableLogging.setText("Enable Log"); // Load default/previous setting mntmEnableLogging.setSelection(accounts.isLogEnabled()); // Listener for selection of Enable Log mntmEnableLogging.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e) { ProxyLog.setLogEnabled(mntmEnableLogging.getSelection()); accounts.setLogEnabled(mntmEnableLogging.getSelection()); accounts.saveAccounts(); } }); /* * MenuItem for Enable Dialog */ final MenuItem mntmNewCheckbox = new MenuItem(menu_logging, SWT.CHECK); mntmNewCheckbox.setText("Enable Dialog"); // Load default/previous setting mntmNewCheckbox.setSelection(accounts.isDialogEnabled()); // Listener for selection of Enable Dialog mntmNewCheckbox.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e) { if (mntmNewCheckbox.getSelection() == true) { ProxyLog.setDialogText(textAreaDialog); accounts.setDialogEnabled(true); } else { ProxyLog.setDialogText(null); accounts.setDialogEnabled(false); } accounts.saveAccounts(); } }); /* * Menu Item for Connection List */ final MenuItem mntmEnableConnectionList = new MenuItem(menu_logging, SWT.CHECK); mntmEnableConnectionList.setText("Enable Connection List"); // Load default/previous setting mntmEnableConnectionList.setSelection(accounts.isConnectionListEnabled()); // Listener for selection of Enable Connection List mntmEnableConnectionList.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e) { if (mntmEnableConnectionList.getSelection() == true) { ProxyLog.setConnectionText(textAreaConnectionList); accounts.setConnectionListEnabled(true); } else { ProxyLog.setConnectionText(null); accounts.setConnectionListEnabled(false); } accounts.saveAccounts(); } }); } } }
protected void createContents() { shlButterfly = new Shell(SWT.ON_TOP | SWT.CLOSE | SWT.TITLE | SWT.MIN); shlButterfly.setSize(800, 600); shlButterfly.setText("Butterfly - Logged in as "+ account.getName()); shlButterfly.setLayout(new FillLayout(SWT.HORIZONTAL)); CTabFolder tabFolder = new CTabFolder(shlButterfly, SWT.BORDER); tabFolder.setSelectionBackground(Display.getCurrent().getSystemColor(SWT.COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT)); Border border; border = BorderFactory.createLineBorder(Color.black); //----------------------------------------------------------------- // Status Menu Item //----------------------------------------------------------------- CTabItem tbtmStatus = new CTabItem(tabFolder, SWT.NONE); tbtmStatus.setText("Status"); Composite statusComposite = new Composite(tabFolder, SWT.NONE); tbtmStatus.setControl(statusComposite); statusComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); Composite statusCompositeLeft = new Composite(statusComposite, SWT.NONE); formToolkit.adapt(statusCompositeLeft); formToolkit.paintBordersFor(statusCompositeLeft); statusCompositeLeft.setLayout(new GridLayout(1, false)); Composite composite_1 = new Composite(statusCompositeLeft, SWT.BORDER); composite_1.setLayout(new GridLayout(1, false)); GridData gd_composite_1 = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_composite_1.heightHint = 453; gd_composite_1.widthHint = 469; composite_1.setLayoutData(gd_composite_1); formToolkit.adapt(composite_1); formToolkit.paintBordersFor(composite_1); //Connection List label Label lblConnectionList = new Label(composite_1, SWT.NONE); lblConnectionList.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblConnectionList, true, true); lblConnectionList.setText("Connection List"); //Tons of stuff for putting jtext areas in swt applications Composite composite_4 = new Composite(composite_1, SWT.NONE); composite_4.setLayout(new FillLayout(SWT.HORIZONTAL)); GridData gd_composite_4 = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_composite_4.heightHint = 431; gd_composite_4.widthHint = 386; composite_4.setLayoutData(gd_composite_4); formToolkit.adapt(composite_4); formToolkit.paintBordersFor(composite_4); Composite composite_5 = new Composite(composite_4, SWT.EMBEDDED); formToolkit.adapt(composite_5); formToolkit.paintBordersFor(composite_5); Frame frame_2 = SWT_AWT.new_Frame(composite_5); Panel panel_1 = new Panel(); frame_2.add(panel_1); panel_1.setLayout(new BorderLayout(0, 0)); JRootPane rootPane_1 = new JRootPane(); panel_1.add(rootPane_1); rootPane_1.getContentPane().setLayout(new java.awt.GridLayout(1, 0, 0, 0)); // Initialize text area connection list textAreaConnectionList = new JTextArea(); //rootPane_1.getContentPane().add(textAreaConnectionList); textAreaConnectionList.setEditable(false); textAreaConnectionList.setBorder(border); JScrollPane sbConnectionList = new JScrollPane(textAreaConnectionList); rootPane_1.getContentPane().add(sbConnectionList); Composite composite = new Composite(statusCompositeLeft, SWT.BORDER); GridData gd_composite = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1); gd_composite.widthHint = 385; composite.setLayoutData(gd_composite); composite.setLayout(new GridLayout(3, false)); //composite.setBorder(border); formToolkit.adapt(composite); formToolkit.paintBordersFor(composite); //Port Label Label lblPort = new Label(composite, SWT.NONE); formToolkit.adapt(lblPort, true, true); lblPort.setText("Port:"); // Initialize Port Text Field textPort = new Text(composite, SWT.BORDER); textPort.setText(Integer.toString(accounts.getPortNumber())); GridData gd_textPort = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1); gd_textPort.widthHint = 262; textPort.setLayoutData(gd_textPort); formToolkit.adapt(textPort, true, true); if (!account.getPermissions().contains(Permission.SETPORT)) { textPort.setEditable(false); } // Initialize Listen Button for the port final Button btnListen = new Button(composite, SWT.NONE); GridData gd_btnListen = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 2); gd_btnListen.heightHint = 50; gd_btnListen.widthHint = 70; btnListen.setLayoutData(gd_btnListen); btnListen.setSelection(true); formToolkit.adapt(btnListen, true, true); btnListen.setText("Listen"); //Listen Button listener btnListen.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch(e.type){ case SWT.Selection: if(server != null && server.isRunning()) { server.stop(); btnListen.setText("Listen"); } else { accounts.setPortNumber(Integer.parseInt(textPort.getText())); server = new ProxyServer(accounts.getPortNumber(), new HttpResponseFilters() { public HttpFilter getFilter(String hostAndPort) { return new CustomHttpResponseFilter(account.getActiveFilters()); }}, null); server.start(); btnListen.setText("Stop"); } accounts.saveAccounts(); } } }); // Connection Count Label Label lblConnections = new Label(composite, SWT.NONE); lblConnections.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblConnections, true, true); lblConnections.setText("Connection Count:"); // Initialize connection count text field //TODO change to JTextArea not Text textConnectionCount = new Text(composite, SWT.BORDER); textConnectionCount.setText("0"); GridData gd_textConnectionCount = new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1); gd_textConnectionCount.widthHint = 266; textConnectionCount.setLayoutData(gd_textConnectionCount); formToolkit.adapt(textConnectionCount, true, true); //disable the fields textConnectionCount.setEnabled(false); //ProxyLog.setCountText(textConnectionCount); Composite statusCompositeRight = new Composite(statusComposite, SWT.NONE); formToolkit.adapt(statusCompositeRight); formToolkit.paintBordersFor(statusCompositeRight); statusCompositeRight.setLayout(new GridLayout(1, false)); Composite composite_2 = new Composite(statusCompositeRight, SWT.BORDER); composite_2.setLayout(new GridLayout(1, false)); GridData gd_composite_2 = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_composite_2.heightHint = 529; gd_composite_2.widthHint = 390; composite_2.setLayoutData(gd_composite_2); formToolkit.adapt(composite_2); formToolkit.paintBordersFor(composite_2); //Dialog label Label lblNewLabel_2 = new Label(composite_2, SWT.NONE); lblNewLabel_2.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblNewLabel_2, true, true); lblNewLabel_2.setText("Dialog"); //Tons of stuff for the dialog text area Composite composite_3 = new Composite(composite_2, SWT.EMBEDDED); composite_3.setLayout(new FillLayout(SWT.HORIZONTAL)); GridData gd_composite_3 = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_composite_3.heightHint = 523; gd_composite_3.widthHint = 407; composite_3.setLayoutData(gd_composite_3); formToolkit.adapt(composite_3); formToolkit.paintBordersFor(composite_3); Frame frame_1 = SWT_AWT.new_Frame(composite_3); Panel panel = new Panel(); frame_1.add(panel); panel.setLayout(new BorderLayout(0, 0)); JRootPane rootPane = new JRootPane(); panel.add(rootPane); rootPane.getContentPane().setLayout(new java.awt.GridLayout(1, 0, 0, 0)); // Initialize Text Area for Dialog textAreaDialog= new JTextArea(); textAreaDialog.setLineWrap(true); //rootPane.getContentPane().add(textAreaDialog); textAreaDialog.setBorder(border); //set border textAreaDialog.setEditable(false); // meddling in my text area JScrollPane sbDialog = new JScrollPane(textAreaDialog); rootPane.getContentPane().add(sbDialog); //----------------------------------------------------------------- // Filters menu item //----------------------------------------------------------------- CTabItem tbtmNewItem = new CTabItem(tabFolder, SWT.NONE); tbtmNewItem.setText("Filters"); Composite filterComposite = new Composite(tabFolder, SWT.NONE); tbtmNewItem.setControl(filterComposite); formToolkit.paintBordersFor(filterComposite); filterComposite.setLayout(new GridLayout(1, false)); Composite filterComposite_1 = new Composite(filterComposite, SWT.NONE); GridData gd_filterComposite_1 = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_filterComposite_1.widthHint = 768; gd_filterComposite_1.heightHint = 474; filterComposite_1.setLayoutData(gd_filterComposite_1); formToolkit.adapt(filterComposite_1); formToolkit.paintBordersFor(filterComposite_1); filterComposite_1.setLayout(new GridLayout(3, false)); Label lblActiveFilters = new Label(filterComposite_1, SWT.NONE); lblActiveFilters.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblActiveFilters, true, true); lblActiveFilters.setText("Active Filters"); new Label(filterComposite_1, SWT.NONE); Label lblInactiveFilters = new Label(filterComposite_1, SWT.NONE); lblInactiveFilters.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblInactiveFilters, true, true); lblInactiveFilters.setText("Inactive Filters"); //Active Filter composite Composite filterActiveComposite = new Composite(filterComposite_1, SWT.NONE); GridData gd_filterActiveComposite = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_filterActiveComposite.heightHint = 465; gd_filterActiveComposite.widthHint = 333; filterActiveComposite.setLayoutData(gd_filterActiveComposite); formToolkit.adapt(filterActiveComposite); formToolkit.paintBordersFor(filterActiveComposite); filterActiveComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); // Active filter list viewer filterActiveListViewer = new ListViewer(filterActiveComposite, SWT.BORDER | SWT.V_SCROLL); List filterActiveList = filterActiveListViewer.getList(); java.util.List<Filter> f = account.getActiveFilters(); for(Filter fil: f){ filterActiveList.add(fil.toString()); } if(account.getGroup()!= Group.STANDARD){ f = account.getDefaultFilters(); for(Filter fil : f){ filterActiveList.add(fil.toString()); } } //Filter middle button bar Composite filterBtnComposite = new Composite(filterComposite_1, SWT.NONE); filterBtnComposite.setLayout(new FillLayout(SWT.VERTICAL)); GridData gd_filterBtnComposite = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_filterBtnComposite.heightHint = 465; gd_filterBtnComposite.widthHint = 85; filterBtnComposite.setLayoutData(gd_filterBtnComposite); formToolkit.adapt(filterBtnComposite); formToolkit.paintBordersFor(filterBtnComposite); Composite filterBtnComposite_NORTH = new Composite(filterBtnComposite, SWT.NONE); formToolkit.adapt(filterBtnComposite_NORTH); formToolkit.paintBordersFor(filterBtnComposite_NORTH); Composite filterBtnComposite_CENTER = new Composite(filterBtnComposite, SWT.NONE); formToolkit.adapt(filterBtnComposite_CENTER); formToolkit.paintBordersFor(filterBtnComposite_CENTER); filterBtnComposite_CENTER.setLayout(new FillLayout(SWT.HORIZONTAL)); //Add from inactive to active Button btnAdd = new Button(filterBtnComposite_CENTER, SWT.NONE); formToolkit.adapt(btnAdd, true, true); btnAdd.setText("<"); //Remove from active to inactive Button btnRemove = new Button(filterBtnComposite_CENTER, SWT.NONE); formToolkit.adapt(btnRemove, true, true); btnRemove.setText(">"); Composite filterBtnComposite_SOUTH = new Composite(filterBtnComposite, SWT.NONE); formToolkit.adapt(filterBtnComposite_SOUTH); formToolkit.paintBordersFor(filterBtnComposite_SOUTH); //Inactive filter composite Composite filterInactiveComposite = new Composite(filterComposite_1, SWT.NONE); GridData gd_filterInactiveComposite = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1); gd_filterInactiveComposite.heightHint = 465; gd_filterInactiveComposite.widthHint = 333; filterInactiveComposite.setLayoutData(gd_filterInactiveComposite); formToolkit.adapt(filterInactiveComposite); formToolkit.paintBordersFor(filterInactiveComposite); filterInactiveComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); //Inactive List viewer filterInactiveListViewer = new ListViewer(filterInactiveComposite, SWT.BORDER | SWT.V_SCROLL); List filterInactiveList = filterInactiveListViewer.getList(); java.util.List<Filter> fml = account.getInactiveFilters(); for(Filter fil: fml){ filterInactiveList.add(fil.toString()); } //Filter Button Bar Composite filterBtnBarComposite = new Composite(filterComposite, SWT.NONE); filterBtnBarComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); GridData gd_filterBtnBarComposite = new GridData(SWT.LEFT, SWT.BOTTOM, true, true, 1, 1); gd_filterBtnBarComposite.widthHint = 771; gd_filterBtnBarComposite.heightHint = 28; filterBtnBarComposite.setLayoutData(gd_filterBtnBarComposite); formToolkit.adapt(filterBtnBarComposite); formToolkit.paintBordersFor(filterBtnBarComposite); //Create filter btnCreate = new Button(filterBtnBarComposite, SWT.NONE); formToolkit.adapt(btnCreate, true, true); btnCreate.setText(CREATE); //Create filter button listener. Open blank text area. btnCreate.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: btnCreateHandleEvent(); } } } ); if(!account.getPermissions().contains(Permission.CREATEFILTER)){ btnCreate.setEnabled(false); } //Add Filter from inactive to active list btnAdd.addListener(SWT.Selection, new Listener(){ @Override public void handleEvent(Event event) { switch(event.type){ case SWT.Selection: btnAddHandleEvent(); } } }); btnRemove.addListener(SWT.Selection, new Listener(){ @Override public void handleEvent(Event event) { switch(event.type){ case SWT.Selection: btnRemoveHandleEvent(); } } }); //Edit filter btnEdit = new Button(filterBtnBarComposite, SWT.NONE); formToolkit.adapt(btnEdit, true, true); btnEdit.setText(EDIT); //Create filter button listener. Open text area with highlighted filters text. btnEdit.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: btnEditHandleEvent(); } } } ); if(!account.getPermissions().contains(Permission.EDITFILTER)){ btnEdit.setEnabled(false); } //Delete filter btnDelete = new Button(filterBtnBarComposite, SWT.NONE); formToolkit.adapt(btnDelete, true, true); btnDelete.setText("Delete"); btnDelete.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch(e.type){ case SWT.Selection: btnDeleteHandleEvent(); } } }); if(!account.getPermissions().contains(Permission.DELETEFILTER)){ btnDelete.setEnabled(false); } //----------------------------------------------------------------- //Administrator Tab //----------------------------------------------------------------- if(account.getGroup()==Group.ADMINISTRATOR){ CTabItem tbtmAdministrator = new CTabItem(tabFolder, SWT.NONE); tbtmAdministrator.setText("Administrator"); Composite admComposite = new Composite(tabFolder, SWT.NONE); tbtmAdministrator.setControl(admComposite); formToolkit.paintBordersFor(admComposite); admComposite.setLayout(new GridLayout(3, false)); Label lblAccounts = new Label(admComposite, SWT.NONE); lblAccounts.setAlignment(SWT.CENTER); GridData gd_lblAccounts = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1); gd_lblAccounts.widthHint = 256; lblAccounts.setLayoutData(gd_lblAccounts); formToolkit.adapt(lblAccounts, true, true); lblAccounts.setText("Accounts"); //Active Filter label Label lblNewLabel = new Label(admComposite, SWT.NONE); lblNewLabel.setAlignment(SWT.CENTER); GridData gd_lblNewLabel = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1); gd_lblNewLabel.widthHint = 255; lblNewLabel.setLayoutData(gd_lblNewLabel); formToolkit.adapt(lblNewLabel, true, true); lblNewLabel.setText("Active Filters"); //Inactive filter label Label lblNewLabel_1 = new Label(admComposite, SWT.NONE); lblNewLabel_1.setAlignment(SWT.CENTER); lblNewLabel_1.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); formToolkit.adapt(lblNewLabel_1, true, true); lblNewLabel_1.setText("Inactive Filters"); Composite admTableTreeComposite = new Composite(admComposite, SWT.NONE); GridData gd_admTableTreeComposite = new GridData(SWT.LEFT, SWT.TOP, true, true, 3, 1); gd_admTableTreeComposite.heightHint = 484; gd_admTableTreeComposite.widthHint = 778; admTableTreeComposite.setLayoutData(gd_admTableTreeComposite); formToolkit.adapt(admTableTreeComposite); formToolkit.paintBordersFor(admTableTreeComposite); admTableTreeComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); // Account viewer AccountListViewer = new ListViewer(admTableTreeComposite, SWT.BORDER | SWT.V_SCROLL); final List AccountList = AccountListViewer.getList(); AccountList.add("Administrator"); AccountList.add("Power"); AccountList.add("Standard"); //TODO set active list to selections current active filters ListViewer activeViewer = new ListViewer(admTableTreeComposite, SWT.BORDER | SWT.V_SCROLL); final List activeList = activeViewer.getList(); //TODO set inactive list to selections current inactive filters ListViewer inactiveViewer = new ListViewer(admTableTreeComposite, SWT.BORDER | SWT.V_SCROLL); final List inactiveList = inactiveViewer.getList(); // Administrator button bar Composite admBtnBarComposite = formToolkit.createComposite(admComposite, SWT.NONE); GridData gd_admBtnBarComposite = new GridData(SWT.LEFT, SWT.TOP, true, false, 3, 1); gd_admBtnBarComposite.widthHint = 779; gd_admBtnBarComposite.heightHint = 28; admBtnBarComposite.setLayoutData(gd_admBtnBarComposite); formToolkit.paintBordersFor(admBtnBarComposite); admBtnBarComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); //Create an Account Button admBtnCreate = new Button(admBtnBarComposite, SWT.NONE); formToolkit.adapt(admBtnCreate, true, true); admBtnCreate.setText(CREATE); admBtnCreate.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: Shell accShell = new Shell(display); accountShell(accShell); } } } ); //TODO implement user group edit/accounts //Edit User Groups/Accounts Button admBtnEdit = new Button(admBtnBarComposite, SWT.NONE); formToolkit.adapt(admBtnEdit, true, true); admBtnEdit.setText(EDIT); admBtnEdit.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: Accounts acc = new Accounts(); acc.loadAccounts(); try{ String selection = AccountList.getSelection()[0].trim(); Account a =acc.getAccount(selection); if(a == null){ if(Group.valueOf(selection.toUpperCase())!= null){ editUserGroup(Group.valueOf(selection.toUpperCase())); } } else{ //editShell(a,"Administrator"); //TODO If an account is selected editUserAccount(a); } //TODO If a user group is selected //editUserGroup(group); }catch(ArrayIndexOutOfBoundsException ex){ } catch(IllegalArgumentException ex){} } } } ); //Delete User Accounts final Button admBtnDelete = new Button(admBtnBarComposite, SWT.NONE); formToolkit.adapt(admBtnDelete, true, true); admBtnDelete.setText("Delete"); admBtnDelete.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch(e.type){ case SWT.Selection: Accounts acc = new Accounts(); acc.loadAccounts(); Account a =acc.getAccount(AccountList.getSelection()[0].trim()); if(a!=null){ if(!a.getName().equals(account.getName())){ acc.removeAccount(a); acc.saveAccounts(); AccountList.removeAll(); AccountList.add("Administrator"); AccountList.add("Power"); AccountList.add("Standard"); for(Account ac: acc){ AccountList.add(ac.getName()); } } } else System.err.println("No account selected"); } } }); AccountListViewer.addSelectionChangedListener(new ISelectionChangedListener(){ @Override public void selectionChanged(SelectionChangedEvent e) { try{ String selection = AccountList.getSelection()[0].trim(); if(selection.equals("Administrator")||selection.equals("Power")||selection.equals("Standard")){ activeList.removeAll(); inactiveList.removeAll(); admBtnDelete.setEnabled(false); } else if(accounts.getAccount(selection)!=null){ Account acc = accounts.getAccount(selection); activeList.removeAll(); inactiveList.removeAll(); for(Filter f: acc.getActiveFilters()) activeList.add(f.getName()); for(Filter f: acc.getInactiveFilters()) inactiveList.add(f.getName()); if(acc.getName().equals(account.getName())) admBtnDelete.setEnabled(false); else admBtnDelete.setEnabled(true); } else admBtnDelete.setEnabled(true); }catch(ArrayIndexOutOfBoundsException ex){ } } }); Accounts a = new Accounts(); a.loadAccounts(); for(Account acc: a){ if(acc.getGroup()==Group.ADMINISTRATOR) AccountList.add("\t"+acc.getName()); } for(Account acc: a){ if(acc.getGroup()==Group.POWER) AccountList.add("\t"+acc.getName()); } for(Account acc: a){ if(acc.getGroup()==Group.STANDARD) AccountList.add("\t"+acc.getName()); } } //----------------------------------------------------------------- //Main menu bar //----------------------------------------------------------------- Menu menu = new Menu(shlButterfly, SWT.BAR); shlButterfly.setMenuBar(menu); // Menu Bar Main MenuItem mntmMain = new MenuItem(menu, SWT.CASCADE); mntmMain.setText("Main"); Menu menu_main = new Menu(mntmMain); mntmMain.setMenu(menu_main); /* commented this out because we moved it but I'm leaving this here for now //Listen if the user is not a standard user if (account.getGroup() != Group.STANDARD) { final MenuItem mntmListen = new MenuItem(menu_main, SWT.CHECK); //Set Listen to default on mntmListen.setSelection(false); mntmListen.setText("Listen"); mntmListen.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ if (mntmListen.getSelection()) { //TODO turn on the proxy System.out.println("Checked"); } else { //TODO turn off the proxy System.out.println("Uncheck"); } } }); }*/ //Import MenuItem mntmImport = new MenuItem(menu_main, SWT.NONE); mntmImport.setText(IMPORT); mntmImport.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: impExpShell(account, IMPORT); } } } ); //Export MenuItem mntmExport = new MenuItem(menu_main, SWT.NONE); mntmExport.setText(EXPORT); mntmExport.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: impExpShell(account, EXPORT); } } } ); //Logout MenuItem mntmNewItem = new MenuItem(menu_main, SWT.NONE); mntmNewItem.setText("Logout"); mntmNewItem.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: //TODO Logout, currently I (Zong) implemented this naive way of doing it. Please correct it if its wrong if (server != null && server.isRunning()) { server.stop(); } if (!shlButterfly.isDisposed()) { shlButterfly.dispose(); } open(); } } } ); //Quit MenuItem mntmQuit = new MenuItem(menu_main, SWT.NONE); mntmQuit.setText("Quit"); mntmQuit.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e){ switch (e.type){ case SWT.Selection: if (!shlButterfly.isDisposed()) { shlButterfly.dispose(); } } } }); // Menu Bar Settings MenuItem mntmSettings = new MenuItem(menu, SWT.CASCADE); mntmSettings.setText("Settings"); Menu menu_settings = new Menu(mntmSettings); mntmSettings.setMenu(menu_settings); //Change Password MenuItem mntmChangePassword = new MenuItem(menu_settings, SWT.NONE); mntmChangePassword.setText("Change Password"); mntmChangePassword.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e) { Shell aShell = new Shell(display); changePassword(aShell, account.getName(), account.getGroup()); } }); // Initialize proxy log items to settings previously set ProxyLog.setLogEnabled(accounts.isLogEnabled()); if (accounts.isDialogEnabled()) { ProxyLog.setDialogText(textAreaDialog); } if (accounts.isConnectionListEnabled()) { ProxyLog.setConnectionText(textAreaConnectionList); } if (account.getGroup()==Group.ADMINISTRATOR || accounts.isDialogEnabled()) { MenuItem mntmLogging = new MenuItem(menu, SWT.CASCADE); mntmLogging.setText("Logging"); Menu menu_logging = new Menu(mntmLogging); mntmLogging.setMenu(menu_logging); /* * Menu Item for Clear Dialog */ final MenuItem mntmClearDialog = new MenuItem(menu_logging, SWT.NONE); mntmClearDialog.setText("Clear Dialog"); // Listener for selection of Clear Dialog mntmClearDialog.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e) { ProxyLog.clearDialog(); } }); if (account.getGroup()==Group.ADMINISTRATOR) { /* * MenuItem for Enable Log */ final MenuItem mntmEnableLogging = new MenuItem(menu_logging, SWT.CHECK); mntmEnableLogging.setText("Enable Log"); // Load default/previous setting mntmEnableLogging.setSelection(accounts.isLogEnabled()); // Listener for selection of Enable Log mntmEnableLogging.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e) { ProxyLog.setLogEnabled(mntmEnableLogging.getSelection()); accounts.setLogEnabled(mntmEnableLogging.getSelection()); accounts.saveAccounts(); } }); /* * MenuItem for Enable Dialog */ final MenuItem mntmNewCheckbox = new MenuItem(menu_logging, SWT.CHECK); mntmNewCheckbox.setText("Enable Dialog"); // Load default/previous setting mntmNewCheckbox.setSelection(accounts.isDialogEnabled()); // Listener for selection of Enable Dialog mntmNewCheckbox.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e) { if (mntmNewCheckbox.getSelection() == true) { ProxyLog.setDialogText(textAreaDialog); accounts.setDialogEnabled(true); } else { ProxyLog.setDialogText(null); accounts.setDialogEnabled(false); } accounts.saveAccounts(); } }); /* * Menu Item for Connection List */ final MenuItem mntmEnableConnectionList = new MenuItem(menu_logging, SWT.CHECK); mntmEnableConnectionList.setText("Enable Connection List"); // Load default/previous setting mntmEnableConnectionList.setSelection(accounts.isConnectionListEnabled()); // Listener for selection of Enable Connection List mntmEnableConnectionList.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event e) { if (mntmEnableConnectionList.getSelection() == true) { ProxyLog.setConnectionText(textAreaConnectionList); accounts.setConnectionListEnabled(true); } else { ProxyLog.setConnectionText(null); accounts.setConnectionListEnabled(false); } accounts.saveAccounts(); } }); } } }
diff --git a/org.rubypeople.rdt.ui/src/org/rubypeople/rdt/internal/ui/text/RubyWordFinder.java b/org.rubypeople.rdt.ui/src/org/rubypeople/rdt/internal/ui/text/RubyWordFinder.java index 0c75586c..6af23387 100644 --- a/org.rubypeople.rdt.ui/src/org/rubypeople/rdt/internal/ui/text/RubyWordFinder.java +++ b/org.rubypeople.rdt.ui/src/org/rubypeople/rdt/internal/ui/text/RubyWordFinder.java @@ -1,82 +1,83 @@ /******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.rubypeople.rdt.internal.ui.text; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Region; public class RubyWordFinder { /** * The characters which mark the end of a "word" in Ruby. Essentially these * are what break up the tokens for double-clicking and for hovers. */ private static final char[] BOUNDARIES = { ' ', '\n', '\t', '\r', '.', '(', ')', '{', '}', '[', ']', '=', '*', '+', '-', '"', '\'', '#', ','}; public static IRegion findWord(IDocument document, int offset) { int start = -1; int end = -1; try { int pos = offset; char c; while (pos >= 0) { c = document.getChar(pos); if (!isRubyWordPart(c)) break; --pos; } start = pos; pos = offset; int length = document.getLength(); while (pos < length) { c = document.getChar(pos); if (!isRubyWordPart(c)) break; ++pos; } end = pos; } catch (BadLocationException x) { + return null; } - if (start > -1 && end > -1) { + if (start >= -1 && end > -1) { if (start == offset && end == offset) return new Region(offset, 0); else if (start == offset) return new Region(start, end - start); else return new Region(start + 1, end - start - 1); } return null; } private static boolean isRubyWordPart(char c) { return !isBoundary(c); } private static boolean isBoundary(char c) { return contains(BOUNDARIES, c); } private static boolean contains(char[] boundaries2, char c) { if (boundaries2 == null || boundaries2.length == 0) return false; for (int i = 0; i < boundaries2.length; i++) { if (boundaries2[i] == c) return true; } return false; } }
false
true
public static IRegion findWord(IDocument document, int offset) { int start = -1; int end = -1; try { int pos = offset; char c; while (pos >= 0) { c = document.getChar(pos); if (!isRubyWordPart(c)) break; --pos; } start = pos; pos = offset; int length = document.getLength(); while (pos < length) { c = document.getChar(pos); if (!isRubyWordPart(c)) break; ++pos; } end = pos; } catch (BadLocationException x) { } if (start > -1 && end > -1) { if (start == offset && end == offset) return new Region(offset, 0); else if (start == offset) return new Region(start, end - start); else return new Region(start + 1, end - start - 1); } return null; }
public static IRegion findWord(IDocument document, int offset) { int start = -1; int end = -1; try { int pos = offset; char c; while (pos >= 0) { c = document.getChar(pos); if (!isRubyWordPart(c)) break; --pos; } start = pos; pos = offset; int length = document.getLength(); while (pos < length) { c = document.getChar(pos); if (!isRubyWordPart(c)) break; ++pos; } end = pos; } catch (BadLocationException x) { return null; } if (start >= -1 && end > -1) { if (start == offset && end == offset) return new Region(offset, 0); else if (start == offset) return new Region(start, end - start); else return new Region(start + 1, end - start - 1); } return null; }
diff --git a/src/com/tactfactory/mda/plateforme/SqliteAdapter.java b/src/com/tactfactory/mda/plateforme/SqliteAdapter.java index f3d483a0..7d4dd3a8 100644 --- a/src/com/tactfactory/mda/plateforme/SqliteAdapter.java +++ b/src/com/tactfactory/mda/plateforme/SqliteAdapter.java @@ -1,313 +1,313 @@ /** * This file is part of the Harmony package. * * (c) Mickael Gaillard <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ package com.tactfactory.mda.plateforme; import java.lang.reflect.Field; import com.tactfactory.mda.annotation.Column; import com.tactfactory.mda.annotation.Column.Type; import com.tactfactory.mda.meta.FieldMetadata; import com.tactfactory.mda.utils.ConsoleUtils; /** * SQliteAdapter. */ public abstract class SqliteAdapter { /** Prefix for column name generation. */ private static final String PREFIX = "COL_"; /** Suffix for column name generation. */ private static final String SUFFIX = "_ID"; /** * Generate field's structure for database creation schema. * @param fm The field * @return The field's structure */ public static String generateStructure(final FieldMetadata fm) { final StringBuilder builder = new StringBuilder(); builder.append(' '); builder.append(generateColumnType(fm.getColumnDefinition())); if (fm.isId()) { builder.append(" PRIMARY KEY"); - if (fm.getColumnDefinition().equals("INTEGER")) { + if (fm.getColumnDefinition().equalsIgnoreCase("INTEGER")) { builder.append(" AUTOINCREMENT"); } } else { // Set Length final Type fieldType = Type.fromName(fm.getType()); if (fieldType != null) { if (fm.getLength() != null && fm.getLength() != fieldType.getLength()) { builder.append('('); builder.append(fm.getLength()); builder.append(')'); } else if (fm.getPrecision() != null && fm.getPrecision() != fieldType.getPrecision()) { builder.append('('); builder.append(fm.getPrecision()); if (fm.getScale() != null && fm.getScale() != fieldType.getScale()) { builder.append(','); builder.append(fm.getScale()); } builder.append(')'); } } // Set Unique if (fm.isUnique() != null && fm.isUnique()) { builder.append(" UNIQUE"); } // Set Nullable if (fm.isNullable() == null || !fm.isNullable()) { builder.append(" NOT NULL"); } } return builder.toString(); } /** * Generate the column type for a given harmony type. * @param fieldType The harmony type of a field. * @return The columnType for SQLite */ public static String generateColumnType(final String fieldType) { String type = fieldType; if (type.equalsIgnoreCase(Column.Type.STRING.getValue()) || type.equalsIgnoreCase(Column.Type.TEXT.getValue()) || type.equalsIgnoreCase(Column.Type.LOGIN.getValue()) || type.equalsIgnoreCase(Column.Type.PHONE.getValue()) || type.equalsIgnoreCase(Column.Type.PASSWORD.getValue()) || type.equalsIgnoreCase(Column.Type.EMAIL.getValue()) || type.equalsIgnoreCase(Column.Type.CITY.getValue()) || type.equalsIgnoreCase(Column.Type.ZIPCODE.getValue()) || type.equalsIgnoreCase(Column.Type.COUNTRY.getValue())) { type = "VARCHAR"; } else if (type.equalsIgnoreCase(Column.Type.DATETIME.getValue())) { type = "DATETIME"; } else if (type.equalsIgnoreCase(Column.Type.DATE.getValue())) { type = "DATE"; } else if (type.equalsIgnoreCase(Column.Type.TIME.getValue())) { type = "DATETIME"; } else if (type.equalsIgnoreCase(Column.Type.BOOLEAN.getValue())) { type = "BOOLEAN"; } else if (type.equalsIgnoreCase(Column.Type.INTEGER.getValue()) || type.equalsIgnoreCase(Column.Type.INT.getValue()) || type.equalsIgnoreCase(Column.Type.BC_EAN.getValue())) { type = "INTEGER"; } else if (type.equalsIgnoreCase(Column.Type.FLOAT.getValue())) { type = "FLOAT"; } return type; } /** * Generate a column name. * @param fieldName The original field's name * @return the generated column name */ public static String generateColumnName(final String fieldName) { return PREFIX + fieldName.toUpperCase(); } /** * Generate a relation column name. * @param fieldName The original field's name * @return the generated column name */ public static String generateRelationColumnName(final String fieldName) { return PREFIX + fieldName.toUpperCase() + SUFFIX; } /** * Generate a column definition. * @param type The original field's type * @return the generated column definition */ public static String generateColumnDefinition(final String type) { String ret = type; if (type.equalsIgnoreCase("int")) { ret = "integer"; } return ret; } /** * SQLite Reserved keywords. */ public static enum Keywords { // CHECKSTYLE:OFF ABORT, ACTION, ADD, AFTER, ALL, ALTER, ANALYZE, AND, AS, ASC, ATTACH, AUTOINCREMENT, BEFORE, BEGIN, BETWEEN, BY, CASCADE, CASE, CAST, CHECK, COLLATE, COLUMN, COMMIT, CONFLICT, CONSTRAINT, CREATE, CROSS, CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP, DATABASE, DEFAULT, DEFERRABLE, DEFERRED, DELETE, DESC, DETACH, DISTINCT, DROP, EACH, ELSE, END, ESCAPE, EXCEPT, EXCLUSIVE, EXISTS, EXPLAIN, FAIL, FOR, FOREIGN, FROM, FULL, GLOB, GROUP, HAVING, IF, IGNORE, IMMEDIATE, IN, INDEX, INDEXED, INITIALLY, INNER, INSERT, INSTEAD, INTERSECT, INTO, IS, ISNULL, JOIN, KEY, LEFT, LIKE, LIMIT, MATCH, NATURAL, NO, NOT, NOTNULL, NULL, OF, OFFSET, ON, OR, ORDER, OUTER, PLAN, PRAGMA, PRIMARY, QUERY, RAISE, REFERENCES, REGEXP, REINDEX, RELEASE, RENAME, REPLACE, RESTRICT, RIGHT, ROLLBACK, ROW, SAVEPOINT, SELECT, SET, TABLE, TEMP, TEMPORARY, THEN, TO, TRANSACTION, TRIGGER, UNION, UNIQUE, UPDATE, USING, VACUUM, VALUES, VIEW, VIRTUAL, WHEN, WHERE; // CHECKSTYLE:ON /** * Tests if the given String is a reserverd SQLite keyword. * @param name The string * @return True if it is */ public static boolean exists(final String name) { boolean exists = false; try { final Field field = Keywords.class.getField(name.toUpperCase()); if (field.isEnumConstant()) { ConsoleUtils.displayWarning( name + " is a reserved SQLite keyword." + " You may have problems with" + " your database schema."); exists = true; } else { exists = false; } } catch (final NoSuchFieldException e) { exists = false; } return exists; } } }
true
true
public static String generateStructure(final FieldMetadata fm) { final StringBuilder builder = new StringBuilder(); builder.append(' '); builder.append(generateColumnType(fm.getColumnDefinition())); if (fm.isId()) { builder.append(" PRIMARY KEY"); if (fm.getColumnDefinition().equals("INTEGER")) { builder.append(" AUTOINCREMENT"); } } else { // Set Length final Type fieldType = Type.fromName(fm.getType()); if (fieldType != null) { if (fm.getLength() != null && fm.getLength() != fieldType.getLength()) { builder.append('('); builder.append(fm.getLength()); builder.append(')'); } else if (fm.getPrecision() != null && fm.getPrecision() != fieldType.getPrecision()) { builder.append('('); builder.append(fm.getPrecision()); if (fm.getScale() != null && fm.getScale() != fieldType.getScale()) { builder.append(','); builder.append(fm.getScale()); } builder.append(')'); } } // Set Unique if (fm.isUnique() != null && fm.isUnique()) { builder.append(" UNIQUE"); } // Set Nullable if (fm.isNullable() == null || !fm.isNullable()) { builder.append(" NOT NULL"); } } return builder.toString(); }
public static String generateStructure(final FieldMetadata fm) { final StringBuilder builder = new StringBuilder(); builder.append(' '); builder.append(generateColumnType(fm.getColumnDefinition())); if (fm.isId()) { builder.append(" PRIMARY KEY"); if (fm.getColumnDefinition().equalsIgnoreCase("INTEGER")) { builder.append(" AUTOINCREMENT"); } } else { // Set Length final Type fieldType = Type.fromName(fm.getType()); if (fieldType != null) { if (fm.getLength() != null && fm.getLength() != fieldType.getLength()) { builder.append('('); builder.append(fm.getLength()); builder.append(')'); } else if (fm.getPrecision() != null && fm.getPrecision() != fieldType.getPrecision()) { builder.append('('); builder.append(fm.getPrecision()); if (fm.getScale() != null && fm.getScale() != fieldType.getScale()) { builder.append(','); builder.append(fm.getScale()); } builder.append(')'); } } // Set Unique if (fm.isUnique() != null && fm.isUnique()) { builder.append(" UNIQUE"); } // Set Nullable if (fm.isNullable() == null || !fm.isNullable()) { builder.append(" NOT NULL"); } } return builder.toString(); }
diff --git a/src/net/sf/freecol/client/control/ConnectController.java b/src/net/sf/freecol/client/control/ConnectController.java index 2e4b1d9f4..0e9c0cd01 100644 --- a/src/net/sf/freecol/client/control/ConnectController.java +++ b/src/net/sf/freecol/client/control/ConnectController.java @@ -1,524 +1,524 @@ package net.sf.freecol.client.control; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.net.ConnectException; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import javax.swing.SwingUtilities; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import net.sf.freecol.FreeCol; 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.client.networking.Client; import net.sf.freecol.common.FreeColException; import net.sf.freecol.common.ServerInfo; import net.sf.freecol.common.model.Game; import net.sf.freecol.common.model.Player; import net.sf.freecol.common.networking.Connection; import net.sf.freecol.common.networking.Message; import net.sf.freecol.server.FreeColServer; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * The controller responsible for starting a server and * connecting to it. {@link PreGameInputHandler} will be set * as the input handler when a successful login has been completed, */ public final class ConnectController { private static final Logger logger = Logger.getLogger(ConnectController.class.getName()); public static final String COPYRIGHT = "Copyright (C) 2003-2005 The FreeCol Team"; public static final String LICENSE = "http://www.gnu.org/licenses/gpl.html"; public static final String REVISION = "$Revision$"; private final FreeColClient freeColClient; /** * Creates a new <code>ConnectController</code>. * @param freeColClient The main controller. */ public ConnectController(FreeColClient freeColClient) { this.freeColClient = freeColClient; } /** * Starts a multiplayer server and connects to it. * * @param publicServer Should this server be listed at the meta server. * @param username The name to use when logging in. * @param port The port in which the server should listen for new clients. */ public void startMultiplayerGame(boolean publicServer, String username, int port) { if (freeColClient.isLoggedIn()) { logout(true); } if (freeColClient.getFreeColServer() != null && freeColClient.getFreeColServer().getServer().getPort() == port) { if (freeColClient.getCanvas().showConfirmDialog("stopServer.text", "stopServer.yes", "stopServer.no")) { freeColClient.getFreeColServer().getController().shutdown(); } else { return; } } try { FreeColServer freeColServer = new FreeColServer(publicServer, false, port, null); freeColClient.setFreeColServer(freeColServer); } catch (IOException e) { freeColClient.getCanvas().errorMessage("server.couldNotStart"); return; } joinMultiplayerGame(username, "localhost", port); } /** * Starts a new singleplayer game by connecting to the server. * * @param username The name to use when logging in. */ public void startSingleplayerGame(String username) { if (freeColClient.isLoggedIn()) { logout(true); } // TODO-MUCH-LATER: connect client/server directly (not using network-classes) int port = 3541; if (freeColClient.getFreeColServer() != null && freeColClient.getFreeColServer().getServer().getPort() == port) { if (freeColClient.getCanvas().showConfirmDialog("stopServer.text", "stopServer.yes", "stopServer.no")) { freeColClient.getFreeColServer().getController().shutdown(); } else { return; } } try { FreeColServer freeColServer = new FreeColServer(false, true, port, null); freeColClient.setFreeColServer(freeColServer); } catch (IOException e) { freeColClient.getCanvas().errorMessage("server.couldNotStart"); return; } freeColClient.setSingleplayer(true); boolean loggedIn = login(username, "127.0.0.1", 3541); if (loggedIn) { freeColClient.getPreGameController().setReady(true); freeColClient.getCanvas().showStartGamePanel(freeColClient.getGame(), freeColClient.getMyPlayer(), true); } } /** * Starts a new multiplayer game by connecting to the server. * * @param username The name to use when logging in. * @param host The name of the machine running the <code>FreeColServer</code>. * @param port The port to use when connecting to the host. */ public void joinMultiplayerGame(String username, String host, int port) { final Canvas canvas = freeColClient.getCanvas(); if (freeColClient.isLoggedIn()) { logout(true); } List vacantPlayers = getVacantPlayers(host, port); if (vacantPlayers != null) { Object choice = canvas.showChoiceDialog(Messages.message("connectController.choicePlayer"), Messages.message("cancel"), vacantPlayers.iterator()); if (choice != null) { username = (String) choice; } else { return; } } freeColClient.setSingleplayer(false); if (login(username, host, port) && !freeColClient.getGUI().isInGame()) { canvas.showStartGamePanel(freeColClient.getGame(), freeColClient.getMyPlayer(), false); } } /** * Starts the client and connects to <i>host:port</i>. * * @param username The name to use when logging in. This should be a unique identifier. * @param host The name of the machine running the <code>FreeColServer</code>. * @param port The port to use when connecting to the host. * @return <i>true</i> if the login was completed successfully. */ private boolean login(String username, String host, int port) { Client client = freeColClient.getClient(); Canvas canvas = freeColClient.getCanvas(); if (client != null) { client.disconnect(); } try { client = new Client(host, port, freeColClient.getPreGameInputHandler()); } catch (ConnectException e) { canvas.errorMessage("server.couldNotConnect"); return false; } catch (IOException e) { canvas.errorMessage("server.couldNotConnect"); return false; } freeColClient.setClient(client); Connection c = client.getConnection(); XMLStreamReader in = null; try { XMLStreamWriter out = c.ask(); out.writeStartElement("login"); out.writeAttribute("username", username); out.writeAttribute("freeColVersion", FreeCol.getVersion()); out.writeEndElement(); in = c.getReply(); if (in.getLocalName().equals("loginConfirmed")) { final String startGameStr = in.getAttributeValue(null, "startGame"); boolean startGame = (startGameStr != null) && Boolean.valueOf(startGameStr).booleanValue(); boolean isCurrentPlayer = Boolean.valueOf(in.getAttributeValue(null, "isCurrentPlayer")).booleanValue(); in.nextTag(); Game game = new Game(freeColClient.getModelController(), in, username); Player thisPlayer = game.getPlayerByName(username); freeColClient.setGame(game); freeColClient.setMyPlayer(thisPlayer); + c.endTransmission(in); // If (true) --> reconnect if (startGame) { freeColClient.setSingleplayer(false); freeColClient.getPreGameController().startGame(); if (isCurrentPlayer) { freeColClient.getInGameController().setCurrentPlayer(thisPlayer); } } - c.endTransmission(in); } else if (in.getLocalName().equals("error")) { canvas.errorMessage(in.getAttributeValue(null, "messageID"), in.getAttributeValue(null, "message")); c.endTransmission(in); return false; } else { logger.warning("Unkown message received: " + in.getLocalName()); c.endTransmission(in); return false; } } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); logger.warning(sw.toString()); canvas.errorMessage(null, "Could not send XML to the server."); try { c.endTransmission(in); } catch (IOException ie) { logger.warning("Exception while trying to end transmission: " + ie.toString()); } } freeColClient.setLoggedIn(true); return true; } /** * Reconnects to the server. */ public void reconnect() { final String username = freeColClient.getMyPlayer().getUsername(); final String host = freeColClient.getClient().getHost(); final int port = freeColClient.getClient().getPort(); freeColClient.getCanvas().removeInGameComponents(); logout(true); login(username, host, port); } /** * Opens a dialog where the user should specify the filename * and loads the game. */ public void loadGame() { File file = freeColClient.getCanvas().showLoadDialog(FreeCol.getSaveDirectory()); if (file != null) { loadGame(file); } } /** * Loads a game from the given file. * @param file The <code>File</code>. */ public void loadGame(File file) { final Canvas canvas = freeColClient.getCanvas(); final int port = 3541; if (freeColClient.getFreeColServer() != null && freeColClient.getFreeColServer().getServer().getPort() == port) { if (freeColClient.getCanvas().showConfirmDialog("stopServer.text", "stopServer.yes", "stopServer.no")) { freeColClient.getFreeColServer().getController().shutdown(); } else { return; } } canvas.showStatusPanel(Messages.message("status.loadingGame")); final File theFile = file; Runnable loadGameJob = new Runnable() { public void run() { class ErrorJob implements Runnable { private final String message; ErrorJob( String message ) { this.message = message; } public void run() { canvas.closeMenus(); canvas.errorMessage( message ); } }; FreeColServer freeColServer = null; try { freeColServer = new FreeColServer( theFile, port ); freeColClient.setFreeColServer( freeColServer ); final String username = freeColServer.getOwner(); freeColClient.setSingleplayer( freeColServer.isSingleplayer() ); SwingUtilities.invokeLater( new Runnable() { public void run() { login( username, "127.0.0.1", 3541 ); canvas.closeStatusPanel(); } } ); } catch ( FileNotFoundException e ) { SwingUtilities.invokeLater( new ErrorJob("fileNotFound") ); if (freeColServer != null) { freeColServer.getServer().shutdown(); } } catch ( IOException e ) { SwingUtilities.invokeLater( new ErrorJob("server.couldNotStart") ); if (freeColServer != null) { freeColServer.getServer().shutdown(); } } catch ( FreeColException e ) { SwingUtilities.invokeLater( new ErrorJob(e.getMessage()) ); if (freeColServer != null) { freeColServer.getServer().shutdown(); } } } }; freeColClient.worker.schedule( loadGameJob ); } /** * Sends a logout message to the server. * * @param notifyServer Whether or not the server should be notified of the logout. * For example: if the server kicked us out then we don't need to confirm with a logout * message. */ public void logout(boolean notifyServer) { if (notifyServer) { Element logoutMessage = Message.createNewRootElement("logout"); logoutMessage.setAttribute("reason", "User has quit the client."); freeColClient.getClient().sendAndWait(logoutMessage); } try { freeColClient.getClient().getConnection().close(); } catch (IOException e) { logger.warning("Could not close connection!"); } freeColClient.getGUI().setInGame(false); freeColClient.setGame(null); freeColClient.setMyPlayer(null); freeColClient.setClient(null); freeColClient.setLoggedIn(false); } /** * Quits the current game. If a server is running it will be stopped if bStopServer is * <i>true</i>. * If a server is running through this client and bStopServer is true then the clients * connected to that server will be notified. If a local client is connected to a server * then the server will be notified with a logout in case <i>notifyServer</i> is true. * * @param bStopServer Indicates whether or not a server that was started through this * client should be stopped. * * @param notifyServer Whether or not the server should be notified of the logout. * For example: if the server kicked us out then we don't need to confirm with a logout * message. */ public void quitGame(boolean bStopServer, boolean notifyServer) { final FreeColServer server = freeColClient.getFreeColServer(); if (bStopServer && server != null) { server.getController().shutdown(); freeColClient.setFreeColServer(null); freeColClient.getGUI().setInGame(false); freeColClient.setGame(null); freeColClient.setMyPlayer(null); freeColClient.setClient(null); freeColClient.setLoggedIn(false); } else if (freeColClient.isLoggedIn()) { logout(notifyServer); } } /** * Quits the current game. If a server is running it will be stopped if bStopServer is * <i>true</i>. * The server and perhaps the clients (if a server is running through this client and * bStopServer is true) will be notified. * * @param bStopServer Indicates whether or not a server that was started through this * client should be stopped. */ public void quitGame(boolean bStopServer) { quitGame(bStopServer, true); } /** * Returns a list of vacant players on a given server. * * @param host The name of the machine running the <code>FreeColServer</code>. * @param port The port to use when connecting to the host. * @return A list of available {@link Player#getUsername() usernames}. */ private List getVacantPlayers(String host, int port) { Canvas canvas = freeColClient.getCanvas(); Connection mc; try { mc = new Connection(host, port, null); } catch (IOException e) { logger.warning("Could not connect to server."); return null; } List items = new ArrayList(); Element element = Message.createNewRootElement("getVacantPlayers"); try { Element reply = mc.ask(element); if (reply == null) { logger.warning("The server did not return a list."); return null; } if (!reply.getTagName().equals("vacantPlayers")) { logger.warning("The reply has an unknown type: " + reply.getTagName()); return null; } NodeList nl = reply.getChildNodes(); for (int i=0; i<nl.getLength(); i++) { items.add(((Element) nl.item(i)).getAttribute("username")); } } catch (IOException e) { logger.warning("Could not send message to server."); } finally { try { mc.close(); } catch (IOException e) { logger.warning("Could not close connection."); } } return items; } /** * Gets a list of servers from the meta server. * @return A list of {@link ServerInfo} objects. */ public ArrayList getServerList() { Canvas canvas = freeColClient.getCanvas(); Connection mc; try { mc = new Connection(FreeCol.META_SERVER_ADDRESS, FreeCol.META_SERVER_PORT, null); } catch (IOException e) { logger.warning("Could not connect to meta-server."); canvas.errorMessage("metaServer.couldNotConnect"); return null; } try { Element gslElement = Message.createNewRootElement("getServerList"); Element reply = mc.ask(gslElement); if (reply == null) { logger.warning("The meta-server did not return a list."); canvas.errorMessage("metaServer.communicationError"); return null; } else { ArrayList items = new ArrayList(); NodeList nl = reply.getChildNodes(); for (int i=0; i<nl.getLength(); i++) { items.add(new ServerInfo((Element) nl.item(i))); } return items; } } catch (IOException e) { logger.warning("Network error while communicating with the meta-server."); canvas.errorMessage("metaServer.communicationError"); return null; } finally { try { mc.close(); } catch (IOException e) { logger.warning("Could not close connection to meta-server."); return null; } } } }
false
true
private boolean login(String username, String host, int port) { Client client = freeColClient.getClient(); Canvas canvas = freeColClient.getCanvas(); if (client != null) { client.disconnect(); } try { client = new Client(host, port, freeColClient.getPreGameInputHandler()); } catch (ConnectException e) { canvas.errorMessage("server.couldNotConnect"); return false; } catch (IOException e) { canvas.errorMessage("server.couldNotConnect"); return false; } freeColClient.setClient(client); Connection c = client.getConnection(); XMLStreamReader in = null; try { XMLStreamWriter out = c.ask(); out.writeStartElement("login"); out.writeAttribute("username", username); out.writeAttribute("freeColVersion", FreeCol.getVersion()); out.writeEndElement(); in = c.getReply(); if (in.getLocalName().equals("loginConfirmed")) { final String startGameStr = in.getAttributeValue(null, "startGame"); boolean startGame = (startGameStr != null) && Boolean.valueOf(startGameStr).booleanValue(); boolean isCurrentPlayer = Boolean.valueOf(in.getAttributeValue(null, "isCurrentPlayer")).booleanValue(); in.nextTag(); Game game = new Game(freeColClient.getModelController(), in, username); Player thisPlayer = game.getPlayerByName(username); freeColClient.setGame(game); freeColClient.setMyPlayer(thisPlayer); // If (true) --> reconnect if (startGame) { freeColClient.setSingleplayer(false); freeColClient.getPreGameController().startGame(); if (isCurrentPlayer) { freeColClient.getInGameController().setCurrentPlayer(thisPlayer); } } c.endTransmission(in); } else if (in.getLocalName().equals("error")) { canvas.errorMessage(in.getAttributeValue(null, "messageID"), in.getAttributeValue(null, "message")); c.endTransmission(in); return false; } else { logger.warning("Unkown message received: " + in.getLocalName()); c.endTransmission(in); return false; } } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); logger.warning(sw.toString()); canvas.errorMessage(null, "Could not send XML to the server."); try { c.endTransmission(in); } catch (IOException ie) { logger.warning("Exception while trying to end transmission: " + ie.toString()); } } freeColClient.setLoggedIn(true); return true; }
private boolean login(String username, String host, int port) { Client client = freeColClient.getClient(); Canvas canvas = freeColClient.getCanvas(); if (client != null) { client.disconnect(); } try { client = new Client(host, port, freeColClient.getPreGameInputHandler()); } catch (ConnectException e) { canvas.errorMessage("server.couldNotConnect"); return false; } catch (IOException e) { canvas.errorMessage("server.couldNotConnect"); return false; } freeColClient.setClient(client); Connection c = client.getConnection(); XMLStreamReader in = null; try { XMLStreamWriter out = c.ask(); out.writeStartElement("login"); out.writeAttribute("username", username); out.writeAttribute("freeColVersion", FreeCol.getVersion()); out.writeEndElement(); in = c.getReply(); if (in.getLocalName().equals("loginConfirmed")) { final String startGameStr = in.getAttributeValue(null, "startGame"); boolean startGame = (startGameStr != null) && Boolean.valueOf(startGameStr).booleanValue(); boolean isCurrentPlayer = Boolean.valueOf(in.getAttributeValue(null, "isCurrentPlayer")).booleanValue(); in.nextTag(); Game game = new Game(freeColClient.getModelController(), in, username); Player thisPlayer = game.getPlayerByName(username); freeColClient.setGame(game); freeColClient.setMyPlayer(thisPlayer); c.endTransmission(in); // If (true) --> reconnect if (startGame) { freeColClient.setSingleplayer(false); freeColClient.getPreGameController().startGame(); if (isCurrentPlayer) { freeColClient.getInGameController().setCurrentPlayer(thisPlayer); } } } else if (in.getLocalName().equals("error")) { canvas.errorMessage(in.getAttributeValue(null, "messageID"), in.getAttributeValue(null, "message")); c.endTransmission(in); return false; } else { logger.warning("Unkown message received: " + in.getLocalName()); c.endTransmission(in); return false; } } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); logger.warning(sw.toString()); canvas.errorMessage(null, "Could not send XML to the server."); try { c.endTransmission(in); } catch (IOException ie) { logger.warning("Exception while trying to end transmission: " + ie.toString()); } } freeColClient.setLoggedIn(true); return true; }
diff --git a/src/main/java/bencode/ParallelPieceDigest.java b/src/main/java/bencode/ParallelPieceDigest.java index 24a96c8..60fd069 100644 --- a/src/main/java/bencode/ParallelPieceDigest.java +++ b/src/main/java/bencode/ParallelPieceDigest.java @@ -1,86 +1,86 @@ package bencode; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; public class ParallelPieceDigest { private final FileSet fileSet; private final int pieceLength; public ParallelPieceDigest(List<File> files, int pieceLength) { this.fileSet = new FileSet(files); this.pieceLength = pieceLength; } public byte[] computeHash(int numWorkers) throws IOException { AtomicInteger hashedPieces = new AtomicInteger(); int piece = 0; int totalPieces = this.fileSet.totalPieces(this.pieceLength); byte[] globalHash = new byte[totalPieces * 20]; byte[] pieceBuffer = new byte[this.pieceLength]; int bytesRead = 0; int bytesLeft = this.pieceLength; - FileInputStream in = null; + FileInputStream in = null; ExecutorService pool = Executors.newFixedThreadPool(numWorkers); try { for (File file : this.fileSet.getFiles()) { in = new FileInputStream(file); int lastRead = 0; do { lastRead = in.read(pieceBuffer, bytesRead, bytesLeft); if (lastRead >= 0) { bytesRead += lastRead; bytesLeft -= lastRead; } // piece is ready for hashing if (bytesLeft == 0) { // new buffer for the next piece byte[] pieceData = pieceBuffer; pieceBuffer = new byte[this.pieceLength]; // submit piece for hashing pool.execute(new PieceDigestJob(globalHash, pieceData, bytesRead, piece++, hashedPieces)); // new piece bytesRead = 0; bytesLeft = this.pieceLength; } } while (lastRead > 0); // eof in.close(); } // submit the final piece for hashing pool.execute(new PieceDigestJob(globalHash, pieceBuffer, bytesRead, piece++, hashedPieces)); // wait for all workers to finish while (hashedPieces.get() < totalPieces); } finally { if (in != null) { in.close(); } pool.shutdown(); } return globalHash; } }
true
true
public byte[] computeHash(int numWorkers) throws IOException { AtomicInteger hashedPieces = new AtomicInteger(); int piece = 0; int totalPieces = this.fileSet.totalPieces(this.pieceLength); byte[] globalHash = new byte[totalPieces * 20]; byte[] pieceBuffer = new byte[this.pieceLength]; int bytesRead = 0; int bytesLeft = this.pieceLength; FileInputStream in = null; ExecutorService pool = Executors.newFixedThreadPool(numWorkers); try { for (File file : this.fileSet.getFiles()) { in = new FileInputStream(file); int lastRead = 0; do { lastRead = in.read(pieceBuffer, bytesRead, bytesLeft); if (lastRead >= 0) { bytesRead += lastRead; bytesLeft -= lastRead; } // piece is ready for hashing if (bytesLeft == 0) { // new buffer for the next piece byte[] pieceData = pieceBuffer; pieceBuffer = new byte[this.pieceLength]; // submit piece for hashing pool.execute(new PieceDigestJob(globalHash, pieceData, bytesRead, piece++, hashedPieces)); // new piece bytesRead = 0; bytesLeft = this.pieceLength; } } while (lastRead > 0); // eof in.close(); } // submit the final piece for hashing pool.execute(new PieceDigestJob(globalHash, pieceBuffer, bytesRead, piece++, hashedPieces)); // wait for all workers to finish while (hashedPieces.get() < totalPieces); } finally { if (in != null) { in.close(); } pool.shutdown(); } return globalHash; }
public byte[] computeHash(int numWorkers) throws IOException { AtomicInteger hashedPieces = new AtomicInteger(); int piece = 0; int totalPieces = this.fileSet.totalPieces(this.pieceLength); byte[] globalHash = new byte[totalPieces * 20]; byte[] pieceBuffer = new byte[this.pieceLength]; int bytesRead = 0; int bytesLeft = this.pieceLength; FileInputStream in = null; ExecutorService pool = Executors.newFixedThreadPool(numWorkers); try { for (File file : this.fileSet.getFiles()) { in = new FileInputStream(file); int lastRead = 0; do { lastRead = in.read(pieceBuffer, bytesRead, bytesLeft); if (lastRead >= 0) { bytesRead += lastRead; bytesLeft -= lastRead; } // piece is ready for hashing if (bytesLeft == 0) { // new buffer for the next piece byte[] pieceData = pieceBuffer; pieceBuffer = new byte[this.pieceLength]; // submit piece for hashing pool.execute(new PieceDigestJob(globalHash, pieceData, bytesRead, piece++, hashedPieces)); // new piece bytesRead = 0; bytesLeft = this.pieceLength; } } while (lastRead > 0); // eof in.close(); } // submit the final piece for hashing pool.execute(new PieceDigestJob(globalHash, pieceBuffer, bytesRead, piece++, hashedPieces)); // wait for all workers to finish while (hashedPieces.get() < totalPieces); } finally { if (in != null) { in.close(); } pool.shutdown(); } return globalHash; }
diff --git a/src/com/cyanogenmod/filemanager/commands/shell/AsyncResultProgram.java b/src/com/cyanogenmod/filemanager/commands/shell/AsyncResultProgram.java index 9d00002..922de7b 100644 --- a/src/com/cyanogenmod/filemanager/commands/shell/AsyncResultProgram.java +++ b/src/com/cyanogenmod/filemanager/commands/shell/AsyncResultProgram.java @@ -1,399 +1,396 @@ /* * Copyright (C) 2012 The CyanogenMod 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.cyanogenmod.filemanager.commands.shell; import com.cyanogenmod.filemanager.commands.AsyncResultExecutable; import com.cyanogenmod.filemanager.commands.AsyncResultListener; import com.cyanogenmod.filemanager.commands.SIGNAL; import com.cyanogenmod.filemanager.util.FileHelper; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * An abstract class that allow the consumption of partial data. Commands * can parse the results while this are still retrieving. */ public abstract class AsyncResultProgram extends Program implements AsyncResultExecutable, AsyncResultProgramListener { /** * @hide */ static final Byte STDIN = new Byte((byte)0); /** * @hide */ static final Byte STDERR = new Byte((byte)1); private final AsyncResultListener mAsyncResultListener; private AsyncResultProgramThread mWorkerThread; /** * @hide */ final List<String> mPartialData; /** * @hide */ final List<Byte> mPartialDataType; final Object mSync = new Object(); /** * @hide */ final Object mTerminateSync = new Object(); private boolean mCancelled; private OnCancelListener mOnCancelListener; private OnEndListener mOnEndListener; private StringBuffer mTempBuffer; /** * @Constructor of <code>AsyncResultProgram</code>. * * @param id The resource identifier of the command * @param asyncResultListener The partial result listener * @param args Arguments of the command (will be formatted with the arguments from * the command definition) * @throws InvalidCommandDefinitionException If the command has an invalid definition */ public AsyncResultProgram( String id, AsyncResultListener asyncResultListener, String... args) throws InvalidCommandDefinitionException { this(id, true, asyncResultListener, args); } /** * @Constructor of <code>AsyncResultProgram</code>. * * @param id The resource identifier of the command * @param prepare Indicates if the argument must be prepared * @param asyncResultListener The partial result listener * @param args Arguments of the command (will be formatted with the arguments from * the command definition) * @throws InvalidCommandDefinitionException If the command has an invalid definition */ public AsyncResultProgram( String id, boolean prepare, AsyncResultListener asyncResultListener, String... args) throws InvalidCommandDefinitionException { super(id, prepare, args); this.mAsyncResultListener = asyncResultListener; this.mPartialData = Collections.synchronizedList(new ArrayList<String>()); this.mPartialDataType = Collections.synchronizedList(new ArrayList<Byte>()); this.mTempBuffer = new StringBuffer(); this.mOnCancelListener = null; this.mOnEndListener = null; this.mCancelled = false; } /** * Method that communicates that a new partial result parse will start. * @hide */ public final void onRequestStartParsePartialResult() { this.mWorkerThread = new AsyncResultProgramThread(); this.mWorkerThread.start(); //Notify start to command class this.onStartParsePartialResult(); //If a listener is defined, then send the start event if (getAsyncResultListener() != null) { getAsyncResultListener().onAsyncStart(); } } /** * Method that communicates that partial result is ended and no new result * will be received. * * @param cancelled If the program was cancelled * @hide */ public final void onRequestEndParsePartialResult(boolean cancelled) { synchronized (this.mSync) { this.mWorkerThread.mAlive = false; this.mSync.notify(); } synchronized (this.mTerminateSync) { if (this.mWorkerThread.isAlive()) { try { this.mTerminateSync.wait(); } catch (Exception e) { /**NON BLOCK**/ } } } //Notify end to command class this.onEndParsePartialResult(cancelled); //If a listener is defined, then send the start event if (getAsyncResultListener() != null) { getAsyncResultListener().onAsyncEnd(cancelled); } } /** * Method that communicates the exit code of the program * * @param exitCode The exit code of the program * @hide */ public final void onRequestExitCode(int exitCode) { //If a listener is defined, then send the start event if (getAsyncResultListener() != null) { getAsyncResultListener().onAsyncExitCode(exitCode); } } /** * Method that parse the result of a program invocation. * * @param partialIn A partial standard input buffer (incremental buffer) * @hide */ public final void onRequestParsePartialResult(String partialIn) { synchronized (this.mSync) { String data = partialIn; String rest = ""; //$NON-NLS-1$ if (parseOnlyCompleteLines()) { int pos = partialIn.lastIndexOf(FileHelper.NEWLINE); if (pos == -1) { //Save partial data this.mTempBuffer.append(partialIn); return; } //Retrieve the data data = this.mTempBuffer.append(partialIn.substring(0, pos + 1)).toString(); rest = partialIn.substring(pos + 1); } this.mPartialDataType.add(STDIN); this.mPartialData.add(data); this.mTempBuffer = new StringBuffer(rest); this.mSync.notify(); } } /** * Method that parse the error result of a program invocation. * * @param partialErr A partial standard err buffer (incremental buffer) * @hide */ public final void parsePartialErrResult(String partialErr) { synchronized (this.mSync) { String data = partialErr; String rest = ""; //$NON-NLS-1$ if (parseOnlyCompleteLines()) { int pos = partialErr.lastIndexOf(FileHelper.NEWLINE); if (pos == -1) { //Save partial data this.mTempBuffer.append(partialErr); return; } //Retrieve the data data = this.mTempBuffer.append(partialErr.substring(0, pos + 1)).toString(); rest = partialErr.substring(pos + 1); } this.mPartialDataType.add(STDERR); this.mPartialData.add(data); this.mTempBuffer = new StringBuffer(rest); this.mSync.notify(); } } /** * Method that returns if the <code>onParsePartialResult</code> method will * be called only complete lines are filled. * * @return boolean if the <code>onParsePartialResult</code> method will * be called only complete lines are filled */ @SuppressWarnings("static-method") public boolean parseOnlyCompleteLines() { return true; } /** * {@inheritDoc} */ @Override public AsyncResultListener getAsyncResultListener() { return this.mAsyncResultListener; } /** * {@inheritDoc} */ @Override public final boolean isCancelled() { return this.mCancelled; } /** * {@inheritDoc} */ @Override public final boolean cancel() { //Is't cancellable by definition? if (!isCancellable()) { return false; } //Stop the thread synchronized (this.mSync) { this.mWorkerThread.mAlive = false; this.mSync.notify(); } //Notify cancellation if (this.mOnCancelListener != null) { this.mCancelled = this.mOnCancelListener.onCancel(); return this.mCancelled; } return false; } /** * {@inheritDoc} */ @Override public final boolean end() { // Internally this method do the same things that cancel method, but invokes // onEnd instead of onCancel //Is't cancellable by definition? if (!isCancellable()) { return false; } //Stop the thread synchronized (this.mSync) { this.mWorkerThread.mAlive = false; this.mSync.notify(); } //Notify ending SIGNAL signal = onRequestEnd(); if (this.mOnEndListener != null) { if (signal == null) { this.mCancelled = this.mOnEndListener.onEnd(); } else { this.mCancelled = this.mOnEndListener.onSendSignal(signal); } return this.mCancelled; } return false; } /** * {@inheritDoc} */ @Override public final void setOnCancelListener(OnCancelListener onCancelListener) { this.mOnCancelListener = onCancelListener; } /** * {@inheritDoc} */ @Override public final void setOnEndListener(OnEndListener onEndListener) { this.mOnEndListener = onEndListener; } /** * {@inheritDoc} */ @Override public boolean isCancellable() { //By defect an asynchronous command is cancellable return true; } /** * Method that returns if the command is expected to finalize by it self, or needs * a call to end method. * * @return boolean If the command is expected to finalize by it self. */ @SuppressWarnings("static-method") public boolean isExpectEnd() { return true; } /** * An internal class for process partial results sequentially in a * secure way. */ private class AsyncResultProgramThread extends Thread { boolean mAlive = true; /** * Constructor of <code>AsyncResultProgramThread</code>. */ AsyncResultProgramThread() { super(); } /** * {@inheritDoc} */ @Override public void run() { try { this.mAlive = true; while (this.mAlive) { synchronized (AsyncResultProgram.this.mSync) { AsyncResultProgram.this.mSync.wait(); while (AsyncResultProgram.this.mPartialData.size() > 0) { - if (!this.mAlive) { - return; - } Byte type = AsyncResultProgram.this.mPartialDataType.remove(0); String data = AsyncResultProgram.this.mPartialData.remove(0); try { if (type.compareTo(STDIN) == 0) { AsyncResultProgram.this.onParsePartialResult(data); } else { AsyncResultProgram.this.onParseErrorPartialResult(data); } } catch (Throwable ex) { /**NON BLOCK**/ } } } } } catch (Exception e) { /**NON BLOCK**/ } finally { this.mAlive = false; synchronized (AsyncResultProgram.this.mTerminateSync) { AsyncResultProgram.this.mTerminateSync.notify(); } } } } }
true
true
public void run() { try { this.mAlive = true; while (this.mAlive) { synchronized (AsyncResultProgram.this.mSync) { AsyncResultProgram.this.mSync.wait(); while (AsyncResultProgram.this.mPartialData.size() > 0) { if (!this.mAlive) { return; } Byte type = AsyncResultProgram.this.mPartialDataType.remove(0); String data = AsyncResultProgram.this.mPartialData.remove(0); try { if (type.compareTo(STDIN) == 0) { AsyncResultProgram.this.onParsePartialResult(data); } else { AsyncResultProgram.this.onParseErrorPartialResult(data); } } catch (Throwable ex) { /**NON BLOCK**/ } } } } } catch (Exception e) { /**NON BLOCK**/ } finally { this.mAlive = false; synchronized (AsyncResultProgram.this.mTerminateSync) { AsyncResultProgram.this.mTerminateSync.notify(); } } }
public void run() { try { this.mAlive = true; while (this.mAlive) { synchronized (AsyncResultProgram.this.mSync) { AsyncResultProgram.this.mSync.wait(); while (AsyncResultProgram.this.mPartialData.size() > 0) { Byte type = AsyncResultProgram.this.mPartialDataType.remove(0); String data = AsyncResultProgram.this.mPartialData.remove(0); try { if (type.compareTo(STDIN) == 0) { AsyncResultProgram.this.onParsePartialResult(data); } else { AsyncResultProgram.this.onParseErrorPartialResult(data); } } catch (Throwable ex) { /**NON BLOCK**/ } } } } } catch (Exception e) { /**NON BLOCK**/ } finally { this.mAlive = false; synchronized (AsyncResultProgram.this.mTerminateSync) { AsyncResultProgram.this.mTerminateSync.notify(); } } }
diff --git a/WasherCheck/src/main/java/net/zdremann/wc/service/NotificationService.java b/WasherCheck/src/main/java/net/zdremann/wc/service/NotificationService.java index 53d9492..50727ac 100755 --- a/WasherCheck/src/main/java/net/zdremann/wc/service/NotificationService.java +++ b/WasherCheck/src/main/java/net/zdremann/wc/service/NotificationService.java @@ -1,135 +1,135 @@ /* * Copyright (c) 2013. Zachary Dremann * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.zdremann.wc.service; import android.app.AlarmManager; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Intent; import android.database.Cursor; import android.os.SystemClock; import android.support.v4.app.NotificationCompat; import android.support.v4.util.LongSparseArray; import android.util.Log; import net.zdremann.wc.R; import net.zdremann.wc.provider.MachinesContract.Machines; import net.zdremann.wc.provider.NotificationsContract.Notifications; import net.zdremann.wc.ui.RoomViewer; import java.util.ArrayList; import java.util.List; import static java.util.concurrent.TimeUnit.*; public class NotificationService extends IntentService { public static final String TAG = "NotificationService"; private static final long DEFAULT_WAIT_FOR_CYCLE_COMPLETE = MILLISECONDS.convert(5, MINUTES); public NotificationService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); final PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0); final ContentResolver contentResolver = getContentResolver(); final Cursor notifications = contentResolver.query(Notifications.CONTENT_URI, null, null, null, Notifications.ROOM_ID); if (notifications == null || !notifications.moveToFirst()) { throw new IllegalStateException("Notifications Cursor is Invalid"); } final String[] machineProjection = {Machines._ID, Machines.TYPE, Machines.NUMBER, Machines.STATUS, Machines.TIME_REMAINING}; final int notif_idx_id = notifications.getColumnIndexOrThrow(Notifications._ID); final int notif_idx_room_id = notifications.getColumnIndexOrThrow(Notifications.ROOM_ID); final int notif_idx_type = notifications.getColumnIndexOrThrow(Notifications.TYPE); final int notif_idx_number = notifications.getColumnIndexOrThrow(Notifications.NUMBER); final int notif_idx_status = notifications.getColumnIndexOrThrow(Notifications.STATUS); final LongSparseArray<Cursor> rooms = new LongSparseArray<Cursor>(); long nextCheckMillis = Long.MAX_VALUE; List<Long> finishedNotifications = new ArrayList<Long>(); while (notifications.moveToNext()) { long roomId = notifications.getLong(notif_idx_room_id); Cursor machines = rooms.get(roomId); if (machines == null) { machines = contentResolver.query(Machines.buildRoomUri(roomId, MILLISECONDS.convert(30, SECONDS)), machineProjection, null, null, null); assert machines != null; rooms.put(roomId, machines); } for (boolean hasMachine = machines.moveToFirst(); hasMachine; hasMachine = machines.moveToNext()) { // TODO: Check if machine found if (machines.getInt(1) == notifications.getInt(notif_idx_type) && machines.getInt(2) == notifications.getInt(notif_idx_number)) { if (machines.getInt(3) <= notifications.getInt(notif_idx_status)) { finishedNotifications.add(notifications.getLong(notif_idx_id)); } else { - long checkThisNext = (long) (MILLISECONDS.convert(1, MINUTES) * machines.getFloat(4)) + MILLISECONDS.convert(10, SECONDS); + long checkThisNext = machines.getLong(4) + MILLISECONDS.convert(30, SECONDS); if (checkThisNext <= 0) checkThisNext = DEFAULT_WAIT_FOR_CYCLE_COMPLETE; nextCheckMillis = Math.min(nextCheckMillis, checkThisNext); } break; } } } for (Long notificationId : finishedNotifications) { contentResolver.delete(Notifications.fromId(notificationId), null, null); } if (finishedNotifications.size() > 0) { NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); NotificationCompat.Builder builder = new NotificationCompat.Builder(this); final String title = String.format("%d machines ready", finishedNotifications.size()); builder.setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL) .setContentTitle(title) .setSmallIcon(R.drawable.ic_launcher) .setWhen(System.currentTimeMillis()) .setTicker(title) .setUsesChronometer(true) .setContentIntent( PendingIntent.getActivity(this, 1, new Intent(this, RoomViewer.class), 0)); final Notification notification = builder.build(); notificationManager.notify(0, notification); } if (nextCheckMillis != Long.MAX_VALUE) { am.cancel(pendingIntent); Log.d(TAG, "retrying in " + SECONDS.convert(nextCheckMillis, MILLISECONDS) + " seconds"); am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + nextCheckMillis, pendingIntent); } } }
true
true
protected void onHandleIntent(Intent intent) { AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); final PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0); final ContentResolver contentResolver = getContentResolver(); final Cursor notifications = contentResolver.query(Notifications.CONTENT_URI, null, null, null, Notifications.ROOM_ID); if (notifications == null || !notifications.moveToFirst()) { throw new IllegalStateException("Notifications Cursor is Invalid"); } final String[] machineProjection = {Machines._ID, Machines.TYPE, Machines.NUMBER, Machines.STATUS, Machines.TIME_REMAINING}; final int notif_idx_id = notifications.getColumnIndexOrThrow(Notifications._ID); final int notif_idx_room_id = notifications.getColumnIndexOrThrow(Notifications.ROOM_ID); final int notif_idx_type = notifications.getColumnIndexOrThrow(Notifications.TYPE); final int notif_idx_number = notifications.getColumnIndexOrThrow(Notifications.NUMBER); final int notif_idx_status = notifications.getColumnIndexOrThrow(Notifications.STATUS); final LongSparseArray<Cursor> rooms = new LongSparseArray<Cursor>(); long nextCheckMillis = Long.MAX_VALUE; List<Long> finishedNotifications = new ArrayList<Long>(); while (notifications.moveToNext()) { long roomId = notifications.getLong(notif_idx_room_id); Cursor machines = rooms.get(roomId); if (machines == null) { machines = contentResolver.query(Machines.buildRoomUri(roomId, MILLISECONDS.convert(30, SECONDS)), machineProjection, null, null, null); assert machines != null; rooms.put(roomId, machines); } for (boolean hasMachine = machines.moveToFirst(); hasMachine; hasMachine = machines.moveToNext()) { // TODO: Check if machine found if (machines.getInt(1) == notifications.getInt(notif_idx_type) && machines.getInt(2) == notifications.getInt(notif_idx_number)) { if (machines.getInt(3) <= notifications.getInt(notif_idx_status)) { finishedNotifications.add(notifications.getLong(notif_idx_id)); } else { long checkThisNext = (long) (MILLISECONDS.convert(1, MINUTES) * machines.getFloat(4)) + MILLISECONDS.convert(10, SECONDS); if (checkThisNext <= 0) checkThisNext = DEFAULT_WAIT_FOR_CYCLE_COMPLETE; nextCheckMillis = Math.min(nextCheckMillis, checkThisNext); } break; } } } for (Long notificationId : finishedNotifications) { contentResolver.delete(Notifications.fromId(notificationId), null, null); } if (finishedNotifications.size() > 0) { NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); NotificationCompat.Builder builder = new NotificationCompat.Builder(this); final String title = String.format("%d machines ready", finishedNotifications.size()); builder.setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL) .setContentTitle(title) .setSmallIcon(R.drawable.ic_launcher) .setWhen(System.currentTimeMillis()) .setTicker(title) .setUsesChronometer(true) .setContentIntent( PendingIntent.getActivity(this, 1, new Intent(this, RoomViewer.class), 0)); final Notification notification = builder.build(); notificationManager.notify(0, notification); } if (nextCheckMillis != Long.MAX_VALUE) { am.cancel(pendingIntent); Log.d(TAG, "retrying in " + SECONDS.convert(nextCheckMillis, MILLISECONDS) + " seconds"); am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + nextCheckMillis, pendingIntent); } }
protected void onHandleIntent(Intent intent) { AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); final PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0); final ContentResolver contentResolver = getContentResolver(); final Cursor notifications = contentResolver.query(Notifications.CONTENT_URI, null, null, null, Notifications.ROOM_ID); if (notifications == null || !notifications.moveToFirst()) { throw new IllegalStateException("Notifications Cursor is Invalid"); } final String[] machineProjection = {Machines._ID, Machines.TYPE, Machines.NUMBER, Machines.STATUS, Machines.TIME_REMAINING}; final int notif_idx_id = notifications.getColumnIndexOrThrow(Notifications._ID); final int notif_idx_room_id = notifications.getColumnIndexOrThrow(Notifications.ROOM_ID); final int notif_idx_type = notifications.getColumnIndexOrThrow(Notifications.TYPE); final int notif_idx_number = notifications.getColumnIndexOrThrow(Notifications.NUMBER); final int notif_idx_status = notifications.getColumnIndexOrThrow(Notifications.STATUS); final LongSparseArray<Cursor> rooms = new LongSparseArray<Cursor>(); long nextCheckMillis = Long.MAX_VALUE; List<Long> finishedNotifications = new ArrayList<Long>(); while (notifications.moveToNext()) { long roomId = notifications.getLong(notif_idx_room_id); Cursor machines = rooms.get(roomId); if (machines == null) { machines = contentResolver.query(Machines.buildRoomUri(roomId, MILLISECONDS.convert(30, SECONDS)), machineProjection, null, null, null); assert machines != null; rooms.put(roomId, machines); } for (boolean hasMachine = machines.moveToFirst(); hasMachine; hasMachine = machines.moveToNext()) { // TODO: Check if machine found if (machines.getInt(1) == notifications.getInt(notif_idx_type) && machines.getInt(2) == notifications.getInt(notif_idx_number)) { if (machines.getInt(3) <= notifications.getInt(notif_idx_status)) { finishedNotifications.add(notifications.getLong(notif_idx_id)); } else { long checkThisNext = machines.getLong(4) + MILLISECONDS.convert(30, SECONDS); if (checkThisNext <= 0) checkThisNext = DEFAULT_WAIT_FOR_CYCLE_COMPLETE; nextCheckMillis = Math.min(nextCheckMillis, checkThisNext); } break; } } } for (Long notificationId : finishedNotifications) { contentResolver.delete(Notifications.fromId(notificationId), null, null); } if (finishedNotifications.size() > 0) { NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); NotificationCompat.Builder builder = new NotificationCompat.Builder(this); final String title = String.format("%d machines ready", finishedNotifications.size()); builder.setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL) .setContentTitle(title) .setSmallIcon(R.drawable.ic_launcher) .setWhen(System.currentTimeMillis()) .setTicker(title) .setUsesChronometer(true) .setContentIntent( PendingIntent.getActivity(this, 1, new Intent(this, RoomViewer.class), 0)); final Notification notification = builder.build(); notificationManager.notify(0, notification); } if (nextCheckMillis != Long.MAX_VALUE) { am.cancel(pendingIntent); Log.d(TAG, "retrying in " + SECONDS.convert(nextCheckMillis, MILLISECONDS) + " seconds"); am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + nextCheckMillis, pendingIntent); } }
diff --git a/src/minecraft/org/spoutcraft/client/io/CustomTextureManager.java b/src/minecraft/org/spoutcraft/client/io/CustomTextureManager.java index 26b50eff..ad4ffef6 100644 --- a/src/minecraft/org/spoutcraft/client/io/CustomTextureManager.java +++ b/src/minecraft/org/spoutcraft/client/io/CustomTextureManager.java @@ -1,259 +1,260 @@ /* * This file is part of Spoutcraft. * * Copyright (c) 2011-2012, SpoutDev <http://www.spout.org/> * Spoutcraft is licensed under the GNU Lesser General Public License. * * Spoutcraft 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. * * Spoutcraft 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, see <http://www.gnu.org/licenses/>. */ package org.spoutcraft.client.io; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLDecoder; import java.util.HashMap; import org.lwjgl.opengl.GL11; import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.TextureLoader; import net.minecraft.client.Minecraft; import org.spoutcraft.client.SpoutClient; import org.spoutcraft.client.gui.minimap.ZanMinimap; public class CustomTextureManager { static HashMap<String, Texture> textures = new HashMap<String, Texture>(); static HashMap<String, File> cacheTextureFiles = new HashMap<String, File>(); public static void downloadTexture(String url) { downloadTexture(null, url, false); } public static void downloadTexture(String url, boolean ignoreEnding) { downloadTexture(null, url, ignoreEnding); } public static void downloadTexture(String plugin, String url, boolean ignoreEnding) { boolean wasSandboxed = SpoutClient.isSandboxed(); SpoutClient.disableSandbox(); try { String fileName = FileUtil.getFileName(url); if (!ignoreEnding && !FileUtil.isImageFile(fileName)) { System.out.println("Rejecting download of invalid texture: " + fileName); } else if (!isTextureDownloading(url) && !isTextureDownloaded(plugin, url)) { File dir = FileUtil.getTempDir(); if (plugin != null) { dir = new File(FileUtil.getCacheDir(), plugin); dir.mkdir(); } Download download = new Download(fileName, dir, url, null); FileDownloadThread.getInstance().addToDownloadQueue(download); } } finally { SpoutClient.enableSandbox(wasSandboxed); } } public static void downloadTexture(String plugin, String url) { downloadTexture(plugin, url, false); } public static boolean isTextureDownloading(String url) { return FileDownloadThread.getInstance().isDownloading(url); } public static boolean isTextureDownloaded(String url) { boolean wasSandboxed = SpoutClient.isSandboxed(); SpoutClient.disableSandbox(); try { return getTextureFile(null, url).exists(); } finally { SpoutClient.enableSandbox(wasSandboxed); } } public static boolean isTextureDownloaded(String addon, String url) { boolean wasSandboxed = SpoutClient.isSandboxed(); SpoutClient.disableSandbox(); try { return getTextureFile(addon, url).exists(); } finally { SpoutClient.enableSandbox(wasSandboxed); } } public static File getTextureFile(String plugin, String url) { boolean wasSandboxed = SpoutClient.isSandboxed(); SpoutClient.disableSandbox(); try { String fileName = FileUtil.getFileName(url); File cache = cacheTextureFiles.get(plugin + File.separator + fileName); if (cache != null) { return cache; } if (plugin != null) { File file = FileUtil.findFile(plugin, fileName); if (file != null) { cacheTextureFiles.put(plugin + File.separator + fileName, file); return file; } } return new File(FileUtil.getTempDir(), fileName); } finally { SpoutClient.enableSandbox(wasSandboxed); } } public static Texture getTextureFromPath(String path) { boolean wasSandboxed = SpoutClient.isSandboxed(); SpoutClient.disableSandbox(); try { if (textures.containsKey(path)) { return textures.get(path); } Texture texture = null; try { FileInputStream stream = new FileInputStream(path); if (stream.available() > 0) { texture = TextureLoader.getTexture(path.toLowerCase().endsWith(".png") ? "PNG" : "JPG", stream, true, GL11.GL_NEAREST); } stream.close(); } catch (IOException e) { } if (texture != null) { textures.put(path, texture); } return texture; } finally { SpoutClient.enableSandbox(wasSandboxed); } } public static Texture getTextureFromJar(String path) { boolean wasSandboxed = SpoutClient.isSandboxed(); SpoutClient.disableSandbox(); try { if (textures.containsKey(path)) { return textures.get(path); } Texture texture = null; //Check inside jar try { InputStream stream = Minecraft.class.getResourceAsStream(path); texture = TextureLoader.getTexture(path.toLowerCase().endsWith(".png") ? "PNG" : "JPG", stream, true, GL11.GL_NEAREST); stream.close(); } catch (Exception e) { } //Check MCP/Eclipse Path if (texture == null) { String pathToJar; File jar = new File(CustomTextureManager.class.getProtectionDomain().getCodeSource().getLocation().getFile()); try { pathToJar = jar.getCanonicalPath(); } catch (IOException e1) { pathToJar = jar.getAbsolutePath(); } try { pathToJar = URLDecoder.decode(pathToJar, "UTF-8"); } catch (java.io.UnsupportedEncodingException ignore) { } - File relative = new File(pathToJar + "../../../../" + path); + File relative = new File(pathToJar + "/../../" + path); + System.out.println(relative.getAbsolutePath()); try { pathToJar = relative.getCanonicalPath(); } catch (IOException e) { pathToJar = relative.getAbsolutePath(); } texture = getTextureFromPath(pathToJar); } if (texture != null) { textures.put(path, texture); } return texture; } finally { SpoutClient.enableSandbox(wasSandboxed); } } public static void resetTextures() { for (Texture texture : textures.values()) { texture.release(); } cacheTextureFiles.clear(); textures.clear(); ZanMinimap.instance.texman.reset(); } public static Texture getTextureFromUrl(String url) { return getTextureFromUrl(null, url, true); } public static Texture getTextureFromUrl(String url, boolean download) { return getTextureFromUrl(null, url); } public static Texture getTextureFromUrl(String plugin, String url) { return getTextureFromUrl(plugin, url, true); } public static Texture getTextureFromUrl(String plugin, String url, boolean download) { boolean wasSandboxed = SpoutClient.isSandboxed(); SpoutClient.disableSandbox(); try { File texture = getTextureFile(plugin, url); if (!texture.exists()) { return null; } try { return getTextureFromPath(texture.getCanonicalPath()); } catch (IOException e) { e.printStackTrace(); return null; } } finally { SpoutClient.enableSandbox(wasSandboxed); } } public static String getTexturePathFromUrl(String url) { return getTexturePathFromUrl(null, url); } public static String getTexturePathFromUrl(String plugin, String url) { if (!isTextureDownloaded(plugin, url)) { return null; } boolean wasSandboxed = SpoutClient.isSandboxed(); SpoutClient.disableSandbox(); try { File download = new File(FileUtil.getTempDir(), FileUtil.getFileName(url)); try { return download.getCanonicalPath(); } catch (IOException e) { e.printStackTrace(); } } finally { SpoutClient.enableSandbox(wasSandboxed); } return null; } }
true
true
public static Texture getTextureFromJar(String path) { boolean wasSandboxed = SpoutClient.isSandboxed(); SpoutClient.disableSandbox(); try { if (textures.containsKey(path)) { return textures.get(path); } Texture texture = null; //Check inside jar try { InputStream stream = Minecraft.class.getResourceAsStream(path); texture = TextureLoader.getTexture(path.toLowerCase().endsWith(".png") ? "PNG" : "JPG", stream, true, GL11.GL_NEAREST); stream.close(); } catch (Exception e) { } //Check MCP/Eclipse Path if (texture == null) { String pathToJar; File jar = new File(CustomTextureManager.class.getProtectionDomain().getCodeSource().getLocation().getFile()); try { pathToJar = jar.getCanonicalPath(); } catch (IOException e1) { pathToJar = jar.getAbsolutePath(); } try { pathToJar = URLDecoder.decode(pathToJar, "UTF-8"); } catch (java.io.UnsupportedEncodingException ignore) { } File relative = new File(pathToJar + "../../../../" + path); try { pathToJar = relative.getCanonicalPath(); } catch (IOException e) { pathToJar = relative.getAbsolutePath(); } texture = getTextureFromPath(pathToJar); } if (texture != null) { textures.put(path, texture); } return texture; } finally { SpoutClient.enableSandbox(wasSandboxed); } }
public static Texture getTextureFromJar(String path) { boolean wasSandboxed = SpoutClient.isSandboxed(); SpoutClient.disableSandbox(); try { if (textures.containsKey(path)) { return textures.get(path); } Texture texture = null; //Check inside jar try { InputStream stream = Minecraft.class.getResourceAsStream(path); texture = TextureLoader.getTexture(path.toLowerCase().endsWith(".png") ? "PNG" : "JPG", stream, true, GL11.GL_NEAREST); stream.close(); } catch (Exception e) { } //Check MCP/Eclipse Path if (texture == null) { String pathToJar; File jar = new File(CustomTextureManager.class.getProtectionDomain().getCodeSource().getLocation().getFile()); try { pathToJar = jar.getCanonicalPath(); } catch (IOException e1) { pathToJar = jar.getAbsolutePath(); } try { pathToJar = URLDecoder.decode(pathToJar, "UTF-8"); } catch (java.io.UnsupportedEncodingException ignore) { } File relative = new File(pathToJar + "/../../" + path); System.out.println(relative.getAbsolutePath()); try { pathToJar = relative.getCanonicalPath(); } catch (IOException e) { pathToJar = relative.getAbsolutePath(); } texture = getTextureFromPath(pathToJar); } if (texture != null) { textures.put(path, texture); } return texture; } finally { SpoutClient.enableSandbox(wasSandboxed); } }
diff --git a/org.eclipse.mylyn.commons.sdk.util/src/org/eclipse/mylyn/commons/sdk/util/TestConfiguration.java b/org.eclipse.mylyn.commons.sdk.util/src/org/eclipse/mylyn/commons/sdk/util/TestConfiguration.java index 9debd896..0dfed03a 100644 --- a/org.eclipse.mylyn.commons.sdk.util/src/org/eclipse/mylyn/commons/sdk/util/TestConfiguration.java +++ b/org.eclipse.mylyn.commons.sdk.util/src/org/eclipse/mylyn/commons/sdk/util/TestConfiguration.java @@ -1,188 +1,188 @@ /******************************************************************************* * Copyright (c) 2011 Tasktop Technologies 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: * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.commons.sdk.util; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.List; import junit.framework.AssertionFailedError; import org.eclipse.core.runtime.Assert; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; /** * @author Steffen Pingel */ public class TestConfiguration { private static final String URL_SERVICES_LOCALHOST = "http://localhost:2080"; private static final String URL_SERVICES_DEFAULT = "http://mylyn.org"; public enum TestKind { UNIT, COMPONENT, INTEGRATION, SYSTEM }; public static TestConfiguration defaultConfiguration; private static final String SERVER = System.getProperty("mylyn.test.server", "mylyn.org"); public static TestConfiguration getDefault() { if (defaultConfiguration == null) { defaultConfiguration = new TestConfiguration(TestKind.UNIT); defaultConfiguration.setDefaultOnly(CommonTestUtil.runHeartbeatTestsOnly()); } return defaultConfiguration; } public static String getRepositoryUrl(String service) { return getDefault().getUrl(service); } public static String getRepositoryUrl(String service, boolean secure) { return getDefault().getUrl(service, secure); } public static void setDefault(TestConfiguration defaultConfiguration) { TestConfiguration.defaultConfiguration = defaultConfiguration; } private final EnumSet<TestKind> kinds; private boolean localOnly; private boolean defaultOnly; private boolean headless; public TestConfiguration(TestKind firstKind, TestKind... moreKinds) { Assert.isNotNull(firstKind); this.kinds = EnumSet.of(firstKind, moreKinds); } public String getUrl(String service) { return getUrl(service, false); } public String getUrl(String service, boolean secure) { return ((secure) ? "https://" : "http://") + SERVER + "/" + service; } public boolean hasKind(TestKind kind) { return kinds.contains(kind); } public boolean isDefaultOnly() { return defaultOnly; } public boolean isHeadless() { return headless; } public boolean isLocalOnly() { return localOnly; } public void setDefaultOnly(boolean heartbeat) { this.defaultOnly = heartbeat; } public void setHeadless(boolean headless) { this.headless = headless; } public void setLocalOnly(boolean localOnly) { this.localOnly = localOnly; } public <T> List<T> discover(Class<T> clazz, String fixtureType) { List<T> fixtures = Collections.emptyList(); try { File file = CommonTestUtil.getFile(clazz, "local.json"); fixtures = discover("file://" + file.getAbsolutePath(), "", clazz, fixtureType); } catch (AssertionFailedError e) { // ignore } catch (IOException e) { // ignore } if (fixtures.isEmpty()) { fixtures = discover(URL_SERVICES_LOCALHOST + "/cgi-bin/services", URL_SERVICES_LOCALHOST, clazz, fixtureType); } if (fixtures.isEmpty()) { - fixtures = discover(URL_SERVICES_DEFAULT + "/cgi-bin/services", URL_SERVICES_LOCALHOST, clazz, fixtureType); + fixtures = discover(URL_SERVICES_DEFAULT + "/cgi-bin/services", URL_SERVICES_DEFAULT, clazz, fixtureType); } return fixtures; } public static <T> List<T> discover(String location, String baseUrl, Class<T> clazz, String fixtureType) { Assert.isNotNull(fixtureType); List<FixtureConfiguration> configurations = getConfigurations(location); if (configurations != null) { for (FixtureConfiguration configuration : configurations) { if (configuration != null) { configuration.setUrl(baseUrl + configuration.getUrl()); } } return loadFixtures(configurations, clazz, fixtureType); } return Collections.emptyList(); } private static <T> List<T> loadFixtures(List<FixtureConfiguration> configurations, Class<T> clazz, String fixtureType) { List<T> result = new ArrayList<T>(); for (FixtureConfiguration configuration : configurations) { if (configuration != null && fixtureType.equals(configuration.getType())) { try { Constructor<T> constructor = clazz.getConstructor(FixtureConfiguration.class); result.add(constructor.newInstance(configuration)); } catch (Exception e) { throw new RuntimeException("Unexpected error creating test fixture", e); } } } return result; } private static List<FixtureConfiguration> getConfigurations(String url) { try { URLConnection connection = new URL(url).openConnection(); InputStreamReader in = new InputStreamReader(connection.getInputStream()); try { TypeToken<List<FixtureConfiguration>> type = new TypeToken<List<FixtureConfiguration>>() { }; return new Gson().fromJson(in, type.getType()); } finally { in.close(); } } catch (IOException e) { return null; } } }
true
true
public <T> List<T> discover(Class<T> clazz, String fixtureType) { List<T> fixtures = Collections.emptyList(); try { File file = CommonTestUtil.getFile(clazz, "local.json"); fixtures = discover("file://" + file.getAbsolutePath(), "", clazz, fixtureType); } catch (AssertionFailedError e) { // ignore } catch (IOException e) { // ignore } if (fixtures.isEmpty()) { fixtures = discover(URL_SERVICES_LOCALHOST + "/cgi-bin/services", URL_SERVICES_LOCALHOST, clazz, fixtureType); } if (fixtures.isEmpty()) { fixtures = discover(URL_SERVICES_DEFAULT + "/cgi-bin/services", URL_SERVICES_LOCALHOST, clazz, fixtureType); } return fixtures; }
public <T> List<T> discover(Class<T> clazz, String fixtureType) { List<T> fixtures = Collections.emptyList(); try { File file = CommonTestUtil.getFile(clazz, "local.json"); fixtures = discover("file://" + file.getAbsolutePath(), "", clazz, fixtureType); } catch (AssertionFailedError e) { // ignore } catch (IOException e) { // ignore } if (fixtures.isEmpty()) { fixtures = discover(URL_SERVICES_LOCALHOST + "/cgi-bin/services", URL_SERVICES_LOCALHOST, clazz, fixtureType); } if (fixtures.isEmpty()) { fixtures = discover(URL_SERVICES_DEFAULT + "/cgi-bin/services", URL_SERVICES_DEFAULT, clazz, fixtureType); } return fixtures; }
diff --git a/bundles/org.eclipse.test.performance.ui/src/org/eclipse/test/internal/performance/results/ui/PerformanceResultsPreferencePage.java b/bundles/org.eclipse.test.performance.ui/src/org/eclipse/test/internal/performance/results/ui/PerformanceResultsPreferencePage.java index 459d1ed..afbb650 100644 --- a/bundles/org.eclipse.test.performance.ui/src/org/eclipse/test/internal/performance/results/ui/PerformanceResultsPreferencePage.java +++ b/bundles/org.eclipse.test.performance.ui/src/org/eclipse/test/internal/performance/results/ui/PerformanceResultsPreferencePage.java @@ -1,1249 +1,1249 @@ /******************************************************************************* * Copyright (c) 2000, 2009 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.test.internal.performance.results.ui; import java.io.File; import java.util.Arrays; import java.util.Iterator; import org.osgi.service.prefs.BackingStoreException; import org.eclipse.test.internal.performance.PerformanceTestPlugin; import org.eclipse.test.internal.performance.results.db.DB_Results; import org.eclipse.test.internal.performance.results.utils.IPerformancesConstants; import org.eclipse.test.internal.performance.results.utils.Util; import org.eclipse.test.performance.ui.UiPlugin; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Text; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; /** * Defines the 'Performances' preferences page. */ public class PerformanceResultsPreferencePage extends PreferencePage implements IWorkbenchPreferencePage, SelectionListener, ModifyListener, IPerformancesConstants { private Button mVersionRadioButton; private Button dVersionRadionButton; private CCombo databaseLocationCombo; private Button dbConnectionCheckBox; private Button dbLocalBrowseButton; private Button dbRelengRadioButton; private Button dbLocalRadioButton; private CCombo defaultDimensionCombo; private CCombo lastBuildCombo; private List resultsDimensionsList; private CCombo milestonesCombo; private Label dbLocationLabel; // Status SWT objects private Button statusValuesCheckBox; private Button statusErrorNoneRadioButton; private Button statusErrorNoticeableRadioButton; private Button statusErrorSuspiciousRadioButton; private Button statusErrorWeirdRadioButton; private Button statusErrorInvalidRadioButton; private Button statusSmallBuildValueCheckBox; private Button statusSmallDeltaValueCheckBox; private Button statusStatisticNoneRadioButton; private Button statusStatisticErraticRadioButton; private Button statusStatisticUnstableRadioButton; private Text statusBuildsToConfirm; private Text comparisonThresholdFailure; private Text comparisonThresholdError; private Text comparisonThresholdImprovement; // TODO See whether config descriptors need to be set as preferences or not... // private Table configDescriptorsTable; private BuildsView buildsView; /** * Utility method that creates a push button instance and sets the default * layout data. * * @param parent * the parent for the new button * @param label * the label for the new button * @return the newly-created button */ private Button createCheckBox(Composite parent, String label) { Button button = new Button(parent, SWT.CHECK); button.setText(label); button.addSelectionListener(this); GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; data.horizontalSpan = 5; button.setLayoutData(data); return button; } /** * Create a text field specific for this application * * @param parent * the parent of the new text field * @return the new text field */ private CCombo createCombo(Composite parent) { CCombo combo= new CCombo(parent, SWT.BORDER); combo.addModifyListener(this); GridData data = new GridData(); data.horizontalSpan = 3; data.horizontalAlignment = GridData.FILL; data.grabExcessHorizontalSpace = true; data.verticalAlignment = GridData.CENTER; data.grabExcessVerticalSpace = false; combo.setLayoutData(data); return combo; } /** * Creates composite control and sets the default layout data. * * @param parent * the parent of the new composite * @param numColumns * the number of columns for the new composite * @param hSpan TODO * @return the newly-created coposite */ private Composite createComposite(Composite parent, int numColumns, int hSpan) { Composite composite = new Composite(parent, SWT.NULL); // GridLayout GridLayout layout = new GridLayout(); layout.numColumns = numColumns; composite.setLayout(layout); // GridData GridData data = new GridData(); data.verticalAlignment = GridData.FILL; data.horizontalAlignment = GridData.FILL; data.horizontalSpan = hSpan; composite.setLayoutData(data); return composite; } /** * (non-Javadoc) Method declared on PreferencePage */ protected Control createContents(Composite parent) { this.buildsView = (BuildsView) PerformancesView.getWorkbenchView("org.eclipse.test.internal.performance.results.ui.BuildsView"); if (this.buildsView == null) { Label errorLabel = createLabel(parent, "No performances preferences can be set because the build view has not been created yet!", false); errorLabel.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_RED)); } else { // Eclipse version choice Composite composite_eclipseVersion = createComposite(parent, 5, 1); createLabel(composite_eclipseVersion, "Eclipse version", false); Composite composite_versionChoice = createComposite(composite_eclipseVersion, 5, 1); this.mVersionRadioButton = createRadioButton(composite_versionChoice, "v"+ECLIPSE_MAINTENANCE_VERSION); this.dVersionRadionButton = createRadioButton(composite_versionChoice, "v"+ECLIPSE_DEVELOPMENT_VERSION); // Database location Composite compositeDatabase = createComposite(parent, 5, 1); Group databaseGroup = createGroup(compositeDatabase, "Database", 5); Composite compositeDatabaseConnection = createComposite(databaseGroup, 3, 5); this.dbConnectionCheckBox = createCheckBox(compositeDatabaseConnection, "Connected"); this.dbRelengRadioButton = createRadioButton(compositeDatabaseConnection, "Releng"); this.dbLocalRadioButton = createRadioButton(compositeDatabaseConnection, "Local"); this.dbLocationLabel = createLabel(databaseGroup, "Location", false); this.databaseLocationCombo = createCombo(databaseGroup); this.databaseLocationCombo.setEditable(false); this.dbLocalBrowseButton = createPushButton(databaseGroup, "Browse"); // Status Composite compositeStatus = createComposite(parent, 1, 3); Group statusGroup = createGroup(compositeStatus, "Status", 1); this.statusValuesCheckBox = createCheckBox(statusGroup, "Values"); this.statusValuesCheckBox.setToolTipText("Include numbers while writing status"); Group statusErrorGroup = createGroup(statusGroup, "Error level", 5); statusErrorGroup.setToolTipText("Exclude from the written status failures depending on their build result error..."); this.statusErrorNoneRadioButton = createRadioButton(statusErrorGroup, "None"); this.statusErrorNoneRadioButton.setToolTipText("Do not exclude failures if they have a noticeable error"); this.statusErrorInvalidRadioButton = createRadioButton(statusErrorGroup, "Invalid"); this.statusErrorInvalidRadioButton.setToolTipText("Exclude all invalid failures (i.e. result error is over 100%)"); this.statusErrorWeirdRadioButton = createRadioButton(statusErrorGroup, "Weird"); this.statusErrorWeirdRadioButton.setToolTipText("Exclude all weird failures (i.e. result error is over 50%)"); this.statusErrorSuspiciousRadioButton = createRadioButton(statusErrorGroup, "Suspicious"); this.statusErrorSuspiciousRadioButton.setToolTipText("Exclude all suspicious failures (i.e. result error is over 25%)"); this.statusErrorNoticeableRadioButton = createRadioButton(statusErrorGroup, "Noticeable"); this.statusErrorNoticeableRadioButton.setToolTipText("Exclude all failures which have a noticeable error (i.e result error is over 3%)"); Group statusSmallGroup = createGroup(statusGroup, "Small value", 5); statusErrorGroup.setToolTipText("Exclude from the written status failures depending on their value"); this.statusSmallBuildValueCheckBox = createCheckBox(statusSmallGroup, "Build value"); this.statusSmallBuildValueCheckBox.setToolTipText("Exclude all failures which have a build result value smaller than 100ms"); this.statusSmallDeltaValueCheckBox = createCheckBox(statusSmallGroup, "Delta value"); this.statusSmallDeltaValueCheckBox.setToolTipText("Exclude all failures which have a delta result value smaller than 100ms"); Group statusStatisticsGroup = createGroup(statusGroup, "Statistics", 5); statusStatisticsGroup.setToolTipText("Exclude from the written status failures depending on build results statistics..."); this.statusStatisticNoneRadioButton = createRadioButton(statusStatisticsGroup, "None"); this.statusStatisticNoneRadioButton.setToolTipText("Do not exclude failures which have bad baseline results statistics (i.e. variation is over 10%)"); this.statusStatisticUnstableRadioButton = createRadioButton(statusStatisticsGroup, "Unstable"); this.statusStatisticUnstableRadioButton.setToolTipText("Exclude all failures which have unstable baseline results statistics (i.e. variation is between 10% and 20%)"); this.statusStatisticErraticRadioButton = createRadioButton(statusStatisticsGroup, "Erratic"); this.statusStatisticErraticRadioButton.setToolTipText("Exclude all failures which have erratic baseline results statistics (i.e. variation is over 20%)"); createLabel(statusGroup, "Builds to confirm:", false); this.statusBuildsToConfirm = createTextField(statusGroup); this.statusBuildsToConfirm.setToolTipText("The number of previous builds to take into account to confirm a regression"); // Comparison Composite compositeComparison = createComposite(parent, 1, 3); Group comparisonGroup = createGroup(compositeComparison, "Comparison", 1); Group thresholdsGroup = createGroup(comparisonGroup, "Thresholds", 6); // Composite compositeFailureThreshold = createComposite(comparisonGroup, 2, 2); createLabel(thresholdsGroup, "Failure:", false); this.comparisonThresholdFailure = createTextField(thresholdsGroup); this.comparisonThresholdFailure.setToolTipText("The threshold in percentage to report a failure"); createLabel(thresholdsGroup, "Error:", false); this.comparisonThresholdError = createTextField(thresholdsGroup); this.comparisonThresholdError.setToolTipText("The threshold in percentage to report an error"); createLabel(thresholdsGroup, "Improvement:", false); this.comparisonThresholdImprovement = createTextField(thresholdsGroup); this.comparisonThresholdImprovement.setToolTipText("The threshold in percentage to report an improvement"); // Milestones Composite compositeMilestones = createComposite(parent, 3, 1); createLabel(compositeMilestones, "Milestones", false); this.milestonesCombo = createCombo(compositeMilestones); this.milestonesCombo.setToolTipText("Enter the date of the milestone as yyyymmddHHMM"); // Last build StringBuffer tooltip = new StringBuffer("Select the last build to display performance results\n"); tooltip.append("If set then performance results won't be displayed for any build after this date..."); String tooltipText = tooltip.toString(); Composite compositeLastBuild = createComposite(parent, 3, 1); // this.lastBuildCheckBox = createCheckBox(compositeLastBuild, "Until last build"); createLabel(compositeLastBuild, "Last build: ", false); this.lastBuildCombo = createCombo(compositeLastBuild); this.lastBuildCombo.setEditable(false); this.lastBuildCombo.setToolTipText(tooltipText); this.lastBuildCombo.add(""); initBuildsList(); // Default dimension layout tooltip = new StringBuffer("Select the default dimension which will be used for performance results\n"); tooltip.append("When changed, the new selected dimension is automatically added to the dimensions list below..."); tooltipText = tooltip.toString(); Composite compositeDefaultDimension = createComposite(parent, 3, 1); createLabel(compositeDefaultDimension, "Default dimension: ", false); this.defaultDimensionCombo = createCombo(compositeDefaultDimension); this.defaultDimensionCombo.setEditable(false); this.defaultDimensionCombo.setToolTipText(tooltipText); // Results dimensions layout tooltip = new StringBuffer("Select the dimensions which will be used while generating performance results\n"); tooltip.append("When changed, the default dimension above is automatically added to the new list..."); tooltipText = tooltip.toString(); Composite compositeResultsDimensions = createComposite(parent, 3, 1); createLabel(compositeResultsDimensions, "Results dimensions: ", true/*beginning*/); this.resultsDimensionsList = createList(compositeResultsDimensions); this.resultsDimensionsList.setToolTipText(tooltipText); // Config descriptors layout /* TODO See whether config descriptors need to be set as preferences or not... Composite compositeConfigDescriptors = createComposite(parent, 3); createLabel(compositeConfigDescriptors, "Config descriptors: ", false); this.configDescriptorsTable = createTable(compositeConfigDescriptors); TableColumn firstColumn = new TableColumn(this.configDescriptorsTable, SWT.LEFT); firstColumn.setText ("Name"); firstColumn.setWidth(50); TableColumn secondColumn = new TableColumn(this.configDescriptorsTable, SWT.FILL | SWT.LEFT); secondColumn.setText ("Description"); secondColumn.setWidth(300); */ // init values initializeValues(); } // font = null; Composite contents = new Composite(parent, SWT.NULL); contents.pack(true); return contents; } /** * Utility method that creates a label instance and sets the default layout * data. * * @param parent * the parent for the new label * @param text * the text for the new label * @return the new label */ private Group createGroup(Composite parent, String text, int columns) { Group group = new Group(parent, SWT.NONE); group.setLayout(new GridLayout(columns, false)); group.setText(text); GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); // data.horizontalSpan = 1; group.setLayoutData(data); return group; } /** * Utility method that creates a label instance and sets the default layout * data. * * @param parent * the parent for the new label * @param text * the text for the new label * @param beginning TODO * @return the new label */ private Label createLabel(Composite parent, String text, boolean beginning) { Label label = new Label(parent, SWT.BEGINNING|SWT.LEFT); label.setText(text); GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; data.verticalAlignment = beginning ? GridData.BEGINNING : GridData.CENTER; label.setLayoutData(data); return label; } /** * Create a text field specific for this application * * @param parent * the parent of the new text field * @return the new text field */ private List createList(Composite parent) { List list = new List(parent, SWT.MULTI | SWT.BORDER); list.addSelectionListener(this); GridData data = new GridData(); data.horizontalSpan = 2; data.horizontalAlignment = GridData.FILL; data.grabExcessHorizontalSpace = true; data.verticalAlignment = GridData.CENTER; data.grabExcessVerticalSpace = false; list.setLayoutData(data); return list; } /** * Utility method that creates a push button instance and sets the default * layout data. * * @param parent * the parent for the new button * @param label * the label for the new button * @return the newly-created button */ private Button createPushButton(Composite parent, String label) { Button button = new Button(parent, SWT.PUSH); button.setText(label); button.addSelectionListener(this); GridData data = new GridData(); data.horizontalAlignment = SWT.LEFT; data.grabExcessHorizontalSpace = true; // data.horizontalSpan = 2; data.minimumWidth = 100; button.setLayoutData(data); return button; } /** * Utility method that creates a radio button instance and sets the default * layout data. * * @param parent * the parent for the new button * @param label * the label for the new button * @return the newly-created button */ private Button createRadioButton(Composite parent, String label) { Button button = new Button(parent, SWT.RADIO | SWT.LEFT); button.setText(label); button.addSelectionListener(this); GridData data = new GridData(); button.setLayoutData(data); return button; } /* * Create a text field specific for this application * * @param parent * the parent of the new text field * @return the new text field * private Table createTable(Composite parent) { Table table = new Table(parent, SWT.BORDER); table.setLinesVisible (true); table.setHeaderVisible (true); GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1); gridData.heightHint = 150; table.setLayoutData(gridData); return table; } */ /* * Create a text field specific for this application * * @param parent * the parent of the new text field * @return the new text field */ private Text createTextField(Composite parent) { Text text = new Text(parent, SWT.SINGLE | SWT.BORDER); text.addModifyListener(this); GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; data.grabExcessHorizontalSpace = true; data.verticalAlignment = GridData.CENTER; data.grabExcessVerticalSpace = false; text.setLayoutData(data); return text; } /** * The <code>ReadmePreferencePage</code> implementation of this * <code>PreferencePage</code> method returns preference store that belongs to * the our plugin. This is important because we want to store our preferences * separately from the workbench. */ protected IPreferenceStore doGetPreferenceStore() { return UiPlugin.getDefault().getPreferenceStore(); } /** * @return */ String getDialogTitle() { String title = DB_Results.getDbTitle(); if (title == null) { // DB is not connected int version; if (this.mVersionRadioButton.getSelection()) { version = ECLIPSE_MAINTENANCE_VERSION; } else { version = ECLIPSE_DEVELOPMENT_VERSION; } title = "Eclipse " + version + " - DB not connected"; } return title; } /* * Get the directory path using the given location as default. */ private String getDirectoryPath(String location) { DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.OPEN); dialog.setText(getDialogTitle()); dialog.setMessage("Select local database directory:"); dialog.setFilterPath(location); String path = dialog.open(); if (path != null) { File dir = new File(path); if (dir.exists() && dir.isDirectory()) { return dir.getAbsolutePath(); } } return null; } /* * (non-Javadoc) Method declared on IWorkbenchPreferencePage */ public void init(IWorkbench workbench) { // do nothing } /* * Init he contents of the dimensions list controls. */ void initDimensionsLists() { // Dimensions lists java.util.List dimensions = PerformanceTestPlugin.getDimensions(); Iterator names = dimensions.iterator(); while (names.hasNext()) { String name = (String) names.next(); this.defaultDimensionCombo.add(name); this.resultsDimensionsList.add(name); } } /* * Init he contents of the dimensions list controls. */ private void initBuildsList() { String[] builds = DB_Results.getBuilds(); Arrays.sort(builds, Util.BUILD_DATE_COMPARATOR); int length = builds.length; for (int i=length-1; i>=0; i--) { this.lastBuildCombo.add(builds[i]); } } /** * Initializes states of the controls using default values in the preference * store. */ private void initializeDefaults() { IPreferenceStore store = getPreferenceStore(); // Init default database values this.dbConnectionCheckBox.setSelection(store.getDefaultBoolean(PRE_DATABASE_CONNECTION)); this.dbRelengRadioButton.setSelection(false); this.dbLocalRadioButton.setSelection(false); final boolean dbLocal = store.getDefaultBoolean(PRE_DATABASE_LOCAL); if (dbLocal) { this.dbLocalRadioButton.setSelection(true); } else { this.dbRelengRadioButton.setSelection(true); } this.databaseLocationCombo.removeAll(); this.databaseLocationCombo.setText(store.getDefaultString(PRE_DATABASE_LOCATION)); updateDatabaseGroup(); // Init default status values int writeStatus = store.getDefaultInt(PRE_WRITE_STATUS); initStatusValues(writeStatus); // Init comparison thresholds this.comparisonThresholdFailure.setText(String.valueOf(store.getDefaultInt(PRE_COMPARISON_THRESHOLD_FAILURE))); this.comparisonThresholdError.setText(String.valueOf(store.getDefaultInt(PRE_COMPARISON_THRESHOLD_ERROR))); this.comparisonThresholdImprovement.setText(String.valueOf(store.getDefaultInt(PRE_COMPARISON_THRESHOLD_IMPROVEMENT))); // Init eclipse version this.mVersionRadioButton.setSelection(false); this.dVersionRadionButton.setSelection(false); int version = store.getDefaultInt(PRE_ECLIPSE_VERSION); if (version == ECLIPSE_MAINTENANCE_VERSION) { this.mVersionRadioButton.setSelection(true); } else { this.dVersionRadionButton.setSelection(true); } updateBrowseButtonToolTip(version); // Milestones this.milestonesCombo.removeAll(); String prefix = PRE_MILESTONE_BUILDS + "." + version; String milestone = store.getDefaultString(prefix + "0"); int index = 0; while (milestone != null && milestone.length() > 0) { this.milestonesCombo.add(milestone); milestone = store.getDefaultString(prefix + ++index); } // Init last build String lastBuild = store.getDefaultString(PRE_LAST_BUILD); // if (lastBuild.length() == 0) { // this.lastBuildCheckBox.setSelection(false); // this.lastBuildCombo.setEnabled(false); // } else { // this.lastBuildCombo.setEnabled(true); // } this.lastBuildCombo.setText(lastBuild); // Init default default dimension String defaultDimension = store.getDefaultString(PRE_DEFAULT_DIMENSION); this.defaultDimensionCombo.setText(defaultDimension); // Init default generated dimensions this.resultsDimensionsList.add(store.getDefaultString(PRE_RESULTS_DIMENSION+".0")); this.resultsDimensionsList.add(store.getDefaultString(PRE_RESULTS_DIMENSION+".1")); } /** * Initializes states of the controls from the preference store. */ private void initializeValues() { IPreferenceStore store = getPreferenceStore(); // Init database info this.dbConnectionCheckBox.setSelection(store.getBoolean(PRE_DATABASE_CONNECTION)); final boolean dbLocal = store.getBoolean(PRE_DATABASE_LOCAL); if (dbLocal) { this.dbLocalRadioButton.setSelection(true); this.dbRelengRadioButton.setToolTipText(""); } else { this.dbRelengRadioButton.setSelection(true); this.dbRelengRadioButton.setToolTipText(NETWORK_DATABASE_LOCATION); } this.databaseLocationCombo.removeAll(); this.databaseLocationCombo.setText(store.getString(PRE_DATABASE_LOCATION)); for (int i = 0; i < 3; i++) { String history = store.getString(PRE_DATABASE_LOCATION + "." + i); if (history.length() == 0) break; this.databaseLocationCombo.add(history); } updateDatabaseGroup(); // Init status values int writeStatus = store.getInt(PRE_WRITE_STATUS); initStatusValues(writeStatus); // Init comparison thresholds this.comparisonThresholdFailure.setText(String.valueOf(store.getInt(PRE_COMPARISON_THRESHOLD_FAILURE))); this.comparisonThresholdError.setText(String.valueOf(store.getInt(PRE_COMPARISON_THRESHOLD_ERROR))); this.comparisonThresholdImprovement.setText(String.valueOf(store.getInt(PRE_COMPARISON_THRESHOLD_IMPROVEMENT))); // Init eclipse version int version = store.getInt(PRE_ECLIPSE_VERSION); if (version == ECLIPSE_MAINTENANCE_VERSION) { this.mVersionRadioButton.setSelection(true); } else { this.dVersionRadionButton.setSelection(true); } updateBrowseButtonToolTip(version); // Milestones String prefix = PRE_MILESTONE_BUILDS + "." + version; int index = 0; String milestone = store.getString(prefix + index); while (milestone != null && milestone.length() > 0) { this.milestonesCombo.add(milestone); milestone = store.getString(prefix + ++index); } // Init last build String lastBuild = store.getString(PRE_LAST_BUILD); // if (lastBuild.length() == 0) { // this.lastBuildCheckBox.setSelection(false); // this.lastBuildCombo.setEnabled(false); // } else { // this.lastBuildCombo.setEnabled(true); // } this.lastBuildCombo.setText(lastBuild); // Init composite lists initDimensionsLists(); // Init default dimension String defaultDimension = store.getString(PRE_DEFAULT_DIMENSION); this.defaultDimensionCombo.setText(defaultDimension); // Init generated dimensions int count = this.resultsDimensionsList.getItemCount(); int[] indices = new int[count]; int n = 0; String resultsDimension = store.getString(PRE_RESULTS_DIMENSION + "." + n); while (resultsDimension.length() > 0) { indices[n++] = this.resultsDimensionsList.indexOf(resultsDimension); resultsDimension = store.getString(PRE_RESULTS_DIMENSION + "." + n); } if (n < count) { System.arraycopy(indices, 0, indices = new int[n], 0, n); } this.resultsDimensionsList.select(indices); // Init config descriptors /* TODO See whether config descriptors need to be set as preferences or not... this.configDescriptorsTable.clearAll(); int d = 0; String descriptorName = store.getString(PRE_CONFIG_DESCRIPTOR_NAME + "." + d); String descriptorDescription = store.getString(PRE_CONFIG_DESCRIPTOR_DESCRIPTION + "." + d++); while (descriptorName.length() > 0) { TableItem tableItem = new TableItem (this.configDescriptorsTable, SWT.NONE); tableItem.setText (0, descriptorName); tableItem.setText (1, descriptorDescription); descriptorName = store.getString(PRE_CONFIG_DESCRIPTOR_NAME + "." + d); descriptorDescription = store.getString(PRE_CONFIG_DESCRIPTOR_DESCRIPTION + "." + d++); } */ } /** * @param store */ private void initStatusValues(int writeStatus) { this.statusValuesCheckBox.setSelection((writeStatus & STATUS_VALUES) != 0); this.statusErrorNoneRadioButton.setSelection(false); this.statusErrorNoticeableRadioButton.setSelection(false); this.statusErrorSuspiciousRadioButton.setSelection(false); this.statusErrorWeirdRadioButton.setSelection(false); this.statusErrorInvalidRadioButton.setSelection(false); switch (writeStatus & STATUS_ERROR_LEVEL_MASK) { case STATUS_ERROR_NONE: this.statusErrorNoneRadioButton.setSelection(true); break; case STATUS_ERROR_NOTICEABLE: this.statusErrorNoticeableRadioButton.setSelection(true); break; case STATUS_ERROR_SUSPICIOUS: this.statusErrorSuspiciousRadioButton.setSelection(true); break; case STATUS_ERROR_WEIRD: this.statusErrorWeirdRadioButton.setSelection(true); break; case STATUS_ERROR_INVALID: this.statusErrorInvalidRadioButton.setSelection(true); break; } this.statusSmallBuildValueCheckBox.setSelection(false); this.statusSmallDeltaValueCheckBox.setSelection(false); switch (writeStatus & STATUS_SMALL_VALUE_MASK) { case STATUS_SMALL_VALUE_BUILD: this.statusSmallBuildValueCheckBox.setSelection(true); break; case STATUS_SMALL_VALUE_DELTA: this.statusSmallDeltaValueCheckBox.setSelection(true); break; } this.statusStatisticNoneRadioButton.setSelection(false); this.statusStatisticErraticRadioButton.setSelection(false); this.statusStatisticUnstableRadioButton.setSelection(false); switch (writeStatus & STATUS_STATISTICS_MASK) { case 0: this.statusStatisticNoneRadioButton.setSelection(true); break; case STATUS_STATISTICS_ERRATIC: this.statusStatisticErraticRadioButton.setSelection(true); break; case STATUS_STATISTICS_UNSTABLE: this.statusStatisticUnstableRadioButton.setSelection(true); break; } this.statusBuildsToConfirm.setText(String.valueOf(writeStatus & STATUS_BUILDS_NUMBER_MASK)); } /** * (non-Javadoc) Method declared on ModifyListener */ public void modifyText(ModifyEvent event) { // Add default dimension to results if necessary if (event.getSource() == this.defaultDimensionCombo) { String[] resultsDimensions = this.resultsDimensionsList.getSelection(); int length = resultsDimensions.length; String defaultDimension = this.defaultDimensionCombo.getText(); for (int i = 0; i < length; i++) { if (resultsDimensions[i].equals(defaultDimension)) { // Default dim is already set as a results dimension, hence nothing has to be done return; } } System.arraycopy(resultsDimensions, 0, resultsDimensions = new String[length + 1], 0, length); resultsDimensions[length] = defaultDimension; this.resultsDimensionsList.setSelection(resultsDimensions); } // Add default dimension to results if necessary if (event.getSource() == this.milestonesCombo) { // Verify the only digits are entered String milestoneDate = this.milestonesCombo.getText(); final int mLength = milestoneDate.length(); if (mLength > 0) { for (int i=0; i<mLength; i++) { if (!Character.isDigit(milestoneDate.charAt(i))) { String[] items = this.milestonesCombo.getItems(); int length = items.length; for (int j=0; j<length; j++) { if (items[j].equals(milestoneDate)) { // already existing milestone, leave silently if (MessageDialog.openQuestion(getShell(), getDialogTitle(), "Do you want to select milestone "+milestoneDate+" as the last build?")) { String builds[] = this.lastBuildCombo.getItems(); int bLength = builds.length; String milestone = milestoneDate.substring(milestoneDate.indexOf('-')+1); for (int b=0; b<bLength; b++) { if (builds[b].length() > 0 && Util.getBuildDate(builds[b]).equals(milestone)) { this.lastBuildCombo.select(b); break; } } } return; } } openMilestoneErrorMessage(milestoneDate); return; } } } // Do not verify further until a complete milestone date is entered if (mLength < 12) return; // Verify the digits try { String str = milestoneDate.substring(0, 4); int year = Integer.parseInt(str); if (year < 2009 || year > 2020) { // 2020 should be enough! MessageDialog.openError(getShell(), getDialogTitle(), milestoneDate+": "+str+" is an invalid year, only value between 2009 and 2020 is accepted!"); return; } str = milestoneDate.substring(4, 6); int month = Integer.parseInt(str); if (month <= 0 || month > 12) { MessageDialog.openError(getShell(), getDialogTitle(), milestoneDate+": "+str+" is an invalid month, it should be only from 01 to 12!"); return; } str = milestoneDate.substring(6, 8); int day = Integer.parseInt(str); if (day <= 0 || day > 31) { // TODO improve this verification MessageDialog.openError(getShell(), getDialogTitle(), milestoneDate+": "+str+" is an invalid day, it should be only from 01 to 31!"); return; } str = milestoneDate.substring(8, 10); int hour = Integer.parseInt(str); if (hour < 0 || hour > 23) { MessageDialog.openError(getShell(), getDialogTitle(), milestoneDate+": "+str+" is an invalid hour, it should be only from 00 to 23!"); return; } str = milestoneDate.substring(10, 12); int min = Integer.parseInt(str); if (min < 0 || min > 59) { MessageDialog.openError(getShell(), getDialogTitle(), milestoneDate+": "+str+" is invalid minutes, it should be only from 00 to 59!"); return; } } catch (NumberFormatException nfe) { openMilestoneErrorMessage(milestoneDate); } // Get combo info String[] milestones = this.milestonesCombo.getItems(); int length = milestones.length; String lastMilestone = length == 0 ? null : milestones[length-1]; // Verify that the added milestone is valid final String databaseLocation = this.databaseLocationCombo.getText(); char version = databaseLocation.charAt(databaseLocation.length()-1); // Verify that the milestone follow the last one String milestoneName; if (lastMilestone == null) { // No previous last milestone milestoneName = "M1"; } else { // Compare with last milestone if (lastMilestone.charAt(0) == 'M') { char digit = lastMilestone.charAt(1); if (digit == '6') { // M6 is the last dvpt milestone milestoneName = "RC1"; } else { milestoneName = "M" +((char)(digit+1)); } } else if (lastMilestone.startsWith("RC")) { char digit = lastMilestone.charAt(2); if (digit == '4') { // RC4 is the last release candidate milestone milestoneName = "R3_"+version; } else { milestoneName = "RC" +((char)(digit+1)); } } else if (lastMilestone.startsWith("R3_"+version+"-")) { milestoneName = "R3_" + version + "_1"; } else if (lastMilestone.startsWith("R3_"+version+"_")) { char digit = lastMilestone.charAt(5); milestoneName = "R3_" + version + "_" + ((char)(digit+1)); } else { MessageDialog.openError(getShell(), getDialogTitle(), "Unexpected last milestone name: "+lastMilestone+"!"); return; } // Verify the date of the new milestone int lastMilestoneDash = lastMilestone.indexOf('-'); final String lastMilestoneDate = lastMilestone.substring(lastMilestoneDash+1); if (milestoneDate.compareTo(lastMilestoneDate) <= 0) { // TODO improve this verification MessageDialog.openError(getShell(), getDialogTitle(), "Milestone "+milestoneDate+" should be after the last milestone: "+lastMilestoneDate+"!"); return; } } // Verification are ok, ask to add the milestone final String milestone = milestoneName + "-" + milestoneDate; if (MessageDialog.openConfirm(getShell(), getDialogTitle(), milestoneDate+" is a valid milestone date.\n\nDo you want to add the milestone '"+milestone+"' to the preferences?")) { this.milestonesCombo.add(milestone); this.milestonesCombo.setText(""); } } // Verify the 'builds to confirm' number if (event.getSource() == this.statusBuildsToConfirm) { try { int number = Integer.parseInt(this.statusBuildsToConfirm.getText()); - if (number < 1 ) { - this.statusBuildsToConfirm.setText("1"); + if (number < 0) { + this.statusBuildsToConfirm.setText("0"); } else { int buildsNumber = DB_Results.getBuildsNumber(); if (number > buildsNumber) { this.statusBuildsToConfirm.setText(String.valueOf(buildsNumber)); } } } catch (NumberFormatException nfe) { this.statusBuildsToConfirm.setText("1"); } } } /** * @param milestone */ void openMilestoneErrorMessage(String milestone) { MessageDialog.openError(getShell(), getDialogTitle(), milestone+" is an invalid milestone date. Only 'yyyymmddHHMM' format is accepted!"); } /* * (non-Javadoc) Method declared on PreferencePage */ protected void performDefaults() { super.performDefaults(); initializeDefaults(); } /* * (non-Javadoc) Method declared on PreferencePage */ public boolean performOk() { final boolean hasBuildsView = this.buildsView != null; if (hasBuildsView) { storeValues(); try { IEclipsePreferences preferences = new InstanceScope().getNode(PLUGIN_ID); preferences.flush(); this.buildsView.resetView(); } catch (BackingStoreException e) { e.printStackTrace(); return false; } } return true; } /** * Stores the values of the controls back to the preference store. */ private void storeValues() { IPreferenceStore store = getPreferenceStore(); // Set version int version; if (this.mVersionRadioButton.getSelection()) { version = ECLIPSE_MAINTENANCE_VERSION; } else { version = ECLIPSE_DEVELOPMENT_VERSION; } store.setValue(PRE_ECLIPSE_VERSION, version); // Set database values store.setValue(PRE_DATABASE_CONNECTION, this.dbConnectionCheckBox.getSelection()); final boolean dbLocal = this.dbLocalRadioButton.getSelection(); store.setValue(PRE_DATABASE_LOCAL, dbLocal); String location = this.databaseLocationCombo.getText(); if (dbLocal) { store.setValue(PRE_DATABASE_LOCATION, location); } else { store.setValue(PRE_DATABASE_LOCATION, NETWORK_DATABASE_LOCATION); } int count = this.databaseLocationCombo.getItemCount(); for (int i=0; i<count; i++) { String item = this.databaseLocationCombo.getItem(i); if (item.equals(location)) { this.databaseLocationCombo.remove(i); break; } } if (dbLocal) { this.databaseLocationCombo.add(location, 0); } int i=0; for (; i<count; i++) { String item = this.databaseLocationCombo.getItem(i); if (item.length() == 0) break; store.setValue(PRE_DATABASE_LOCATION+"."+i, item); } while (store.getString(PRE_DATABASE_LOCATION+"."+i).length() > 0) { store.setToDefault(PRE_DATABASE_LOCATION+"."+i); i++; } // Set status values int writeStatus = 0; if (this.statusValuesCheckBox.getSelection()) { writeStatus |= STATUS_VALUES; } if (this.statusErrorNoneRadioButton.getSelection()) { writeStatus |= STATUS_ERROR_NONE; } else if (this.statusErrorNoticeableRadioButton.getSelection()) { writeStatus |= STATUS_ERROR_NOTICEABLE; } else if (this.statusErrorSuspiciousRadioButton.getSelection()) { writeStatus |= STATUS_ERROR_SUSPICIOUS; } else if (this.statusErrorWeirdRadioButton.getSelection()) { writeStatus |= STATUS_ERROR_WEIRD; } else if (this.statusErrorInvalidRadioButton.getSelection()) { writeStatus |= STATUS_ERROR_INVALID; } if (this.statusSmallBuildValueCheckBox.getSelection()) { writeStatus |= STATUS_SMALL_VALUE_BUILD; } if (this.statusSmallDeltaValueCheckBox.getSelection()) { writeStatus |= STATUS_SMALL_VALUE_DELTA; } if (this.statusStatisticNoneRadioButton.getSelection()) { writeStatus &= ~STATUS_STATISTICS_MASK; } else if (this.statusStatisticErraticRadioButton.getSelection()) { writeStatus |= STATUS_STATISTICS_ERRATIC; } else if (this.statusStatisticUnstableRadioButton.getSelection()) { writeStatus |= STATUS_STATISTICS_UNSTABLE; } writeStatus += Integer.parseInt(this.statusBuildsToConfirm.getText()); store.setValue(PRE_WRITE_STATUS, writeStatus); // Init comparison thresholds store.setValue(PRE_COMPARISON_THRESHOLD_FAILURE, Integer.parseInt(this.comparisonThresholdFailure.getText())); store.setValue(PRE_COMPARISON_THRESHOLD_ERROR, Integer.parseInt(this.comparisonThresholdError.getText())); store.setValue(PRE_COMPARISON_THRESHOLD_IMPROVEMENT, Integer.parseInt(this.comparisonThresholdImprovement.getText())); // Set milestones String prefix = PRE_MILESTONE_BUILDS + "." + version; count = this.milestonesCombo.getItemCount(); for (i=0; i<count; i++) { store.putValue(prefix + i, this.milestonesCombo.getItem(i)); } Util.setMilestones(this.milestonesCombo.getItems()); // Unset previous additional milestones String milestone = store.getString(prefix + count); while (milestone != null && milestone.length() > 0) { store.putValue(prefix + count++, ""); milestone = store.getString(prefix + count); } // Set last build String lastBuild = this.lastBuildCombo.getText(); store.putValue(PRE_LAST_BUILD, lastBuild); // Set default dimension String defaultDimension = this.defaultDimensionCombo.getText(); store.putValue(PRE_DEFAULT_DIMENSION, defaultDimension); DB_Results.setDefaultDimension(defaultDimension); // Set generated dimensions int[] indices = this.resultsDimensionsList.getSelectionIndices(); int length = indices.length; String[] dimensions = new String[length]; if (length > 0) { for (i = 0; i < indices.length; i++) { dimensions[i] = this.resultsDimensionsList.getItem(indices[i]); store.putValue(PRE_RESULTS_DIMENSION + "." + i, dimensions[i]); } } int currentLength = DB_Results.getResultsDimensions().length; if (currentLength > length) { for (i = currentLength - 1; i >= length; i--) { store.putValue(PRE_RESULTS_DIMENSION + "." + i, ""); // reset extra dimensions } } DB_Results.setResultsDimensions(dimensions); // Set config descriptors /* TODO See whether config descriptors need to be set as preferences or not... TableItem[] items = this.configDescriptorsTable.getItems(); length = items.length; for (int i = 0; i < length; i++) { TableItem item = items[i]; store.putValue(PRE_CONFIG_DESCRIPTOR_NAME + "." + i, item.getText(0)); store.putValue(PRE_CONFIG_DESCRIPTOR_DESCRIPTION + "." + i, item.getText(1)); } */ } /** * (non-Javadoc) Method declared on SelectionListener */ public void widgetDefaultSelected(SelectionEvent event) { } /** * (non-Javadoc) Method declared on SelectionListener */ public void widgetSelected(SelectionEvent event) { // As for directory when 'Local' button is pushed final Object source = event.getSource(); if (source == this.dbLocalBrowseButton) { String location = this.databaseLocationCombo.getText(); String path = getDirectoryPath(location); if (path != null) { // First verify that the selected dir was correct int version; if (this.mVersionRadioButton.getSelection()) { version = ECLIPSE_MAINTENANCE_VERSION; } else { version = ECLIPSE_DEVELOPMENT_VERSION; } File dbDir = new File(path, "perfDb"+version); if (!dbDir.exists() || !dbDir.isDirectory()) { StringBuffer message = new StringBuffer("Invalid performance database directory\n"); message.append(path+" should contain 'perfDb"); message.append(version); message.append("' directory and none was found!"); MessageDialog.openError(getShell(), getDialogTitle(), message.toString()); return; } // Look for selected dir in combo box list int count = this.databaseLocationCombo.getItemCount(); int index = -1; for (int i = 0; i < count; i++) { String item = this.databaseLocationCombo.getItem(i); if (item.length() == 0) { // nothing in the combo-box list break; } if (item.equals(path)) { index = i; break; } } // Set the selected dir the more recent in the previous dirs list if (index != 0) { if (index > 0) { // the dir was used before, but not recently => remove it from previous dirs list this.databaseLocationCombo.remove(index); } // add the selected dir on the top of the previous dirs list this.databaseLocationCombo.add(path, 0); } // Set combo box text this.databaseLocationCombo.setText(path); updateLocalDb(); } } // Reset dabase location when 'Releng' button is pushed if (source == this.dbConnectionCheckBox) { updateDatabaseGroup(); } // Reset dabase location when 'Releng' check-box is checked if (source == this.dbLocalRadioButton) { updateLocalDb(); } // Add default dimension to results if necessary if (source == this.resultsDimensionsList) { String[] resultsDimensions = this.resultsDimensionsList.getSelection(); int length = resultsDimensions.length; String defaultDimension = this.defaultDimensionCombo.getText(); for (int i = 0; i < length; i++) { if (resultsDimensions[i].equals(defaultDimension)) { // Default dim is already set as a results dimension, hence nothing has to be done return; } } System.arraycopy(resultsDimensions, 0, resultsDimensions = new String[length + 1], 0, length); resultsDimensions[length] = defaultDimension; this.resultsDimensionsList.setSelection(resultsDimensions); } // if (source == this.lastBuildCheckBox) { // this.lastBuildCombo.setEnabled(this.lastBuildCheckBox.getSelection()); // } if (source == this.mVersionRadioButton) { if (this.mVersionRadioButton.getSelection()) { updateBrowseButtonToolTip(ECLIPSE_MAINTENANCE_VERSION); } } if (source == this.dVersionRadionButton) { if (this.dVersionRadionButton.getSelection()) { updateBrowseButtonToolTip(ECLIPSE_DEVELOPMENT_VERSION); } } } /* * Update browse tooltip */ void updateBrowseButtonToolTip(int version) { this.dbLocalBrowseButton.setToolTipText("Select the directory where the database was unzipped\n(i.e. should contain the perfDb"+version+" subdirectory)"); } /* * Update database group controls. */ void updateDatabaseGroup() { if (this.dbConnectionCheckBox.getSelection()) { this.dbRelengRadioButton.setEnabled(true); this.dbLocalRadioButton.setEnabled(true); updateLocalDb(); } else { this.dbRelengRadioButton.setEnabled(false); this.dbLocalRadioButton.setEnabled(false); this.databaseLocationCombo.setEnabled(false); this.dbLocalBrowseButton.setEnabled(false); setValid(true); } } /* * Update database location controls. */ void updateLocalDb() { if (this.dbLocalRadioButton.getSelection()) { this.databaseLocationCombo.setEnabled(true); this.dbLocalBrowseButton.setEnabled(true); if (this.databaseLocationCombo.getItemCount() == 0) { this.databaseLocationCombo.setText(""); setValid(false); } else { this.databaseLocationCombo.select(0); setValid(true); } this.dbRelengRadioButton.setToolTipText(""); this.dbLocationLabel.setEnabled(true); } else { this.dbRelengRadioButton.setToolTipText(NETWORK_DATABASE_LOCATION); this.databaseLocationCombo.setText(""); this.databaseLocationCombo.setEnabled(false); this.dbLocalBrowseButton.setEnabled(false); setValid(true); this.dbLocationLabel.setEnabled(false); } } }
true
true
public void modifyText(ModifyEvent event) { // Add default dimension to results if necessary if (event.getSource() == this.defaultDimensionCombo) { String[] resultsDimensions = this.resultsDimensionsList.getSelection(); int length = resultsDimensions.length; String defaultDimension = this.defaultDimensionCombo.getText(); for (int i = 0; i < length; i++) { if (resultsDimensions[i].equals(defaultDimension)) { // Default dim is already set as a results dimension, hence nothing has to be done return; } } System.arraycopy(resultsDimensions, 0, resultsDimensions = new String[length + 1], 0, length); resultsDimensions[length] = defaultDimension; this.resultsDimensionsList.setSelection(resultsDimensions); } // Add default dimension to results if necessary if (event.getSource() == this.milestonesCombo) { // Verify the only digits are entered String milestoneDate = this.milestonesCombo.getText(); final int mLength = milestoneDate.length(); if (mLength > 0) { for (int i=0; i<mLength; i++) { if (!Character.isDigit(milestoneDate.charAt(i))) { String[] items = this.milestonesCombo.getItems(); int length = items.length; for (int j=0; j<length; j++) { if (items[j].equals(milestoneDate)) { // already existing milestone, leave silently if (MessageDialog.openQuestion(getShell(), getDialogTitle(), "Do you want to select milestone "+milestoneDate+" as the last build?")) { String builds[] = this.lastBuildCombo.getItems(); int bLength = builds.length; String milestone = milestoneDate.substring(milestoneDate.indexOf('-')+1); for (int b=0; b<bLength; b++) { if (builds[b].length() > 0 && Util.getBuildDate(builds[b]).equals(milestone)) { this.lastBuildCombo.select(b); break; } } } return; } } openMilestoneErrorMessage(milestoneDate); return; } } } // Do not verify further until a complete milestone date is entered if (mLength < 12) return; // Verify the digits try { String str = milestoneDate.substring(0, 4); int year = Integer.parseInt(str); if (year < 2009 || year > 2020) { // 2020 should be enough! MessageDialog.openError(getShell(), getDialogTitle(), milestoneDate+": "+str+" is an invalid year, only value between 2009 and 2020 is accepted!"); return; } str = milestoneDate.substring(4, 6); int month = Integer.parseInt(str); if (month <= 0 || month > 12) { MessageDialog.openError(getShell(), getDialogTitle(), milestoneDate+": "+str+" is an invalid month, it should be only from 01 to 12!"); return; } str = milestoneDate.substring(6, 8); int day = Integer.parseInt(str); if (day <= 0 || day > 31) { // TODO improve this verification MessageDialog.openError(getShell(), getDialogTitle(), milestoneDate+": "+str+" is an invalid day, it should be only from 01 to 31!"); return; } str = milestoneDate.substring(8, 10); int hour = Integer.parseInt(str); if (hour < 0 || hour > 23) { MessageDialog.openError(getShell(), getDialogTitle(), milestoneDate+": "+str+" is an invalid hour, it should be only from 00 to 23!"); return; } str = milestoneDate.substring(10, 12); int min = Integer.parseInt(str); if (min < 0 || min > 59) { MessageDialog.openError(getShell(), getDialogTitle(), milestoneDate+": "+str+" is invalid minutes, it should be only from 00 to 59!"); return; } } catch (NumberFormatException nfe) { openMilestoneErrorMessage(milestoneDate); } // Get combo info String[] milestones = this.milestonesCombo.getItems(); int length = milestones.length; String lastMilestone = length == 0 ? null : milestones[length-1]; // Verify that the added milestone is valid final String databaseLocation = this.databaseLocationCombo.getText(); char version = databaseLocation.charAt(databaseLocation.length()-1); // Verify that the milestone follow the last one String milestoneName; if (lastMilestone == null) { // No previous last milestone milestoneName = "M1"; } else { // Compare with last milestone if (lastMilestone.charAt(0) == 'M') { char digit = lastMilestone.charAt(1); if (digit == '6') { // M6 is the last dvpt milestone milestoneName = "RC1"; } else { milestoneName = "M" +((char)(digit+1)); } } else if (lastMilestone.startsWith("RC")) { char digit = lastMilestone.charAt(2); if (digit == '4') { // RC4 is the last release candidate milestone milestoneName = "R3_"+version; } else { milestoneName = "RC" +((char)(digit+1)); } } else if (lastMilestone.startsWith("R3_"+version+"-")) { milestoneName = "R3_" + version + "_1"; } else if (lastMilestone.startsWith("R3_"+version+"_")) { char digit = lastMilestone.charAt(5); milestoneName = "R3_" + version + "_" + ((char)(digit+1)); } else { MessageDialog.openError(getShell(), getDialogTitle(), "Unexpected last milestone name: "+lastMilestone+"!"); return; } // Verify the date of the new milestone int lastMilestoneDash = lastMilestone.indexOf('-'); final String lastMilestoneDate = lastMilestone.substring(lastMilestoneDash+1); if (milestoneDate.compareTo(lastMilestoneDate) <= 0) { // TODO improve this verification MessageDialog.openError(getShell(), getDialogTitle(), "Milestone "+milestoneDate+" should be after the last milestone: "+lastMilestoneDate+"!"); return; } } // Verification are ok, ask to add the milestone final String milestone = milestoneName + "-" + milestoneDate; if (MessageDialog.openConfirm(getShell(), getDialogTitle(), milestoneDate+" is a valid milestone date.\n\nDo you want to add the milestone '"+milestone+"' to the preferences?")) { this.milestonesCombo.add(milestone); this.milestonesCombo.setText(""); } } // Verify the 'builds to confirm' number if (event.getSource() == this.statusBuildsToConfirm) { try { int number = Integer.parseInt(this.statusBuildsToConfirm.getText()); if (number < 1 ) { this.statusBuildsToConfirm.setText("1"); } else { int buildsNumber = DB_Results.getBuildsNumber(); if (number > buildsNumber) { this.statusBuildsToConfirm.setText(String.valueOf(buildsNumber)); } } } catch (NumberFormatException nfe) { this.statusBuildsToConfirm.setText("1"); } } }
public void modifyText(ModifyEvent event) { // Add default dimension to results if necessary if (event.getSource() == this.defaultDimensionCombo) { String[] resultsDimensions = this.resultsDimensionsList.getSelection(); int length = resultsDimensions.length; String defaultDimension = this.defaultDimensionCombo.getText(); for (int i = 0; i < length; i++) { if (resultsDimensions[i].equals(defaultDimension)) { // Default dim is already set as a results dimension, hence nothing has to be done return; } } System.arraycopy(resultsDimensions, 0, resultsDimensions = new String[length + 1], 0, length); resultsDimensions[length] = defaultDimension; this.resultsDimensionsList.setSelection(resultsDimensions); } // Add default dimension to results if necessary if (event.getSource() == this.milestonesCombo) { // Verify the only digits are entered String milestoneDate = this.milestonesCombo.getText(); final int mLength = milestoneDate.length(); if (mLength > 0) { for (int i=0; i<mLength; i++) { if (!Character.isDigit(milestoneDate.charAt(i))) { String[] items = this.milestonesCombo.getItems(); int length = items.length; for (int j=0; j<length; j++) { if (items[j].equals(milestoneDate)) { // already existing milestone, leave silently if (MessageDialog.openQuestion(getShell(), getDialogTitle(), "Do you want to select milestone "+milestoneDate+" as the last build?")) { String builds[] = this.lastBuildCombo.getItems(); int bLength = builds.length; String milestone = milestoneDate.substring(milestoneDate.indexOf('-')+1); for (int b=0; b<bLength; b++) { if (builds[b].length() > 0 && Util.getBuildDate(builds[b]).equals(milestone)) { this.lastBuildCombo.select(b); break; } } } return; } } openMilestoneErrorMessage(milestoneDate); return; } } } // Do not verify further until a complete milestone date is entered if (mLength < 12) return; // Verify the digits try { String str = milestoneDate.substring(0, 4); int year = Integer.parseInt(str); if (year < 2009 || year > 2020) { // 2020 should be enough! MessageDialog.openError(getShell(), getDialogTitle(), milestoneDate+": "+str+" is an invalid year, only value between 2009 and 2020 is accepted!"); return; } str = milestoneDate.substring(4, 6); int month = Integer.parseInt(str); if (month <= 0 || month > 12) { MessageDialog.openError(getShell(), getDialogTitle(), milestoneDate+": "+str+" is an invalid month, it should be only from 01 to 12!"); return; } str = milestoneDate.substring(6, 8); int day = Integer.parseInt(str); if (day <= 0 || day > 31) { // TODO improve this verification MessageDialog.openError(getShell(), getDialogTitle(), milestoneDate+": "+str+" is an invalid day, it should be only from 01 to 31!"); return; } str = milestoneDate.substring(8, 10); int hour = Integer.parseInt(str); if (hour < 0 || hour > 23) { MessageDialog.openError(getShell(), getDialogTitle(), milestoneDate+": "+str+" is an invalid hour, it should be only from 00 to 23!"); return; } str = milestoneDate.substring(10, 12); int min = Integer.parseInt(str); if (min < 0 || min > 59) { MessageDialog.openError(getShell(), getDialogTitle(), milestoneDate+": "+str+" is invalid minutes, it should be only from 00 to 59!"); return; } } catch (NumberFormatException nfe) { openMilestoneErrorMessage(milestoneDate); } // Get combo info String[] milestones = this.milestonesCombo.getItems(); int length = milestones.length; String lastMilestone = length == 0 ? null : milestones[length-1]; // Verify that the added milestone is valid final String databaseLocation = this.databaseLocationCombo.getText(); char version = databaseLocation.charAt(databaseLocation.length()-1); // Verify that the milestone follow the last one String milestoneName; if (lastMilestone == null) { // No previous last milestone milestoneName = "M1"; } else { // Compare with last milestone if (lastMilestone.charAt(0) == 'M') { char digit = lastMilestone.charAt(1); if (digit == '6') { // M6 is the last dvpt milestone milestoneName = "RC1"; } else { milestoneName = "M" +((char)(digit+1)); } } else if (lastMilestone.startsWith("RC")) { char digit = lastMilestone.charAt(2); if (digit == '4') { // RC4 is the last release candidate milestone milestoneName = "R3_"+version; } else { milestoneName = "RC" +((char)(digit+1)); } } else if (lastMilestone.startsWith("R3_"+version+"-")) { milestoneName = "R3_" + version + "_1"; } else if (lastMilestone.startsWith("R3_"+version+"_")) { char digit = lastMilestone.charAt(5); milestoneName = "R3_" + version + "_" + ((char)(digit+1)); } else { MessageDialog.openError(getShell(), getDialogTitle(), "Unexpected last milestone name: "+lastMilestone+"!"); return; } // Verify the date of the new milestone int lastMilestoneDash = lastMilestone.indexOf('-'); final String lastMilestoneDate = lastMilestone.substring(lastMilestoneDash+1); if (milestoneDate.compareTo(lastMilestoneDate) <= 0) { // TODO improve this verification MessageDialog.openError(getShell(), getDialogTitle(), "Milestone "+milestoneDate+" should be after the last milestone: "+lastMilestoneDate+"!"); return; } } // Verification are ok, ask to add the milestone final String milestone = milestoneName + "-" + milestoneDate; if (MessageDialog.openConfirm(getShell(), getDialogTitle(), milestoneDate+" is a valid milestone date.\n\nDo you want to add the milestone '"+milestone+"' to the preferences?")) { this.milestonesCombo.add(milestone); this.milestonesCombo.setText(""); } } // Verify the 'builds to confirm' number if (event.getSource() == this.statusBuildsToConfirm) { try { int number = Integer.parseInt(this.statusBuildsToConfirm.getText()); if (number < 0) { this.statusBuildsToConfirm.setText("0"); } else { int buildsNumber = DB_Results.getBuildsNumber(); if (number > buildsNumber) { this.statusBuildsToConfirm.setText(String.valueOf(buildsNumber)); } } } catch (NumberFormatException nfe) { this.statusBuildsToConfirm.setText("1"); } } }
diff --git a/src/main/org/codehaus/groovy/classgen/ClassGenerator.java b/src/main/org/codehaus/groovy/classgen/ClassGenerator.java index 743796406..40f7b081d 100644 --- a/src/main/org/codehaus/groovy/classgen/ClassGenerator.java +++ b/src/main/org/codehaus/groovy/classgen/ClassGenerator.java @@ -1,1773 +1,1776 @@ /* * $Id$ * * Copyright 2003 (C) James Strachan and Bob Mcwhirter. All Rights Reserved. * * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: 1. Redistributions of source code must retain * copyright statements and notices. Redistributions must also contain a copy * of this document. 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 "groovy" must not be used to endorse or promote products derived * from this Software without prior written permission of The Codehaus. For * written permission, please contact [email protected]. 4. Products derived * from this Software may not be called "groovy" nor may "groovy" appear in * their names without prior written permission of The Codehaus. "groovy" is a * registered trademark of The Codehaus. 5. Due credit should be given to The * Codehaus - http://groovy.codehaus.org/ * * THIS SOFTWARE IS PROVIDED BY THE CODEHAUS AND CONTRIBUTORS ``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 CODEHAUS OR ITS 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.codehaus.groovy.classgen; import groovy.lang.GString; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ConstructorNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.GroovyClassVisitor; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.InnerClassNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.PropertyNode; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.ast.expr.ArrayExpression; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.BooleanExpression; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.ClosureExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.ConstructorCallExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.FieldExpression; import org.codehaus.groovy.ast.expr.GStringExpression; import org.codehaus.groovy.ast.expr.ListExpression; import org.codehaus.groovy.ast.expr.MapEntryExpression; import org.codehaus.groovy.ast.expr.MapExpression; import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.ast.expr.PropertyExpression; import org.codehaus.groovy.ast.expr.RangeExpression; import org.codehaus.groovy.ast.expr.RegexExpression; import org.codehaus.groovy.ast.expr.StaticMethodCallExpression; import org.codehaus.groovy.ast.expr.TupleExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.AssertStatement; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.CatchStatement; import org.codehaus.groovy.ast.stmt.DoWhileStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.ForStatement; import org.codehaus.groovy.ast.stmt.IfStatement; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.ast.stmt.SwitchStatement; import org.codehaus.groovy.ast.stmt.TryCatchStatement; import org.codehaus.groovy.ast.stmt.WhileStatement; import org.codehaus.groovy.runtime.InvokerException; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.NoSuchClassException; import org.codehaus.groovy.syntax.Token; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.CodeVisitor; import org.objectweb.asm.Constants; import org.objectweb.asm.Label; import org.objectweb.asm.Type; /** * Generates Java class versions of Groovy classes * * @author <a href="mailto:[email protected]">James Strachan</a> * @version $Revision$ */ public class ClassGenerator implements GroovyClassVisitor, GroovyCodeVisitor, Constants { private ClassVisitor cw; private ClassLoader classLoader; private CodeVisitor cv; private GeneratorContext context; private String sourceFile; // current class details private ClassNode classNode; private String internalClassName; private String internalBaseClassName; /** maps the variable names to the JVM indices */ private Map variableStack = new HashMap(); /** have we output a return statement yet */ private boolean outputReturn; /** are we on the left or right of an expression */ private boolean leftHandExpression; // cached values MethodCaller invokeMethodMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeMethod"); MethodCaller invokeStaticMethodMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeStaticMethod"); MethodCaller invokeConstructorMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeConstructor"); MethodCaller getPropertyMethod = MethodCaller.newStatic(InvokerHelper.class, "getProperty"); MethodCaller setPropertyMethod = MethodCaller.newStatic(InvokerHelper.class, "setProperty"); MethodCaller asIteratorMethod = MethodCaller.newStatic(InvokerHelper.class, "asIterator"); MethodCaller asBool = MethodCaller.newStatic(InvokerHelper.class, "asBool"); MethodCaller compareIdenticalMethod = MethodCaller.newStatic(InvokerHelper.class, "compareIdentical"); MethodCaller compareEqualMethod = MethodCaller.newStatic(InvokerHelper.class, "compareEqual"); MethodCaller compareNotEqualMethod = MethodCaller.newStatic(InvokerHelper.class, "compareNotEqual"); MethodCaller compareLessThanMethod = MethodCaller.newStatic(InvokerHelper.class, "compareLessThan"); MethodCaller compareLessThanEqualMethod = MethodCaller.newStatic(InvokerHelper.class, "compareLessThanEqual"); MethodCaller compareGreaterThanMethod = MethodCaller.newStatic(InvokerHelper.class, "compareGreaterThan"); MethodCaller compareGreaterThanEqualMethod = MethodCaller.newStatic(InvokerHelper.class, "compareGreaterThanEqual"); MethodCaller createListMethod = MethodCaller.newStatic(InvokerHelper.class, "createList"); MethodCaller createTupleMethod = MethodCaller.newStatic(InvokerHelper.class, "createTuple"); MethodCaller createMapMethod = MethodCaller.newStatic(InvokerHelper.class, "createMap"); MethodCaller createRangeMethod = MethodCaller.newStatic(InvokerHelper.class, "createRange"); MethodCaller assertFailedMethod = MethodCaller.newStatic(InvokerHelper.class, "assertFailed"); MethodCaller iteratorNextMethod = MethodCaller.newInterface(Iterator.class, "next"); MethodCaller iteratorHasNextMethod = MethodCaller.newInterface(Iterator.class, "hasNext"); // current stack index private int idx; // exception blocks list private List exceptionBlocks = new ArrayList(); // inner classes created while generating bytecode private LinkedList innerClasses = new LinkedList(); private boolean definingParameters; private Set syntheticStaticFields = new HashSet(); private int lastVariableIndex; private MethodNode methodNode; public ClassGenerator( GeneratorContext context, ClassVisitor classVisitor, ClassLoader classLoader, String sourceFile) { this.context = context; this.cw = classVisitor; this.classLoader = classLoader; this.sourceFile = sourceFile; } public LinkedList getInnerClasses() { return innerClasses; } public ClassLoader getClassLoader() { return classLoader; } // GroovyClassVisitor interface //------------------------------------------------------------------------- public void visitClass(ClassNode classNode) { try { syntheticStaticFields.clear(); this.classNode = classNode; this.internalClassName = getClassInternalName(classNode.getName()); this.internalBaseClassName = getClassInternalName(classNode.getSuperClass()); cw.visit( classNode.getModifiers(), internalClassName, internalBaseClassName, getClassInternalNames(classNode.getInterfaces()), sourceFile); classNode.visitContents(this); createSyntheticStaticFields(); for (Iterator iter = innerClasses.iterator(); iter.hasNext();) { ClassNode innerClass = (ClassNode) iter.next(); String innerClassName = innerClass.getName(); String innerClassInternalName = getClassInternalName(innerClassName); cw.visitInnerClass( innerClassInternalName, internalClassName, innerClassName, innerClass.getModifiers()); } cw.visitEnd(); } catch (InvokerException e) { e.setModule(classNode.getModule()); throw e; } } public void visitConstructor(ConstructorNode node) { // creates a MethodWriter for the (implicit) constructor //String methodType = Type.getMethodDescriptor(VOID_TYPE, ) this.methodNode = null; String methodType = getMethodDescriptor("void", node.getParameters()); cv = cw.visitMethod(node.getModifiers(), "<init>", methodType, null); resetVariableStack(node.getParameters()); Statement code = node.getCode(); if (code == null || !firstStatementIsSuperMethodCall(code)) { // invokes the super class constructor cv.visitVarInsn(ALOAD, 0); cv.visitMethodInsn(INVOKESPECIAL, internalBaseClassName, "<init>", "()V"); } if (code != null) { code.visit(this); } cv.visitInsn(RETURN); cv.visitMaxs(0, 0); } public void visitMethod(MethodNode node) { //System.out.println("Visiting method: " + node.getName() + " with // return type: " + node.getReturnType()); this.methodNode = node; String methodType = getMethodDescriptor(node.getReturnType(), node.getParameters()); cv = cw.visitMethod(node.getModifiers(), node.getName(), methodType, null); resetVariableStack(node.getParameters()); outputReturn = false; node.getCode().visit(this); if (!outputReturn) { cv.visitInsn(RETURN); } // lets do all the exception blocks for (Iterator iter = exceptionBlocks.iterator(); iter.hasNext();) { Runnable runnable = (Runnable) iter.next(); runnable.run(); } exceptionBlocks.clear(); cv.visitMaxs(0, 0); } public void visitField(FieldNode fieldNode) { onLineNumber(fieldNode); //System.out.println("Visiting field: " + fieldNode.getName() + " on // class: " + classNode.getName()); Object fieldValue = null; Expression expression = fieldNode.getInitialValueExpression(); if (expression instanceof ConstantExpression) { ConstantExpression constantExp = (ConstantExpression) expression; Object value = constantExp.getValue(); if (isPrimitiveFieldType(value)) { fieldValue = value; } } cw.visitField( fieldNode.getModifiers(), fieldNode.getName(), getTypeDescription(fieldNode.getType()), fieldValue); } /** * Creates a getter, setter and field */ public void visitProperty(PropertyNode statement) { onLineNumber(statement); } // GroovyCodeVisitor interface //------------------------------------------------------------------------- // Statements //------------------------------------------------------------------------- public void visitForLoop(ForStatement loop) { onLineNumber(loop); loop.getCollectionExpression().visit(this); asIteratorMethod.call(cv); int iteratorIdx = defineVariable(createIteratorName(), "java.util.Iterator", false).getIndex(); cv.visitVarInsn(ASTORE, iteratorIdx); int iIdx = defineVariable(loop.getVariable(), "java.lang.Object", false).getIndex(); Label label1 = new Label(); cv.visitJumpInsn(GOTO, label1); Label label2 = new Label(); cv.visitLabel(label2); cv.visitVarInsn(ALOAD, iteratorIdx); iteratorNextMethod.call(cv); cv.visitVarInsn(ASTORE, iIdx); loop.getLoopBlock().visit(this); cv.visitLabel(label1); cv.visitVarInsn(ALOAD, iteratorIdx); iteratorHasNextMethod.call(cv); cv.visitJumpInsn(IFNE, label2); } public void visitWhileLoop(WhileStatement loop) { onLineNumber(loop); /* // quick hack if (!methodNode.isStatic()) { cv.visitVarInsn(ALOAD, 0); } */ Label l0 = new Label(); cv.visitJumpInsn(GOTO, l0); Label l1 = new Label(); cv.visitLabel(l1); loop.getLoopBlock().visit(this); cv.visitLabel(l0); //cv.visitVarInsn(ALOAD, 0); loop.getBooleanExpression().visit(this); cv.visitJumpInsn(IFNE, l1); } public void visitDoWhileLoop(DoWhileStatement loop) { onLineNumber(loop); Label l0 = new Label(); cv.visitLabel(l0); loop.getLoopBlock().visit(this); loop.getBooleanExpression().visit(this); cv.visitJumpInsn(IFNE, l0); } public void visitIfElse(IfStatement ifElse) { onLineNumber(ifElse); ifElse.getBooleanExpression().visit(this); Label l0 = new Label(); cv.visitJumpInsn(IFEQ, l0); //cv.visitVarInsn(ALOAD, 0); ifElse.getIfBlock().visit(this); Label l1 = new Label(); cv.visitJumpInsn(GOTO, l1); cv.visitLabel(l0); ifElse.getElseBlock().visit(this); cv.visitLabel(l1); } public void visitAssertStatement(AssertStatement statement) { onLineNumber(statement); //System.out.println("Assert: " + statement.getLineNumber() + " for: " + statement.getText()); BooleanExpression booleanExpression = statement.getBooleanExpression(); booleanExpression.visit(this); Label l0 = new Label(); cv.visitJumpInsn(IFEQ, l0); // do nothing Label l1 = new Label(); cv.visitJumpInsn(GOTO, l1); cv.visitLabel(l0); // push expression string onto stack String expressionText = booleanExpression.getText(); List list = new ArrayList(); addVariableNames(booleanExpression, list); if (list.isEmpty()) { cv.visitLdcInsn(expressionText); } else { boolean first = true; // lets create a new expression cv.visitTypeInsn(NEW, "java/lang/StringBuffer"); cv.visitInsn(DUP); cv.visitLdcInsn(expressionText + ". Values: "); cv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuffer", "<init>", "(Ljava/lang/String;)V"); cv.visitVarInsn(ASTORE, ++idx); for (Iterator iter = list.iterator(); iter.hasNext();) { String name = (String) iter.next(); String text = name + " = "; if (first) { first = false; } else { text = ", " + text; } cv.visitVarInsn(ALOAD, idx); cv.visitLdcInsn(text); cv.visitMethodInsn( INVOKEVIRTUAL, "java/lang/StringBuffer", "append", "(Ljava/lang/String;)Ljava/lang/StringBuffer;"); cv.visitInsn(POP); cv.visitVarInsn(ALOAD, idx); new VariableExpression(name).visit(this); cv.visitMethodInsn( INVOKEVIRTUAL, "java/lang/StringBuffer", "append", "(Ljava/lang/Object;)Ljava/lang/StringBuffer;"); cv.visitInsn(POP); } cv.visitVarInsn(ALOAD, idx); } // now the optional exception expression statement.getMessageExpression().visit(this); assertFailedMethod.call(cv); cv.visitLabel(l1); } private void addVariableNames(Expression expression, List list) { if (expression instanceof BooleanExpression) { BooleanExpression boolExp = (BooleanExpression) expression; addVariableNames(boolExp.getExpression(), list); } else if (expression instanceof BinaryExpression) { BinaryExpression binExp = (BinaryExpression) expression; addVariableNames(binExp.getLeftExpression(), list); addVariableNames(binExp.getRightExpression(), list); } else if (expression instanceof VariableExpression) { VariableExpression varExp = (VariableExpression) expression; list.add(varExp.getVariable()); } } public void visitTryCatchFinally(TryCatchStatement statement) { onLineNumber(statement); CatchStatement catchStatement = statement.getCatchStatement(0); String exceptionType = checkValidType(catchStatement.getExceptionType(), catchStatement, "in catch statement"); String exceptionVar = (catchStatement != null) ? catchStatement.getVariable() : createExceptionVariableName(); int exceptionIndex = defineVariable(exceptionVar, exceptionType, false).getIndex(); int index2 = exceptionIndex + 1; int index3 = index2 + 1; final Label l0 = new Label(); cv.visitLabel(l0); statement.getTryStatement().visit(this); final Label l1 = new Label(); cv.visitLabel(l1); Label l2 = new Label(); cv.visitJumpInsn(JSR, l2); final Label l3 = new Label(); cv.visitLabel(l3); Label l4 = new Label(); cv.visitJumpInsn(GOTO, l4); final Label l5 = new Label(); cv.visitLabel(l5); cv.visitVarInsn(ASTORE, exceptionIndex); if (catchStatement != null) { catchStatement.visit(this); } cv.visitJumpInsn(JSR, l2); final Label l6 = new Label(); cv.visitLabel(l6); cv.visitJumpInsn(GOTO, l4); final Label l7 = new Label(); cv.visitLabel(l7); cv.visitVarInsn(ASTORE, index2); cv.visitJumpInsn(JSR, l2); final Label l8 = new Label(); cv.visitLabel(l8); cv.visitVarInsn(ALOAD, index2); cv.visitInsn(ATHROW); cv.visitLabel(l2); cv.visitVarInsn(ASTORE, index3); statement.getFinallyStatement().visit(this); cv.visitVarInsn(RET, index3); cv.visitLabel(l4); // rest of code goes here... final String exceptionTypeInternalName = (catchStatement != null) ? getTypeDescription(exceptionType) : null; exceptionBlocks.add(new Runnable() { public void run() { cv.visitTryCatchBlock(l0, l1, l5, exceptionTypeInternalName); cv.visitTryCatchBlock(l0, l3, l7, null); cv.visitTryCatchBlock(l5, l6, l7, null); cv.visitTryCatchBlock(l7, l8, l7, null); } }); } public void visitSwitch(SwitchStatement statement) { // TODO Auto-generated method stub } public void visitReturnStatement(ReturnStatement statement) { onLineNumber(statement); statement.getExpression().visit(this); Expression assignExpr = assignmentExpression(statement.getExpression()); if (assignExpr != null) { leftHandExpression = false; assignExpr.visit(this); } Class c = getExpressionType(statement.getExpression()); //return is based on class type //TODO: make work with arrays if (c == Boolean.class) { Label l0 = new Label(); cv.visitJumpInsn(IFEQ, l0); cv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;"); cv.visitInsn(ARETURN); cv.visitLabel(l0); cv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;"); cv.visitInsn(ARETURN); } else if (!c.isPrimitive()) { // we may need to cast String returnType = methodNode.getReturnType(); if (returnType != null && !returnType.equals("java.lang.Object")) { doCast(returnType); } cv.visitInsn(ARETURN); } else { if (c == double.class) { cv.visitInsn(DRETURN); } else if (c == float.class) { cv.visitInsn(FRETURN); } else if (c == long.class) { cv.visitInsn(LRETURN); } else { //byte,short,boolean,int are all IRETURN cv.visitInsn(IRETURN); } } outputReturn = true; } public void visitExpressionStatement(ExpressionStatement statement) { onLineNumber(statement); Expression expression = statement.getExpression(); expression.visit(this); if (expression instanceof MethodCallExpression && !MethodCallExpression.isSuperMethodCall((MethodCallExpression) expression)) { cv.visitInsn(POP); } } // Expressions //------------------------------------------------------------------------- public void visitBinaryExpression(BinaryExpression expression) { switch (expression.getOperation().getType()) { case Token.EQUAL : evaluateEqual(expression); break; case Token.COMPARE_IDENTICAL : evaluateBinaryExpression(compareIdenticalMethod, expression); break; case Token.COMPARE_EQUAL : evaluateBinaryExpression(compareEqualMethod, expression); break; case Token.COMPARE_NOT_EQUAL : evaluateBinaryExpression(compareNotEqualMethod, expression); break; case Token.COMPARE_GREATER_THAN : evaluateBinaryExpression(compareGreaterThanMethod, expression); break; case Token.COMPARE_GREATER_THAN_EQUAL : evaluateBinaryExpression(compareGreaterThanEqualMethod, expression); break; case Token.COMPARE_LESS_THAN : evaluateBinaryExpression(compareLessThanMethod, expression); break; case Token.COMPARE_LESS_THAN_EQUAL : evaluateBinaryExpression(compareLessThanEqualMethod, expression); break; case Token.LOGICAL_AND : evaluateLogicalAndExpression(expression); break; case Token.LOGICAL_OR : evaluateLogicalOrExpression(expression); break; case Token.PLUS : evaluateBinaryExpression("plus", expression); break; case Token.MINUS : evaluateBinaryExpression("minus", expression); break; case Token.MULTIPLY : evaluateBinaryExpression("multiply", expression); break; case Token.DIVIDE : evaluateBinaryExpression("divide", expression); break; case Token.KEYWORD_INSTANCEOF : evaluateInstanceof(expression); break; default : throw new ClassGeneratorException("Operation: " + expression.getOperation() + " not supported"); } } protected void evaluateLogicalOrExpression(BinaryExpression expression) { visitBooleanExpression(new BooleanExpression(expression.getLeftExpression())); Label l0 = new Label(); Label l2 = new Label(); cv.visitJumpInsn(IFEQ, l0); cv.visitLabel(l2); visitConstantExpression(ConstantExpression.TRUE); Label l1 = new Label(); cv.visitJumpInsn(GOTO, l1); cv.visitLabel(l0); visitBooleanExpression(new BooleanExpression(expression.getRightExpression())); cv.visitJumpInsn(IFNE, l2); visitConstantExpression(ConstantExpression.FALSE); cv.visitLabel(l1); } protected void evaluateLogicalAndExpression(BinaryExpression expression) { visitBooleanExpression(new BooleanExpression(expression.getLeftExpression())); Label l0 = new Label(); cv.visitJumpInsn(IFEQ, l0); visitBooleanExpression(new BooleanExpression(expression.getRightExpression())); cv.visitJumpInsn(IFEQ, l0); visitConstantExpression(ConstantExpression.TRUE); Label l1 = new Label(); cv.visitJumpInsn(GOTO, l1); cv.visitLabel(l0); visitConstantExpression(ConstantExpression.FALSE); cv.visitLabel(l1); } public void visitClosureExpression(ClosureExpression expression) { ClassNode innerClass = createClosureClass(expression); addInnerClass(innerClass); String innerClassinternalName = getClassInternalName(innerClass.getName()); ClassNode owner = innerClass.getOuterClass(); String ownerTypeName = owner.getName(); if (isStaticMethod()) { ownerTypeName = "java.lang.Class"; } if (classNode instanceof InnerClassNode) { // lets load the outer this int paramIdx = defineVariable(createArgumentsName(), "java.lang.Object", false).getIndex(); cv.visitVarInsn(ALOAD, 0); cv.visitFieldInsn(GETFIELD, internalClassName, "owner", getTypeDescription(ownerTypeName)); cv.visitVarInsn(ASTORE, paramIdx); cv.visitTypeInsn(NEW, innerClassinternalName); cv.visitInsn(DUP); cv.visitVarInsn(ALOAD, paramIdx); } else { cv.visitTypeInsn(NEW, innerClassinternalName); cv.visitInsn(DUP); if (isStaticMethod()) { visitClassExpression(new ClassExpression(ownerTypeName)); } else { cv.visitVarInsn(ALOAD, 0); } } if (innerClass.getSuperClass().equals("groovy.lang.Closure")) { if (isStaticMethod()) { /** @todo could maybe stash this expression in a JVM variable from previous statement above */ visitClassExpression(new ClassExpression(ownerTypeName)); } else { cv.visitVarInsn(ALOAD, 0); } } // we may need to pass in some other constructors cv.visitMethodInsn( INVOKESPECIAL, innerClassinternalName, "<init>", "(L" + getClassInternalName(ownerTypeName) + ";Ljava/lang/Object;)V"); } public void visitRegexExpression(RegexExpression expression) { // TODO Auto-generated method stub } public void visitConstantExpression(ConstantExpression expression) { Object value = expression.getValue(); if (value == null) { cv.visitInsn(ACONST_NULL); } else if (value instanceof String) { cv.visitLdcInsn(value); } else if (value instanceof Number) { /** @todo it would be more efficient to generate class constants */ Number n = (Number) value; String className = getClassInternalName(value.getClass().getName()); cv.visitTypeInsn(NEW, className); cv.visitInsn(DUP); String methodType = "(I)V"; if (n instanceof Double) { methodType = "(D)V"; } else if (n instanceof Float) { methodType = "(F)V"; } cv.visitLdcInsn(n); cv.visitMethodInsn(INVOKESPECIAL, className, "<init>", methodType); } else if (value instanceof Boolean) { Boolean bool = (Boolean) value; String text = (bool.booleanValue()) ? "TRUE" : "FALSE"; cv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", text, "Ljava/lang/Boolean;"); } else { throw new ClassGeneratorException( "Cannot generate bytecode for constant: " + value + " of type: " + value.getClass().getName()); } } public void visitBooleanExpression(BooleanExpression expression) { expression.getExpression().visit(this); if (!comparisonExpression(expression.getExpression())) { asBool.call(cv); } } public void visitMethodCallExpression(MethodCallExpression call) { this.leftHandExpression = false; Expression arguments = call.getArguments(); if (arguments instanceof TupleExpression) { TupleExpression tupleExpression = (TupleExpression) arguments; int size = tupleExpression.getExpressions().size(); if (size == 0) { arguments = ConstantExpression.EMPTY_ARRAY; } else if (size == 1) { arguments = (Expression) tupleExpression.getExpressions().get(0); } } if (MethodCallExpression.isSuperMethodCall(call)) { /** @todo handle method types! */ cv.visitVarInsn(ALOAD, 0); cv.visitVarInsn(ALOAD, 1); cv.visitMethodInsn(INVOKESPECIAL, internalBaseClassName, "<init>", "(Ljava/lang/Object;)V"); } else { if (argumentsUseStack(arguments)) { int paramIdx = defineVariable(createArgumentsName(), "java.lang.Object", false).getIndex(); arguments.visit(this); cv.visitVarInsn(ASTORE, paramIdx); call.getObjectExpression().visit(this); cv.visitLdcInsn(call.getMethod()); cv.visitVarInsn(ALOAD, paramIdx); idx--; } else { call.getObjectExpression().visit(this); cv.visitLdcInsn(call.getMethod()); arguments.visit(this); } invokeMethodMethod.call(cv); } } public void visitStaticMethodCallExpression(StaticMethodCallExpression call) { this.leftHandExpression = false; Expression arguments = call.getArguments(); if (arguments instanceof TupleExpression) { TupleExpression tupleExpression = (TupleExpression) arguments; int size = tupleExpression.getExpressions().size(); if (size == 0) { arguments = ConstantExpression.EMPTY_ARRAY; } else if (size == 1) { arguments = (Expression) tupleExpression.getExpressions().get(0); } } cv.visitLdcInsn(call.getType()); cv.visitLdcInsn(call.getMethod()); arguments.visit(this); invokeStaticMethodMethod.call(cv); } public void visitConstructorCallExpression(ConstructorCallExpression call) { this.leftHandExpression = false; Expression arguments = call.getArguments(); if (arguments instanceof TupleExpression) { TupleExpression tupleExpression = (TupleExpression) arguments; int size = tupleExpression.getExpressions().size(); if (size == 0) { arguments = ConstantExpression.EMPTY_ARRAY; } else if (size == 1) { arguments = (Expression) tupleExpression.getExpressions().get(0); } } // lets check that the type exists String type = checkValidType(call.getType(), call, "in constructor call"); //System.out.println("Constructing: " + type); //visitClassExpression(new ClassExpression(type)); cv.visitLdcInsn(type); arguments.visit(this); invokeConstructorMethod.call(cv); } public void visitPropertyExpression(PropertyExpression expression) { boolean left = leftHandExpression; // we need to clear the LHS flag to avoid "this." evaluating as ASTORE // rather than ALOAD leftHandExpression = false; int i = idx + 1; if (left) { cv.visitVarInsn(ASTORE, i); } Expression objectExpression = expression.getObjectExpression(); objectExpression.visit(this); cv.visitLdcInsn(expression.getProperty()); if (left) { cv.visitVarInsn(ALOAD, i); setPropertyMethod.call(cv); } else { getPropertyMethod.call(cv); } //cv.visitInsn(POP); } public void visitFieldExpression(FieldExpression expression) { FieldNode field = expression.getField(); boolean isStatic = field.isStatic(); if (!isStatic && !leftHandExpression) { cv.visitVarInsn(ALOAD, 0); } String type = field.getType(); if (leftHandExpression) { // this may be superflous doCast(type); } int opcode = (leftHandExpression) ? ((isStatic) ? PUTSTATIC : PUTFIELD) : ((isStatic) ? GETSTATIC : GETFIELD); String ownerName = (field.getOwner().equals(classNode.getName())) ? internalClassName : Type.getInternalName(loadClass(field.getOwner())); cv.visitFieldInsn(opcode, ownerName, expression.getFieldName(), getTypeDescription(type)); // lets push this back on the stack // if (! isStatic && leftHandExpression) { // cv.visitVarInsn(ALOAD, 0); // } } protected void visitOuterFieldExpression(FieldExpression expression) { ClassNode outerClassNode = classNode.getOuterClass(); int valueIdx = idx + 1; if (leftHandExpression) { cv.visitVarInsn(ASTORE, valueIdx); } cv.visitVarInsn(ALOAD, 0); cv.visitFieldInsn(GETFIELD, internalClassName, "owner", getTypeDescription(outerClassNode.getName())); FieldNode field = expression.getField(); boolean isStatic = field.isStatic(); int opcode = (leftHandExpression) ? ((isStatic) ? PUTSTATIC : PUTFIELD) : ((isStatic) ? GETSTATIC : GETFIELD); String ownerName = getClassInternalName(outerClassNode.getName()); if (leftHandExpression) { cv.visitVarInsn(ALOAD, valueIdx); } cv.visitFieldInsn(opcode, ownerName, expression.getFieldName(), getTypeDescription(field.getType())); } public void visitVariableExpression(VariableExpression expression) { // lets see if the variable is a field String variableName = expression.getVariable(); if (isStaticMethod() && variableName.equals("this")) { visitClassExpression(new ClassExpression(classNode.getName())); return; } if (variableName.equals("super")) { visitClassExpression(new ClassExpression(classNode.getSuperClass())); return; } String className = classNode.getClassNameForExpression(variableName); if (className != null) { visitClassExpression(new ClassExpression(className)); return; } FieldNode field = classNode.getField(variableName); if (field != null) { visitFieldExpression(new FieldExpression(field)); } else { field = classNode.getOuterField(variableName); if (field != null) { visitOuterFieldExpression(new FieldExpression(field)); } else { String name = variableName; Variable variable = null; if (!leftHandExpression) { variable = (Variable) variableStack.get(name); } else { variable = defineVariable(name, "java.lang.Object"); } if (variable == null) { - //System.out.println("No such variable '" + name + "' available, so trying property"); visitPropertyExpression(new PropertyExpression(new VariableExpression("this"), variableName)); + // We need to store this in a local variable now since it has been looked at in this scope and possibly + // compared and it hasn't been referenced before. + cv.visitInsn(DUP); + cv.visitVarInsn(ASTORE, idx + 1); return; } String type = variable.getType(); int index = variable.getIndex(); lastVariableIndex = index; if (leftHandExpression) { //TODO: make work with arrays if (type.equals("double")) { cv.visitVarInsn(DSTORE, index); } else if (type.equals("float")) { cv.visitVarInsn(FSTORE, index); } else if (type.equals("long")) { cv.visitVarInsn(LSTORE, index); } else if ( type.equals("byte") || type.equals("short") || type.equals("boolean") || type.equals("int")) { cv.visitVarInsn(ISTORE, index); } else { cv.visitVarInsn(ASTORE, index); } } else { //TODO: make work with arrays if (type.equals("double")) { cv.visitVarInsn(DLOAD, index); } else if (type.equals("float")) { cv.visitVarInsn(FLOAD, index); } else if (type.equals("long")) { cv.visitVarInsn(LLOAD, index); } else if ( type.equals("byte") || type.equals("short") || type.equals("boolean") || type.equals("int")) { cv.visitVarInsn(ILOAD, index); } else { cv.visitVarInsn(ALOAD, index); } } } } } protected boolean firstStatementIsSuperMethodCall(Statement code) { if (code instanceof BlockStatement) { BlockStatement block = (BlockStatement) code; if (!block.getStatements().isEmpty()) { Object expr = block.getStatements().get(0); if (expr instanceof ExpressionStatement) { ExpressionStatement expStmt = (ExpressionStatement) expr; expr = expStmt.getExpression(); if (expr instanceof MethodCallExpression) { return MethodCallExpression.isSuperMethodCall((MethodCallExpression) expr); } } } } return false; } protected void createSyntheticStaticFields() { for (Iterator iter = syntheticStaticFields.iterator(); iter.hasNext();) { String staticFieldName = (String) iter.next(); // generate a field node cw.visitField(ACC_STATIC + ACC_SYNTHETIC, staticFieldName, "Ljava/lang/Class;", null); } if (!syntheticStaticFields.isEmpty()) { cv = cw.visitMethod(ACC_STATIC + ACC_SYNTHETIC, "class$", "(Ljava/lang/String;)Ljava/lang/Class;", null); Label l0 = new Label(); cv.visitLabel(l0); cv.visitVarInsn(ALOAD, 0); cv.visitMethodInsn(INVOKESTATIC, "java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;"); Label l1 = new Label(); cv.visitLabel(l1); cv.visitInsn(ARETURN); Label l2 = new Label(); cv.visitLabel(l2); cv.visitVarInsn(ASTORE, 1); cv.visitTypeInsn(NEW, "java/lang/NoClassDefFoundError"); cv.visitInsn(DUP); cv.visitVarInsn(ALOAD, 1); cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/ClassNotFoundException", "getMessage", "()Ljava/lang/String;"); cv.visitMethodInsn(INVOKESPECIAL, "java/lang/NoClassDefFoundError", "<init>", "(Ljava/lang/String;)V"); cv.visitInsn(ATHROW); cv.visitTryCatchBlock(l0, l1, l2, "java/lang/ClassNotFoundException"); cv.visitMaxs(3, 2); cw.visitEnd(); } } public void visitClassExpression(ClassExpression expression) { String type = expression.getText(); final String staticFieldName = (type.equals(classNode.getName())) ? "class$0" : "class$" + type.replace('.', '$'); syntheticStaticFields.add(staticFieldName); cv.visitFieldInsn(GETSTATIC, internalClassName, staticFieldName, "Ljava/lang/Class;"); Label l0 = new Label(); cv.visitJumpInsn(IFNONNULL, l0); cv.visitLdcInsn(type); cv.visitMethodInsn(INVOKESTATIC, internalClassName, "class$", "(Ljava/lang/String;)Ljava/lang/Class;"); cv.visitInsn(DUP); cv.visitFieldInsn(PUTSTATIC, internalClassName, staticFieldName, "Ljava/lang/Class;"); Label l1 = new Label(); cv.visitJumpInsn(GOTO, l1); cv.visitLabel(l0); cv.visitFieldInsn(GETSTATIC, internalClassName, staticFieldName, "Ljava/lang/Class;"); cv.visitLabel(l1); } public void visitRangeExpression(RangeExpression expression) { leftHandExpression = false; expression.getFrom().visit(this); leftHandExpression = false; expression.getTo().visit(this); createRangeMethod.call(cv); } public void visitMapEntryExpression(MapEntryExpression expression) { } public void visitMapExpression(MapExpression expression) { List entries = expression.getMapEntryExpressions(); int size = entries.size(); pushConstant(size * 2); cv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); int i = 0; for (Iterator iter = entries.iterator(); iter.hasNext();) { MapEntryExpression entry = (MapEntryExpression) iter.next(); cv.visitInsn(DUP); pushConstant(i++); entry.getKeyExpression().visit(this); cv.visitInsn(AASTORE); cv.visitInsn(DUP); pushConstant(i++); entry.getValueExpression().visit(this); cv.visitInsn(AASTORE); } createMapMethod.call(cv); } public void visitTupleExpression(TupleExpression expression) { int size = expression.getExpressions().size(); pushConstant(size); cv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); for (int i = 0; i < size; i++) { cv.visitInsn(DUP); pushConstant(i); expression.getExpression(i).visit(this); cv.visitInsn(AASTORE); } createTupleMethod.call(cv); } public void visitArrayExpression(ArrayExpression expression) { int size = expression.getExpressions().size(); pushConstant(size); String typeName = getClassInternalName(expression.getType()); cv.visitTypeInsn(ANEWARRAY, typeName); for (int i = 0; i < size; i++) { cv.visitInsn(DUP); pushConstant(i); Expression elementExpression = expression.getExpression(i); if (elementExpression == null) { ConstantExpression.NULL.visit(this); } else { elementExpression.visit(this); } cv.visitInsn(AASTORE); } } public void visitListExpression(ListExpression expression) { int size = expression.getExpressions().size(); pushConstant(size); cv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); for (int i = 0; i < size; i++) { cv.visitInsn(DUP); pushConstant(i); expression.getExpression(i).visit(this); cv.visitInsn(AASTORE); } createListMethod.call(cv); } public void visitGStringExpression(GStringExpression expression) { int size = expression.getValues().size(); pushConstant(size); cv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); for (int i = 0; i < size; i++) { cv.visitInsn(DUP); pushConstant(i); expression.getValue(i).visit(this); cv.visitInsn(AASTORE); } int paramIdx = defineVariable(createArgumentsName(), "java.lang.Object", false).getIndex(); cv.visitVarInsn(ASTORE, paramIdx); ClassNode innerClass = createGStringClass(expression); addInnerClass(innerClass); String innerClassinternalName = getClassInternalName(innerClass.getName()); cv.visitTypeInsn(NEW, innerClassinternalName); cv.visitInsn(DUP); cv.visitVarInsn(ALOAD, paramIdx); cv.visitMethodInsn(INVOKESPECIAL, innerClassinternalName, "<init>", "([Ljava/lang/Object;)V"); } // Implementation methods //------------------------------------------------------------------------- protected boolean addInnerClass(ClassNode innerClass) { innerClass.setModule(classNode.getModule()); return innerClasses.add(innerClass); } protected ClassNode createClosureClass(ClosureExpression expression) { ClassNode owner = classNode; if (owner instanceof InnerClassNode) { owner = owner.getOuterClass(); } String outerClassName = owner.getName(); String name = outerClassName + "$" + context.getNextInnerClassIdx(); if (isStaticMethod()) { outerClassName = "java.lang.Class"; } Parameter[] parameters = expression.getParameters(); if (parameters == null || parameters.length == 0) { // lets create a default 'it' parameter parameters = new Parameter[] { new Parameter("it")}; } InnerClassNode answer = new InnerClassNode(owner, name, ACC_PUBLIC, "groovy.lang.Closure"); answer.addMethod("doCall", ACC_PUBLIC, "java.lang.Object", parameters, expression.getCode()); FieldNode field = answer.addField("owner", ACC_PRIVATE, outerClassName, null); // lets make the constructor BlockStatement block = new BlockStatement(); block.addStatement( new ExpressionStatement( new MethodCallExpression( new VariableExpression("super"), "<init>", new VariableExpression("outerInstance")))); block.addStatement( new ExpressionStatement( new BinaryExpression( new FieldExpression(field), Token.equal(-1, -1), new VariableExpression("outerInstance")))); Parameter[] contructorParams = new Parameter[] { new Parameter(outerClassName, "outerInstance"), new Parameter("java.lang.Object", "delegate")}; answer.addConstructor(ACC_PUBLIC, contructorParams, block); return answer; } protected ClassNode createGStringClass(GStringExpression expression) { ClassNode owner = classNode; if (owner instanceof InnerClassNode) { owner = owner.getOuterClass(); } String outerClassName = owner.getName(); String name = outerClassName + "$" + context.getNextInnerClassIdx(); InnerClassNode answer = new InnerClassNode(owner, name, ACC_PUBLIC, GString.class.getName()); FieldNode stringsField = answer.addField( "strings", ACC_PRIVATE | ACC_STATIC, "java.lang.String[]", new ArrayExpression("java.lang.String", expression.getStrings())); answer.addMethod( "getStrings", ACC_PUBLIC, "java.lang.String[]", Parameter.EMPTY_ARRAY, new ReturnStatement(new FieldExpression(stringsField))); // lets make the constructor BlockStatement block = new BlockStatement(); block.addStatement( new ExpressionStatement( new MethodCallExpression(new VariableExpression("super"), "<init>", new VariableExpression("values")))); Parameter[] contructorParams = new Parameter[] { new Parameter("java.lang.Object[]", "values")}; answer.addConstructor(ACC_PUBLIC, contructorParams, block); return answer; } protected void doCast(String type) { cv.visitTypeInsn(CHECKCAST, type.endsWith("[]") ? getTypeDescription(type) : getClassInternalName(type)); } protected void evaluateBinaryExpression(String method, BinaryExpression expression) { Expression leftExpression = expression.getLeftExpression(); // if (isNonStaticField(leftExpression)) { // cv.visitVarInsn(ALOAD, 0); // } // leftHandExpression = false; leftExpression.visit(this); cv.visitLdcInsn(method); leftHandExpression = false; new ArgumentListExpression(new Expression[] { expression.getRightExpression() }).visit(this); // expression.getRightExpression().visit(this); invokeMethodMethod.call(cv); } protected void evaluateBinaryExpression(MethodCaller compareMethod, BinaryExpression expression) { Expression leftExpression = expression.getLeftExpression(); if (isNonStaticField(leftExpression)) { cv.visitVarInsn(ALOAD, 0); } leftHandExpression = false; leftExpression.visit(this); leftHandExpression = false; expression.getRightExpression().visit(this); // now lets invoke the method compareMethod.call(cv); } protected void evaluateEqual(BinaryExpression expression) { // lets evaluate the RHS then hopefully the LHS will be a field Expression leftExpression = expression.getLeftExpression(); if (isNonStaticField(leftExpression)) { cv.visitVarInsn(ALOAD, 0); } leftHandExpression = false; Expression rightExpression = expression.getRightExpression(); rightExpression.visit(this); if (comparisonExpression(rightExpression)) { Label l0 = new Label(); cv.visitJumpInsn(IFEQ, l0); cv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;"); Label l1 = new Label(); cv.visitJumpInsn(GOTO, l1); cv.visitLabel(l0); cv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;"); cv.visitLabel(l1); } leftHandExpression = true; leftExpression.visit(this); leftHandExpression = false; } protected void evaluateInstanceof(BinaryExpression expression) { expression.getLeftExpression().visit(this); Expression rightExp = expression.getRightExpression(); String className = null; if (rightExp instanceof ClassExpression) { ClassExpression classExp = (ClassExpression) rightExp; className = classExp.getType(); } else { throw new RuntimeException( "Right hand side of the instanceof keyworld must be a class name, not: " + rightExp); } String classInternalName = getClassInternalName(className); cv.visitTypeInsn(INSTANCEOF, classInternalName); } /** * @return true if the given argument expression requires the stack, in * which case the arguments are evaluated first, stored in the * variable stack and then reloaded to make a method call */ protected boolean argumentsUseStack(Expression arguments) { return arguments instanceof TupleExpression || arguments instanceof ClosureExpression; } /** * @return true if the given expression represents a non-static field */ protected boolean isNonStaticField(Expression expression) { FieldNode field = null; if (expression instanceof VariableExpression) { VariableExpression varExp = (VariableExpression) expression; field = classNode.getField(varExp.getVariable()); } else if (expression instanceof FieldExpression) { FieldExpression fieldExp = (FieldExpression) expression; field = classNode.getField(fieldExp.getFieldName()); } if (field != null) { return !field.isStatic(); } return false; } protected boolean isThisExpression(Expression expression) { if (expression instanceof VariableExpression) { VariableExpression varExp = (VariableExpression) expression; return varExp.getVariable().equals("this"); } return false; } protected Expression assignmentExpression(Expression expression) { if (expression instanceof BinaryExpression) { BinaryExpression binExp = (BinaryExpression) expression; if (binExp.getOperation().getType() == Token.EQUAL) { return binExp.getLeftExpression(); } } return null; } protected boolean comparisonExpression(Expression expression) { if (expression instanceof BinaryExpression) { BinaryExpression binExpr = (BinaryExpression) expression; switch (binExpr.getOperation().getType()) { case Token.COMPARE_EQUAL : case Token.COMPARE_GREATER_THAN : case Token.COMPARE_GREATER_THAN_EQUAL : case Token.COMPARE_LESS_THAN : case Token.COMPARE_LESS_THAN_EQUAL : case Token.COMPARE_IDENTICAL : case Token.COMPARE_NOT_EQUAL : case Token.KEYWORD_INSTANCEOF : return true; } } else if (expression instanceof BooleanExpression) { return true; } return false; } protected void onLineNumber(ASTNode statement) { int number = statement.getLineNumber(); if (number >= 0 && cv != null) { cv.visitLineNumber(number, new Label()); } } protected void pushConstant(int value) { switch (value) { case 0 : cv.visitInsn(ICONST_0); break; case 1 : cv.visitInsn(ICONST_1); break; case 2 : cv.visitInsn(ICONST_2); break; case 3 : cv.visitInsn(ICONST_3); break; case 4 : cv.visitInsn(ICONST_4); break; case 5 : cv.visitInsn(ICONST_5); break; default : cv.visitIntInsn(BIPUSH, value); break; } } /** * @return the last ID used by the stack */ protected int getLastStackId() { return variableStack.size(); } protected void resetVariableStack(Parameter[] parameters) { idx = 0; variableStack.clear(); // lets push this onto the stack definingParameters = true; if (!isStaticMethod()) { defineVariable("this", classNode.getName()).getIndex(); } // now lets create indices for the parameteres for (int i = 0; i < parameters.length; i++) { defineVariable(parameters[i].getName(), parameters[i].getType()); } definingParameters = false; } /** * Defines the given variable in scope and assigns it to the stack */ protected Variable defineVariable(String name, String type) { return defineVariable(name, type, true); } protected Variable defineVariable(String name, String type, boolean define) { Variable answer = (Variable) variableStack.get(name); if (answer == null) { idx = Math.max(idx, variableStack.size()); answer = new Variable(idx, type, name); variableStack.put(name, answer); if (define && !definingParameters && !leftHandExpression) { // using new variable inside a comparison expression // so lets initialize it too cv.visitInsn(ACONST_NULL); cv.visitVarInsn(ASTORE, idx); } } return answer; } protected String checkValidType(String type, ASTNode node, String message) { String original = type; if (type != null) { if (classNode.getNameWithoutPackage().equals(type)) { return classNode.getName(); } for (int i = 0; i < 2; i++) { if (context.getCompileUnit().getClass(type) != null) { return type; } try { classLoader.loadClass(type); return type; } catch (Throwable e) { // fall through } // lets try the system class loader try { Class.forName(type); return type; } catch (Throwable e) { // fall through } // lets try class in same package String packageName = classNode.getPackageName(); if (packageName == null || packageName.length() <= 0) { break; } type = packageName + "." + type; } } throw new NoSuchClassException(original, node, message); } protected String createIteratorName() { return "__iterator" + idx; } protected String createArgumentsName() { return "__argumentList" + idx; } private String createExceptionVariableName() { return "__exception" + idx; } /** * @return if the type of the expression can be determined at compile time * then this method returns the type - otherwise java.lang.Object * is returned. */ protected Class getExpressionType(Expression expression) { if (comparisonExpression(expression)) { return Boolean.class; } /** @todo we need a way to determine this from an expression */ return Object.class; } /** * @return true if the value is an Integer, a Float, a Long, a Double or a * String . */ protected boolean isPrimitiveFieldType(Object value) { return value instanceof String || value instanceof Integer || value instanceof Double || value instanceof Long || value instanceof Float; } protected boolean isStaticMethod() { if (methodNode == null) { // we're in a constructor return false; } return methodNode.isStatic(); } /** * @return an array of ASM internal names of the type */ private String[] getClassInternalNames(String[] names) { int size = names.length; String[] answer = new String[size]; for (int i = 0; i < size; i++) { answer[i] = getClassInternalName(names[i]); } return answer; } /** * @return the ASM internal name of the type */ protected String getClassInternalName(String name) { if (name == null) { return "java/lang/Object"; } String answer = name.replace('.', '/'); if (answer.endsWith("[]")) { return "[" + answer.substring(0, answer.length() - 2); } return answer; } /** * @return the ASM method type descriptor */ protected String getMethodDescriptor(String returnTypeName, Parameter[] paramTypeNames) { // lets avoid class loading StringBuffer buffer = new StringBuffer("("); for (int i = 0; i < paramTypeNames.length; i++) { buffer.append(getTypeDescription(paramTypeNames[i].getType())); } buffer.append(")"); buffer.append(getTypeDescription(returnTypeName)); return buffer.toString(); } /** * @return the ASM type description */ protected String getTypeDescription(String name) { // lets avoid class loading // return getType(name).getDescriptor(); if (name == null) { return "Ljava/lang/Object;"; } if (name.equals("void")) { return "V"; } String prefix = ""; if (name.endsWith("[]")) { prefix = "["; name = name.substring(0, name.length() - 2); } return prefix + "L" + name.replace('.', '/') + ";"; } /** * @return the ASM type for the given class name */ protected Type getType(String className) { if (className.equals("void")) { return Type.VOID_TYPE; } return Type.getType(loadClass(className)); //return Type.getType(className); } /** * @return loads the given type name */ protected Class loadClass(String name) { try { return getClassLoader().loadClass(name); } catch (ClassNotFoundException e) { throw new ClassGeneratorException("Could not load class: " + name + " reason: " + e, e); } } }
false
true
public void visitVariableExpression(VariableExpression expression) { // lets see if the variable is a field String variableName = expression.getVariable(); if (isStaticMethod() && variableName.equals("this")) { visitClassExpression(new ClassExpression(classNode.getName())); return; } if (variableName.equals("super")) { visitClassExpression(new ClassExpression(classNode.getSuperClass())); return; } String className = classNode.getClassNameForExpression(variableName); if (className != null) { visitClassExpression(new ClassExpression(className)); return; } FieldNode field = classNode.getField(variableName); if (field != null) { visitFieldExpression(new FieldExpression(field)); } else { field = classNode.getOuterField(variableName); if (field != null) { visitOuterFieldExpression(new FieldExpression(field)); } else { String name = variableName; Variable variable = null; if (!leftHandExpression) { variable = (Variable) variableStack.get(name); } else { variable = defineVariable(name, "java.lang.Object"); } if (variable == null) { //System.out.println("No such variable '" + name + "' available, so trying property"); visitPropertyExpression(new PropertyExpression(new VariableExpression("this"), variableName)); return; } String type = variable.getType(); int index = variable.getIndex(); lastVariableIndex = index; if (leftHandExpression) { //TODO: make work with arrays if (type.equals("double")) { cv.visitVarInsn(DSTORE, index); } else if (type.equals("float")) { cv.visitVarInsn(FSTORE, index); } else if (type.equals("long")) { cv.visitVarInsn(LSTORE, index); } else if ( type.equals("byte") || type.equals("short") || type.equals("boolean") || type.equals("int")) { cv.visitVarInsn(ISTORE, index); } else { cv.visitVarInsn(ASTORE, index); } } else { //TODO: make work with arrays if (type.equals("double")) { cv.visitVarInsn(DLOAD, index); } else if (type.equals("float")) { cv.visitVarInsn(FLOAD, index); } else if (type.equals("long")) { cv.visitVarInsn(LLOAD, index); } else if ( type.equals("byte") || type.equals("short") || type.equals("boolean") || type.equals("int")) { cv.visitVarInsn(ILOAD, index); } else { cv.visitVarInsn(ALOAD, index); } } } } }
public void visitVariableExpression(VariableExpression expression) { // lets see if the variable is a field String variableName = expression.getVariable(); if (isStaticMethod() && variableName.equals("this")) { visitClassExpression(new ClassExpression(classNode.getName())); return; } if (variableName.equals("super")) { visitClassExpression(new ClassExpression(classNode.getSuperClass())); return; } String className = classNode.getClassNameForExpression(variableName); if (className != null) { visitClassExpression(new ClassExpression(className)); return; } FieldNode field = classNode.getField(variableName); if (field != null) { visitFieldExpression(new FieldExpression(field)); } else { field = classNode.getOuterField(variableName); if (field != null) { visitOuterFieldExpression(new FieldExpression(field)); } else { String name = variableName; Variable variable = null; if (!leftHandExpression) { variable = (Variable) variableStack.get(name); } else { variable = defineVariable(name, "java.lang.Object"); } if (variable == null) { visitPropertyExpression(new PropertyExpression(new VariableExpression("this"), variableName)); // We need to store this in a local variable now since it has been looked at in this scope and possibly // compared and it hasn't been referenced before. cv.visitInsn(DUP); cv.visitVarInsn(ASTORE, idx + 1); return; } String type = variable.getType(); int index = variable.getIndex(); lastVariableIndex = index; if (leftHandExpression) { //TODO: make work with arrays if (type.equals("double")) { cv.visitVarInsn(DSTORE, index); } else if (type.equals("float")) { cv.visitVarInsn(FSTORE, index); } else if (type.equals("long")) { cv.visitVarInsn(LSTORE, index); } else if ( type.equals("byte") || type.equals("short") || type.equals("boolean") || type.equals("int")) { cv.visitVarInsn(ISTORE, index); } else { cv.visitVarInsn(ASTORE, index); } } else { //TODO: make work with arrays if (type.equals("double")) { cv.visitVarInsn(DLOAD, index); } else if (type.equals("float")) { cv.visitVarInsn(FLOAD, index); } else if (type.equals("long")) { cv.visitVarInsn(LLOAD, index); } else if ( type.equals("byte") || type.equals("short") || type.equals("boolean") || type.equals("int")) { cv.visitVarInsn(ILOAD, index); } else { cv.visitVarInsn(ALOAD, index); } } } } }
diff --git a/src/lib/com/izforge/izpack/installer/Unpacker.java b/src/lib/com/izforge/izpack/installer/Unpacker.java index 3dddc9095..76a4dfc35 100644 --- a/src/lib/com/izforge/izpack/installer/Unpacker.java +++ b/src/lib/com/izforge/izpack/installer/Unpacker.java @@ -1,614 +1,619 @@ /* * $Id$ * IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved. * * http://izpack.org/ * http://izpack.codehaus.org/ * * Copyright 2001 Johannes Lehtinen * * 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.izforge.izpack.installer; import com.izforge.izpack.*; import com.izforge.izpack.event.InstallerListener; import com.izforge.izpack.util.*; import java.io.*; import java.lang.reflect.Constructor; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.jar.Pack200; /** * Unpacker class. * * @author Julien Ponge * @author Johannes Lehtinen */ public class Unpacker extends UnpackerBase { private static final String tempSubPath = "/IzpackWebTemp"; private Pack200.Unpacker unpacker; /** * The constructor. * * @param idata The installation data. * @param handler The installation progress handler. */ public Unpacker(AutomatedInstallData idata, AbstractUIProgressHandler handler) { super(idata, handler); } /* (non-Javadoc) * @see com.izforge.izpack.installer.IUnpacker#run() */ public void run() { addToInstances(); try { // // Initialisations FileOutputStream out = null; ArrayList<ParsableFile> parsables = new ArrayList<ParsableFile>(); ArrayList<ExecutableFile> executables = new ArrayList<ExecutableFile>(); ArrayList<UpdateCheck> updatechecks = new ArrayList<UpdateCheck>(); List packs = idata.selectedPacks; int npacks = packs.size(); handler.startAction("Unpacking", npacks); udata = UninstallData.getInstance(); // Custom action listener stuff --- load listeners ---- List[] customActions = getCustomActions(); // Custom action listener stuff --- beforePacks ---- informListeners(customActions, InstallerListener.BEFORE_PACKS, idata, npacks, handler); packs = idata.selectedPacks; npacks = packs.size(); // We unpack the selected packs for (int i = 0; i < npacks; i++) { // We get the pack stream //int n = idata.allPacks.indexOf(packs.get(i)); Pack p = (Pack) packs.get(i); // evaluate condition if (p.hasCondition()) { if (rules != null) { if (!rules.isConditionTrue(p.getCondition())) { // skip pack, condition is not fullfilled. continue; } } else { // TODO: skip pack, because condition can not be checked } } // Custom action listener stuff --- beforePack ---- informListeners(customActions, InstallerListener.BEFORE_PACK, packs.get(i), npacks, handler); ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(p.id, p.uninstall)); // We unpack the files int nfiles = objIn.readInt(); // We get the internationalized name of the pack final Pack pack = ((Pack) packs.get(i)); String stepname = pack.name;// the message to be passed to the // installpanel if (langpack != null && !(pack.id == null || "".equals(pack.id))) { final String name = langpack.getString(pack.id); if (name != null && !"".equals(name)) { stepname = name; } } if (pack.isHidden()){ // TODO: hide the pack completely // hide the pack name if pack is hidden stepname = ""; } handler.nextStep(stepname, i + 1, nfiles); for (int j = 0; j < nfiles; j++) { // We read the header PackFile pf = (PackFile) objIn.readObject(); // TODO: reaction if condition can not be checked if (pf.hasCondition() && (rules != null)) { if (!rules.isConditionTrue(pf.getCondition())) { if (!pf.isBackReference()){ // skip, condition is not fulfilled objIn.skip(pf.length()); } continue; } } if (OsConstraint.oneMatchesCurrentSystem(pf.osConstraints())) { // We translate & build the path String path = IoHelper.translatePath(pf.getTargetPath(), vs); File pathFile = new File(path); File dest = pathFile; if (!pf.isDirectory()) { dest = pathFile.getParentFile(); } if (!dest.exists()) { // If there are custom actions which would be called // at // creating a directory, create it recursively. List fileListeners = customActions[customActions.length - 1]; if (fileListeners != null && fileListeners.size() > 0) { mkDirsWithEnhancement(dest, pf, customActions); } else // Create it in on step. { if (!dest.mkdirs()) { handler.emitError("Error creating directories", "Could not create directory\n" + dest.getPath()); handler.stopAction(); this.result = false; return; } } } if (pf.isDirectory()) { continue; } // Custom action listener stuff --- beforeFile ---- informListeners(customActions, InstallerListener.BEFORE_FILE, pathFile, pf, null); // We add the path to the log, udata.addFile(path, pack.uninstall); handler.progress(j, path); // if this file exists and should not be overwritten, // check // what to do if ((pathFile.exists()) && (pf.override() != PackFile.OVERRIDE_TRUE)) { boolean overwritefile = false; // don't overwrite file if the user said so if (pf.override() != PackFile.OVERRIDE_FALSE) { if (pf.override() == PackFile.OVERRIDE_TRUE) { overwritefile = true; } else if (pf.override() == PackFile.OVERRIDE_UPDATE) { // check mtime of involved files // (this is not 100% perfect, because the // already existing file might // still be modified but the new installed // is just a bit newer; we would // need the creation time of the existing // file or record with which mtime // it was installed...) overwritefile = (pathFile.lastModified() < pf.lastModified()); } else { int def_choice = -1; if (pf.override() == PackFile.OVERRIDE_ASK_FALSE) { def_choice = AbstractUIHandler.ANSWER_NO; } if (pf.override() == PackFile.OVERRIDE_ASK_TRUE) { def_choice = AbstractUIHandler.ANSWER_YES; } int answer = handler.askQuestion(idata.langpack .getString("InstallPanel.overwrite.title") + " - " + pathFile.getName(), idata.langpack .getString("InstallPanel.overwrite.question") + pathFile.getAbsolutePath(), AbstractUIHandler.CHOICES_YES_NO, def_choice); overwritefile = (answer == AbstractUIHandler.ANSWER_YES); } } if (!overwritefile) { if (!pf.isBackReference() && !((Pack) packs.get(i)).loose) { + if ( pf.isPack200Jar() ) { + objIn.skip( Integer.SIZE / 8 ); + } + else { objIn.skip(pf.length()); } + } continue; } } // We copy the file InputStream pis = objIn; if (pf.isBackReference()) { InputStream is = getPackAsStream(pf.previousPackId, pack.uninstall); pis = new ObjectInputStream(is); // must wrap for blockdata use by objectstream // (otherwise strange result) // skip on underlaying stream (for some reason not // possible on ObjectStream) is.skip(pf.offsetInPreviousPack - 4); // but the stream header is now already read (== 4 // bytes) } else if (((Pack) packs.get(i)).loose) { /* Old way of doing the job by using the (absolute) sourcepath. * Since this is very likely to fail and does not confirm to the documentation, * prefer using relative path's pis = new FileInputStream(pf.sourcePath); */ File resolvedFile = new File(getAbsolutInstallSource(), pf .getRelativeSourcePath()); if (!resolvedFile.exists()) { //try alternative destination - the current working directory //user.dir is likely (depends on launcher type) the current directory of the executable or jar-file... final File userDir = new File(System.getProperty("user.dir")); resolvedFile = new File(userDir, pf.getRelativeSourcePath()); } if (resolvedFile.exists()) { pis = new FileInputStream(resolvedFile); //may have a different length & last modified than we had at compiletime, therefore we have to build a new PackFile for the copy process... pf = new PackFile(resolvedFile.getParentFile(), resolvedFile, pf.getTargetPath(), pf.osConstraints(), pf.override(), pf.getAdditionals()); } else { //file not found //issue a warning (logging api pending) //since this file was loosely bundled, we continue with the installation. System.out.println("Could not find loosely bundled file: " + pf.getRelativeSourcePath()); if (!handler.emitWarning("File not found", "Could not find loosely bundled file: " + pf.getRelativeSourcePath())) { throw new InstallerException("Installation cancelled"); } continue; } } if (pf.isPack200Jar()) { int key = objIn.readInt(); InputStream pack200Input = Unpacker.class.getResourceAsStream("/packs/pack200-" + key); Pack200.Unpacker unpacker = getPack200Unpacker(); java.util.jar.JarOutputStream jarOut = new java.util.jar.JarOutputStream(new FileOutputStream(pathFile)); unpacker.unpack(pack200Input, jarOut); jarOut.close(); } else { out = new FileOutputStream(pathFile); byte[] buffer = new byte[5120]; long bytesCopied = 0; while (bytesCopied < pf.length()) { if (performInterrupted()) { // Interrupt was initiated; perform it. out.close(); if (pis != objIn) { pis.close(); } return; } int maxBytes = (int) Math.min(pf.length() - bytesCopied, buffer.length); int bytesInBuffer = pis.read(buffer, 0, maxBytes); if (bytesInBuffer == -1) { throw new IOException("Unexpected end of stream (installer corrupted?)"); } out.write(buffer, 0, bytesInBuffer); bytesCopied += bytesInBuffer; } out.close(); } if (pis != objIn) { pis.close(); } // Set file modification time if specified if (pf.lastModified() >= 0) { pathFile.setLastModified(pf.lastModified()); } // Custom action listener stuff --- afterFile ---- informListeners(customActions, InstallerListener.AFTER_FILE, pathFile, pf, null); } else { if (!pf.isBackReference()) { objIn.skip(pf.length()); } } } // Load information about parsable files int numParsables = objIn.readInt(); for (int k = 0; k < numParsables; k++) { ParsableFile pf = (ParsableFile) objIn.readObject(); if (pf.hasCondition() && (rules != null)) { if (!rules.isConditionTrue(pf.getCondition())) { // skip, condition is not fulfilled continue; } } pf.path = IoHelper.translatePath(pf.path, vs); parsables.add(pf); } // Load information about executable files int numExecutables = objIn.readInt(); for (int k = 0; k < numExecutables; k++) { ExecutableFile ef = (ExecutableFile) objIn.readObject(); if (ef.hasCondition() && (rules != null)) { if (!rules.isConditionTrue(ef.getCondition())) { // skip, condition is false continue; } } ef.path = IoHelper.translatePath(ef.path, vs); if (null != ef.argList && !ef.argList.isEmpty()) { String arg = null; for (int j = 0; j < ef.argList.size(); j++) { arg = ef.argList.get(j); arg = IoHelper.translatePath(arg, vs); ef.argList.set(j, arg); } } executables.add(ef); if (ef.executionStage == ExecutableFile.UNINSTALL) { udata.addExecutable(ef); } } // Custom action listener stuff --- uninstall data ---- handleAdditionalUninstallData(udata, customActions); // Load information about updatechecks int numUpdateChecks = objIn.readInt(); for (int k = 0; k < numUpdateChecks; k++) { UpdateCheck uc = (UpdateCheck) objIn.readObject(); updatechecks.add(uc); } objIn.close(); if (performInterrupted()) { // Interrupt was initiated; perform it. return; } // Custom action listener stuff --- afterPack ---- informListeners(customActions, InstallerListener.AFTER_PACK, packs.get(i), i, handler); } // We use the scripts parser ScriptParser parser = new ScriptParser(parsables, vs); parser.parseFiles(); if (performInterrupted()) { // Interrupt was initiated; perform it. return; } // We use the file executor FileExecutor executor = new FileExecutor(executables); if (executor.executeFiles(ExecutableFile.POSTINSTALL, handler) != 0) { handler.emitError("File execution failed", "The installation was not completed"); this.result = false; } if (performInterrupted()) { // Interrupt was initiated; perform it. return; } // We put the uninstaller (it's not yet complete...) putUninstaller(); // update checks _after_ uninstaller was put, so we don't delete it performUpdateChecks(updatechecks); if (performInterrupted()) { // Interrupt was initiated; perform it. return; } // Custom action listener stuff --- afterPacks ---- informListeners(customActions, InstallerListener.AFTER_PACKS, idata, handler, null); if (performInterrupted()) { // Interrupt was initiated; perform it. return; } // write installation information writeInstallationInformation(); // The end :-) handler.stopAction(); } catch (Exception err) { // TODO: finer grained error handling with useful error messages handler.stopAction(); String message = err.getMessage(); if ("Installation cancelled".equals(message)) { handler.emitNotification("Installation cancelled"); } else { if (message == null || "".equals(message)) { message = "Internal error occured : " + err.toString(); } handler.emitError("An error occured", message); err.printStackTrace(); } this.result = false; Housekeeper.getInstance().shutDown(4); } finally { removeFromInstances(); } } private Pack200.Unpacker getPack200Unpacker() { if (unpacker == null) { unpacker = Pack200.newUnpacker(); } return unpacker; } /** * Returns a stream to a pack, location depending on if it's web based. * * @param uninstall true if pack must be uninstalled * @return The stream or null if it could not be found. * @throws Exception Description of the Exception */ private InputStream getPackAsStream(String packid, boolean uninstall) throws Exception { InputStream in = null; String webDirURL = idata.info.getWebDirURL(); packid = "-" + packid; if (webDirURL == null) // local { in = Unpacker.class.getResourceAsStream("/packs/pack" + packid); } else // web based { // TODO: Look first in same directory as primary jar // This may include prompting for changing of media // TODO: download and cache them all before starting copy process // See compiler.Packager#getJarOutputStream for the counterpart String baseName = idata.info.getInstallerBase(); String packURL = webDirURL + "/" + baseName + ".pack" + packid + ".jar"; String tf = IoHelper.translatePath(idata.info.getUninstallerPath()+ Unpacker.tempSubPath, vs); String tempfile; try { tempfile = WebRepositoryAccessor.getCachedUrl(packURL, tf); udata.addFile(tempfile, uninstall); } catch (Exception e) { if ("Cancelled".equals(e.getMessage())) { throw new InstallerException("Installation cancelled", e); } else { throw new InstallerException("Installation failed", e); } } URL url = new URL("jar:" + tempfile + "!/packs/pack" + packid); //URL url = new URL("jar:" + packURL + "!/packs/pack" + packid); // JarURLConnection jarConnection = (JarURLConnection) // url.openConnection(); // TODO: what happens when using an automated installer? in = new WebAccessor(null).openInputStream(url); // TODO: Fails miserably when pack jars are not found, so this is // temporary if (in == null) { throw new InstallerException(url.toString() + " not available", new FileNotFoundException(url.toString())); } } if (in != null && idata.info.getPackDecoderClassName() != null) { Class<Object> decoder = (Class<Object>) Class.forName(idata.info.getPackDecoderClassName()); Class[] paramsClasses = new Class[1]; paramsClasses[0] = Class.forName("java.io.InputStream"); Constructor<Object> constructor = decoder.getDeclaredConstructor(paramsClasses); // Our first used decoder input stream (bzip2) reads byte for byte from // the source. Therefore we put a buffering stream between it and the // source. InputStream buffer = new BufferedInputStream(in); Object[] params = {buffer}; Object instance = null; instance = constructor.newInstance(params); if (!InputStream.class.isInstance(instance)) { throw new InstallerException("'" + idata.info.getPackDecoderClassName() + "' must be derived from " + InputStream.class.toString()); } in = (InputStream) instance; } return in; } }
false
true
public void run() { addToInstances(); try { // // Initialisations FileOutputStream out = null; ArrayList<ParsableFile> parsables = new ArrayList<ParsableFile>(); ArrayList<ExecutableFile> executables = new ArrayList<ExecutableFile>(); ArrayList<UpdateCheck> updatechecks = new ArrayList<UpdateCheck>(); List packs = idata.selectedPacks; int npacks = packs.size(); handler.startAction("Unpacking", npacks); udata = UninstallData.getInstance(); // Custom action listener stuff --- load listeners ---- List[] customActions = getCustomActions(); // Custom action listener stuff --- beforePacks ---- informListeners(customActions, InstallerListener.BEFORE_PACKS, idata, npacks, handler); packs = idata.selectedPacks; npacks = packs.size(); // We unpack the selected packs for (int i = 0; i < npacks; i++) { // We get the pack stream //int n = idata.allPacks.indexOf(packs.get(i)); Pack p = (Pack) packs.get(i); // evaluate condition if (p.hasCondition()) { if (rules != null) { if (!rules.isConditionTrue(p.getCondition())) { // skip pack, condition is not fullfilled. continue; } } else { // TODO: skip pack, because condition can not be checked } } // Custom action listener stuff --- beforePack ---- informListeners(customActions, InstallerListener.BEFORE_PACK, packs.get(i), npacks, handler); ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(p.id, p.uninstall)); // We unpack the files int nfiles = objIn.readInt(); // We get the internationalized name of the pack final Pack pack = ((Pack) packs.get(i)); String stepname = pack.name;// the message to be passed to the // installpanel if (langpack != null && !(pack.id == null || "".equals(pack.id))) { final String name = langpack.getString(pack.id); if (name != null && !"".equals(name)) { stepname = name; } } if (pack.isHidden()){ // TODO: hide the pack completely // hide the pack name if pack is hidden stepname = ""; } handler.nextStep(stepname, i + 1, nfiles); for (int j = 0; j < nfiles; j++) { // We read the header PackFile pf = (PackFile) objIn.readObject(); // TODO: reaction if condition can not be checked if (pf.hasCondition() && (rules != null)) { if (!rules.isConditionTrue(pf.getCondition())) { if (!pf.isBackReference()){ // skip, condition is not fulfilled objIn.skip(pf.length()); } continue; } } if (OsConstraint.oneMatchesCurrentSystem(pf.osConstraints())) { // We translate & build the path String path = IoHelper.translatePath(pf.getTargetPath(), vs); File pathFile = new File(path); File dest = pathFile; if (!pf.isDirectory()) { dest = pathFile.getParentFile(); } if (!dest.exists()) { // If there are custom actions which would be called // at // creating a directory, create it recursively. List fileListeners = customActions[customActions.length - 1]; if (fileListeners != null && fileListeners.size() > 0) { mkDirsWithEnhancement(dest, pf, customActions); } else // Create it in on step. { if (!dest.mkdirs()) { handler.emitError("Error creating directories", "Could not create directory\n" + dest.getPath()); handler.stopAction(); this.result = false; return; } } } if (pf.isDirectory()) { continue; } // Custom action listener stuff --- beforeFile ---- informListeners(customActions, InstallerListener.BEFORE_FILE, pathFile, pf, null); // We add the path to the log, udata.addFile(path, pack.uninstall); handler.progress(j, path); // if this file exists and should not be overwritten, // check // what to do if ((pathFile.exists()) && (pf.override() != PackFile.OVERRIDE_TRUE)) { boolean overwritefile = false; // don't overwrite file if the user said so if (pf.override() != PackFile.OVERRIDE_FALSE) { if (pf.override() == PackFile.OVERRIDE_TRUE) { overwritefile = true; } else if (pf.override() == PackFile.OVERRIDE_UPDATE) { // check mtime of involved files // (this is not 100% perfect, because the // already existing file might // still be modified but the new installed // is just a bit newer; we would // need the creation time of the existing // file or record with which mtime // it was installed...) overwritefile = (pathFile.lastModified() < pf.lastModified()); } else { int def_choice = -1; if (pf.override() == PackFile.OVERRIDE_ASK_FALSE) { def_choice = AbstractUIHandler.ANSWER_NO; } if (pf.override() == PackFile.OVERRIDE_ASK_TRUE) { def_choice = AbstractUIHandler.ANSWER_YES; } int answer = handler.askQuestion(idata.langpack .getString("InstallPanel.overwrite.title") + " - " + pathFile.getName(), idata.langpack .getString("InstallPanel.overwrite.question") + pathFile.getAbsolutePath(), AbstractUIHandler.CHOICES_YES_NO, def_choice); overwritefile = (answer == AbstractUIHandler.ANSWER_YES); } } if (!overwritefile) { if (!pf.isBackReference() && !((Pack) packs.get(i)).loose) { objIn.skip(pf.length()); } continue; } } // We copy the file InputStream pis = objIn; if (pf.isBackReference()) { InputStream is = getPackAsStream(pf.previousPackId, pack.uninstall); pis = new ObjectInputStream(is); // must wrap for blockdata use by objectstream // (otherwise strange result) // skip on underlaying stream (for some reason not // possible on ObjectStream) is.skip(pf.offsetInPreviousPack - 4); // but the stream header is now already read (== 4 // bytes) } else if (((Pack) packs.get(i)).loose) { /* Old way of doing the job by using the (absolute) sourcepath. * Since this is very likely to fail and does not confirm to the documentation, * prefer using relative path's pis = new FileInputStream(pf.sourcePath); */ File resolvedFile = new File(getAbsolutInstallSource(), pf .getRelativeSourcePath()); if (!resolvedFile.exists()) { //try alternative destination - the current working directory //user.dir is likely (depends on launcher type) the current directory of the executable or jar-file... final File userDir = new File(System.getProperty("user.dir")); resolvedFile = new File(userDir, pf.getRelativeSourcePath()); } if (resolvedFile.exists()) { pis = new FileInputStream(resolvedFile); //may have a different length & last modified than we had at compiletime, therefore we have to build a new PackFile for the copy process... pf = new PackFile(resolvedFile.getParentFile(), resolvedFile, pf.getTargetPath(), pf.osConstraints(), pf.override(), pf.getAdditionals()); } else { //file not found //issue a warning (logging api pending) //since this file was loosely bundled, we continue with the installation. System.out.println("Could not find loosely bundled file: " + pf.getRelativeSourcePath()); if (!handler.emitWarning("File not found", "Could not find loosely bundled file: " + pf.getRelativeSourcePath())) { throw new InstallerException("Installation cancelled"); } continue; } } if (pf.isPack200Jar()) { int key = objIn.readInt(); InputStream pack200Input = Unpacker.class.getResourceAsStream("/packs/pack200-" + key); Pack200.Unpacker unpacker = getPack200Unpacker(); java.util.jar.JarOutputStream jarOut = new java.util.jar.JarOutputStream(new FileOutputStream(pathFile)); unpacker.unpack(pack200Input, jarOut); jarOut.close(); } else { out = new FileOutputStream(pathFile); byte[] buffer = new byte[5120]; long bytesCopied = 0; while (bytesCopied < pf.length()) { if (performInterrupted()) { // Interrupt was initiated; perform it. out.close(); if (pis != objIn) { pis.close(); } return; } int maxBytes = (int) Math.min(pf.length() - bytesCopied, buffer.length); int bytesInBuffer = pis.read(buffer, 0, maxBytes); if (bytesInBuffer == -1) { throw new IOException("Unexpected end of stream (installer corrupted?)"); } out.write(buffer, 0, bytesInBuffer); bytesCopied += bytesInBuffer; } out.close(); } if (pis != objIn) { pis.close(); } // Set file modification time if specified if (pf.lastModified() >= 0) { pathFile.setLastModified(pf.lastModified()); } // Custom action listener stuff --- afterFile ---- informListeners(customActions, InstallerListener.AFTER_FILE, pathFile, pf, null); } else { if (!pf.isBackReference()) { objIn.skip(pf.length()); } } } // Load information about parsable files int numParsables = objIn.readInt(); for (int k = 0; k < numParsables; k++) { ParsableFile pf = (ParsableFile) objIn.readObject(); if (pf.hasCondition() && (rules != null)) { if (!rules.isConditionTrue(pf.getCondition())) { // skip, condition is not fulfilled continue; } } pf.path = IoHelper.translatePath(pf.path, vs); parsables.add(pf); } // Load information about executable files int numExecutables = objIn.readInt(); for (int k = 0; k < numExecutables; k++) { ExecutableFile ef = (ExecutableFile) objIn.readObject(); if (ef.hasCondition() && (rules != null)) { if (!rules.isConditionTrue(ef.getCondition())) { // skip, condition is false continue; } } ef.path = IoHelper.translatePath(ef.path, vs); if (null != ef.argList && !ef.argList.isEmpty()) { String arg = null; for (int j = 0; j < ef.argList.size(); j++) { arg = ef.argList.get(j); arg = IoHelper.translatePath(arg, vs); ef.argList.set(j, arg); } } executables.add(ef); if (ef.executionStage == ExecutableFile.UNINSTALL) { udata.addExecutable(ef); } } // Custom action listener stuff --- uninstall data ---- handleAdditionalUninstallData(udata, customActions); // Load information about updatechecks int numUpdateChecks = objIn.readInt(); for (int k = 0; k < numUpdateChecks; k++) { UpdateCheck uc = (UpdateCheck) objIn.readObject(); updatechecks.add(uc); } objIn.close(); if (performInterrupted()) { // Interrupt was initiated; perform it. return; } // Custom action listener stuff --- afterPack ---- informListeners(customActions, InstallerListener.AFTER_PACK, packs.get(i), i, handler); } // We use the scripts parser ScriptParser parser = new ScriptParser(parsables, vs); parser.parseFiles(); if (performInterrupted()) { // Interrupt was initiated; perform it. return; } // We use the file executor FileExecutor executor = new FileExecutor(executables); if (executor.executeFiles(ExecutableFile.POSTINSTALL, handler) != 0) { handler.emitError("File execution failed", "The installation was not completed"); this.result = false; } if (performInterrupted()) { // Interrupt was initiated; perform it. return; } // We put the uninstaller (it's not yet complete...) putUninstaller(); // update checks _after_ uninstaller was put, so we don't delete it performUpdateChecks(updatechecks); if (performInterrupted()) { // Interrupt was initiated; perform it. return; } // Custom action listener stuff --- afterPacks ---- informListeners(customActions, InstallerListener.AFTER_PACKS, idata, handler, null); if (performInterrupted()) { // Interrupt was initiated; perform it. return; } // write installation information writeInstallationInformation(); // The end :-) handler.stopAction(); } catch (Exception err) { // TODO: finer grained error handling with useful error messages handler.stopAction(); String message = err.getMessage(); if ("Installation cancelled".equals(message)) { handler.emitNotification("Installation cancelled"); } else { if (message == null || "".equals(message)) { message = "Internal error occured : " + err.toString(); } handler.emitError("An error occured", message); err.printStackTrace(); } this.result = false; Housekeeper.getInstance().shutDown(4); } finally { removeFromInstances(); } }
public void run() { addToInstances(); try { // // Initialisations FileOutputStream out = null; ArrayList<ParsableFile> parsables = new ArrayList<ParsableFile>(); ArrayList<ExecutableFile> executables = new ArrayList<ExecutableFile>(); ArrayList<UpdateCheck> updatechecks = new ArrayList<UpdateCheck>(); List packs = idata.selectedPacks; int npacks = packs.size(); handler.startAction("Unpacking", npacks); udata = UninstallData.getInstance(); // Custom action listener stuff --- load listeners ---- List[] customActions = getCustomActions(); // Custom action listener stuff --- beforePacks ---- informListeners(customActions, InstallerListener.BEFORE_PACKS, idata, npacks, handler); packs = idata.selectedPacks; npacks = packs.size(); // We unpack the selected packs for (int i = 0; i < npacks; i++) { // We get the pack stream //int n = idata.allPacks.indexOf(packs.get(i)); Pack p = (Pack) packs.get(i); // evaluate condition if (p.hasCondition()) { if (rules != null) { if (!rules.isConditionTrue(p.getCondition())) { // skip pack, condition is not fullfilled. continue; } } else { // TODO: skip pack, because condition can not be checked } } // Custom action listener stuff --- beforePack ---- informListeners(customActions, InstallerListener.BEFORE_PACK, packs.get(i), npacks, handler); ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(p.id, p.uninstall)); // We unpack the files int nfiles = objIn.readInt(); // We get the internationalized name of the pack final Pack pack = ((Pack) packs.get(i)); String stepname = pack.name;// the message to be passed to the // installpanel if (langpack != null && !(pack.id == null || "".equals(pack.id))) { final String name = langpack.getString(pack.id); if (name != null && !"".equals(name)) { stepname = name; } } if (pack.isHidden()){ // TODO: hide the pack completely // hide the pack name if pack is hidden stepname = ""; } handler.nextStep(stepname, i + 1, nfiles); for (int j = 0; j < nfiles; j++) { // We read the header PackFile pf = (PackFile) objIn.readObject(); // TODO: reaction if condition can not be checked if (pf.hasCondition() && (rules != null)) { if (!rules.isConditionTrue(pf.getCondition())) { if (!pf.isBackReference()){ // skip, condition is not fulfilled objIn.skip(pf.length()); } continue; } } if (OsConstraint.oneMatchesCurrentSystem(pf.osConstraints())) { // We translate & build the path String path = IoHelper.translatePath(pf.getTargetPath(), vs); File pathFile = new File(path); File dest = pathFile; if (!pf.isDirectory()) { dest = pathFile.getParentFile(); } if (!dest.exists()) { // If there are custom actions which would be called // at // creating a directory, create it recursively. List fileListeners = customActions[customActions.length - 1]; if (fileListeners != null && fileListeners.size() > 0) { mkDirsWithEnhancement(dest, pf, customActions); } else // Create it in on step. { if (!dest.mkdirs()) { handler.emitError("Error creating directories", "Could not create directory\n" + dest.getPath()); handler.stopAction(); this.result = false; return; } } } if (pf.isDirectory()) { continue; } // Custom action listener stuff --- beforeFile ---- informListeners(customActions, InstallerListener.BEFORE_FILE, pathFile, pf, null); // We add the path to the log, udata.addFile(path, pack.uninstall); handler.progress(j, path); // if this file exists and should not be overwritten, // check // what to do if ((pathFile.exists()) && (pf.override() != PackFile.OVERRIDE_TRUE)) { boolean overwritefile = false; // don't overwrite file if the user said so if (pf.override() != PackFile.OVERRIDE_FALSE) { if (pf.override() == PackFile.OVERRIDE_TRUE) { overwritefile = true; } else if (pf.override() == PackFile.OVERRIDE_UPDATE) { // check mtime of involved files // (this is not 100% perfect, because the // already existing file might // still be modified but the new installed // is just a bit newer; we would // need the creation time of the existing // file or record with which mtime // it was installed...) overwritefile = (pathFile.lastModified() < pf.lastModified()); } else { int def_choice = -1; if (pf.override() == PackFile.OVERRIDE_ASK_FALSE) { def_choice = AbstractUIHandler.ANSWER_NO; } if (pf.override() == PackFile.OVERRIDE_ASK_TRUE) { def_choice = AbstractUIHandler.ANSWER_YES; } int answer = handler.askQuestion(idata.langpack .getString("InstallPanel.overwrite.title") + " - " + pathFile.getName(), idata.langpack .getString("InstallPanel.overwrite.question") + pathFile.getAbsolutePath(), AbstractUIHandler.CHOICES_YES_NO, def_choice); overwritefile = (answer == AbstractUIHandler.ANSWER_YES); } } if (!overwritefile) { if (!pf.isBackReference() && !((Pack) packs.get(i)).loose) { if ( pf.isPack200Jar() ) { objIn.skip( Integer.SIZE / 8 ); } else { objIn.skip(pf.length()); } } continue; } } // We copy the file InputStream pis = objIn; if (pf.isBackReference()) { InputStream is = getPackAsStream(pf.previousPackId, pack.uninstall); pis = new ObjectInputStream(is); // must wrap for blockdata use by objectstream // (otherwise strange result) // skip on underlaying stream (for some reason not // possible on ObjectStream) is.skip(pf.offsetInPreviousPack - 4); // but the stream header is now already read (== 4 // bytes) } else if (((Pack) packs.get(i)).loose) { /* Old way of doing the job by using the (absolute) sourcepath. * Since this is very likely to fail and does not confirm to the documentation, * prefer using relative path's pis = new FileInputStream(pf.sourcePath); */ File resolvedFile = new File(getAbsolutInstallSource(), pf .getRelativeSourcePath()); if (!resolvedFile.exists()) { //try alternative destination - the current working directory //user.dir is likely (depends on launcher type) the current directory of the executable or jar-file... final File userDir = new File(System.getProperty("user.dir")); resolvedFile = new File(userDir, pf.getRelativeSourcePath()); } if (resolvedFile.exists()) { pis = new FileInputStream(resolvedFile); //may have a different length & last modified than we had at compiletime, therefore we have to build a new PackFile for the copy process... pf = new PackFile(resolvedFile.getParentFile(), resolvedFile, pf.getTargetPath(), pf.osConstraints(), pf.override(), pf.getAdditionals()); } else { //file not found //issue a warning (logging api pending) //since this file was loosely bundled, we continue with the installation. System.out.println("Could not find loosely bundled file: " + pf.getRelativeSourcePath()); if (!handler.emitWarning("File not found", "Could not find loosely bundled file: " + pf.getRelativeSourcePath())) { throw new InstallerException("Installation cancelled"); } continue; } } if (pf.isPack200Jar()) { int key = objIn.readInt(); InputStream pack200Input = Unpacker.class.getResourceAsStream("/packs/pack200-" + key); Pack200.Unpacker unpacker = getPack200Unpacker(); java.util.jar.JarOutputStream jarOut = new java.util.jar.JarOutputStream(new FileOutputStream(pathFile)); unpacker.unpack(pack200Input, jarOut); jarOut.close(); } else { out = new FileOutputStream(pathFile); byte[] buffer = new byte[5120]; long bytesCopied = 0; while (bytesCopied < pf.length()) { if (performInterrupted()) { // Interrupt was initiated; perform it. out.close(); if (pis != objIn) { pis.close(); } return; } int maxBytes = (int) Math.min(pf.length() - bytesCopied, buffer.length); int bytesInBuffer = pis.read(buffer, 0, maxBytes); if (bytesInBuffer == -1) { throw new IOException("Unexpected end of stream (installer corrupted?)"); } out.write(buffer, 0, bytesInBuffer); bytesCopied += bytesInBuffer; } out.close(); } if (pis != objIn) { pis.close(); } // Set file modification time if specified if (pf.lastModified() >= 0) { pathFile.setLastModified(pf.lastModified()); } // Custom action listener stuff --- afterFile ---- informListeners(customActions, InstallerListener.AFTER_FILE, pathFile, pf, null); } else { if (!pf.isBackReference()) { objIn.skip(pf.length()); } } } // Load information about parsable files int numParsables = objIn.readInt(); for (int k = 0; k < numParsables; k++) { ParsableFile pf = (ParsableFile) objIn.readObject(); if (pf.hasCondition() && (rules != null)) { if (!rules.isConditionTrue(pf.getCondition())) { // skip, condition is not fulfilled continue; } } pf.path = IoHelper.translatePath(pf.path, vs); parsables.add(pf); } // Load information about executable files int numExecutables = objIn.readInt(); for (int k = 0; k < numExecutables; k++) { ExecutableFile ef = (ExecutableFile) objIn.readObject(); if (ef.hasCondition() && (rules != null)) { if (!rules.isConditionTrue(ef.getCondition())) { // skip, condition is false continue; } } ef.path = IoHelper.translatePath(ef.path, vs); if (null != ef.argList && !ef.argList.isEmpty()) { String arg = null; for (int j = 0; j < ef.argList.size(); j++) { arg = ef.argList.get(j); arg = IoHelper.translatePath(arg, vs); ef.argList.set(j, arg); } } executables.add(ef); if (ef.executionStage == ExecutableFile.UNINSTALL) { udata.addExecutable(ef); } } // Custom action listener stuff --- uninstall data ---- handleAdditionalUninstallData(udata, customActions); // Load information about updatechecks int numUpdateChecks = objIn.readInt(); for (int k = 0; k < numUpdateChecks; k++) { UpdateCheck uc = (UpdateCheck) objIn.readObject(); updatechecks.add(uc); } objIn.close(); if (performInterrupted()) { // Interrupt was initiated; perform it. return; } // Custom action listener stuff --- afterPack ---- informListeners(customActions, InstallerListener.AFTER_PACK, packs.get(i), i, handler); } // We use the scripts parser ScriptParser parser = new ScriptParser(parsables, vs); parser.parseFiles(); if (performInterrupted()) { // Interrupt was initiated; perform it. return; } // We use the file executor FileExecutor executor = new FileExecutor(executables); if (executor.executeFiles(ExecutableFile.POSTINSTALL, handler) != 0) { handler.emitError("File execution failed", "The installation was not completed"); this.result = false; } if (performInterrupted()) { // Interrupt was initiated; perform it. return; } // We put the uninstaller (it's not yet complete...) putUninstaller(); // update checks _after_ uninstaller was put, so we don't delete it performUpdateChecks(updatechecks); if (performInterrupted()) { // Interrupt was initiated; perform it. return; } // Custom action listener stuff --- afterPacks ---- informListeners(customActions, InstallerListener.AFTER_PACKS, idata, handler, null); if (performInterrupted()) { // Interrupt was initiated; perform it. return; } // write installation information writeInstallationInformation(); // The end :-) handler.stopAction(); } catch (Exception err) { // TODO: finer grained error handling with useful error messages handler.stopAction(); String message = err.getMessage(); if ("Installation cancelled".equals(message)) { handler.emitNotification("Installation cancelled"); } else { if (message == null || "".equals(message)) { message = "Internal error occured : " + err.toString(); } handler.emitError("An error occured", message); err.printStackTrace(); } this.result = false; Housekeeper.getInstance().shutDown(4); } finally { removeFromInstances(); } }
diff --git a/src/com/android/launcher/DialogSeekBarPreference.java b/src/com/android/launcher/DialogSeekBarPreference.java index b016600..2ee1960 100644 --- a/src/com/android/launcher/DialogSeekBarPreference.java +++ b/src/com/android/launcher/DialogSeekBarPreference.java @@ -1,107 +1,107 @@ package com.android.launcher; import android.content.Context; import android.content.res.TypedArray; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.widget.SeekBar; import android.widget.TextView; public class DialogSeekBarPreference extends DialogPreference implements SeekBar.OnSeekBarChangeListener { private static final String androidns = "http://schemas.android.com/apk/res/android"; private SeekBar mSeekBar; private TextView mValueText; private String mSuffix; private int mMax, mMin, mValue = 0; public DialogSeekBarPreference(Context context, AttributeSet attrs) { super(context, attrs); setPersistent(true); mSuffix = attrs.getAttributeValue(androidns, "text"); mMin = attrs.getAttributeIntValue(androidns, "min", 0); mMax = attrs.getAttributeIntValue(androidns, "max", 100); setDialogLayoutResource(R.layout.my_seekbar_preference); } @Override protected void onBindDialogView(View v) { super.onBindDialogView(v); TextView dialogMessage = (TextView) v.findViewById(R.id.dialogMessage); - dialogMessage.setText(getSummary()); + dialogMessage.setText(getDialogMessage()); mValueText = (TextView) v.findViewById(R.id.actualValue); mSeekBar = (SeekBar) v.findViewById(R.id.myBar); mSeekBar.setOnSeekBarChangeListener(this); mSeekBar.setMax(mMax); mSeekBar.setProgress(mValue); String t = String.valueOf(mValue + mMin); mValueText.setText(mSuffix == null ? t : t.concat(mSuffix)); } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return a.getInt(index, 0); } @Override protected void onSetInitialValue(boolean restore, Object defaultValue) { mValue = getPersistedInt(defaultValue == null ? 0 : (Integer) defaultValue); } @Override protected void onDialogClosed(boolean positiveResult) { super.onDialogClosed(positiveResult); if (positiveResult) { int value = mSeekBar.getProgress(); if (callChangeListener(value)) { setValue(value); } } } public void setValue(int value) { if (value > mMax) { value = mMax; } else if (value < 0) { value = 0; } mValue = value; persistInt(value); } public void setMax(int max) { mMax = max; if (mValue > mMax) { setValue(mMax); } } public void setMin(int min) { if (min < mMax) { mMin = min; } } public void onProgressChanged(SeekBar seek, int value, boolean fromTouch) { String t = String.valueOf(value + mMin); mValueText.setText(mSuffix == null ? t : t.concat(mSuffix)); } public void onStartTrackingTouch(SeekBar seek) { } public void onStopTrackingTouch(SeekBar seek) { } }
true
true
protected void onBindDialogView(View v) { super.onBindDialogView(v); TextView dialogMessage = (TextView) v.findViewById(R.id.dialogMessage); dialogMessage.setText(getSummary()); mValueText = (TextView) v.findViewById(R.id.actualValue); mSeekBar = (SeekBar) v.findViewById(R.id.myBar); mSeekBar.setOnSeekBarChangeListener(this); mSeekBar.setMax(mMax); mSeekBar.setProgress(mValue); String t = String.valueOf(mValue + mMin); mValueText.setText(mSuffix == null ? t : t.concat(mSuffix)); }
protected void onBindDialogView(View v) { super.onBindDialogView(v); TextView dialogMessage = (TextView) v.findViewById(R.id.dialogMessage); dialogMessage.setText(getDialogMessage()); mValueText = (TextView) v.findViewById(R.id.actualValue); mSeekBar = (SeekBar) v.findViewById(R.id.myBar); mSeekBar.setOnSeekBarChangeListener(this); mSeekBar.setMax(mMax); mSeekBar.setProgress(mValue); String t = String.valueOf(mValue + mMin); mValueText.setText(mSuffix == null ? t : t.concat(mSuffix)); }
diff --git a/net.sf.eclipsefp.haskell.buildwrapper/src/net/sf/eclipsefp/haskell/buildwrapper/types/Location.java b/net.sf.eclipsefp.haskell.buildwrapper/src/net/sf/eclipsefp/haskell/buildwrapper/types/Location.java index 78dc188f..04d3f605 100644 --- a/net.sf.eclipsefp.haskell.buildwrapper/src/net/sf/eclipsefp/haskell/buildwrapper/types/Location.java +++ b/net.sf.eclipsefp.haskell.buildwrapper/src/net/sf/eclipsefp/haskell/buildwrapper/types/Location.java @@ -1,288 +1,289 @@ package net.sf.eclipsefp.haskell.buildwrapper.types; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import net.sf.eclipsefp.haskell.buildwrapper.BWFacade; import net.sf.eclipsefp.haskell.buildwrapper.BuildWrapperPlugin; import net.sf.eclipsefp.haskell.buildwrapper.util.BWText; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultLineTracker; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ILineTracker; import org.eclipse.jface.text.IRegion; import org.eclipse.ui.texteditor.MarkerUtilities; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * A span of text within a file, in line:column format. * Lines are one-based, columns are zero-based. * The start is inclusive; the end is exclusive. * * @author Thomas ten Cate */ public class Location { private String fileName; private String otherName; private int startLine, startColumn, endLine, endColumn; public Location(JSONObject json) throws JSONException { this(null,json); } public Location(IFile f, JSONArray json) throws JSONException { this(f!=null?f.getLocation().toOSString():"",json); } public Location(String fn, JSONArray json) throws JSONException { startLine=json.getInt(0); startColumn=json.getInt(1)-1; // we're zero based, Haskell code 1 based if (json.length()>3){ endLine=json.getInt(2); endColumn=json.getInt(3)-1;// we're zero based, Haskell code 1 based } else if (json.length()>2){ endLine=startLine; endColumn=json.getInt(2)-1;// we're zero based, Haskell code 1 based } else { endLine=startLine; endColumn=startColumn+1; } if (endColumn==-1 && endLine>startLine){ endLine--; } this.fileName = fn; } public Location(IFile f, JSONObject json) throws JSONException { this.fileName = json.optString("file"); this.otherName = json.optString("other"); if ( f != null && (this.fileName == null || this.fileName.length() == 0) && (this.otherName == null || this.otherName.length() == 0) ) { // Default the file name to the Java file resource this.fileName = f.getLocation().toOSString(); } if (json.optString("no-location").length() == 0) { JSONArray region = json.getJSONArray("region"); startLine = region.getInt(0); startColumn = region.getInt(1); if (startColumn<0){ startColumn=0; } endLine = region.getInt(2); endColumn = region.getInt(3); } } public Location(String fileName, int startLine, int startColumn, int endLine, int endColumn) { this.fileName = fileName; this.startLine = startLine; this.startColumn = startColumn; int mv=0; if (startColumn<0){ mv=0-startColumn; this.startColumn=0; } this.endLine = endLine; this.endColumn = endColumn+mv; } public Location(String fileName, IDocument document, IRegion region) throws BadLocationException { this.fileName = fileName; int startOffset = region.getOffset(); int endOffset = startOffset + region.getLength(); int docLine=document.getLineOfOffset(startOffset); this.startLine =docLine+1 ; this.startColumn = startOffset - document.getLineOffset(docLine); docLine=document.getLineOfOffset(endOffset); this.endLine = docLine+1; this.endColumn = endOffset - document.getLineOffset(docLine); } /** * Create a location from a buildwrapper location, expanding empty spans when possible. */ public Location(IProject project, String fileName, int startLin, int startCol, int endLin, int endCol) { this.fileName = fileName; startLine = startLin; startColumn = startCol - 1; // Buildwrapper columns start at 1 endLine = endLin; endColumn = endCol - 1; // Buildwrapper columns start at 1 if (endLine > startLine) { // IMarker does not support multi-line spans, so we reduce it to an empty span endLine = startLine; endColumn = startColumn; } // If the span is empty, we try to extend it to extend it to a single character span. ILineTracker lineTracker = getLineTracker(project.getLocation().toOSString() +"/"+ BWFacade.DIST_FOLDER+"/"+fileName); if (lineTracker != null) { try { //System.err.println("Initial span: "+startLine+":"+startColumn+" to "+endLine+":"+endColumn); + String delimiter = lineTracker.getLineDelimiter(startLine-1); // apparently this can return null int lineLength = lineTracker.getLineLength(startLine-1 /*LineTracker is 0 based*/ ) - - lineTracker.getLineDelimiter(startLine-1).length(); // subtract the delimiter length + - (delimiter == null ? 0 : delimiter.length()); // subtract the delimiter length if (startLine==endLine && startColumn==endColumn) { // span is empty if (startColumn < lineLength) { // not past the last character, so we can extend to the right. endColumn += 1; } else { if (startColumn > 0) { // past last character, but there are characters to the left. startColumn -= 1; } // else, we have startColumn == lineLength == 0, so the line is empty and we cannot extend the span. } } //System.err.println("Fixed span: "+startLine+":"+startColumn+" to "+endLine+":"+endColumn); } catch (BadLocationException e){ BuildWrapperPlugin.logError(BWText.process_parse_note_error, e); } } else { //System.err.println("LineTracker is null for file "+fileName); } } /** * Create a LineTracker for the file at filePath, for easy querying line lengths. * If any exception occurs, we simply return null. * Note that line numbers are 0 based, and the returned length includes the separator. */ private static ILineTracker getLineTracker(String filePath) { ILineTracker lineTracker; InputStream input = null; try { lineTracker = new DefaultLineTracker(); input = new FileInputStream( filePath ); byte[] contents = new byte[input.available()]; input.read(contents); String stringContents = new String(contents); lineTracker.set(stringContents); } catch(Exception e) { // CoreException or IOException lineTracker = null; } finally { if (input != null) try { input.close(); } catch (IOException e) { lineTracker = null; } } return lineTracker; } /** * Returns the offset within the given document * that the start of this {@link Location} object represents. */ public int getStartOffset(IDocument document) throws BadLocationException { return document.getLineOffset(startLine-1) + startColumn; } /** * Returns the offset within the given document * that the end of this {@link Location} object represents. */ public int getEndOffset(IDocument document) throws BadLocationException { return document.getLineOffset(endLine-1) + endColumn; } public int getLength(IDocument document) throws BadLocationException { return getEndOffset(document) - getStartOffset(document); } public String getContents(IDocument document) throws BadLocationException { int st=getStartOffset(document); return document.get(st,getEndOffset(document)-st); } public String getFileName() { return fileName; } public String getOtherName() { return otherName; } public int getStartLine() { return startLine; } public int getStartColumn() { return startColumn; } public int getEndLine() { return endLine; } public int getEndColumn() { return endColumn; } @Override public boolean equals(Object obj) { if (!(obj instanceof Location)) { return false; } Location other = (Location)obj; return fileName.equals(other.fileName) && startLine == other.startLine && startColumn == other.startColumn && endLine == other.endLine && endColumn == other.endColumn; } @Override public int hashCode() { return fileName.hashCode()<<16+startLine<<8+startColumn; } @Override public String toString() { return String.format("%d:%d-%d:%d", startLine, startColumn, endLine, endColumn); } public IFile getIFile(IProject p){ String pl=p.getLocation().toOSString(); String loc=getFileName(); if (loc!=null && loc.startsWith(pl)){ return (IFile)p.getFile(loc.substring(pl.length())); } return null; } public Map<Object,Object> getMarkerProperties(int maxLines){ int line= Math.min(getStartLine(),maxLines); final Map<Object,Object> attributes=new HashMap<Object,Object>(); MarkerUtilities.setLineNumber(attributes, line); int start=getStartColumn(); int end=getEndColumn(); // if we have startColumn==endColumn we could take end+1 // BUT if end goes over the document size, or start is zero, or if Eclipse feels like it, the marker is not shown on the document // so it's better to just show the line without more info if (end>start){ MarkerUtilities.setCharStart(attributes, start); // exclusive MarkerUtilities.setCharEnd(attributes, end-1); } return attributes; } }
false
true
public Location(IProject project, String fileName, int startLin, int startCol, int endLin, int endCol) { this.fileName = fileName; startLine = startLin; startColumn = startCol - 1; // Buildwrapper columns start at 1 endLine = endLin; endColumn = endCol - 1; // Buildwrapper columns start at 1 if (endLine > startLine) { // IMarker does not support multi-line spans, so we reduce it to an empty span endLine = startLine; endColumn = startColumn; } // If the span is empty, we try to extend it to extend it to a single character span. ILineTracker lineTracker = getLineTracker(project.getLocation().toOSString() +"/"+ BWFacade.DIST_FOLDER+"/"+fileName); if (lineTracker != null) { try { //System.err.println("Initial span: "+startLine+":"+startColumn+" to "+endLine+":"+endColumn); int lineLength = lineTracker.getLineLength(startLine-1 /*LineTracker is 0 based*/ ) - lineTracker.getLineDelimiter(startLine-1).length(); // subtract the delimiter length if (startLine==endLine && startColumn==endColumn) { // span is empty if (startColumn < lineLength) { // not past the last character, so we can extend to the right. endColumn += 1; } else { if (startColumn > 0) { // past last character, but there are characters to the left. startColumn -= 1; } // else, we have startColumn == lineLength == 0, so the line is empty and we cannot extend the span. } } //System.err.println("Fixed span: "+startLine+":"+startColumn+" to "+endLine+":"+endColumn); } catch (BadLocationException e){ BuildWrapperPlugin.logError(BWText.process_parse_note_error, e); } } else { //System.err.println("LineTracker is null for file "+fileName); } }
public Location(IProject project, String fileName, int startLin, int startCol, int endLin, int endCol) { this.fileName = fileName; startLine = startLin; startColumn = startCol - 1; // Buildwrapper columns start at 1 endLine = endLin; endColumn = endCol - 1; // Buildwrapper columns start at 1 if (endLine > startLine) { // IMarker does not support multi-line spans, so we reduce it to an empty span endLine = startLine; endColumn = startColumn; } // If the span is empty, we try to extend it to extend it to a single character span. ILineTracker lineTracker = getLineTracker(project.getLocation().toOSString() +"/"+ BWFacade.DIST_FOLDER+"/"+fileName); if (lineTracker != null) { try { //System.err.println("Initial span: "+startLine+":"+startColumn+" to "+endLine+":"+endColumn); String delimiter = lineTracker.getLineDelimiter(startLine-1); // apparently this can return null int lineLength = lineTracker.getLineLength(startLine-1 /*LineTracker is 0 based*/ ) - (delimiter == null ? 0 : delimiter.length()); // subtract the delimiter length if (startLine==endLine && startColumn==endColumn) { // span is empty if (startColumn < lineLength) { // not past the last character, so we can extend to the right. endColumn += 1; } else { if (startColumn > 0) { // past last character, but there are characters to the left. startColumn -= 1; } // else, we have startColumn == lineLength == 0, so the line is empty and we cannot extend the span. } } //System.err.println("Fixed span: "+startLine+":"+startColumn+" to "+endLine+":"+endColumn); } catch (BadLocationException e){ BuildWrapperPlugin.logError(BWText.process_parse_note_error, e); } } else { //System.err.println("LineTracker is null for file "+fileName); } }
diff --git a/src/com/spazedog/xposed/additionsgb/Common.java b/src/com/spazedog/xposed/additionsgb/Common.java index 838a1eb..717d4bb 100644 --- a/src/com/spazedog/xposed/additionsgb/Common.java +++ b/src/com/spazedog/xposed/additionsgb/Common.java @@ -1,402 +1,402 @@ /* * This file is part of the Xposed Additions Project: https://github.com/spazedog/xposed-additions * * Copyright (c) 2014 Daniel Bergløv * * Xposed Additions 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. * Xposed Additions 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 Xposed Additions. If not, see <http://www.gnu.org/licenses/> */ package com.spazedog.xposed.additionsgb; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.drawable.Drawable.ConstantState; import android.os.Build; import android.text.TextUtils; import android.view.KeyEvent; public final class Common { public static final Boolean DEBUG = false; public static final String PACKAGE_NAME = Common.class.getPackage().getName(); public static final String PACKAGE_NAME_PRO = PACKAGE_NAME + ".pro"; public static final String XSERVICE_NAME = PACKAGE_NAME + ".service.XSERVICE"; public static final String XSERVICE_PERMISSIONS = PACKAGE_NAME + ".permissions.XSERVICE"; public static final String XSERVICE_BROADCAST = PACKAGE_NAME + ".filters.XSERVICE"; public static final String PREFERENCE_FILE = "config"; public static List<AppInfo> oPackageListCache; private static List<String> oPackageBlackList = new ArrayList<String>(1); static { oPackageBlackList.add("com.android.systemui"); oPackageBlackList.add("android"); } public static final class Index { public static final class integer { public static final class key { public static final String remapTapDelay = "remap_tap_delay"; public static final String remapPressDelay = "remap_press_delay"; } public static final class value { public static final Integer remapTapDelay = 100; public static final Integer remapPressDelay = 500; } } public static final class string { public static final class key { public static final String usbPlugAction = "usb_plug_action"; public static final String usbUnPlugAction = "usb_unplug_action"; } public static final class value { public static final String usbPlugAction = "usb"; public static final String usbUnPlugAction = "off"; } } public static final class bool { public static final class key { public static final String usbPlugSwitch = "usb_plug_switch"; public static final String usbUnPlugSwitch = "usb_unplug_switch"; public static final String layoutRotationSwitch = "layout_rotation_switch"; } public static final class value { public static final Boolean usbPlugSwitch = false; public static final Boolean usbUnPlugSwitch = false; public static final Boolean layoutRotationSwitch = false; } } public static final class array { public static final class groupKey { public static final String remapKeyConditions = "remap_key_conditions"; public static final String remapKeyActions_$ = "remap_key_actions:%1$s"; } public static final class key { public static final String layoutRotationBlacklist = "layout_rotation_blacklist"; public static final String remapKeys = "remap_keys"; public static final String forcedHapticKeys = "forced_haptic_keys"; } public static final class value { public static final ArrayList<String> layoutRotationBlacklist = new ArrayList<String>(); public static final ArrayList<String> remapKeys = new ArrayList<String>(); public static final ArrayList<String> forcedHapticKeys = new ArrayList<String>(); } } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static class RemapAction { public final Boolean dispatch; public final String name; public final Integer labelRes; public final Integer descriptionRes; public final List<String> blacklist = new ArrayList<String>(); public static final List<RemapAction> VALUES = new ArrayList<RemapAction>(); public static final List<String> NAMES = new ArrayList<String>(); static { new RemapAction("disabled", R.string.remap_title_disabled, R.string.remap_summary_disabled, false); new RemapAction("guarddismiss", R.string.remap_title_dismissguard, R.string.remap_summary_dismissguard, false, "off", "on"); new RemapAction("recentapps", R.string.remap_title_recentapps, R.string.remap_summary_recentapps, false, "off"); new RemapAction("powermenu", R.string.remap_title_powermenu, R.string.remap_summary_powermenu, false, "off"); new RemapAction("killapp", R.string.remap_title_killapp, R.string.remap_summary_killapp, false, "off", "guard"); new RemapAction("fliptoggle", R.string.remap_title_fliptoggle, R.string.remap_summary_fliptoggle, false, "off"); if (android.os.Build.VERSION.SDK_INT >= 11) { new RemapAction("flipleft", R.string.remap_title_flipleft, R.string.remap_summary_flipleft, false, "off"); new RemapAction("flipright", R.string.remap_title_flipright, R.string.remap_summary_flipright, false, "off"); } new RemapAction("" + KeyEvent.KEYCODE_POWER, 0, 0, true); new RemapAction("" + KeyEvent.KEYCODE_HOME, 0, 0, true, "off", "guard"); new RemapAction("" + KeyEvent.KEYCODE_MENU, 0, 0, true, "off", "guard"); new RemapAction("" + KeyEvent.KEYCODE_BACK, 0, 0, true, "off", "guard"); new RemapAction("" + KeyEvent.KEYCODE_SEARCH, 0, 0, true, "off"); new RemapAction("" + KeyEvent.KEYCODE_CAMERA, 0, 0, true, "off"); new RemapAction("" + KeyEvent.KEYCODE_FOCUS, 0, 0, true, "off", "guard"); new RemapAction("" + KeyEvent.KEYCODE_ENDCALL, 0, 0, true); new RemapAction("" + KeyEvent.KEYCODE_MUTE, 0, 0, true); new RemapAction("" + KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, 0, 0, true); new RemapAction("" + KeyEvent.KEYCODE_MEDIA_NEXT, 0, 0, true); new RemapAction("" + KeyEvent.KEYCODE_MEDIA_PREVIOUS, 0, 0, true); new RemapAction("" + KeyEvent.KEYCODE_PAGE_UP, 0, 0, true, "off", "guard"); new RemapAction("" + KeyEvent.KEYCODE_PAGE_DOWN, 0, 0, true, "off", "guard"); new RemapAction("" + KeyEvent.KEYCODE_HEADSETHOOK, 0, 0, true); new RemapAction("" + KeyEvent.KEYCODE_VOLUME_UP, 0, 0, true); new RemapAction("" + KeyEvent.KEYCODE_VOLUME_DOWN, 0, 0, true); if (android.os.Build.VERSION.SDK_INT >= 11) { new RemapAction("" + KeyEvent.KEYCODE_VOLUME_MUTE, 0, 0, true); new RemapAction("" + KeyEvent.KEYCODE_ZOOM_IN, 0, 0, true, "off", "guard"); new RemapAction("" + KeyEvent.KEYCODE_ZOOM_OUT, 0, 0, true, "off", "guard"); } } private RemapAction(String name, Integer labelRes, Integer descriptionRes, Boolean dispatch, String... blacklist) { this.name = name; this.labelRes = labelRes; this.descriptionRes = descriptionRes; this.dispatch = dispatch; for (int i=0; i < blacklist.length; i++) { this.blacklist.add( blacklist[i] ); } VALUES.add(this); NAMES.add(name); } public String getLabel(Context context) { if (labelRes > 0) { return context.getResources().getString(labelRes); } return keyToString(name); } public String getDescription(Context context) { if (descriptionRes > 0) { return context.getResources().getString(descriptionRes); } return null; } } public static String actionType(String action) { return action == null ? null : action.matches("^[0-9]+$") ? "dispatch" : action.contains(".") ? "launcher" : "custom"; } public static String actionToString(Context context, String action) { String type = actionType(action); if ("dispatch".equals(type)) { return keyToString( Integer.parseInt(action) ); } else if ("launcher".equals(type)) { try { PackageManager packageManager = context.getPackageManager(); ApplicationInfo applicationInfo = packageManager.getApplicationInfo(action, 0); return (String) packageManager.getApplicationLabel(applicationInfo); } catch(Throwable e) {} } else { try { return RemapAction.VALUES.get( RemapAction.NAMES.indexOf(action) ).getLabel(context); } catch(Throwable e) {} } return null; } public static String conditionToString(Context context, String condition) { Integer id = context.getResources().getIdentifier("condition_type_$" + condition, "string", PACKAGE_NAME); if (id > 0) { return context.getResources().getString(id); } else { try { PackageManager packageManager = context.getPackageManager(); ApplicationInfo applicationInfo = packageManager.getApplicationInfo(condition, 0); return (String) packageManager.getApplicationLabel(applicationInfo); } catch(Throwable e) {} } return condition; } public static String keyToString(String keyCode) { String[] codes = keyCode.trim().split("[^0-9]+"); List<String> output = new ArrayList<String>(); for (int i=0; i < codes.length; i++) { if(codes[i] != null && !codes[i].equals("0")) { output.add(keyToString( Integer.parseInt(codes[i]) )); } } return TextUtils.join("+", output); } @SuppressLint("NewApi") public static String keyToString(Integer keyCode) { /* * KeyEvent to string is not supported in Gingerbread, * so we define the most basics ourself. */ if (keyCode != null) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: return "Volume Up"; case KeyEvent.KEYCODE_VOLUME_DOWN: return "Volume Down"; case KeyEvent.KEYCODE_SETTINGS: return "Settings"; case KeyEvent.KEYCODE_SEARCH: return "Search"; case KeyEvent.KEYCODE_POWER: return "Power"; case KeyEvent.KEYCODE_NOTIFICATION: return "Notification"; case KeyEvent.KEYCODE_MUTE: return "Mic Mute"; case KeyEvent.KEYCODE_MUSIC: return "Music"; case KeyEvent.KEYCODE_MOVE_HOME: return "Home"; case KeyEvent.KEYCODE_MENU: return "Menu"; case KeyEvent.KEYCODE_MEDIA_STOP: return "Media Stop"; case KeyEvent.KEYCODE_MEDIA_REWIND: return "Media Rewind"; case KeyEvent.KEYCODE_MEDIA_RECORD: return "Media Record"; case KeyEvent.KEYCODE_MEDIA_PREVIOUS: return "Media Previous"; case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: return "Media Play/Pause"; case KeyEvent.KEYCODE_MEDIA_PLAY: return "Media Play"; case KeyEvent.KEYCODE_MEDIA_PAUSE: return "Media Pause"; case KeyEvent.KEYCODE_MEDIA_NEXT: return "Media Next"; - case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: return "Media Fast Farward"; + case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: return "Media Fast Forward"; case KeyEvent.KEYCODE_HOME: return "Home"; case KeyEvent.KEYCODE_FUNCTION: return "Function"; case KeyEvent.KEYCODE_FOCUS: return "Camera Focus"; case KeyEvent.KEYCODE_ENDCALL: return "End Call"; case KeyEvent.KEYCODE_DPAD_UP: return "DPad Up"; case KeyEvent.KEYCODE_DPAD_RIGHT: return "DPad Right"; case KeyEvent.KEYCODE_DPAD_LEFT: return "DPad Left"; case KeyEvent.KEYCODE_DPAD_DOWN: return "DPad Down"; case KeyEvent.KEYCODE_DPAD_CENTER: return "DPad Center"; case KeyEvent.KEYCODE_CAMERA: return "Camera"; case KeyEvent.KEYCODE_CALL: return "Call"; case KeyEvent.KEYCODE_BUTTON_START: return "Start"; case KeyEvent.KEYCODE_BUTTON_SELECT: return "Select"; case KeyEvent.KEYCODE_BACK: return "Back"; case KeyEvent.KEYCODE_APP_SWITCH: return "App Switch"; case KeyEvent.KEYCODE_3D_MODE: return "3D Mode"; case KeyEvent.KEYCODE_ASSIST: return "Assist"; case KeyEvent.KEYCODE_PAGE_UP: return "Page Up"; case KeyEvent.KEYCODE_PAGE_DOWN: return "Page Down"; case KeyEvent.KEYCODE_HEADSETHOOK: return "Headset Hook"; } if (android.os.Build.VERSION.SDK_INT >= 11) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_MUTE: return "Volume Mute"; - case KeyEvent.KEYCODE_ZOOM_OUT: return "zoom Out"; + case KeyEvent.KEYCODE_ZOOM_OUT: return "Zoom Out"; case KeyEvent.KEYCODE_ZOOM_IN: return "Zoom In"; } } if (android.os.Build.VERSION.SDK_INT >= 12) { String codeName = KeyEvent.keyCodeToString(keyCode); if (codeName.startsWith("KEYCODE_")) { String[] codeWords = codeName.toLowerCase(Locale.US).split("_"); StringBuilder builder = new StringBuilder(); for (int i=1; i < codeWords.length; i++) { char[] codeChars = codeWords[i].trim().toCharArray(); codeChars[0] = Character.toUpperCase(codeChars[0]); if (i > 1) { builder.append(" "); } builder.append(codeChars); } return builder.toString(); } } } return "" + keyCode; } public static Integer getConditionIdentifier(Context context, String condition) { return context.getResources().getIdentifier("condition_type_$" + condition, "string", Common.PACKAGE_NAME); } /* * Quantity Strings are broken on some Platforms and phones which is described in the below tracker. * To make up for this, we use this little helper. We don't need options like 'few' or 'many', so * no larger library replacement is needed. * * http://code.google.com/p/android/issues/detail?id=8287 */ public static int getQuantityResource(Resources resources, String idRef, int quantity) { int id = resources.getIdentifier(idRef + "_$" + quantity, "string", PACKAGE_NAME); if (id == 0) { id = resources.getIdentifier(idRef, "string", PACKAGE_NAME); } return id; } public static List<AppInfo> loadApplicationList(Context context) { if (oPackageListCache == null) { oPackageListCache = new ArrayList<AppInfo>(); PackageManager packageManager = context.getPackageManager(); List<PackageInfo> packages = packageManager.getInstalledPackages(0); for(int i=0; i < packages.size(); i++) { PackageInfo packageInfo = packages.get(i); if (!oPackageBlackList.contains(packageInfo.packageName)) { AppInfo appInfo = new AppInfo(); if (android.os.Build.VERSION.SDK_INT >= 11) { appInfo.icon = packageInfo.applicationInfo.loadIcon(packageManager).getConstantState(); } appInfo.label = packageInfo.applicationInfo.loadLabel(packageManager).toString(); appInfo.name = packageInfo.packageName; oPackageListCache.add(appInfo); } } } return oPackageListCache; } public static class AppInfo { public String name; public String label; public ConstantState icon; } }
false
true
public static String keyToString(Integer keyCode) { /* * KeyEvent to string is not supported in Gingerbread, * so we define the most basics ourself. */ if (keyCode != null) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: return "Volume Up"; case KeyEvent.KEYCODE_VOLUME_DOWN: return "Volume Down"; case KeyEvent.KEYCODE_SETTINGS: return "Settings"; case KeyEvent.KEYCODE_SEARCH: return "Search"; case KeyEvent.KEYCODE_POWER: return "Power"; case KeyEvent.KEYCODE_NOTIFICATION: return "Notification"; case KeyEvent.KEYCODE_MUTE: return "Mic Mute"; case KeyEvent.KEYCODE_MUSIC: return "Music"; case KeyEvent.KEYCODE_MOVE_HOME: return "Home"; case KeyEvent.KEYCODE_MENU: return "Menu"; case KeyEvent.KEYCODE_MEDIA_STOP: return "Media Stop"; case KeyEvent.KEYCODE_MEDIA_REWIND: return "Media Rewind"; case KeyEvent.KEYCODE_MEDIA_RECORD: return "Media Record"; case KeyEvent.KEYCODE_MEDIA_PREVIOUS: return "Media Previous"; case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: return "Media Play/Pause"; case KeyEvent.KEYCODE_MEDIA_PLAY: return "Media Play"; case KeyEvent.KEYCODE_MEDIA_PAUSE: return "Media Pause"; case KeyEvent.KEYCODE_MEDIA_NEXT: return "Media Next"; case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: return "Media Fast Farward"; case KeyEvent.KEYCODE_HOME: return "Home"; case KeyEvent.KEYCODE_FUNCTION: return "Function"; case KeyEvent.KEYCODE_FOCUS: return "Camera Focus"; case KeyEvent.KEYCODE_ENDCALL: return "End Call"; case KeyEvent.KEYCODE_DPAD_UP: return "DPad Up"; case KeyEvent.KEYCODE_DPAD_RIGHT: return "DPad Right"; case KeyEvent.KEYCODE_DPAD_LEFT: return "DPad Left"; case KeyEvent.KEYCODE_DPAD_DOWN: return "DPad Down"; case KeyEvent.KEYCODE_DPAD_CENTER: return "DPad Center"; case KeyEvent.KEYCODE_CAMERA: return "Camera"; case KeyEvent.KEYCODE_CALL: return "Call"; case KeyEvent.KEYCODE_BUTTON_START: return "Start"; case KeyEvent.KEYCODE_BUTTON_SELECT: return "Select"; case KeyEvent.KEYCODE_BACK: return "Back"; case KeyEvent.KEYCODE_APP_SWITCH: return "App Switch"; case KeyEvent.KEYCODE_3D_MODE: return "3D Mode"; case KeyEvent.KEYCODE_ASSIST: return "Assist"; case KeyEvent.KEYCODE_PAGE_UP: return "Page Up"; case KeyEvent.KEYCODE_PAGE_DOWN: return "Page Down"; case KeyEvent.KEYCODE_HEADSETHOOK: return "Headset Hook"; } if (android.os.Build.VERSION.SDK_INT >= 11) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_MUTE: return "Volume Mute"; case KeyEvent.KEYCODE_ZOOM_OUT: return "zoom Out"; case KeyEvent.KEYCODE_ZOOM_IN: return "Zoom In"; } } if (android.os.Build.VERSION.SDK_INT >= 12) { String codeName = KeyEvent.keyCodeToString(keyCode); if (codeName.startsWith("KEYCODE_")) { String[] codeWords = codeName.toLowerCase(Locale.US).split("_"); StringBuilder builder = new StringBuilder(); for (int i=1; i < codeWords.length; i++) { char[] codeChars = codeWords[i].trim().toCharArray(); codeChars[0] = Character.toUpperCase(codeChars[0]); if (i > 1) { builder.append(" "); } builder.append(codeChars); } return builder.toString(); } } } return "" + keyCode; }
public static String keyToString(Integer keyCode) { /* * KeyEvent to string is not supported in Gingerbread, * so we define the most basics ourself. */ if (keyCode != null) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: return "Volume Up"; case KeyEvent.KEYCODE_VOLUME_DOWN: return "Volume Down"; case KeyEvent.KEYCODE_SETTINGS: return "Settings"; case KeyEvent.KEYCODE_SEARCH: return "Search"; case KeyEvent.KEYCODE_POWER: return "Power"; case KeyEvent.KEYCODE_NOTIFICATION: return "Notification"; case KeyEvent.KEYCODE_MUTE: return "Mic Mute"; case KeyEvent.KEYCODE_MUSIC: return "Music"; case KeyEvent.KEYCODE_MOVE_HOME: return "Home"; case KeyEvent.KEYCODE_MENU: return "Menu"; case KeyEvent.KEYCODE_MEDIA_STOP: return "Media Stop"; case KeyEvent.KEYCODE_MEDIA_REWIND: return "Media Rewind"; case KeyEvent.KEYCODE_MEDIA_RECORD: return "Media Record"; case KeyEvent.KEYCODE_MEDIA_PREVIOUS: return "Media Previous"; case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: return "Media Play/Pause"; case KeyEvent.KEYCODE_MEDIA_PLAY: return "Media Play"; case KeyEvent.KEYCODE_MEDIA_PAUSE: return "Media Pause"; case KeyEvent.KEYCODE_MEDIA_NEXT: return "Media Next"; case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: return "Media Fast Forward"; case KeyEvent.KEYCODE_HOME: return "Home"; case KeyEvent.KEYCODE_FUNCTION: return "Function"; case KeyEvent.KEYCODE_FOCUS: return "Camera Focus"; case KeyEvent.KEYCODE_ENDCALL: return "End Call"; case KeyEvent.KEYCODE_DPAD_UP: return "DPad Up"; case KeyEvent.KEYCODE_DPAD_RIGHT: return "DPad Right"; case KeyEvent.KEYCODE_DPAD_LEFT: return "DPad Left"; case KeyEvent.KEYCODE_DPAD_DOWN: return "DPad Down"; case KeyEvent.KEYCODE_DPAD_CENTER: return "DPad Center"; case KeyEvent.KEYCODE_CAMERA: return "Camera"; case KeyEvent.KEYCODE_CALL: return "Call"; case KeyEvent.KEYCODE_BUTTON_START: return "Start"; case KeyEvent.KEYCODE_BUTTON_SELECT: return "Select"; case KeyEvent.KEYCODE_BACK: return "Back"; case KeyEvent.KEYCODE_APP_SWITCH: return "App Switch"; case KeyEvent.KEYCODE_3D_MODE: return "3D Mode"; case KeyEvent.KEYCODE_ASSIST: return "Assist"; case KeyEvent.KEYCODE_PAGE_UP: return "Page Up"; case KeyEvent.KEYCODE_PAGE_DOWN: return "Page Down"; case KeyEvent.KEYCODE_HEADSETHOOK: return "Headset Hook"; } if (android.os.Build.VERSION.SDK_INT >= 11) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_MUTE: return "Volume Mute"; case KeyEvent.KEYCODE_ZOOM_OUT: return "Zoom Out"; case KeyEvent.KEYCODE_ZOOM_IN: return "Zoom In"; } } if (android.os.Build.VERSION.SDK_INT >= 12) { String codeName = KeyEvent.keyCodeToString(keyCode); if (codeName.startsWith("KEYCODE_")) { String[] codeWords = codeName.toLowerCase(Locale.US).split("_"); StringBuilder builder = new StringBuilder(); for (int i=1; i < codeWords.length; i++) { char[] codeChars = codeWords[i].trim().toCharArray(); codeChars[0] = Character.toUpperCase(codeChars[0]); if (i > 1) { builder.append(" "); } builder.append(codeChars); } return builder.toString(); } } } return "" + keyCode; }
diff --git a/src/main/java/cz/muni/fi/bapr/entity/validator/CustomerValidator.java b/src/main/java/cz/muni/fi/bapr/entity/validator/CustomerValidator.java index 3c219f2..25c60fa 100644 --- a/src/main/java/cz/muni/fi/bapr/entity/validator/CustomerValidator.java +++ b/src/main/java/cz/muni/fi/bapr/entity/validator/CustomerValidator.java @@ -1,48 +1,48 @@ package cz.muni.fi.bapr.entity.validator; import cz.muni.fi.bapr.entity.Customer; import cz.muni.fi.bapr.service.CustomerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; /** * @author Andrej Kuročenko <[email protected]> */ @Component public class CustomerValidator implements Validator { @Autowired @Qualifier("springValidator") private Validator validator; @Autowired private CustomerService customerService; @Override public boolean supports(Class<?> clazz) { return Customer.class.equals(clazz); } @Override public void validate(Object target, Errors errors) { Customer customer = (Customer) target; if (customer.getId() == null) { if ((customerService.findByEmail(customer.getEmail()) != null)) { - errors.rejectValue("email", "customer.validation.mailexists"); + errors.rejectValue("email", "customer.validation.mail.exists"); } } else { Customer customerDB = customerService.findByEmail(customer.getEmail()); if ((customerDB != null) && !customerDB.getId().equals(customer.getId())) { - errors.rejectValue("email", "customer.validation.mailexists"); + errors.rejectValue("email", "customer.validation.mail.exists"); } } validator.validate(target, errors); } }
false
true
public void validate(Object target, Errors errors) { Customer customer = (Customer) target; if (customer.getId() == null) { if ((customerService.findByEmail(customer.getEmail()) != null)) { errors.rejectValue("email", "customer.validation.mailexists"); } } else { Customer customerDB = customerService.findByEmail(customer.getEmail()); if ((customerDB != null) && !customerDB.getId().equals(customer.getId())) { errors.rejectValue("email", "customer.validation.mailexists"); } } validator.validate(target, errors); }
public void validate(Object target, Errors errors) { Customer customer = (Customer) target; if (customer.getId() == null) { if ((customerService.findByEmail(customer.getEmail()) != null)) { errors.rejectValue("email", "customer.validation.mail.exists"); } } else { Customer customerDB = customerService.findByEmail(customer.getEmail()); if ((customerDB != null) && !customerDB.getId().equals(customer.getId())) { errors.rejectValue("email", "customer.validation.mail.exists"); } } validator.validate(target, errors); }
diff --git a/linkedlists/List.java b/linkedlists/List.java index 29c879f..839c8cc 100644 --- a/linkedlists/List.java +++ b/linkedlists/List.java @@ -1,142 +1,146 @@ package linkedlists; public class List<T extends Comparable<? super T>> { ListNode<T> first; ListNode<T> last; String name; public List() { this( "list" ); } public List( String listName ) { name = listName; first = last = null; } public void insertAtFront( T item ) { if ( isEmpty() ) first = last = new ListNode<T>( item ); else first = new ListNode<T>( item, first ); } public void insertAtBack( T item ) { if ( isEmpty() ) first = last = new ListNode<T>( item ); else last = last.next = new ListNode<T>( item ); } public void insertInOrder( T item ) { if ( isEmpty() ) { insertAtBack( item ); return; } ListNode<T> node = first; if ( first.data.compareTo( item ) >= 0 ) { ListNode<T> insert = new ListNode<T>( item ); insert.next = first; first = insert; return; } while ( node.next != null ) { if ( node.next.data.compareTo( item ) >= 0 ) { ListNode<T> insert = new ListNode<T>( item ); insert.next = node.next; node.next = insert; return; } node = node.next; } + ListNode<T> insert = new ListNode<T>( item ); + insert.next = null; + last.next = insert; + last = insert; } public T front() throws EmptyListException { if ( isEmpty() ) throw new EmptyListException( name ); T item = first.data; return item; } public T removeFromFront() throws EmptyListException { if ( isEmpty() ) throw new EmptyListException( name ); T item = first.data; if ( first == last ) first = last = null; else first = first.next; return item; } public T back() throws EmptyListException { if ( isEmpty() ) throw new EmptyListException( name ); T item = last.data; return item; } public T removeFromBack() throws EmptyListException { if ( isEmpty() ) throw new EmptyListException( name ); T item = last.data; if ( first == last ) first = last = null; else { ListNode<T> curr = first; while ( curr.next != last ) curr = curr.next; last = curr; curr.next = null; } return item; } public boolean isEmpty() { return first == null; } public void print() { if ( isEmpty() ) { System.out.printf( "Empty %s\n", name ); return; } System.out.printf( "The %s is:", name ); ListNode<T> curr = first; while ( curr != null ) { System.out.printf( " %s", curr.data ); curr = curr.next; } System.out.println( "\n" ); } }
true
true
public void insertInOrder( T item ) { if ( isEmpty() ) { insertAtBack( item ); return; } ListNode<T> node = first; if ( first.data.compareTo( item ) >= 0 ) { ListNode<T> insert = new ListNode<T>( item ); insert.next = first; first = insert; return; } while ( node.next != null ) { if ( node.next.data.compareTo( item ) >= 0 ) { ListNode<T> insert = new ListNode<T>( item ); insert.next = node.next; node.next = insert; return; } node = node.next; } }
public void insertInOrder( T item ) { if ( isEmpty() ) { insertAtBack( item ); return; } ListNode<T> node = first; if ( first.data.compareTo( item ) >= 0 ) { ListNode<T> insert = new ListNode<T>( item ); insert.next = first; first = insert; return; } while ( node.next != null ) { if ( node.next.data.compareTo( item ) >= 0 ) { ListNode<T> insert = new ListNode<T>( item ); insert.next = node.next; node.next = insert; return; } node = node.next; } ListNode<T> insert = new ListNode<T>( item ); insert.next = null; last.next = insert; last = insert; }
diff --git a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/OrganizeGroovyImports.java b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/OrganizeGroovyImports.java index 43c4f4a71..7ab950e7a 100644 --- a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/OrganizeGroovyImports.java +++ b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/OrganizeGroovyImports.java @@ -1,477 +1,480 @@ package org.codehaus.groovy.eclipse.refactoring.actions; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassCodeVisitorSupport; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ConstructorNode; import org.codehaus.groovy.ast.DynamicVariable; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.GenericsType; import org.codehaus.groovy.ast.ImportNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.ModuleNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.expr.CastExpression; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.ClosureExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.ConstructorCallExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.eclipse.core.GroovyCore; import org.codehaus.jdt.groovy.model.GroovyCompilationUnit; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.core.search.TypeNameMatch; import org.eclipse.jdt.groovy.core.util.ReflectionUtils; import org.eclipse.jdt.internal.core.SourceRange; import org.eclipse.jdt.internal.core.search.JavaSearchTypeNameMatch; import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation; import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery; import org.eclipse.jdt.internal.corext.util.TypeNameMatchCollector; import org.eclipse.text.edits.InsertEdit; import org.eclipse.text.edits.MalformedTreeException; import org.eclipse.text.edits.MultiTextEdit; import org.eclipse.text.edits.ReplaceEdit; import org.eclipse.text.edits.TextEdit; import org.eclipse.text.edits.TextEditVisitor; /** * @author andrew * Organize import operation for groovy files */ public class OrganizeGroovyImports { /** * From {@link OrganizeImportsOperation.TypeReferenceProcessor.UnresolvedTypeData} * */ static class UnresolvedTypeData { final String ref; final boolean isAnnotation; final List<TypeNameMatch> foundInfos; final ISourceRange range; public UnresolvedTypeData(String ref, boolean annotation, ISourceRange range) { this.ref = ref; this.isAnnotation = annotation; this.foundInfos = new LinkedList<TypeNameMatch>(); this.range = range; } public void addInfo(TypeNameMatch info) { for (int i= this.foundInfos.size() - 1; i >= 0; i--) { TypeNameMatch curr= (TypeNameMatch) this.foundInfos.get(i); if (curr.getTypeContainerName().equals(info.getTypeContainerName())) { return; // not added. already contains type with same name } } foundInfos.add(info); } } private class FindUnresolvedReferencesVisitor extends ClassCodeVisitorSupport { private ClassNode current; // not needed @Override protected SourceUnit getSourceUnit() { return null; } @Override public void visitCastExpression(CastExpression expression) { handleType(expression.getType(), false); super.visitCastExpression(expression); } @Override public void visitClassExpression(ClassExpression expression) { handleType(expression.getType(), false); } @Override public void visitConstructorCallExpression( ConstructorCallExpression call) { handleType(call.getType(), false); super.visitConstructorCallExpression(call); } @Override public void visitVariableExpression(VariableExpression expression) { handleType(expression.getType(), false); if (expression.getAccessedVariable() instanceof DynamicVariable) { handleVariableExpression(expression); } } @Override public void visitField(FieldNode node) { // can't check for synthetic here because // it seems that non-synthetic nodes are being marked as synthetic if (! node.getName().startsWith("_") && !node.getName().startsWith("$")) { handleType(node.getType(), false); } super.visitField(node); } @Override public void visitConstructor(ConstructorNode node) { if (!node.isSynthetic()) { for (Parameter param : node.getParameters()) { handleType(param.getType(), false); } } super.visitConstructor(node); } @Override public void visitMethod(MethodNode node) { if (!node.isSynthetic()) { handleType(node.getReturnType(), false); for (Parameter param : node.getParameters()) { handleType(param.getType(), false); } } super.visitMethod(node); } @Override public void visitClass(ClassNode node) { current = node; if (!node.isSynthetic()) { handleType(node.getSuperClass(), false); for (ClassNode impls : node.getInterfaces()) { handleType(impls, false); } } super.visitClass(node); } @Override public void visitClosureExpression(ClosureExpression node) { for (Parameter param : node.getParameters()) { handleType(param.getType(), false); } super.visitClosureExpression(node); } @Override public void visitAnnotations(AnnotatedNode node) { for (AnnotationNode an : (Iterable<AnnotationNode>) node.getAnnotations()) { handleType(an.getClassNode(), true); } super.visitAnnotations(node); } /** * Assume dynamic variables are a candidate for Organize imports, * but only if name begins with a capital. This will hopefully * filter out most false positives. * @param expr */ private void handleVariableExpression(VariableExpression expr) { if (Character.isUpperCase(expr.getName().charAt(0)) && !missingTypes.containsKey(expr.getName())) { missingTypes.put(expr.getName(), new UnresolvedTypeData(expr.getName(), false, new SourceRange(expr.getStart(), expr.getEnd()-expr.getStart()))); } } /** * add the type name to missingTypes if it is not resolved * ensure that we don't remove the import if the type is resolved */ private void handleType(ClassNode node, boolean isAnnotation) { if (!node.isResolved() && node != current) { // there may be a partial qualifier if // the type referenced is an inner type. // in this case, only take the first part String semiQualifiedName; if (node.isArray()) { semiQualifiedName = node.getComponentType().getName(); } else { semiQualifiedName = node.getName(); } String simpleName = semiQualifiedName.split("\\.")[0]; if (!missingTypes.containsKey(simpleName)) { missingTypes.put(simpleName, new UnresolvedTypeData(simpleName, isAnnotation, new SourceRange(node.getStart(), node.getEnd()-node.getStart()))); } } else { // We don't know exactly what the // text is. We just know how it resolves // This can be a problem if an inner class. // We don't really know what is in the text // and we don't really know what is the import // So, just ensure that none are slated for removal String name; if (node.isArray()) { name = node.getComponentType().getName(); } else { name = node.getName(); } String nameWithDots = name.replace('$', '.'); int innerIndex = name.lastIndexOf('$'); while (innerIndex > -1) { doNotRemoveImport(nameWithDots); nameWithDots = nameWithDots.substring(0, innerIndex); innerIndex = name.lastIndexOf('$', innerIndex-1); } doNotRemoveImport(nameWithDots); } if (node.isUsingGenerics() && node.getGenericsTypes() != null) { for (GenericsType gen : node.getGenericsTypes()) { if (gen.getLowerBound() != null) { handleType(gen.getLowerBound(), false); } if (gen.getUpperBounds() != null) { for (ClassNode upper : gen.getUpperBounds()) { - handleType(upper, false); + // handle enums where the upper bound is the same as the type + if (! upper.getName().equals(node.getName())) { + handleType(upper, false); + } } } if (gen.getType() != null && gen.getType().getName().charAt(0) != '?') { handleType(gen.getType(), false); } } } } private void doNotRemoveImport(String className) { importsSlatedForRemoval.remove(className); } } private final GroovyCompilationUnit unit; private HashMap<String, UnresolvedTypeData> missingTypes; private HashMap<String, ImportNode> importsSlatedForRemoval; private IChooseImportQuery query; public OrganizeGroovyImports(GroovyCompilationUnit unit, IChooseImportQuery query) { this.unit = unit; this.query = query; } public TextEdit calculateMissingImports() { ModuleNode node = unit.getModuleNode(); if (isEmpty(node)) { // no AST probably a syntax error...do nothing return new MultiTextEdit(); } missingTypes = new HashMap<String,UnresolvedTypeData>(); importsSlatedForRemoval = new HashMap<String, ImportNode>(); FindUnresolvedReferencesVisitor visitor = new FindUnresolvedReferencesVisitor(); for (ImportNode imp : (Iterable<ImportNode>) node.getImports()) { importsSlatedForRemoval.put(imp.getClassName(), imp); } // find all missing types // find all imports that are not referenced for (ClassNode clazz : (Iterable<ClassNode>) node.getClasses()) { visitor.visitClass(clazz); } try { ImportRewrite rewriter = ImportRewrite.create(unit, true); // remove old // will not work for aliased imports for (String impStr : importsSlatedForRemoval.keySet()) { rewriter.removeImport(impStr); } // resolve them IType[] resolvedTypes = resolveMissingTypes(); for (IType resolved : resolvedTypes) { rewriter.addImport(resolved.getFullyQualifiedName('.')); } TextEdit edit = rewriter.rewriteImports(null); // remove ';' from edits edit = removeSemiColons(edit); return edit; } catch (CoreException e) { GroovyCore.logException("Exception thrown when organizing imports for " + unit.getElementName(), e); } catch (MalformedTreeException e) { GroovyCore.logException("Exception thrown when organizing imports for " + unit.getElementName(), e); } return null; } /** * Determine if module is empty...not as easy as it sounds * @param node * @return */ private boolean isEmpty(ModuleNode node) { if (node == null || node.getClasses() == null || node.getClasses().size() == 0) { return true; } if (node.getClasses().size() == 1 && ((ClassNode) node.getClasses().get(0)).isScript()) { if ((node.getStatementBlock() == null || node.getStatementBlock().isEmpty() || isNullReturn(node.getStatementBlock())) && (node.getMethods() == null || node.getMethods().size() == 0)) { return true; } } return false; } /** * @param statementBlock * @return */ private boolean isNullReturn(BlockStatement statementBlock) { List<Statement> statements = statementBlock.getStatements(); if (statements.size() == 1 && statements.get(0) instanceof ReturnStatement) { ReturnStatement ret = (ReturnStatement) statements.get(0); if (ret.getExpression() instanceof ConstantExpression) { return ((ConstantExpression) ret.getExpression()).isNullExpression(); } } return false; } /** * @param edit * @return */ private TextEdit removeSemiColons(TextEdit edit) { TextEditVisitor visitor = new TextEditVisitor() { @Override public boolean visit(InsertEdit edit) { String text = edit.getText(); text = text.replace(';', ' '); ReflectionUtils.setPrivateField(InsertEdit.class, "fText", edit, text); return super.visit(edit); } public boolean visit(ReplaceEdit edit) { String text = edit.getText(); text = text.replace(';', ' '); ReflectionUtils.setPrivateField(InsertEdit.class, "fText", edit, text); return super.visit(edit); } }; edit.accept(visitor); return edit; } public void calculateAndApplyMissingImports() throws JavaModelException { TextEdit edit = calculateMissingImports(); if (edit != null) { unit.applyTextEdit(edit, null); } } private IType[] resolveMissingTypes() throws JavaModelException { // fill in all the potential matches searchForTypes(); List<TypeNameMatch> missingTypesNoChoiceRequired = new ArrayList<TypeNameMatch>(); List<TypeNameMatch[]> missingTypesChoiceRequired = new ArrayList<TypeNameMatch[]>(); List<ISourceRange> ranges = new ArrayList<ISourceRange>(); // go through all the resovled matches and look for ambiguous matches for (UnresolvedTypeData data : missingTypes.values()) { if (data.foundInfos.size() > 1) { missingTypesChoiceRequired.add(data.foundInfos.toArray(new TypeNameMatch[0])); ranges.add(data.range); } else if (data.foundInfos.size() == 1) { missingTypesNoChoiceRequired.add(data.foundInfos.get(0)); } } TypeNameMatch[][] missingTypesArr = missingTypesChoiceRequired.toArray(new TypeNameMatch[0][]); TypeNameMatch[] chosen; if (missingTypesArr.length > 0) { chosen = query.chooseImports(missingTypesArr, ranges.toArray(new ISourceRange[0])); } else { chosen = new TypeNameMatch[0]; } if (chosen != null) { IType[] typeMatches = new IType[missingTypesNoChoiceRequired.size() + chosen.length]; int cnt = 0; for (TypeNameMatch typeNameMatch : missingTypesNoChoiceRequired) { typeMatches[cnt++] = typeNameMatch.getType(); } for (int i = 0; i < chosen.length; i++) { typeMatches[cnt++] = ((JavaSearchTypeNameMatch) chosen[i]).getType(); } return typeMatches; } else { // dialog was canceled. do nothing return new IType[0]; } } /** * Use a SearchEngine to look for the types * This will not find inner types, however * @see OrganizeImportsOperation.TypeReferenceProcessor#process(org.eclipse.core.runtime.IProgressMonitor) * @param missingType * @throws JavaModelException */ private void searchForTypes() throws JavaModelException { char[][] allTypes = new char[missingTypes.size()][]; int i = 0; for (String simpleName : missingTypes.keySet()) { allTypes[i++] = simpleName.toCharArray(); } final List<TypeNameMatch> typesFound= new ArrayList<TypeNameMatch>(); TypeNameMatchCollector collector= new TypeNameMatchCollector(typesFound); IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { unit.getJavaProject() }); new SearchEngine().searchAllTypeNames(null, allTypes, scope, collector, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); for (TypeNameMatch match : typesFound) { UnresolvedTypeData data = missingTypes.get(match.getSimpleTypeName()); if (isOfKind(match, data.isAnnotation)) { data.addInfo(match); } } } /** * If looking for an annotation, then filter out non-annoations, * otherwise everything is acceptable. * @param match * @param isAnnotation * @return */ private boolean isOfKind(TypeNameMatch match, boolean isAnnotation) { return isAnnotation ? Flags.isAnnotation(match.getModifiers()) : true; } }
true
true
private void handleType(ClassNode node, boolean isAnnotation) { if (!node.isResolved() && node != current) { // there may be a partial qualifier if // the type referenced is an inner type. // in this case, only take the first part String semiQualifiedName; if (node.isArray()) { semiQualifiedName = node.getComponentType().getName(); } else { semiQualifiedName = node.getName(); } String simpleName = semiQualifiedName.split("\\.")[0]; if (!missingTypes.containsKey(simpleName)) { missingTypes.put(simpleName, new UnresolvedTypeData(simpleName, isAnnotation, new SourceRange(node.getStart(), node.getEnd()-node.getStart()))); } } else { // We don't know exactly what the // text is. We just know how it resolves // This can be a problem if an inner class. // We don't really know what is in the text // and we don't really know what is the import // So, just ensure that none are slated for removal String name; if (node.isArray()) { name = node.getComponentType().getName(); } else { name = node.getName(); } String nameWithDots = name.replace('$', '.'); int innerIndex = name.lastIndexOf('$'); while (innerIndex > -1) { doNotRemoveImport(nameWithDots); nameWithDots = nameWithDots.substring(0, innerIndex); innerIndex = name.lastIndexOf('$', innerIndex-1); } doNotRemoveImport(nameWithDots); } if (node.isUsingGenerics() && node.getGenericsTypes() != null) { for (GenericsType gen : node.getGenericsTypes()) { if (gen.getLowerBound() != null) { handleType(gen.getLowerBound(), false); } if (gen.getUpperBounds() != null) { for (ClassNode upper : gen.getUpperBounds()) { handleType(upper, false); } } if (gen.getType() != null && gen.getType().getName().charAt(0) != '?') { handleType(gen.getType(), false); } } } }
private void handleType(ClassNode node, boolean isAnnotation) { if (!node.isResolved() && node != current) { // there may be a partial qualifier if // the type referenced is an inner type. // in this case, only take the first part String semiQualifiedName; if (node.isArray()) { semiQualifiedName = node.getComponentType().getName(); } else { semiQualifiedName = node.getName(); } String simpleName = semiQualifiedName.split("\\.")[0]; if (!missingTypes.containsKey(simpleName)) { missingTypes.put(simpleName, new UnresolvedTypeData(simpleName, isAnnotation, new SourceRange(node.getStart(), node.getEnd()-node.getStart()))); } } else { // We don't know exactly what the // text is. We just know how it resolves // This can be a problem if an inner class. // We don't really know what is in the text // and we don't really know what is the import // So, just ensure that none are slated for removal String name; if (node.isArray()) { name = node.getComponentType().getName(); } else { name = node.getName(); } String nameWithDots = name.replace('$', '.'); int innerIndex = name.lastIndexOf('$'); while (innerIndex > -1) { doNotRemoveImport(nameWithDots); nameWithDots = nameWithDots.substring(0, innerIndex); innerIndex = name.lastIndexOf('$', innerIndex-1); } doNotRemoveImport(nameWithDots); } if (node.isUsingGenerics() && node.getGenericsTypes() != null) { for (GenericsType gen : node.getGenericsTypes()) { if (gen.getLowerBound() != null) { handleType(gen.getLowerBound(), false); } if (gen.getUpperBounds() != null) { for (ClassNode upper : gen.getUpperBounds()) { // handle enums where the upper bound is the same as the type if (! upper.getName().equals(node.getName())) { handleType(upper, false); } } } if (gen.getType() != null && gen.getType().getName().charAt(0) != '?') { handleType(gen.getType(), false); } } } }
diff --git a/Model/src/java/fr/cg95/cvq/service/request/external/impl/RequestExternalService.java b/Model/src/java/fr/cg95/cvq/service/request/external/impl/RequestExternalService.java index 1335dae00..93a7dbcf3 100644 --- a/Model/src/java/fr/cg95/cvq/service/request/external/impl/RequestExternalService.java +++ b/Model/src/java/fr/cg95/cvq/service/request/external/impl/RequestExternalService.java @@ -1,541 +1,542 @@ package fr.cg95.cvq.service.request.external.impl; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.apache.xmlbeans.XmlObject; import org.springframework.context.ApplicationListener; import org.springframework.scheduling.annotation.Async; import fr.cg95.cvq.business.request.Request; import fr.cg95.cvq.business.request.RequestState; import fr.cg95.cvq.business.request.external.RequestExternalAction; import fr.cg95.cvq.business.users.HomeFolder; import fr.cg95.cvq.business.users.UserAction; import fr.cg95.cvq.business.users.UserState; import fr.cg95.cvq.business.users.UserEvent; import fr.cg95.cvq.business.users.external.HomeFolderMapping; import fr.cg95.cvq.business.users.external.IndividualMapping; import fr.cg95.cvq.business.users.external.UserExternalAction; import fr.cg95.cvq.dao.hibernate.HibernateUtil; import fr.cg95.cvq.dao.request.IRequestDAO; import fr.cg95.cvq.exception.CvqException; import fr.cg95.cvq.exception.CvqModelException; import fr.cg95.cvq.exception.CvqObjectNotFoundException; import fr.cg95.cvq.external.ExternalServiceBean; import fr.cg95.cvq.external.ExternalServiceUtils; import fr.cg95.cvq.external.IExternalProviderService; import fr.cg95.cvq.external.impl.ExternalService; import fr.cg95.cvq.security.SecurityContext; import fr.cg95.cvq.security.annotation.Context; import fr.cg95.cvq.security.annotation.ContextPrivilege; import fr.cg95.cvq.security.annotation.ContextType; import fr.cg95.cvq.service.authority.ILocalAuthorityLifecycleAware; import fr.cg95.cvq.service.payment.external.ExternalApplicationProviderService; import fr.cg95.cvq.service.request.IRequestExportService; import fr.cg95.cvq.service.request.IRequestSearchService; import fr.cg95.cvq.service.request.IRequestTypeService; import fr.cg95.cvq.service.request.annotation.RequestFilter; import fr.cg95.cvq.service.request.external.IRequestExternalActionService; import fr.cg95.cvq.service.request.external.IRequestExternalService; import fr.cg95.cvq.service.users.IUserSearchService; import fr.cg95.cvq.service.users.external.IExternalHomeFolderService; import fr.cg95.cvq.util.Critere; import fr.cg95.cvq.util.mail.IMailService; import fr.cg95.cvq.util.translation.ITranslationService; import fr.cg95.cvq.xml.common.HomeFolderType; import fr.cg95.cvq.xml.common.IndividualType; import fr.cg95.cvq.xml.common.RequestStateType; import fr.cg95.cvq.xml.common.RequestType; import fr.cg95.cvq.xml.request.ecitizen.HomeFolderModificationRequestDocument; import fr.cg95.cvq.xml.request.ecitizen.HomeFolderModificationRequestDocument.HomeFolderModificationRequest; public class RequestExternalService extends ExternalService implements IRequestExternalService, ILocalAuthorityLifecycleAware, ApplicationListener<UserEvent> { private static Logger logger = Logger.getLogger(RequestExternalService.class); private IRequestDAO requestDAO; private IRequestExternalActionService requestExternalActionService; private IRequestExportService requestExportService; private IUserSearchService userSearchService; private IExternalHomeFolderService externalHomeFolderService; private ITranslationService translationService; private IMailService mailService; private IRequestSearchService requestSearchService; private IRequestTypeService requestTypeService; private static final Set<RequestExternalAction.Status> finalExternalStatuses = new HashSet<RequestExternalAction.Status>(2); static { finalExternalStatuses.add(RequestExternalAction.Status.ACCEPTED); finalExternalStatuses.add(RequestExternalAction.Status.REJECTED); } @Override public IExternalProviderService getExternalServiceByRequestType(String requestTypeLabel) { Set<IExternalProviderService> externalProviderServices = getExternalServicesByRequestType(requestTypeLabel); if (!externalProviderServices.isEmpty()) return getExternalServicesByRequestType(requestTypeLabel).toArray(new IExternalProviderService[1])[0]; return null; } @Override public Set<IExternalProviderService> getExternalServicesByRequestType(String requestTypeLabel) { Set<String> requestTypesLabels = new HashSet<String>(); requestTypesLabels.add(requestTypeLabel); return getExternalServicesByRequestTypes(requestTypesLabels); } /** * Get the list of external services objects for the current local authority * interested in events about the given request types. * * @return an empty set if none found */ private Set<IExternalProviderService> getExternalServicesByRequestTypes(final Set<String> requestTypesLabels) { Set<IExternalProviderService> resultSet = new HashSet<IExternalProviderService>(); for (Map.Entry<IExternalProviderService, ExternalServiceBean> entry : SecurityContext.getCurrentConfigurationBean().getExternalServices().entrySet()) { for (String requestTypeLabel : requestTypesLabels) { if (entry.getValue().supportRequestType(requestTypeLabel)) { resultSet.add(entry.getKey()); } } } return resultSet; } @Override public boolean hasMatchingExternalService(String requestLabel) { Set<IExternalProviderService> externalProviderServices = getExternalServicesByRequestType(requestLabel); return !externalProviderServices.isEmpty(); } @Override public Collection<String> getRequestTypesForExternalService(String externalServiceLabel) { ExternalServiceBean esb = SecurityContext.getCurrentConfigurationBean().getBeanForExternalService(externalServiceLabel); return esb == null ? Collections.<String>emptyList() : esb.getRequestTypes(); } @Context(types = {ContextType.SUPER_ADMIN}, privilege = ContextPrivilege.NONE) public List<Request> getSendableRequests(String externalServiceLabel) { Set<RequestState> set = new HashSet<RequestState>(1); set.add(RequestState.VALIDATED); List<Request> result = new ArrayList<Request>(); for (String rt : getRequestTypesForExternalService(externalServiceLabel)) { for (Request req : requestDAO.listByStatesAndType(set, rt, true)) { Set<Critere> criteriaSet = new HashSet<Critere>(3); criteriaSet.add(new Critere(RequestExternalAction.SEARCH_BY_KEY, String.valueOf(req.getId()), Critere.EQUALS)); criteriaSet.add(new Critere(RequestExternalAction.SEARCH_BY_NAME, externalServiceLabel, Critere.EQUALS)); criteriaSet.add(new Critere( RequestExternalAction.SEARCH_BY_STATUS, finalExternalStatuses, Critere.IN)); if (requestExternalActionService.getTracesCount(criteriaSet) == 0) { result.add(req); } } } return result; } @Override @Context(types = {ContextType.AGENT, ContextType.EXTERNAL_SERVICE}, privilege = ContextPrivilege.READ) public List<String> checkExternalReferential(Request request) throws CvqException { if (!hasMatchingExternalService(request.getRequestType().getLabel())) return Collections.<String>emptyList(); XmlObject xmlRequest = requestExportService.fillRequestXml(request); List<String> errors = new ArrayList<String>(); for (IExternalProviderService eps : getExternalServicesByRequestType(request.getRequestType().getLabel())) { errors.addAll(eps.checkExternalReferential(xmlRequest)); } return errors; } @Override @Context(types = {ContextType.AGENT, ContextType.EXTERNAL_SERVICE}, privilege = ContextPrivilege.WRITE) public void sendRequest(Request request) throws CvqException { if (!request.getState().equals(RequestState.VALIDATED)) throw new CvqException("plugins.externalservices.error.requestMustBeValidated"); if (!hasMatchingExternalService(request.getRequestType().getLabel())) return; RequestType xmlRequest = ExternalServiceUtils.getRequestTypeFromXmlObject( requestExportService.fillRequestXml(request)); HomeFolderType xmlHomeFolder = xmlRequest.getHomeFolder(); for (IExternalProviderService externalProviderService : getExternalServicesByRequestType(request.getRequestType().getLabel())) { if (externalProviderService instanceof ExternalApplicationProviderService) continue; // before sending the request to the external service, eventually set // the external identifiers if they are known ... String externalServiceLabel = externalProviderService.getLabel(); HomeFolderMapping mapping = externalHomeFolderService.getHomeFolderMapping(externalServiceLabel, xmlHomeFolder.getId()); if (mapping != null) { fillRequestWithMapping(xmlRequest, mapping); } else { // no existing external service mapping : create a new one to store // the CapDemat external identifier mapping = new HomeFolderMapping(externalServiceLabel, xmlHomeFolder.getId(), null); for (IndividualType xmlIndividual : xmlHomeFolder.getIndividualsArray()) { mapping.getIndividualsMappings() .add(new IndividualMapping(xmlIndividual.getId(), null, mapping)); } externalHomeFolderService.createHomeFolderMapping(mapping); // Yet another fucking Hibernate hack HomeFolderMapping mappingTest = externalHomeFolderService .getHomeFolderMapping(externalServiceLabel, xmlHomeFolder.getId()); if (mappingTest == null) { logger.warn("sendError() mapping was not created, trying a flush"); HibernateUtil.getSession().flush(); } fillRequestWithMapping(xmlRequest, mapping); } RequestExternalAction trace = null; if (!externalProviderService.handlesTraces()) { trace = new RequestExternalAction(new Date(), String.valueOf(xmlRequest.getId()), "capdemat", null, externalServiceLabel, null); } try { logger.debug("sendRequest() routing request to external service " + externalServiceLabel); String externalId = externalProviderService.sendRequest(xmlRequest); if (externalId != null && !externalId.equals("")) { mapping.setExternalId(externalId); externalHomeFolderService.modifyHomeFolderMapping(mapping); } if (!externalProviderService.handlesTraces()) { trace.setStatus(RequestExternalAction.Status.SENT); } } catch (CvqException ce) { logger.error("sendRequest() error while sending request to " - + externalServiceLabel); + + externalServiceLabel + " (" + ce.getMessage() + ")"); if (!externalProviderService.handlesTraces()) { trace.setStatus(RequestExternalAction.Status.NOT_SENT); + trace.setMessage(ce.getMessage()); } } if (!externalProviderService.handlesTraces()) { requestExternalActionService.addTrace(trace); } } } @Override @Async @Context(types = {ContextType.AGENT}, privilege = ContextPrivilege.MANAGE) @RequestFilter(privilege = ContextPrivilege.MANAGE) public void sendRequests(Set<Critere> ids, String email) throws CvqException { HibernateUtil.beginTransaction(); Set<Long> successes = new HashSet<Long>(); Map<Long, String> failures = new HashMap<Long, String>(); for (Request request : requestSearchService.get(ids, null, null, 0, 0, true)) { try { sendRequest(request); successes.add(request.getId()); } catch (Exception e) { failures.put(request.getId(), e.getMessage()); } } String body = ""; if (!successes.isEmpty()) { body += translationService.translate( "externalService.batchRequestResend.notification.body.success", new Object[]{successes.size()}) + "\n\t* " + StringUtils.join(successes, "\n\t* ") + "\n\n"; } if (!failures.isEmpty()) { String failuresChunk = ""; for (Map.Entry<Long, String> failure : failures.entrySet()) { failuresChunk += "\t* " + failure.getKey() + " : " + failure.getValue() + "\n"; } body += translationService.translate( "externalService.batchRequestResend.notification.body.failure", new Object[]{failures.size()}) + "\n" + failuresChunk; } mailService.send(null, email, null, translationService.translate("externalService.batchRequestResend.notification.subject"), body); HibernateUtil.commitTransaction(); } @Override @Context(types = {ContextType.AGENT}, privilege = ContextPrivilege.MANAGE) @RequestFilter(privilege = ContextPrivilege.MANAGE) public List<String> getKeys(Set<Critere> criterias) { return requestExternalActionService.getKeys(criterias); } private void fillRequestWithMapping(RequestType xmlRequest, HomeFolderMapping mapping) throws CvqModelException { HomeFolderType xmlHomeFolder = xmlRequest.getHomeFolder(); xmlHomeFolder.setExternalId(mapping.getExternalId()); xmlHomeFolder.setExternalCapdematId(mapping.getExternalCapDematId()); for (IndividualType individual : xmlHomeFolder.getIndividualsArray()) { boolean hasMapping = false; for (IndividualMapping iMapping : mapping.getIndividualsMappings()) { if (iMapping.getIndividualId().equals(individual.getId())) hasMapping = true; } if (!hasMapping) { mapping.getIndividualsMappings() .add(new IndividualMapping(individual.getId(), null, mapping)); externalHomeFolderService.modifyHomeFolderMapping(mapping); } } for (IndividualMapping iMapping : mapping.getIndividualsMappings()) { if (iMapping.getIndividualId() == null) { logger.warn("fillRequestWithMapping() Got an individual mapping without individual id " + iMapping.getExternalCapDematId()); continue; } if (iMapping.getIndividualId().equals(xmlRequest.getRequester().getId())) { xmlRequest.getRequester().setExternalCapdematId(iMapping.getExternalCapDematId()); xmlRequest.getRequester().setExternalId(iMapping.getExternalId()); } if (xmlRequest.getSubject() != null && xmlRequest.getSubject().getChild() != null) { IndividualType individualType = null; if (xmlRequest.getSubject().getChild() != null) individualType = xmlRequest.getSubject().getChild(); else if (xmlRequest.getSubject().getAdult() != null) individualType = xmlRequest.getSubject().getAdult(); else if (xmlRequest.getSubject().getIndividual() != null) individualType = xmlRequest.getSubject().getIndividual(); if (individualType == null) { logger.warn("fillRequestWithMapping() Unable to extract individual from requets " + xmlRequest.getId()); } else if (iMapping.getIndividualId().equals(individualType.getId())) { individualType.setExternalCapdematId(iMapping.getExternalCapDematId()); individualType.setExternalId(iMapping.getExternalId()); } } for (IndividualType xmlIndividual : xmlHomeFolder.getIndividualsArray()) { if (iMapping.getIndividualId().equals(xmlIndividual.getId())) { xmlIndividual.setExternalId(iMapping.getExternalId()); xmlIndividual.setExternalCapdematId(iMapping.getExternalCapDematId()); } } } } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.READ) public Map<String, Object> loadExternalInformations(Request request) throws CvqException { if (!hasMatchingExternalService(request.getRequestType().getLabel())) return Collections.emptyMap(); RequestType xmlRequest = ExternalServiceUtils.getRequestTypeFromXmlObject( requestExportService.fillRequestXml(request)); List<HomeFolderMapping> mappings = externalHomeFolderService.getHomeFolderMappings(xmlRequest.getHomeFolder().getId()); if (mappings == null || mappings.isEmpty()) return Collections.emptyMap(); Map<String, Object> informations = new TreeMap<String, Object>(); for (HomeFolderMapping mapping : mappings) { IExternalProviderService externalProviderService = getExternalServiceByLabel(mapping.getExternalServiceLabel()); if (externalProviderService == null) { logger.warn("loadExternalInformations() External service " + mapping.getExternalServiceLabel() + " is no longer existing"); continue; } fillRequestWithMapping(xmlRequest, mapping); try { informations.putAll(externalProviderService.loadExternalInformations(xmlRequest)); } catch (CvqException e) { logger.warn("loadExternalInformations()" + "Failed to retrieve information for " + externalProviderService.getLabel()); } } return informations; } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.READ) public Map<Date, String> getConsumptions(final Long requestId, Date dateFrom, Date dateTo) throws CvqException { Request request = (Request) requestDAO.findById(Request.class, requestId); if (request.getState().equals(RequestState.ARCHIVED)) { logger.debug("getConsumptions() Filtering archived request : " + requestId); return null; } Set<IExternalProviderService> externalProviderServices = getExternalServicesByRequestType(request.getRequestType().getLabel()); if (externalProviderServices == null || externalProviderServices.isEmpty()) return Collections.emptyMap(); Map<Date, String> resultMap = new HashMap<Date, String>(); for (IExternalProviderService externalProviderService : externalProviderServices) { Map<Date, String> serviceMap = externalProviderService.getConsumptions(request.getId(), dateFrom, dateTo); if (serviceMap != null && !serviceMap.isEmpty()) resultMap.putAll(serviceMap); } return resultMap; } @Override @Context(types = {ContextType.SUPER_ADMIN}) public void addLocalAuthority(String localAuthorityName) { for (fr.cg95.cvq.business.request.RequestType rt : requestTypeService.getAllRequestTypes()) { for (IExternalProviderService service : getExternalServicesByRequestType(rt.getLabel())) { for (Long id : requestExternalActionService.getRequestsWithoutExternalAction( rt.getId(), service.getLabel())) { requestExternalActionService.addTrace(new RequestExternalAction( new Date(), id.toString(), "capdemat", translationService.translate("requestExternalAction.message.addTraceOnStartup"), service.getLabel(), RequestExternalAction.Status.NOT_SENT)); } } } } @Override @Context(types = {ContextType.SUPER_ADMIN}) public void removeLocalAuthority(String localAuthorityName) { // nothing to do yet } @Override public void onApplicationEvent(UserEvent event) { if (UserAction.Type.MODIFICATION.equals(event.getAction().getType()) || UserAction.Type.STATE_CHANGE.equals(event.getAction().getType())) { HomeFolder homeFolder; try { homeFolder = userSearchService.getHomeFolderById(event.getAction().getTargetId()); } catch (CvqObjectNotFoundException e1) { try { homeFolder = userSearchService.getById(event.getAction().getTargetId()).getHomeFolder(); } catch (CvqObjectNotFoundException e2) { logger.debug("onApplicationEvent() got an event for a non-existent user ID : " + event.getAction().getTargetId()); return; } } if (UserState.VALID.equals(homeFolder.getState())) { try { for (HomeFolderMapping mapping : externalHomeFolderService.getHomeFolderMappings(homeFolder.getId())) { String externalServiceLabel = mapping.getExternalServiceLabel(); IExternalProviderService externalProviderService = getExternalServiceByLabel(externalServiceLabel); if (externalProviderService instanceof ExternalApplicationProviderService) continue; // to force user action's saving (which implies it will have an id we can use below) HibernateUtil.getSession().flush(); HomeFolderModificationRequestDocument doc = HomeFolderModificationRequestDocument.Factory.newInstance(); HomeFolderModificationRequest xmlRequest = doc.addNewHomeFolderModificationRequest(); Calendar calendar = new GregorianCalendar(); calendar.setTime(event.getAction().getDate()); xmlRequest.setCreationDate(calendar); // set request id to the trigerring action's id to ensure uniqueness and a minimum of coherence xmlRequest.setId(event.getAction().getId()); xmlRequest.setLastModificationDate(calendar); xmlRequest.setRequestTypeLabel("Home Folder Modification"); xmlRequest.setState(RequestStateType.Enum.forString(RequestState.VALIDATED.toString())); xmlRequest.setValidationDate(calendar); xmlRequest.addNewHomeFolder().set(homeFolder.modelToXml()); xmlRequest.addNewRequester().set(userSearchService.getHomeFolderResponsible(homeFolder.getId()).modelToXml()); fillRequestWithMapping(xmlRequest, mapping); String externalId = externalProviderService.sendRequest(xmlRequest); if (externalId != null && !externalId.equals("")) { mapping.setExternalId(externalId); externalHomeFolderService.modifyHomeFolderMapping(mapping); } requestDAO.create(new UserExternalAction( homeFolder.getId().toString(), externalServiceLabel, "Sent")); } } catch (CvqException ex) { throw new RuntimeException(ex); } } } } public void setRequestDAO(IRequestDAO requestDAO) { this.requestDAO = requestDAO; } public void setRequestExportService(IRequestExportService requestExportService) { this.requestExportService = requestExportService; } public void setUserSearchService(IUserSearchService userSearchService) { this.userSearchService = userSearchService; } public void setExternalHomeFolderService(IExternalHomeFolderService externalHomeFolderService) { this.externalHomeFolderService = externalHomeFolderService; } public void setRequestExternalActionService( IRequestExternalActionService requestExternalActionService) { this.requestExternalActionService = requestExternalActionService; } public void setTranslationService(ITranslationService translationService) { this.translationService = translationService; } public void setMailService(IMailService mailService) { this.mailService = mailService; } public void setRequestSearchService(IRequestSearchService requestSearchService) { this.requestSearchService = requestSearchService; } public void setRequestTypeService(IRequestTypeService requestTypeService) { this.requestTypeService = requestTypeService; } }
false
true
public void sendRequest(Request request) throws CvqException { if (!request.getState().equals(RequestState.VALIDATED)) throw new CvqException("plugins.externalservices.error.requestMustBeValidated"); if (!hasMatchingExternalService(request.getRequestType().getLabel())) return; RequestType xmlRequest = ExternalServiceUtils.getRequestTypeFromXmlObject( requestExportService.fillRequestXml(request)); HomeFolderType xmlHomeFolder = xmlRequest.getHomeFolder(); for (IExternalProviderService externalProviderService : getExternalServicesByRequestType(request.getRequestType().getLabel())) { if (externalProviderService instanceof ExternalApplicationProviderService) continue; // before sending the request to the external service, eventually set // the external identifiers if they are known ... String externalServiceLabel = externalProviderService.getLabel(); HomeFolderMapping mapping = externalHomeFolderService.getHomeFolderMapping(externalServiceLabel, xmlHomeFolder.getId()); if (mapping != null) { fillRequestWithMapping(xmlRequest, mapping); } else { // no existing external service mapping : create a new one to store // the CapDemat external identifier mapping = new HomeFolderMapping(externalServiceLabel, xmlHomeFolder.getId(), null); for (IndividualType xmlIndividual : xmlHomeFolder.getIndividualsArray()) { mapping.getIndividualsMappings() .add(new IndividualMapping(xmlIndividual.getId(), null, mapping)); } externalHomeFolderService.createHomeFolderMapping(mapping); // Yet another fucking Hibernate hack HomeFolderMapping mappingTest = externalHomeFolderService .getHomeFolderMapping(externalServiceLabel, xmlHomeFolder.getId()); if (mappingTest == null) { logger.warn("sendError() mapping was not created, trying a flush"); HibernateUtil.getSession().flush(); } fillRequestWithMapping(xmlRequest, mapping); } RequestExternalAction trace = null; if (!externalProviderService.handlesTraces()) { trace = new RequestExternalAction(new Date(), String.valueOf(xmlRequest.getId()), "capdemat", null, externalServiceLabel, null); } try { logger.debug("sendRequest() routing request to external service " + externalServiceLabel); String externalId = externalProviderService.sendRequest(xmlRequest); if (externalId != null && !externalId.equals("")) { mapping.setExternalId(externalId); externalHomeFolderService.modifyHomeFolderMapping(mapping); } if (!externalProviderService.handlesTraces()) { trace.setStatus(RequestExternalAction.Status.SENT); } } catch (CvqException ce) { logger.error("sendRequest() error while sending request to " + externalServiceLabel); if (!externalProviderService.handlesTraces()) { trace.setStatus(RequestExternalAction.Status.NOT_SENT); } } if (!externalProviderService.handlesTraces()) { requestExternalActionService.addTrace(trace); } } }
public void sendRequest(Request request) throws CvqException { if (!request.getState().equals(RequestState.VALIDATED)) throw new CvqException("plugins.externalservices.error.requestMustBeValidated"); if (!hasMatchingExternalService(request.getRequestType().getLabel())) return; RequestType xmlRequest = ExternalServiceUtils.getRequestTypeFromXmlObject( requestExportService.fillRequestXml(request)); HomeFolderType xmlHomeFolder = xmlRequest.getHomeFolder(); for (IExternalProviderService externalProviderService : getExternalServicesByRequestType(request.getRequestType().getLabel())) { if (externalProviderService instanceof ExternalApplicationProviderService) continue; // before sending the request to the external service, eventually set // the external identifiers if they are known ... String externalServiceLabel = externalProviderService.getLabel(); HomeFolderMapping mapping = externalHomeFolderService.getHomeFolderMapping(externalServiceLabel, xmlHomeFolder.getId()); if (mapping != null) { fillRequestWithMapping(xmlRequest, mapping); } else { // no existing external service mapping : create a new one to store // the CapDemat external identifier mapping = new HomeFolderMapping(externalServiceLabel, xmlHomeFolder.getId(), null); for (IndividualType xmlIndividual : xmlHomeFolder.getIndividualsArray()) { mapping.getIndividualsMappings() .add(new IndividualMapping(xmlIndividual.getId(), null, mapping)); } externalHomeFolderService.createHomeFolderMapping(mapping); // Yet another fucking Hibernate hack HomeFolderMapping mappingTest = externalHomeFolderService .getHomeFolderMapping(externalServiceLabel, xmlHomeFolder.getId()); if (mappingTest == null) { logger.warn("sendError() mapping was not created, trying a flush"); HibernateUtil.getSession().flush(); } fillRequestWithMapping(xmlRequest, mapping); } RequestExternalAction trace = null; if (!externalProviderService.handlesTraces()) { trace = new RequestExternalAction(new Date(), String.valueOf(xmlRequest.getId()), "capdemat", null, externalServiceLabel, null); } try { logger.debug("sendRequest() routing request to external service " + externalServiceLabel); String externalId = externalProviderService.sendRequest(xmlRequest); if (externalId != null && !externalId.equals("")) { mapping.setExternalId(externalId); externalHomeFolderService.modifyHomeFolderMapping(mapping); } if (!externalProviderService.handlesTraces()) { trace.setStatus(RequestExternalAction.Status.SENT); } } catch (CvqException ce) { logger.error("sendRequest() error while sending request to " + externalServiceLabel + " (" + ce.getMessage() + ")"); if (!externalProviderService.handlesTraces()) { trace.setStatus(RequestExternalAction.Status.NOT_SENT); trace.setMessage(ce.getMessage()); } } if (!externalProviderService.handlesTraces()) { requestExternalActionService.addTrace(trace); } } }
diff --git a/src/com/wickedspiral/jacss/parser/Parser.java b/src/com/wickedspiral/jacss/parser/Parser.java index 1890b4a..984e042 100644 --- a/src/com/wickedspiral/jacss/parser/Parser.java +++ b/src/com/wickedspiral/jacss/parser/Parser.java @@ -1,560 +1,566 @@ package com.wickedspiral.jacss.parser; import com.google.common.base.Joiner; import com.wickedspiral.jacss.Options; import com.wickedspiral.jacss.lexer.Token; import com.wickedspiral.jacss.lexer.TokenListener; import java.io.PrintStream; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import static com.wickedspiral.jacss.lexer.Token.*; /** * @author wasche * @since 2011.08.04 */ public class Parser implements TokenListener { private static final Joiner NULL_JOINER = Joiner.on( "" ); private static final String MS_ALPHA = "progid:dximagetransform.microsoft.alpha(opacity="; private static final Collection<String> UNITS = new HashSet<>( Arrays.asList( "px", "em", "pt", "in", "cm", "mm", "pc", "ex", "%" ) ); private static final Collection<String> KEYWORDS = new HashSet<>( Arrays.asList( "normal", "bold", "italic", "serif", "sans-serif", "fixed" ) ); private static final Collection<String> BOUNDARY_OPS = new HashSet<>( Arrays.asList( "{", "}", ">", ";", ":", "," ) ); // or comment private static final Collection<String> DUAL_ZERO_PROPERTIES = new HashSet<>( Arrays.asList( "background-position", "-webkit-transform-origin", "-moz-transform-origin" ) ); private static final Collection<String> NONE_PROPERTIES = new HashSet<>(); static { NONE_PROPERTIES.add( "outline" ); for ( String property : new String[]{ "border", "margin", "padding" } ) { NONE_PROPERTIES.add( property ); for ( String edge : new String[]{ "top", "left", "bottom", "right" } ) { NONE_PROPERTIES.add( property + "-" + edge ); } } } // buffers private LinkedList<String> ruleBuffer; private LinkedList<String> valueBuffer; private LinkedList<String> rgbBuffer; private String pending; // flags private boolean inRule; private boolean space; private boolean charset; private boolean at; private boolean ie5mac; private boolean rgb; private int checkSpace; // other state private String property; private Token lastToken; private String lastValue; private final PrintStream out; private final Options options; public Parser( PrintStream outputStream, Options options ) { out = outputStream; ruleBuffer = new LinkedList<>(); valueBuffer = new LinkedList<>(); rgbBuffer = new LinkedList<>(); inRule = false; space = false; charset = false; at = false; ie5mac = false; rgb = false; checkSpace = -1; this.options = options; } // ++ Output functions private void output( Collection<String> strings ) { for ( String s : strings ) { output( s ); } } private void output( String str ) { out.print( str ); } private void dump( String str ) { ruleBuffer.add( pending ); ruleBuffer.add( str ); output( ruleBuffer ); ruleBuffer.clear(); pending = null; } private void write( String str ) { if ( str == null || str.length() == 0 ) return; if ( str.startsWith( "/*!" ) && ruleBuffer.isEmpty() ) { output( str ); return; } ruleBuffer.add( str ); if ( "}".equals( str ) ) { // check for empty rule if ( ruleBuffer.size() < 2 || (ruleBuffer.size() >= 2 && !"{".equals( ruleBuffer.get( ruleBuffer.size() - 2 ) )) ) { output( ruleBuffer ); } ruleBuffer.clear(); } } private void buffer( String str ) { if ( str == null || str.length() == 0 ) return; if ( pending == null ) { pending = str; } else { write( pending ); pending = str; } } private void queue( String str ) { if ( str == null || str.length() == 0 ) return; if ( property != null ) { valueBuffer.add( str ); } else { buffer( str ); } } private void collapseValue() { String value = NULL_JOINER.join( valueBuffer ); valueBuffer.clear(); if ( "0 0".equals( value ) || "0 0 0 0".equals( value ) || "0 0 0".equals( value ) ) { if ( DUAL_ZERO_PROPERTIES.contains( property ) ) { buffer( "0 0" ); } else { buffer("0"); } } else if ("none".equals(value) && (NONE_PROPERTIES.contains(property) || "background".equals(property)) && options.shouldCollapseNone()) { buffer("0"); } else { buffer(value); } } // ++ TokenListener public void token(Token token, String value) { if (options.isDebug()) System.err.printf("Token: %s, value: %s, space? %b, in rule? %b\n", token, value, space, inRule); if (rgb) { if (NUMBER == token) { String h = Integer.toHexString(Integer.parseInt(value)).toLowerCase(); if (h.length() < 2) { h = "0" + h; } rgbBuffer.add(h); } else if (LPAREN == token) { if (NUMBER == lastToken) { queue(" "); } queue("#"); rgbBuffer.clear(); } else if (RPAREN == token) { if (rgbBuffer.size() == 3) { String a = rgbBuffer.get(0); String b = rgbBuffer.get(1); String c = rgbBuffer.get(2); if (a.charAt(0) == a.charAt(1) && b.charAt(0) == b.charAt(1) && c.charAt(0) == c.charAt(1)) { queue(a.substring(0, 1)); queue(b.substring(0, 1)); queue(c.substring(0, 1)); rgb = false; return; } } for (String s : rgbBuffer) { queue(s); } rgb = false; } return; } if (token == WHITESPACE) { space = true; return; // most of these are unneeded } if (token == COMMENT) { // comments are only needed in a few places: // 1) special comments /*! ... */ if ('!' == value.charAt(2)) { queue(value); lastToken = token; lastValue = value; } // 2) IE5/Mac hack else if ('\\' == value.charAt(value.length()-3)) { queue("/*\\*/"); lastToken = token; lastValue = value; ie5mac = true; } else if (ie5mac) { - queue("/**/"); + // if the rule buffer starts with the opening ie5/mac comment hack, + // and the rest of the buffer + pending would collapse to nothing, + // suppress the hack comments + if ( ruleBuffer.size() >= 2 && "}".equals( pending ) && !"{".equals( ruleBuffer.get( ruleBuffer.size() - 1 ) ) ) + { + queue("/**/"); + } lastToken = token; lastValue = value; ie5mac = false; } // 3) After a child selector else if (GT == lastToken) { queue("/**/"); lastToken = token; lastValue = value; } return; } // make sure we have space between values for multi-value properties // margin: 5px 5px if ( inRule && ( ( NUMBER == lastToken && (HASH == token || NUMBER == token) ) || ( (IDENTIFIER == lastToken || PERCENT == lastToken || RPAREN == lastToken) && (NUMBER == token || IDENTIFIER == token || HASH == token) ) )) { queue(" "); space = false; } // rgb() if (IDENTIFIER == token && "rgb".equals(value)) { rgb = true; space = false; return; } if (AT == token) { queue(value); at = true; } else if (inRule && COLON == token && property == null) { queue(value); property = lastValue.toLowerCase(); valueBuffer.clear(); } // first-letter and first-line must be followed by a space else if (!inRule && COLON == lastToken && ("first-letter".equals(value) || "first-line".equals(value))) { queue(value); queue(" "); } else if (SEMICOLON == token) { if (at) { at = false; if ("charset".equals(ruleBuffer.get(1))) { if (charset) { ruleBuffer.clear(); pending = null; } else { charset = true; dump(value); } } else { dump(value); } } else if (SEMICOLON == lastToken) { return; // skip duplicate semicolons } else { collapseValue(); valueBuffer.clear(); property = null; queue(value); } } else if (LBRACE == token) { if (checkSpace != -1) { // start of a rule, the space was correct checkSpace = -1; } if (at) { at = false; dump(value); } else { inRule = true; queue(value); } } else if (RBRACE == token) { if (checkSpace != -1) { // didn't start a rule, space was wrong ruleBuffer.remove(checkSpace); checkSpace = -1; } if (!valueBuffer.isEmpty()) { collapseValue(); } if (";".equals(pending)) { if (options.keepTailingSemicolons()) { buffer(";"); } pending = value; } else { buffer(value); } property = null; inRule = false; } else if (!inRule) { if (!space || GT == token || lastToken == null || BOUNDARY_OPS.contains( lastValue )) { queue(value); } else { if (COLON == token) { checkSpace = ruleBuffer.size() + 1; // include pending value } if ( COMMENT != lastToken && !BOUNDARY_OPS.contains( lastValue ) ) { queue(" "); } queue(value); space = false; } } else if (NUMBER == token && value.startsWith("0.")) { if ( options.shouldCollapseZeroes() ) { queue(value.substring(1)); } else { queue( value ); } } else if (STRING == token && "-ms-filter".equals(property)) { if (value.toLowerCase().startsWith(MS_ALPHA, 1)) { String c = value.substring(0, 1); String o = value.substring(MS_ALPHA.length()+1, value.length()-2); queue(c); queue("alpha(opacity="); queue(o); queue(")"); queue(c); } else { queue(value); } } else if (EQUALS == token) { queue(value); StringBuilder sb = new StringBuilder(); for (String s : valueBuffer) { sb.append(s); } if (MS_ALPHA.equals(sb.toString().toLowerCase())) { buffer("alpha(opacity="); valueBuffer.clear(); } } else { String v = value.toLowerCase(); // values of 0 don't need a unit if (NUMBER == lastToken && "0".equals(lastValue) && (PERCENT == token || IDENTIFIER == token)) { if (!UNITS.contains(value)) { queue(" "); queue(value); } } // use 0 instead of none else if (COLON == lastToken && "none".equals(value) && NONE_PROPERTIES.contains(property) && options.shouldCollapseNone()) { queue("0"); } // force properties to lower case for better gzip compression else if (COLON != lastToken && IDENTIFIER == token) { // #aabbcc if (HASH == lastToken) { if (value.length() == 6 && v.charAt(0) == v.charAt(1) && v.charAt(2) == v.charAt(3) && v.charAt(4) == v.charAt(5)) { queue(v.substring(0, 1)); queue(v.substring(2, 3)); queue(v.substring(4, 5)); } else { queue(v); } } else { if ( space && !BOUNDARY_OPS.contains( lastValue ) && BANG != token ) { queue( " " ); } if (property == null || KEYWORDS.contains(v)) { queue(v); } else { queue(value); } } } // nothing special, just send it along else { if ( space && !BOUNDARY_OPS.contains( lastValue ) && BANG != token ) { queue( " " ); } if (KEYWORDS.contains(v)) { queue(v); } else { queue(value); } } } lastToken = token; lastValue = value; space = false; } public void end() { write(pending); if (!ruleBuffer.isEmpty()) { output(ruleBuffer); } } }
true
true
public void token(Token token, String value) { if (options.isDebug()) System.err.printf("Token: %s, value: %s, space? %b, in rule? %b\n", token, value, space, inRule); if (rgb) { if (NUMBER == token) { String h = Integer.toHexString(Integer.parseInt(value)).toLowerCase(); if (h.length() < 2) { h = "0" + h; } rgbBuffer.add(h); } else if (LPAREN == token) { if (NUMBER == lastToken) { queue(" "); } queue("#"); rgbBuffer.clear(); } else if (RPAREN == token) { if (rgbBuffer.size() == 3) { String a = rgbBuffer.get(0); String b = rgbBuffer.get(1); String c = rgbBuffer.get(2); if (a.charAt(0) == a.charAt(1) && b.charAt(0) == b.charAt(1) && c.charAt(0) == c.charAt(1)) { queue(a.substring(0, 1)); queue(b.substring(0, 1)); queue(c.substring(0, 1)); rgb = false; return; } } for (String s : rgbBuffer) { queue(s); } rgb = false; } return; } if (token == WHITESPACE) { space = true; return; // most of these are unneeded } if (token == COMMENT) { // comments are only needed in a few places: // 1) special comments /*! ... */ if ('!' == value.charAt(2)) { queue(value); lastToken = token; lastValue = value; } // 2) IE5/Mac hack else if ('\\' == value.charAt(value.length()-3)) { queue("/*\\*/"); lastToken = token; lastValue = value; ie5mac = true; } else if (ie5mac) { queue("/**/"); lastToken = token; lastValue = value; ie5mac = false; } // 3) After a child selector else if (GT == lastToken) { queue("/**/"); lastToken = token; lastValue = value; } return; } // make sure we have space between values for multi-value properties // margin: 5px 5px if ( inRule && ( ( NUMBER == lastToken && (HASH == token || NUMBER == token) ) || ( (IDENTIFIER == lastToken || PERCENT == lastToken || RPAREN == lastToken) && (NUMBER == token || IDENTIFIER == token || HASH == token) ) )) { queue(" "); space = false; } // rgb() if (IDENTIFIER == token && "rgb".equals(value)) { rgb = true; space = false; return; } if (AT == token) { queue(value); at = true; } else if (inRule && COLON == token && property == null) { queue(value); property = lastValue.toLowerCase(); valueBuffer.clear(); } // first-letter and first-line must be followed by a space else if (!inRule && COLON == lastToken && ("first-letter".equals(value) || "first-line".equals(value))) { queue(value); queue(" "); } else if (SEMICOLON == token) { if (at) { at = false; if ("charset".equals(ruleBuffer.get(1))) { if (charset) { ruleBuffer.clear(); pending = null; } else { charset = true; dump(value); } } else { dump(value); } } else if (SEMICOLON == lastToken) { return; // skip duplicate semicolons } else { collapseValue(); valueBuffer.clear(); property = null; queue(value); } } else if (LBRACE == token) { if (checkSpace != -1) { // start of a rule, the space was correct checkSpace = -1; } if (at) { at = false; dump(value); } else { inRule = true; queue(value); } } else if (RBRACE == token) { if (checkSpace != -1) { // didn't start a rule, space was wrong ruleBuffer.remove(checkSpace); checkSpace = -1; } if (!valueBuffer.isEmpty()) { collapseValue(); } if (";".equals(pending)) { if (options.keepTailingSemicolons()) { buffer(";"); } pending = value; } else { buffer(value); } property = null; inRule = false; } else if (!inRule) { if (!space || GT == token || lastToken == null || BOUNDARY_OPS.contains( lastValue )) { queue(value); } else { if (COLON == token) { checkSpace = ruleBuffer.size() + 1; // include pending value } if ( COMMENT != lastToken && !BOUNDARY_OPS.contains( lastValue ) ) { queue(" "); } queue(value); space = false; } } else if (NUMBER == token && value.startsWith("0.")) { if ( options.shouldCollapseZeroes() ) { queue(value.substring(1)); } else { queue( value ); } } else if (STRING == token && "-ms-filter".equals(property)) { if (value.toLowerCase().startsWith(MS_ALPHA, 1)) { String c = value.substring(0, 1); String o = value.substring(MS_ALPHA.length()+1, value.length()-2); queue(c); queue("alpha(opacity="); queue(o); queue(")"); queue(c); } else { queue(value); } } else if (EQUALS == token) { queue(value); StringBuilder sb = new StringBuilder(); for (String s : valueBuffer) { sb.append(s); } if (MS_ALPHA.equals(sb.toString().toLowerCase())) { buffer("alpha(opacity="); valueBuffer.clear(); } } else { String v = value.toLowerCase(); // values of 0 don't need a unit if (NUMBER == lastToken && "0".equals(lastValue) && (PERCENT == token || IDENTIFIER == token)) { if (!UNITS.contains(value)) { queue(" "); queue(value); } } // use 0 instead of none else if (COLON == lastToken && "none".equals(value) && NONE_PROPERTIES.contains(property) && options.shouldCollapseNone()) { queue("0"); } // force properties to lower case for better gzip compression else if (COLON != lastToken && IDENTIFIER == token) { // #aabbcc if (HASH == lastToken) { if (value.length() == 6 && v.charAt(0) == v.charAt(1) && v.charAt(2) == v.charAt(3) && v.charAt(4) == v.charAt(5)) { queue(v.substring(0, 1)); queue(v.substring(2, 3)); queue(v.substring(4, 5)); } else { queue(v); } } else { if ( space && !BOUNDARY_OPS.contains( lastValue ) && BANG != token ) { queue( " " ); } if (property == null || KEYWORDS.contains(v)) { queue(v); } else { queue(value); } } } // nothing special, just send it along else { if ( space && !BOUNDARY_OPS.contains( lastValue ) && BANG != token ) { queue( " " ); } if (KEYWORDS.contains(v)) { queue(v); } else { queue(value); } } } lastToken = token; lastValue = value; space = false; }
public void token(Token token, String value) { if (options.isDebug()) System.err.printf("Token: %s, value: %s, space? %b, in rule? %b\n", token, value, space, inRule); if (rgb) { if (NUMBER == token) { String h = Integer.toHexString(Integer.parseInt(value)).toLowerCase(); if (h.length() < 2) { h = "0" + h; } rgbBuffer.add(h); } else if (LPAREN == token) { if (NUMBER == lastToken) { queue(" "); } queue("#"); rgbBuffer.clear(); } else if (RPAREN == token) { if (rgbBuffer.size() == 3) { String a = rgbBuffer.get(0); String b = rgbBuffer.get(1); String c = rgbBuffer.get(2); if (a.charAt(0) == a.charAt(1) && b.charAt(0) == b.charAt(1) && c.charAt(0) == c.charAt(1)) { queue(a.substring(0, 1)); queue(b.substring(0, 1)); queue(c.substring(0, 1)); rgb = false; return; } } for (String s : rgbBuffer) { queue(s); } rgb = false; } return; } if (token == WHITESPACE) { space = true; return; // most of these are unneeded } if (token == COMMENT) { // comments are only needed in a few places: // 1) special comments /*! ... */ if ('!' == value.charAt(2)) { queue(value); lastToken = token; lastValue = value; } // 2) IE5/Mac hack else if ('\\' == value.charAt(value.length()-3)) { queue("/*\\*/"); lastToken = token; lastValue = value; ie5mac = true; } else if (ie5mac) { // if the rule buffer starts with the opening ie5/mac comment hack, // and the rest of the buffer + pending would collapse to nothing, // suppress the hack comments if ( ruleBuffer.size() >= 2 && "}".equals( pending ) && !"{".equals( ruleBuffer.get( ruleBuffer.size() - 1 ) ) ) { queue("/**/"); } lastToken = token; lastValue = value; ie5mac = false; } // 3) After a child selector else if (GT == lastToken) { queue("/**/"); lastToken = token; lastValue = value; } return; } // make sure we have space between values for multi-value properties // margin: 5px 5px if ( inRule && ( ( NUMBER == lastToken && (HASH == token || NUMBER == token) ) || ( (IDENTIFIER == lastToken || PERCENT == lastToken || RPAREN == lastToken) && (NUMBER == token || IDENTIFIER == token || HASH == token) ) )) { queue(" "); space = false; } // rgb() if (IDENTIFIER == token && "rgb".equals(value)) { rgb = true; space = false; return; } if (AT == token) { queue(value); at = true; } else if (inRule && COLON == token && property == null) { queue(value); property = lastValue.toLowerCase(); valueBuffer.clear(); } // first-letter and first-line must be followed by a space else if (!inRule && COLON == lastToken && ("first-letter".equals(value) || "first-line".equals(value))) { queue(value); queue(" "); } else if (SEMICOLON == token) { if (at) { at = false; if ("charset".equals(ruleBuffer.get(1))) { if (charset) { ruleBuffer.clear(); pending = null; } else { charset = true; dump(value); } } else { dump(value); } } else if (SEMICOLON == lastToken) { return; // skip duplicate semicolons } else { collapseValue(); valueBuffer.clear(); property = null; queue(value); } } else if (LBRACE == token) { if (checkSpace != -1) { // start of a rule, the space was correct checkSpace = -1; } if (at) { at = false; dump(value); } else { inRule = true; queue(value); } } else if (RBRACE == token) { if (checkSpace != -1) { // didn't start a rule, space was wrong ruleBuffer.remove(checkSpace); checkSpace = -1; } if (!valueBuffer.isEmpty()) { collapseValue(); } if (";".equals(pending)) { if (options.keepTailingSemicolons()) { buffer(";"); } pending = value; } else { buffer(value); } property = null; inRule = false; } else if (!inRule) { if (!space || GT == token || lastToken == null || BOUNDARY_OPS.contains( lastValue )) { queue(value); } else { if (COLON == token) { checkSpace = ruleBuffer.size() + 1; // include pending value } if ( COMMENT != lastToken && !BOUNDARY_OPS.contains( lastValue ) ) { queue(" "); } queue(value); space = false; } } else if (NUMBER == token && value.startsWith("0.")) { if ( options.shouldCollapseZeroes() ) { queue(value.substring(1)); } else { queue( value ); } } else if (STRING == token && "-ms-filter".equals(property)) { if (value.toLowerCase().startsWith(MS_ALPHA, 1)) { String c = value.substring(0, 1); String o = value.substring(MS_ALPHA.length()+1, value.length()-2); queue(c); queue("alpha(opacity="); queue(o); queue(")"); queue(c); } else { queue(value); } } else if (EQUALS == token) { queue(value); StringBuilder sb = new StringBuilder(); for (String s : valueBuffer) { sb.append(s); } if (MS_ALPHA.equals(sb.toString().toLowerCase())) { buffer("alpha(opacity="); valueBuffer.clear(); } } else { String v = value.toLowerCase(); // values of 0 don't need a unit if (NUMBER == lastToken && "0".equals(lastValue) && (PERCENT == token || IDENTIFIER == token)) { if (!UNITS.contains(value)) { queue(" "); queue(value); } } // use 0 instead of none else if (COLON == lastToken && "none".equals(value) && NONE_PROPERTIES.contains(property) && options.shouldCollapseNone()) { queue("0"); } // force properties to lower case for better gzip compression else if (COLON != lastToken && IDENTIFIER == token) { // #aabbcc if (HASH == lastToken) { if (value.length() == 6 && v.charAt(0) == v.charAt(1) && v.charAt(2) == v.charAt(3) && v.charAt(4) == v.charAt(5)) { queue(v.substring(0, 1)); queue(v.substring(2, 3)); queue(v.substring(4, 5)); } else { queue(v); } } else { if ( space && !BOUNDARY_OPS.contains( lastValue ) && BANG != token ) { queue( " " ); } if (property == null || KEYWORDS.contains(v)) { queue(v); } else { queue(value); } } } // nothing special, just send it along else { if ( space && !BOUNDARY_OPS.contains( lastValue ) && BANG != token ) { queue( " " ); } if (KEYWORDS.contains(v)) { queue(v); } else { queue(value); } } } lastToken = token; lastValue = value; space = false; }
diff --git a/spring-ldap/src/main/java/org/springframework/ldap/core/support/AbstractContextSource.java b/spring-ldap/src/main/java/org/springframework/ldap/core/support/AbstractContextSource.java index eec5bfd..74878b8 100644 --- a/spring-ldap/src/main/java/org/springframework/ldap/core/support/AbstractContextSource.java +++ b/spring-ldap/src/main/java/org/springframework/ldap/core/support/AbstractContextSource.java @@ -1,521 +1,521 @@ /* * Copyright 2005-2007 the original author or authors. * * 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.springframework.ldap.core.support; import java.util.Hashtable; import java.util.Map; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.directory.DirContext; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.JdkVersion; import org.springframework.ldap.core.AuthenticationSource; import org.springframework.ldap.core.ContextSource; import org.springframework.ldap.core.DistinguishedName; import org.springframework.ldap.support.LdapUtils; /** * Abstract implementation of the ContextSource interface. By default, returns * an authenticated DirContext implementation for both read-only and read-write * operations. To have an anonymous environment created for read-only * operations, set the anonymousReadOnly property to <code>true</code>. * <p> * Implementing classes need to implement * {@link #getDirContextInstance(Hashtable)} to create a DirContext instance of * the desired type. * <p> * If an AuthenticationSource is set, this will be used for getting user name * and password for each new connection, otherwise a default one will be created * using the specified userDn and password. * <p> * <b>Note:</b> When using implementations of this class outside of a Spring * Context it is necessary to call {@link #afterPropertiesSet()} when all * properties are set, in order to finish up initialization. * * @see org.springframework.ldap.core.LdapTemplate * @see org.springframework.ldap.core.support.DefaultDirObjectFactory * @see org.springframework.ldap.core.support.LdapContextSource * @see org.springframework.ldap.core.support.DirContextSource * * @author Mattias Arthursson * @author Adam Skogman * @author Ulrik Sandberg */ public abstract class AbstractContextSource implements ContextSource, InitializingBean { private static final Class DEFAULT_CONTEXT_FACTORY = com.sun.jndi.ldap.LdapCtxFactory.class; private static final Class DEFAULT_DIR_OBJECT_FACTORY = DefaultDirObjectFactory.class; private Class dirObjectFactory = DEFAULT_DIR_OBJECT_FACTORY; private Class contextFactory = DEFAULT_CONTEXT_FACTORY; private DistinguishedName base = DistinguishedName.EMPTY_PATH; protected String userDn = ""; protected String password = ""; private String[] urls; private boolean pooled = true; private Hashtable baseEnv = new Hashtable(); private Hashtable anonymousEnv; private AuthenticationSource authenticationSource; private boolean cacheEnvironmentProperties = true; private boolean anonymousReadOnly = false; private static final Log log = LogFactory.getLog(LdapContextSource.class); public static final String SUN_LDAP_POOLING_FLAG = "com.sun.jndi.ldap.connect.pool"; private static final String JDK_142 = "1.4.2"; public DirContext getReadOnlyContext() { if (!anonymousReadOnly) { return createContext(getAuthenticatedEnv()); } else { return createContext(getAnonymousEnv()); } } public DirContext getReadWriteContext() { return createContext(getAuthenticatedEnv()); } /** * Default implementation of setting the environment up to be authenticated. * Override in subclass if necessary. This is needed for Active Directory * connectivity, for example. * * @param env * the environment to modify. */ protected void setupAuthenticatedEnvironment(Hashtable env) { env .put(Context.SECURITY_PRINCIPAL, authenticationSource .getPrincipal()); log.debug("Principal: '" + userDn + "'"); env.put(Context.SECURITY_CREDENTIALS, authenticationSource .getCredentials()); } /** * Close the context and swallow any exceptions. * * @param ctx * the DirContext to close. */ private void closeContext(DirContext ctx) { if (ctx != null) { try { ctx.close(); } catch (Exception e) { } } } /** * Assemble a valid url String from all registered urls to add as * PROVIDER_URL to the environment. * * @param ldapUrls * all individual url Strings. * @return the full url String */ protected String assembleProviderUrlString(String[] ldapUrls) { StringBuffer providerUrlBuffer = new StringBuffer(1024); for (int i = 0; i < ldapUrls.length; i++) { providerUrlBuffer.append(ldapUrls[i]); if (!DistinguishedName.EMPTY_PATH.equals(base)) { if (!ldapUrls[i].endsWith("/")) { providerUrlBuffer.append("/"); } } providerUrlBuffer.append(base.toUrl()); providerUrlBuffer.append(' '); } return providerUrlBuffer.toString().trim(); } /** * Set the base suffix from which all operations should origin. If a base * suffix is set, you will not have to (and, indeed, should not) specify the * full distinguished names in the operations performed. * * @param base * the base suffix. */ public void setBase(String base) { this.base = new DistinguishedName(base); } /** * Get the base suffix from which all operations should originate. If a base * suffix is set, you will not have to (and, indeed, should not) specify the * full distinguished names in the operations performed. * * @return the base suffix */ protected DistinguishedName getBase() { return base; } /** * Create a DirContext using the supplied environment. * * @param environment * the Ldap environment to use when creating the DirContext. * @return a new DirContext implpementation initialized with the supplied * environment. */ DirContext createContext(Hashtable environment) { DirContext ctx = null; try { ctx = getDirContextInstance(environment); if (log.isInfoEnabled()) { Hashtable ctxEnv = ctx.getEnvironment(); String ldapUrl = (String) ctxEnv.get(Context.PROVIDER_URL); log.debug("Got Ldap context on server '" + ldapUrl + "'"); } return ctx; } catch (NamingException e) { closeContext(ctx); throw LdapUtils.convertLdapException(e); } } /** * Set the context factory. Default is com.sun.jndi.ldap.LdapCtxFactory. * * @param contextFactory * the context factory used when creating Contexts. */ public void setContextFactory(Class contextFactory) { this.contextFactory = contextFactory; } /** * Get the context factory. * * @return the context factory used when creating Contexts. */ public Class getContextFactory() { return contextFactory; } /** * Set the DirObjectFactory to use. Default is * {@link DefaultDirObjectFactory}. The specified class needs to be an * implementation of javax.naming.spi.DirObjectFactory. <b>Note: </b>Setting * this value to null may have cause connection leaks when using * ContextMapper methods in LdapTemplate. * * @param dirObjectFactory * the DirObjectFactory to be used. Null means that no * DirObjectFactory will be used. */ public void setDirObjectFactory(Class dirObjectFactory) { this.dirObjectFactory = dirObjectFactory; } /** * Get the DirObjectFactory to use. * * @return the DirObjectFactory to be used. <code>null</code> means that * no DirObjectFactory will be used. */ public Class getDirObjectFactory() { return dirObjectFactory; } /** * Checks that all necessary data is set and that there is no compatibility * issues, after which the instance is initialized. Note that you need to * call this method explicitly after setting all desired properties if using * the class outside of a Spring Context. */ public void afterPropertiesSet() throws Exception { if (ArrayUtils.isEmpty(urls)) { throw new IllegalArgumentException( "At least one server url must be set"); } if (!DistinguishedName.EMPTY_PATH.equals(base) && getJdkVersion().compareTo(JDK_142) < 0) { throw new IllegalArgumentException( "Base path is not supported for JDK versions < 1.4.2"); } if (authenticationSource == null) { log.debug("AuthenticationSource not set - " + "using default implementation"); if (StringUtils.isBlank(userDn)) { log - .warn("Property 'userDn' not set - " + .info("Property 'userDn' not set - " + "anonymous context will be used for read-write operations"); } else if (StringUtils.isBlank(password)) { - log.warn("Property 'password' not set - " + log.info("Property 'password' not set - " + "blank password will be used"); } authenticationSource = new SimpleAuthenticationSource(); } if (cacheEnvironmentProperties) { anonymousEnv = setupAnonymousEnv(); } } private Hashtable setupAnonymousEnv() { if (pooled) { baseEnv.put(SUN_LDAP_POOLING_FLAG, "true"); log.debug("Using LDAP pooling."); } else { log.debug("Not using LDAP pooling"); } Hashtable env = new Hashtable(baseEnv); env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory.getName()); env.put(Context.PROVIDER_URL, assembleProviderUrlString(urls)); if (dirObjectFactory != null) { env.put(Context.OBJECT_FACTORIES, dirObjectFactory.getName()); } if (!DistinguishedName.EMPTY_PATH.equals(base)) { // Save the base path for use in the DefaultDirObjectFactory. env.put(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY, base); } log.debug("Trying provider Urls: " + assembleProviderUrlString(urls)); return env; } /** * Set the password (credentials) to use for getting authenticated contexts. * * @param password * the password. */ public void setPassword(String password) { this.password = password; } /** * Set the user distinguished name (principal) to use for getting * authenticated contexts. * * @param userDn * the user distinguished name. */ public void setUserDn(String userDn) { this.userDn = userDn; } /** * Set the user distinguished name (principal) to use for getting * authenticated contexts. * * @param userName * the user distinguished name. * @deprecated Use {@link #setUserDn(String)} instead. */ public void setUserName(String userName) { setUserDn(userName); } /** * Set the urls of the LDAP servers. Use this method if several servers are * required. * * @param urls * the urls of all servers. */ public void setUrls(String[] urls) { this.urls = urls; } /** * Get the urls of the LDAP servers. * * @return the urls of all servers. */ public String[] getUrls() { return urls; } /** * Set the url of the LDAP server. Utility method if only one server is * used. * * @param url * the url of the LDAP server. */ public void setUrl(String url) { this.urls = new String[] { url }; } /** * Set whether the pooling flag should be set. Default is true. * * @param pooled * whether Contexts should be pooled. */ public void setPooled(boolean pooled) { this.pooled = pooled; } /** * Get whether the pooling flag should be set. * * @return whether Contexts should be pooled. */ public boolean isPooled() { return pooled; } /** * If any custom environment properties are needed, these can be set using * this method. * * @param baseEnvironmentProperties */ public void setBaseEnvironmentProperties(Map baseEnvironmentProperties) { this.baseEnv = new Hashtable(baseEnvironmentProperties); } String getJdkVersion() { return JdkVersion.getJavaVersion(); } protected Hashtable getAnonymousEnv() { if (cacheEnvironmentProperties) { return anonymousEnv; } else { return setupAnonymousEnv(); } } protected Hashtable getAuthenticatedEnv() { // The authenticated environment should always be rebuilt. Hashtable env = new Hashtable(getAnonymousEnv()); setupAuthenticatedEnvironment(env); return env; } /** * Set the authentication source to use when retrieving user principal and * credentials. * * @param authenticationSource * the AuthenticationSource that will provide user info. */ public void setAuthenticationSource( AuthenticationSource authenticationSource) { this.authenticationSource = authenticationSource; } /** * Get the authentication source. * * @return the AuthenticationSource that will provide user info. */ public AuthenticationSource getAuthenticationSource() { return authenticationSource; } /** * Set whether environment properties should be cached between requsts for * anonymous environment. Default is true; setting this property to false * causes the environment Hashmap to be rebuilt from the current property * settings of this instance between each request for an anonymous * environment. * * @param cacheEnvironmentProperties * true causes that the anonymous environment properties should * be cached, false causes the Hashmap to be rebuilt for each * request. */ public void setCacheEnvironmentProperties(boolean cacheEnvironmentProperties) { this.cacheEnvironmentProperties = cacheEnvironmentProperties; } /** * Set whether an anonymous environment should be used for read-only * operations. Default is <code>false</code>. * * @param anonymousReadOnly * <code>true</code> if an anonymous environment should be used * for read-only operations, <code>false</code> otherwise. */ public void setAnonymousReadOnly(boolean anonymousReadOnly) { this.anonymousReadOnly = anonymousReadOnly; } /** * Get whether an anonymous environment should be used for read-only * operations. * * @return <code>true</code> if an anonymous environment should be used * for read-only operations, <code>false</code> otherwise. */ public boolean isAnonymousReadOnly() { return anonymousReadOnly; } /** * Implement in subclass to create a DirContext of the desired type (e.g. * InitialDirContext or InitialLdapContext). * * @param environment * the environment to use when creating the instance. * @return a new DirContext instance. * @throws NamingException * if one is encountered when creating the instance. */ protected abstract DirContext getDirContextInstance(Hashtable environment) throws NamingException; class SimpleAuthenticationSource implements AuthenticationSource { public String getPrincipal() { return userDn; } public String getCredentials() { return password; } } }
false
true
public void afterPropertiesSet() throws Exception { if (ArrayUtils.isEmpty(urls)) { throw new IllegalArgumentException( "At least one server url must be set"); } if (!DistinguishedName.EMPTY_PATH.equals(base) && getJdkVersion().compareTo(JDK_142) < 0) { throw new IllegalArgumentException( "Base path is not supported for JDK versions < 1.4.2"); } if (authenticationSource == null) { log.debug("AuthenticationSource not set - " + "using default implementation"); if (StringUtils.isBlank(userDn)) { log .warn("Property 'userDn' not set - " + "anonymous context will be used for read-write operations"); } else if (StringUtils.isBlank(password)) { log.warn("Property 'password' not set - " + "blank password will be used"); } authenticationSource = new SimpleAuthenticationSource(); } if (cacheEnvironmentProperties) { anonymousEnv = setupAnonymousEnv(); } }
public void afterPropertiesSet() throws Exception { if (ArrayUtils.isEmpty(urls)) { throw new IllegalArgumentException( "At least one server url must be set"); } if (!DistinguishedName.EMPTY_PATH.equals(base) && getJdkVersion().compareTo(JDK_142) < 0) { throw new IllegalArgumentException( "Base path is not supported for JDK versions < 1.4.2"); } if (authenticationSource == null) { log.debug("AuthenticationSource not set - " + "using default implementation"); if (StringUtils.isBlank(userDn)) { log .info("Property 'userDn' not set - " + "anonymous context will be used for read-write operations"); } else if (StringUtils.isBlank(password)) { log.info("Property 'password' not set - " + "blank password will be used"); } authenticationSource = new SimpleAuthenticationSource(); } if (cacheEnvironmentProperties) { anonymousEnv = setupAnonymousEnv(); } }