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/src/java/nz/co/searchwellington/repositories/HibernateResourceDAO.java b/src/java/nz/co/searchwellington/repositories/HibernateResourceDAO.java index eb344d23..32fbb057 100644 --- a/src/java/nz/co/searchwellington/repositories/HibernateResourceDAO.java +++ b/src/java/nz/co/searchwellington/repositories/HibernateResourceDAO.java @@ -1,527 +1,527 @@ package nz.co.searchwellington.repositories; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import nz.co.searchwellington.model.CalendarFeed; import nz.co.searchwellington.model.CommentFeed; import nz.co.searchwellington.model.DiscoveredFeed; import nz.co.searchwellington.model.Feed; import nz.co.searchwellington.model.Newsitem; import nz.co.searchwellington.model.Resource; import nz.co.searchwellington.model.ResourceImpl; import nz.co.searchwellington.model.Tag; import nz.co.searchwellington.model.Twit; import nz.co.searchwellington.model.User; import nz.co.searchwellington.model.Watchlist; import nz.co.searchwellington.model.Website; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Expression; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.joda.time.DateTime; public abstract class HibernateResourceDAO extends AbsractResourceDAO implements ResourceRepository { SessionFactory sessionFactory; private TagDAO tagDAO; private TweetDAO tweetDAO; public HibernateResourceDAO() { } public HibernateResourceDAO(SessionFactory sessionFactory, TagDAO tagDAO, TweetDAO twitterDAO) { this.sessionFactory = sessionFactory; this.tagDAO = tagDAO; this.tweetDAO = twitterDAO; } @SuppressWarnings("unchecked") public List<Integer> getAllResourceIds() { Set<Integer> resourceIds = new HashSet<Integer>(); Session session = sessionFactory.getCurrentSession(); return session.createQuery("select id from nz.co.searchwellington.model.ResourceImpl order by id DESC").setFetchSize(100).list(); } @Override public Tag createNewTag() { return tagDAO.createNewTag(); } public List<String> getPublisherNamesByStartingLetters(String q) { Session session = sessionFactory.getCurrentSession(); List<String> rows = session.createQuery("select name from nz.co.searchwellington.model.ResourceImpl where type='W' and name like ? order by name").setString(0, q + '%').setMaxResults(50).list(); return rows; } @SuppressWarnings("unchecked") final public List<Feed> getAllFeeds() { return sessionFactory.getCurrentSession().createCriteria(Feed.class). addOrder(Order.desc("latestItemDate")). addOrder(Order.asc("name")). setCacheable(true). list(); } @SuppressWarnings("unchecked") final public List<Feed> getAllFeedsByName() { return sessionFactory.getCurrentSession().createCriteria(Feed.class). addOrder(Order.asc("name")). setCacheable(true). list(); } @SuppressWarnings("unchecked") final public List<Feed> getFeedsToRead() { return sessionFactory.getCurrentSession().createCriteria(Feed.class). add(Restrictions.ne("acceptancePolicy", "ignore")). addOrder(Order.asc("lastRead")). setCacheable(false). list(); } @SuppressWarnings("unchecked") final public List<Resource> getAllCalendarFeeds() { return sessionFactory.getCurrentSession().createCriteria(CalendarFeed.class). addOrder(Order.asc("name")). setCacheable(true). list(); } @SuppressWarnings("unchecked") final public List<Resource> getAllWebsites() { return sessionFactory.getCurrentSession().createCriteria(Website.class). addOrder(Order.asc("name")). setCacheable(true). list(); } @SuppressWarnings("unchecked") // TODO add discovered timestamp and order by that. final public List<DiscoveredFeed> getAllDiscoveredFeeds() { return sessionFactory.getCurrentSession().createCriteria(DiscoveredFeed.class). setCacheable(true). addOrder(Order.desc("id")). list(); } @SuppressWarnings("unchecked") final public List<Feed> getPublisherFeeds(Website publisher) { return sessionFactory.getCurrentSession().createCriteria(Feed.class). add(Restrictions.eq("publisher", publisher)). addOrder(Order.asc("name")). list(); } @SuppressWarnings("unchecked") final public List<Watchlist> getPublisherWatchlist(Website publisher) { return sessionFactory.getCurrentSession().createCriteria(Watchlist.class). add(Restrictions.eq("publisher", publisher)). addOrder(Order.asc("name")). list(); } @SuppressWarnings("unchecked") @Override public List<Newsitem> getNewsitemsForFeed(Feed feed) { return sessionFactory.getCurrentSession().createCriteria(Newsitem.class). add(Restrictions.eq("feed", feed)). addOrder(Order.desc("date")). list(); } @SuppressWarnings("unchecked") final public List<Resource> getOwnedBy(User owner, int maxItems) { return sessionFactory.getCurrentSession().createCriteria(Resource.class). add(Restrictions.eq("owner", owner)). addOrder(Order.desc("date")). addOrder(Order.desc("id")). setMaxResults(maxItems). list(); } @SuppressWarnings("unchecked") public List<Newsitem> getRecentUntaggedNewsitems() { return sessionFactory.getCurrentSession().createCriteria(Newsitem.class). add(Restrictions.isEmpty("tags")). add(Expression.eq("httpStatus", 200)). addOrder(Order.desc("date")). setMaxResults(12). setCacheable(true).list(); } @SuppressWarnings("unchecked") public List<Resource> getAllPublishersMatchingStem(String stem, boolean showBroken) { List<Resource> allPublishers = new ArrayList<Resource>(); if (showBroken) { allPublishers = sessionFactory.getCurrentSession().createCriteria(Website.class).add(Restrictions.sqlRestriction(" page like \"%" + stem + "%\" ")).addOrder(Order.asc("name")).list(); } else { allPublishers = sessionFactory.getCurrentSession().createCriteria(Website.class).add(Restrictions.sqlRestriction(" page like \"%" + stem + "%\" ")).add(Expression.eq("httpStatus", 200)).addOrder(Order.asc("name")).list(); } return allPublishers; } @SuppressWarnings("unchecked") public List<Resource> getNewsitemsMatchingStem(String stem) { return sessionFactory.getCurrentSession().createCriteria(Newsitem.class).add(Restrictions.sqlRestriction(" page like \"%" + stem + "%\" ")).addOrder(Order.asc("name")).list(); } @SuppressWarnings("unchecked") public List<Resource> getNotCheckedSince(Date oneMonthAgo, int maxItems) { return sessionFactory.getCurrentSession().createCriteria(Resource.class). add(Restrictions.lt("lastScanned", oneMonthAgo)).addOrder(Order.asc("lastScanned")). setMaxResults(maxItems).list(); } @Override public List<Resource> getNotCheckedSince(Date launchedDate, Date lastScanned, int maxItems) { return sessionFactory.getCurrentSession().createCriteria(Resource.class). add(Restrictions.gt("liveTime", launchedDate)). add(Restrictions.lt("lastScanned", lastScanned)). addOrder(Order.asc("lastScanned")). setMaxResults(maxItems).list(); } @SuppressWarnings("unchecked") public List<CommentFeed> getCommentFeedsToCheck(int maxItems) { return sessionFactory.getCurrentSession().createCriteria(CommentFeed.class). addOrder(Order.desc("lastRead")). setCacheable(false). setMaxResults(maxItems). list(); } @SuppressWarnings("unchecked") public List<Resource> getAllResources() { return sessionFactory.getCurrentSession().createCriteria(Resource.class).list(); } public List<Tag> getAllTags() { return tagDAO.getAllTags(); } public List<Tag> loadTagsById(List<Integer> tagIds) { return tagDAO.loadTagsById(tagIds); } public void saveTag(Tag editTag) { tagDAO.saveTag(editTag); } @SuppressWarnings("unchecked") public List<Tag> getTopLevelTags() { return tagDAO.getTopLevelTags(); } @SuppressWarnings("unchecked") public List<Resource> getTwitterMentionedNewsitems(int maxItems) { return sessionFactory.getCurrentSession().createCriteria(Newsitem.class). setMaxResults(maxItems). add(Restrictions.isNotEmpty("reTwits")). addOrder(Order.desc("date")). setCacheable(true). list(); } @SuppressWarnings("unchecked") public List<Resource> getRecentlyChangedWatchlistItems() { return sessionFactory.getCurrentSession().createCriteria(Watchlist.class) .add(Restrictions.sqlRestriction(" last_changed > DATE_SUB(now(), INTERVAL 7 DAY) ")) .addOrder(Order.desc("lastChanged")) .setCacheable(true). list(); } public int getCommentCount() { // TODO implement show broken logic if the parent newsitem is broken return ((Long) sessionFactory.getCurrentSession(). iterate("select count(*) from Comment"). next()).intValue(); } public boolean isResourceWithUrl(String url) { Resource existingResource = loadResourceByUrl(url); return existingResource != null; } public Resource loadResourceById(int resourceID) { return (Resource) sessionFactory.getCurrentSession().get(ResourceImpl.class, resourceID); } public Resource loadResourceByUrl(String url) { return (Resource) sessionFactory.getCurrentSession().createCriteria(Resource.class).add(Expression.eq("url", url)).setMaxResults(1).uniqueResult(); } public Website getPublisherByUrlWords(String urlWords) { return (Website) sessionFactory.getCurrentSession().createCriteria(Website.class).add(Expression.eq("urlWords", urlWords)).setMaxResults(1).uniqueResult(); } public Website getPublisherByName(String name) { return (Website) sessionFactory.getCurrentSession().createCriteria(Website.class).add(Expression.eq("name", name)).setMaxResults(1).uniqueResult(); } public Feed loadFeedByUrlWords(String urlWords) { return (Feed) sessionFactory.getCurrentSession().createCriteria(Feed.class).add(Expression.eq("urlWords", urlWords)).setMaxResults(1).uniqueResult(); } final public Resource loadResourceByUniqueUrl(String url) { return (Resource) sessionFactory.getCurrentSession().createCriteria(Resource.class).add(Expression.eq("url", url)).uniqueResult(); } public CommentFeed loadCommentFeedByUrl(String url) { return (CommentFeed) sessionFactory.getCurrentSession().createCriteria(CommentFeed.class).add(Expression.eq("url", url)).setMaxResults(1).uniqueResult(); } public DiscoveredFeed loadDiscoveredFeedByUrl(String url) { return (DiscoveredFeed) sessionFactory.getCurrentSession().createCriteria(DiscoveredFeed.class). add(Expression.eq("url", url)). setMaxResults(1). setCacheable(true). uniqueResult(); } public Tag loadTagById(int tagID) { return tagDAO.loadTagById(tagID); } public Tag loadTagByName(String tagName) { return tagDAO.loadTagByName(tagName); } public List<Twit> getAllTweets() { return tweetDAO.getAllTweets(); } public void saveTweet(Twit twit) { tweetDAO.saveTwit(twit); } public Twit loadTweetByTwitterId(Long twitterId) { return tweetDAO.loadTweetByTwitterId(twitterId); } public void saveResource(Resource resource) { if (resource.getType().equals("N")) { if (((Newsitem) resource).getImage() != null) { sessionFactory.getCurrentSession().saveOrUpdate(((Newsitem) resource).getImage()); } } sessionFactory.getCurrentSession().saveOrUpdate(resource); sessionFactory.getCurrentSession().flush(); - //if (resource.getType().equals("F")) { + if (resource.getType().equals("F")) { // TODO can this be done for just the publisher only? - // sessionFactory.evictCollection("nz.co.searchwellington.model.WebsiteImpl.feeds"); - // } + sessionFactory.evictCollection("nz.co.searchwellington.model.WebsiteImpl.feeds"); + } // TODO for related tags, can we be abit more subtle than this? // Clear related tags query. // sessionFactory.evictQueries(); } public void saveDiscoveredFeed(DiscoveredFeed discoveredFeed) { sessionFactory.getCurrentSession().saveOrUpdate(discoveredFeed); sessionFactory.getCurrentSession().flush(); } public void saveCommentFeed(CommentFeed commentFeed) { sessionFactory.getCurrentSession().saveOrUpdate(commentFeed); sessionFactory.getCurrentSession().flush(); } @SuppressWarnings("unchecked") public List<Newsitem> getLatestTwitteredNewsitems(int number, boolean showBroken) { return criteriaForLatestNewsitems(number, showBroken). add(Expression.isNotNull("submittingTwit")). setCacheable(true).list(); } private Criteria criteriaForLatestNewsitems(int number, boolean showBroken) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Newsitem.class). addOrder(Order.desc("date")). addOrder(Order.desc("id")). setMaxResults(number); if (!showBroken) { criteria.add(Expression.eq("httpStatus", 200)); } return criteria; } @SuppressWarnings("unchecked") public List<Resource> getLatestWebsites(int maxNumberOfItems, boolean showBroken) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Website.class).addOrder( Order.desc("date")); if (!showBroken) { criteria.add(Expression.eq("httpStatus", 200)); } return criteria.setCacheable(true). setMaxResults(maxNumberOfItems). list(); } @SuppressWarnings("unchecked") public List<Resource> getTaggedResources(Tag tag, int max_newsitems) { return sessionFactory.getCurrentSession().createCriteria(Resource.class).createCriteria("tags").add(Restrictions.eq("id", tag.getId())).list(); } public void deleteResource(Resource resource) { sessionFactory.getCurrentSession().delete(resource); // flush collection caches. sessionFactory.evictCollection("nz.co.searchwellington.model.WebsiteImpl.newsitems"); sessionFactory.evictCollection("nz.co.searchwellington.model.WebsiteImpl.feeds"); sessionFactory.evictCollection("nz.co.searchwellington.model.WebsiteImpl.watchlist"); sessionFactory.evictCollection("nz.co.searchwellington.model.DiscoveredFeed.references"); sessionFactory.getCurrentSession().flush(); } public void deleteTag(Tag tag) { sessionFactory.getCurrentSession().delete(tag); sessionFactory.getCurrentSession().flush(); } public List<Tag> getTagsMatchingKeywords(String keywords) { throw(new UnsupportedOperationException()); } @SuppressWarnings("unchecked") public Date getNewslogLastChanged() { Criteria latestNewsitemsCriteria = criteriaForLatestNewsitems(20, false); latestNewsitemsCriteria.addOrder( Order.desc("liveTime")); List<Resource> currentNewsitems = latestNewsitemsCriteria.setCacheable(true).list(); for (Resource resource : currentNewsitems) { DateTime latestChange = null; if (latestChange == null) { latestChange = new DateTime(resource.getLastChanged()); log.debug("Setting last changed to: " + latestChange); } if (resource.getLastChanged() != null && new DateTime(resource.getLastChanged()).isAfter(latestChange)) { latestChange = new DateTime(resource.getLastChanged()); return latestChange.toDate(); } } return null; } @SuppressWarnings("unchecked") public List<Resource> getResourcesWithTag(Tag tag) { log.info(tag.getName()); Criteria taggedResources = sessionFactory.getCurrentSession().createCriteria(Resource.class). addOrder(Order.desc("date")). addOrder(Order.desc("id")). createAlias("tags", "rt"). add(Restrictions.eq("rt.id", tag.getId())); return taggedResources.list(); } @Override public Newsitem loadNewsitemBySubmittingTwitterId(long twitterId) { Criteria criteria = sessionFactory.getCurrentSession(). createCriteria(Newsitem.class). createAlias("submittingTwit", "st"). add(Restrictions.eq("st.twitterid", twitterId)); return (Newsitem) criteria.uniqueResult(); } }
false
true
public void saveResource(Resource resource) { if (resource.getType().equals("N")) { if (((Newsitem) resource).getImage() != null) { sessionFactory.getCurrentSession().saveOrUpdate(((Newsitem) resource).getImage()); } } sessionFactory.getCurrentSession().saveOrUpdate(resource); sessionFactory.getCurrentSession().flush(); //if (resource.getType().equals("F")) { // TODO can this be done for just the publisher only? // sessionFactory.evictCollection("nz.co.searchwellington.model.WebsiteImpl.feeds"); // } // TODO for related tags, can we be abit more subtle than this? // Clear related tags query. // sessionFactory.evictQueries(); }
public void saveResource(Resource resource) { if (resource.getType().equals("N")) { if (((Newsitem) resource).getImage() != null) { sessionFactory.getCurrentSession().saveOrUpdate(((Newsitem) resource).getImage()); } } sessionFactory.getCurrentSession().saveOrUpdate(resource); sessionFactory.getCurrentSession().flush(); if (resource.getType().equals("F")) { // TODO can this be done for just the publisher only? sessionFactory.evictCollection("nz.co.searchwellington.model.WebsiteImpl.feeds"); } // TODO for related tags, can we be abit more subtle than this? // Clear related tags query. // sessionFactory.evictQueries(); }
diff --git a/Java_CCN/com/parc/ccn/library/io/CCNInputStream.java b/Java_CCN/com/parc/ccn/library/io/CCNInputStream.java index 5c513488b..783755328 100644 --- a/Java_CCN/com/parc/ccn/library/io/CCNInputStream.java +++ b/Java_CCN/com/parc/ccn/library/io/CCNInputStream.java @@ -1,230 +1,235 @@ package com.parc.ccn.library.io; import java.io.IOException; import javax.xml.stream.XMLStreamException; import com.parc.ccn.Library; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.ContentObject; import com.parc.ccn.data.security.PublisherPublicKeyDigest; import com.parc.ccn.library.CCNLibrary; import com.parc.ccn.security.crypto.ContentKeys; /** * Perform sequential reads on any block-oriented CCN content, namely that * where the name component after the specified name prefix is an optionally * segment-encoded integer, and the content blocks are indicated by * monotonically increasing (but not necessarily sequential) * optionally segment-encoded integers. For example, a file could be * divided into sequential blocks, while an audio stream might have * blocks named by time offsets into the stream. * * This input stream will read from a sequence of blocks, authenticating * each as it goes, and caching what information it can. All it assumes * is that the last component of the name is an increasing integer * value, where we start with the name we are given, and get right siblings * (next blocks) moving forward. * * This input stream works with data with and without a header block; it * opportunistically queries for a header block and uses its information if * one is available. That means an extra interest for content that does not have * a header block. * * Read size is independent of fragment size; the stream will pull additional * content fragments dynamically when possible to fill out the requested number * of bytes. * * TODO remove header handling from here, add use of lastSegment marker in * blocks leading up to the end. Headers, in whatever form they evolve * into, will be used only by higher-level streams. * @author smetters * */ public class CCNInputStream extends CCNAbstractInputStream { protected boolean _atEOF = false; protected int _readlimit = 0; protected int _markOffset = 0; protected long _markBlock = 0; public CCNInputStream(ContentName name, Long startingBlockIndex, PublisherPublicKeyDigest publisher, ContentKeys keys, CCNLibrary library) throws XMLStreamException, IOException { super(name, startingBlockIndex, publisher, keys, library); } public CCNInputStream(ContentName name, Long startingBlockIndex, PublisherPublicKeyDigest publisher, CCNLibrary library) throws XMLStreamException, IOException { super(name, startingBlockIndex, publisher, library); } public CCNInputStream(ContentName name, PublisherPublicKeyDigest publisher, CCNLibrary library) throws XMLStreamException, IOException { this(name, null, publisher, library); } public CCNInputStream(ContentName name) throws XMLStreamException, IOException { this(name, null); } public CCNInputStream(ContentName name, CCNLibrary library) throws XMLStreamException, IOException { this(name, null, null, library); } public CCNInputStream(ContentName name, long blockNumber) throws XMLStreamException, IOException { this(name, blockNumber, null, null); } public CCNInputStream(ContentObject starterBlock, CCNLibrary library) throws XMLStreamException, IOException { super(starterBlock, library); } @Override public int available() throws IOException { if (null == _blockReadStream) return 0; return _blockReadStream.available(); //int available = 0; //if (null != _header) { // available = (int)(_header.length() - blockIndex()*_header.blockSize() - _blockOffset); // //available = (int)(_header.length() - (blockIndex()-_header.start())*_header.blockSize() - _blockOffset); //} else if (null != _currentBlock) { // available = _currentBlock.contentLength() - _blockOffset; //} //Library.logger().info("available(): " + available); //return available; /* unknown */ } public boolean eof() { //Library.logger().info("Checking eof: there yet? " + _atEOF); return _atEOF; } @Override public void close() throws IOException { // don't have to do anything. } @Override public synchronized void mark(int readlimit) { _readlimit = readlimit; _markBlock = blockIndex(); if (null == _currentBlockStream) { _markOffset = 0; } else { _markOffset = _currentBlock.contentLength() - _currentBlockStream.available(); } Library.logger().finer("mark: block: " + blockIndex() + " offset: " + _markOffset); } @Override public boolean markSupported() { return true; } protected int readInternal(byte [] buf, int offset, int len) throws IOException { if (_atEOF) { return -1; } Library.logger().info(baseName() + ": reading " + len + " bytes into buffer of length " + ((null != buf) ? buf.length : "null") + " at offset " + offset); // is this the first block? if (null == _currentBlock) { ContentObject firstBlock = getFirstBlock(); if (null == firstBlock) { _atEOF = true; return -1; // nothing to read } setCurrentBlock(firstBlock); } Library.logger().finer("reading from block: " + _currentBlock.name() + " length: " + _currentBlock.contentLength()); // Now we have a block in place. Read from it. If we run out of block before // we've read len bytes, pull next block. int lenToRead = len; int lenRead = 0; long readCount = 0; while (lenToRead > 0) { if (null == _blockReadStream) { Library.logger().severe("Unexpected null block read stream!"); } if (null != buf) { // use for skip Library.logger().finest("before block read: content length "+_currentBlock.contentLength()+" position "+ tell() +" available: " + _blockReadStream.available() + " dst length "+buf.length+" dst index "+offset+" len to read "+lenToRead); // Read as many bytes as we can readCount = _blockReadStream.read(buf, offset, lenToRead); } else { readCount = _blockReadStream.skip(lenToRead); + // Work around a bug in CipherInputStream - skip will only skip data within a + // single block processed by the encapsulated Cipher. This results in skip doing + // nothing when it's reached the end of a Cipher block, and it returns 0. + if (readCount == 0) + readCount = _blockReadStream.read()==-1?-1:1; } if (readCount <= 0) { Library.logger().info("Tried to read at end of block, go get next block."); setCurrentBlock(getNextBlock()); if (null == _currentBlock) { Library.logger().info("next block was null, setting _atEOF, returning " + ((lenRead > 0) ? lenRead : -1)); _atEOF = true; if (lenRead > 0) { return lenRead; } return -1; // no bytes read, at eof } Library.logger().info("now reading from block: " + _currentBlock.name() + " length: " + _currentBlock.contentLength()); } else { offset += readCount; lenToRead -= readCount; lenRead += readCount; Library.logger().finest(" read " + readCount + " bytes for " + lenRead + " total, " + lenToRead + " remaining."); } } return lenRead; } @Override public synchronized void reset() throws IOException { setCurrentBlock(getBlock(_markBlock)); // TODO -- test -- may have trouble with intervening cipher stream _blockReadStream.skip(_markOffset); _atEOF = false; Library.logger().finer("reset: block: " + blockIndex() + " offset: " + _markOffset + " eof? " + _atEOF); } @Override public long skip(long n) throws IOException { Library.logger().info("in skip("+n+")"); if (n < 0) { return 0; } return readInternal(null,0, (int)n); } protected int blockCount() { return 0; } public long seek(long position) throws IOException { Library.logger().info("Seeking stream to " + position); setCurrentBlock(getFirstBlock()); return skip(position); } public long tell() { return _currentBlock.contentLength() - _currentBlockStream.available(); // could implement a running count... } public long length() { return 0; } public ContentName baseName() { return _baseName; } }
true
true
protected int readInternal(byte [] buf, int offset, int len) throws IOException { if (_atEOF) { return -1; } Library.logger().info(baseName() + ": reading " + len + " bytes into buffer of length " + ((null != buf) ? buf.length : "null") + " at offset " + offset); // is this the first block? if (null == _currentBlock) { ContentObject firstBlock = getFirstBlock(); if (null == firstBlock) { _atEOF = true; return -1; // nothing to read } setCurrentBlock(firstBlock); } Library.logger().finer("reading from block: " + _currentBlock.name() + " length: " + _currentBlock.contentLength()); // Now we have a block in place. Read from it. If we run out of block before // we've read len bytes, pull next block. int lenToRead = len; int lenRead = 0; long readCount = 0; while (lenToRead > 0) { if (null == _blockReadStream) { Library.logger().severe("Unexpected null block read stream!"); } if (null != buf) { // use for skip Library.logger().finest("before block read: content length "+_currentBlock.contentLength()+" position "+ tell() +" available: " + _blockReadStream.available() + " dst length "+buf.length+" dst index "+offset+" len to read "+lenToRead); // Read as many bytes as we can readCount = _blockReadStream.read(buf, offset, lenToRead); } else { readCount = _blockReadStream.skip(lenToRead); } if (readCount <= 0) { Library.logger().info("Tried to read at end of block, go get next block."); setCurrentBlock(getNextBlock()); if (null == _currentBlock) { Library.logger().info("next block was null, setting _atEOF, returning " + ((lenRead > 0) ? lenRead : -1)); _atEOF = true; if (lenRead > 0) { return lenRead; } return -1; // no bytes read, at eof } Library.logger().info("now reading from block: " + _currentBlock.name() + " length: " + _currentBlock.contentLength()); } else { offset += readCount; lenToRead -= readCount; lenRead += readCount; Library.logger().finest(" read " + readCount + " bytes for " + lenRead + " total, " + lenToRead + " remaining."); } } return lenRead; }
protected int readInternal(byte [] buf, int offset, int len) throws IOException { if (_atEOF) { return -1; } Library.logger().info(baseName() + ": reading " + len + " bytes into buffer of length " + ((null != buf) ? buf.length : "null") + " at offset " + offset); // is this the first block? if (null == _currentBlock) { ContentObject firstBlock = getFirstBlock(); if (null == firstBlock) { _atEOF = true; return -1; // nothing to read } setCurrentBlock(firstBlock); } Library.logger().finer("reading from block: " + _currentBlock.name() + " length: " + _currentBlock.contentLength()); // Now we have a block in place. Read from it. If we run out of block before // we've read len bytes, pull next block. int lenToRead = len; int lenRead = 0; long readCount = 0; while (lenToRead > 0) { if (null == _blockReadStream) { Library.logger().severe("Unexpected null block read stream!"); } if (null != buf) { // use for skip Library.logger().finest("before block read: content length "+_currentBlock.contentLength()+" position "+ tell() +" available: " + _blockReadStream.available() + " dst length "+buf.length+" dst index "+offset+" len to read "+lenToRead); // Read as many bytes as we can readCount = _blockReadStream.read(buf, offset, lenToRead); } else { readCount = _blockReadStream.skip(lenToRead); // Work around a bug in CipherInputStream - skip will only skip data within a // single block processed by the encapsulated Cipher. This results in skip doing // nothing when it's reached the end of a Cipher block, and it returns 0. if (readCount == 0) readCount = _blockReadStream.read()==-1?-1:1; } if (readCount <= 0) { Library.logger().info("Tried to read at end of block, go get next block."); setCurrentBlock(getNextBlock()); if (null == _currentBlock) { Library.logger().info("next block was null, setting _atEOF, returning " + ((lenRead > 0) ? lenRead : -1)); _atEOF = true; if (lenRead > 0) { return lenRead; } return -1; // no bytes read, at eof } Library.logger().info("now reading from block: " + _currentBlock.name() + " length: " + _currentBlock.contentLength()); } else { offset += readCount; lenToRead -= readCount; lenRead += readCount; Library.logger().finest(" read " + readCount + " bytes for " + lenRead + " total, " + lenToRead + " remaining."); } } return lenRead; }
diff --git a/src/com/mistphizzle/donationpoints/plugin/Commands.java b/src/com/mistphizzle/donationpoints/plugin/Commands.java index fed1f0a..8781c44 100644 --- a/src/com/mistphizzle/donationpoints/plugin/Commands.java +++ b/src/com/mistphizzle/donationpoints/plugin/Commands.java @@ -1,265 +1,268 @@ package com.mistphizzle.donationpoints.plugin; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.Command; import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; public class Commands { DonationPoints plugin; public Commands(DonationPoints instance) { this.plugin = instance; init(); } private void init() { PluginCommand donationpoints = plugin.getCommand("donationpoints"); CommandExecutor exe; exe = new CommandExecutor() { @Override public boolean onCommand(CommandSender s, Command c, String label, String[] args) { if (args.length < 1) { // Base Command s.sendMessage("-----�4DonationPoints Commands�f-----"); s.sendMessage("�3/dp basic�f - Show basic DonationPoints commands."); s.sendMessage("�3/dp packages�f - Show the DonationPoints packages commands."); s.sendMessage("�3/dp admin�f - Show the DonationPoints Admin Commands."); return true; // Packages Commands } else if (args[0].equalsIgnoreCase("packages")) { s.sendMessage("-----�4DonationPoints Package Commands�f-----"); if (s.hasPermission("donationpoints.package.info")) { s.sendMessage("�3/dp package info <packageName>�f - Shows package information."); } else { s.sendMessage("�cYou don't have permission to use any of the packages commands."); } // Admin Commands } else if (args[0].equalsIgnoreCase("admin")) { s.sendMessage("-----�4DonationPoints Admin Commands�f-----"); if (s.hasPermission("donationpoints.give")) { s.sendMessage("�3/dp give <player> <amount>�f - Give points to a player."); } if (s.hasPermission("donationpoints.take")) { s.sendMessage("�3/dp take <player> <amount>�f - Take points from a player."); } if (s.hasPermission("donationpoints.set")) { s.sendMessage("�3/dp set <player> <amount>�f - Set a player's balance."); } if (s.hasPermission("donationpoints.version")) { s.sendMessage("�3/dp version�f - Shows the version of the plugin you're running."); } if (s.hasPermission("donationpoints.update")) { s.sendMessage("�3/dp update�f - Checks if there is an update available."); } if (s.hasPermission("donationpoints.reload")) { s.sendMessage("�3/dp reload�f - Reloads the Configuration / Packages."); } else { s.sendMessage("�cYou don't have any permission for ANY DonationPoints Admin Commands."); } } else if (args[0].equalsIgnoreCase("basic")) { s.sendMessage("-----�4DonationPoints Basic Commands�f-----"); if (s.hasPermission("donationpoints.create")) { s.sendMessage("�3/dp create�f - Creates a points account for you."); } if (s.hasPermission("donationpoints.balance")) { s.sendMessage("�3/dp balance�f - Checks your points balance."); } if (s.hasPermission("donationpoints.transfer")) { s.sendMessage("�3/dp transfer <player> <amount>�f - Transfer Points."); } else { s.sendMessage("�cYou don't have permission for any DonationPoints Basic Commands."); } } else if (args[0].equalsIgnoreCase("transfer")) { if (!plugin.getConfig().getBoolean("General.Transferrable")) { s.sendMessage("�cThis server does not allow DonationPoints to be transferred."); return true; } if (!s.hasPermission("donationpoints.transfer")) { s.sendMessage("�cYou don't have permission to do that!"); return true; } if (!(s instanceof Player)) { s.sendMessage("�cThis command can only be performed by players."); return true; } if (args.length < 3) { s.sendMessage("�cNot enough arguments."); return true; } else { // Double transferamount = Double.parseDouble(args[2]); // 0 1 2 // /dp transfer player amount // final Player target = Bukkit.getPlayer(args[1].toLowerCase()); String sender = s.getName(); String target = args[1]; Double transferamount = Double.parseDouble(args[2]); if (!Methods.hasAccount(sender)) { s.sendMessage("�cYou don't have a DonationPoints account."); + return true; } if (!Methods.hasAccount(target)) { s.sendMessage("�cThat player does not have a DonationPoints account."); + return true; } if (target.equalsIgnoreCase(sender)) { s.sendMessage("�cYou can't transfer points to yourself."); + return true; } else { if (transferamount > Methods.getBalance(sender)) { s.sendMessage("�cYou don't have enough points to transfer."); return true; } if (transferamount == 0) { s.sendMessage("�cYou can't transfer 0 points."); return true; } } Methods.addPoints(transferamount, target); Methods.removePoints(transferamount, sender); s.sendMessage("�aYou have sent �3" + transferamount + " points �ato �3" + target.toLowerCase() + "."); for (Player player: Bukkit.getOnlinePlayers()) { if (player.getName().equalsIgnoreCase(args[1])) { player.sendMessage("�aYou have received �3" + transferamount + " points �afrom �3" + sender.toLowerCase() + "."); } } } } else if (args[0].equalsIgnoreCase("reload") && s.hasPermission("donationpoints.reload")) { plugin.reloadConfig(); try { plugin.firstRun(); } catch (Exception ex) { ex.printStackTrace(); } s.sendMessage("�aConfig / Packages reloaded."); } else if (args[0].equalsIgnoreCase("balance") && s.hasPermission("donationpoints.balance")) { if (args.length == 1) { if (!Methods.hasAccount(s.getName())) { s.sendMessage("�cYou don't have an account."); } else { Double balance = Methods.getBalance(s.getName()); s.sendMessage("�aYou currently have: �3" + balance + " points."); } } else if (args.length == 2 && s.hasPermission("donationpoints.balance.others")) { String string = args[1]; if (!Methods.hasAccount(string)) { s.sendMessage("�3" + string + "�c does not have an account."); } else { Double balance = Methods.getBalance(string); s.sendMessage("�3" + string + "�a has a balance of: �3" + balance + " points."); } } } else if (args[0].equalsIgnoreCase("create") && s.hasPermission("donationpoints.create")) { if (args.length == 1) { String string = s.getName(); if (!Methods.hasAccount(string)) { Methods.createAccount(string); s.sendMessage("�aAn account has been created."); } else { s.sendMessage("�cYou already have an account."); } } if (args.length == 2 && s.hasPermission("donationpoints.create.others")) { //ResultSet rs2 = DBConnection.sql.readQuery("SELECT player FROM points_players WHERE player = '" + args[1].toLowerCase() + "';"); String string = args[1]; if (!Methods.hasAccount(string)) { Methods.createAccount(string); s.sendMessage("�aAn account has been created for: �3" + string.toLowerCase()); } else if (Methods.hasAccount(string)) { s.sendMessage("�3" + string + "�c already has an account."); } } } else if (args[0].equalsIgnoreCase("give") && args.length == 3 && s.hasPermission("donationpoints.give")) { Double addamount = Double.parseDouble(args[2]); String target = args[1].toLowerCase(); Methods.addPoints(addamount, target); s.sendMessage("�aYou have given �3" + target + " �aa total of �3" + addamount + " �apoints."); } else if (args[0].equalsIgnoreCase("take") && args.length == 3 && s.hasPermission("donationpoints.take")) { Double takeamount = Double.parseDouble(args[2]); String target = args[1].toLowerCase(); Methods.removePoints(takeamount, target); s.sendMessage("�aYou have taken �3" + takeamount + "�a points from �3" + target); } else if (args[0].equalsIgnoreCase("confirm") && s.hasPermission("donationpoints.confirm")) { String sender = s.getName().toLowerCase(); if (PlayerListener.purchases.containsKey(sender)) { String pack2 = PlayerListener.purchases.get(s.getName().toLowerCase()); Double price2 = plugin.getConfig().getDouble("packages." + pack2 + ".price"); int limit = plugin.getConfig().getInt("packages." + pack2 + ".limit"); ResultSet numberpurchased = DBConnection.sql.readQuery("SELECT COUNT (*) AS size FROM points_transactions WHERE player = '" + s.getName().toLowerCase() + "' AND package = '" + pack2 + "';"); if (plugin.getConfig().getBoolean("General.UseLimits")) { try { int size = numberpurchased.getInt("size"); if (size >= limit) { s.sendMessage("�cYou can't purchase �3" + pack2 + "�c because you have reached the limit of �3" + limit); } else if (size < limit) { List<String> commands = plugin.getConfig().getStringList("packages." + pack2 + ".commands"); for (String cmd : commands) { plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), cmd.replace("%player", sender.toLowerCase())); } Methods.removePoints(price2, sender); s.sendMessage("�aYou have just purchased: �3" + pack2 + "�a for �3" + price2 + " points"); s.sendMessage("�aYour new balance is: " + Methods.getBalance(sender)); PlayerListener.purchases.remove(s.getName().toLowerCase()); if (plugin.getConfig().getBoolean("General.LogTransactions", true)) { Methods.logTransaction(sender, price2, pack2); DonationPoints.log.info(s.getName().toLowerCase() + " has made a purchase. It has been logged to the points_transactions table."); } else { DonationPoints.log.info(s.getName().toLowerCase() + " has purchased " + pack2); } } } catch (SQLException e) { e.printStackTrace(); } } else { List<String> commands = plugin.getConfig().getStringList("packages." + pack2 + ".commands"); for (String cmd : commands) { plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), cmd.replace("%player", sender.toLowerCase())); } Methods.removePoints(price2, sender); s.sendMessage("�aYou have just purchased: �3" + pack2 + "�a for �3" + price2 + " points."); s.sendMessage("�aYour new balance is: " + Methods.getBalance(sender)); PlayerListener.purchases.remove(s.getName().toLowerCase()); if (plugin.getConfig().getBoolean("General.LogTransactions", true)) { Methods.logTransaction(sender, price2, pack2); DonationPoints.log.info(s.getName().toLowerCase() + " has made a purchase. It has been logged to the points_transactions table."); } else { DonationPoints.log.info(s.getName().toLowerCase() + " has purchased " + pack2); } } } else { s.sendMessage("�cIt doesn't look like you've started a transaction."); } } else if (args[0].equalsIgnoreCase("set") && s.hasPermission("donationpoints.set")) { String target = args[1].toLowerCase(); Double amount = Double.parseDouble(args[2]); Methods.setPoints(amount, target); s.sendMessage("�aYou have set �3" + target + "'s �abalance to �3" + amount + " points."); } else if (args[0].equalsIgnoreCase("update")) { if (!s.hasPermission("donationpoints.update")) { s.sendMessage("�cYou don't have permission to do that!"); return true; } if (!plugin.getConfig().getBoolean("General.AutoCheckForUpdates")) { s.sendMessage("�cThis server does not have the Update Checker for DonationPoints enabled."); } else if (UpdateChecker.updateNeeded()) { s.sendMessage("�eYour server is not running the same version of DonationPoints as the latest file on Bukkit!"); s.sendMessage("�ePerhaps it's time to upgrade?"); } else if (!UpdateChecker.updateNeeded()) { s.sendMessage("�eYou are running the same DonationPoints version as the one on Bukkit!"); s.sendMessage("�eNo need for an update at this time. :)"); } } else if (args[0].equalsIgnoreCase("package") && args[1].equalsIgnoreCase("info") && s.hasPermission("donationpoints.package.info")) { String packName = args[2]; Double price = plugin.getConfig().getDouble("packages." + packName + ".price"); String description = plugin.getConfig().getString("packages." + packName + ".description"); s.sendMessage("-----�e" + packName + " Info�f-----"); s.sendMessage("�aPackage Name:�3 " + packName); s.sendMessage("�aPrice:�3 " + price + "0"); s.sendMessage("�aDescription:�3 " + description); } else if (args[0].equalsIgnoreCase("version") && s.hasPermission("donationpoints.version")) { s.sendMessage("�aThis server is running �eDonationPoints �aversion �3" + plugin.getDescription().getVersion()); } else { s.sendMessage("Not a valid DonationPoints command / Not Enough Permissions."); } return true; } }; donationpoints.setExecutor(exe); } }
false
true
private void init() { PluginCommand donationpoints = plugin.getCommand("donationpoints"); CommandExecutor exe; exe = new CommandExecutor() { @Override public boolean onCommand(CommandSender s, Command c, String label, String[] args) { if (args.length < 1) { // Base Command s.sendMessage("-----�4DonationPoints Commands�f-----"); s.sendMessage("�3/dp basic�f - Show basic DonationPoints commands."); s.sendMessage("�3/dp packages�f - Show the DonationPoints packages commands."); s.sendMessage("�3/dp admin�f - Show the DonationPoints Admin Commands."); return true; // Packages Commands } else if (args[0].equalsIgnoreCase("packages")) { s.sendMessage("-----�4DonationPoints Package Commands�f-----"); if (s.hasPermission("donationpoints.package.info")) { s.sendMessage("�3/dp package info <packageName>�f - Shows package information."); } else { s.sendMessage("�cYou don't have permission to use any of the packages commands."); } // Admin Commands } else if (args[0].equalsIgnoreCase("admin")) { s.sendMessage("-----�4DonationPoints Admin Commands�f-----"); if (s.hasPermission("donationpoints.give")) { s.sendMessage("�3/dp give <player> <amount>�f - Give points to a player."); } if (s.hasPermission("donationpoints.take")) { s.sendMessage("�3/dp take <player> <amount>�f - Take points from a player."); } if (s.hasPermission("donationpoints.set")) { s.sendMessage("�3/dp set <player> <amount>�f - Set a player's balance."); } if (s.hasPermission("donationpoints.version")) { s.sendMessage("�3/dp version�f - Shows the version of the plugin you're running."); } if (s.hasPermission("donationpoints.update")) { s.sendMessage("�3/dp update�f - Checks if there is an update available."); } if (s.hasPermission("donationpoints.reload")) { s.sendMessage("�3/dp reload�f - Reloads the Configuration / Packages."); } else { s.sendMessage("�cYou don't have any permission for ANY DonationPoints Admin Commands."); } } else if (args[0].equalsIgnoreCase("basic")) { s.sendMessage("-----�4DonationPoints Basic Commands�f-----"); if (s.hasPermission("donationpoints.create")) { s.sendMessage("�3/dp create�f - Creates a points account for you."); } if (s.hasPermission("donationpoints.balance")) { s.sendMessage("�3/dp balance�f - Checks your points balance."); } if (s.hasPermission("donationpoints.transfer")) { s.sendMessage("�3/dp transfer <player> <amount>�f - Transfer Points."); } else { s.sendMessage("�cYou don't have permission for any DonationPoints Basic Commands."); } } else if (args[0].equalsIgnoreCase("transfer")) { if (!plugin.getConfig().getBoolean("General.Transferrable")) { s.sendMessage("�cThis server does not allow DonationPoints to be transferred."); return true; } if (!s.hasPermission("donationpoints.transfer")) { s.sendMessage("�cYou don't have permission to do that!"); return true; } if (!(s instanceof Player)) { s.sendMessage("�cThis command can only be performed by players."); return true; } if (args.length < 3) { s.sendMessage("�cNot enough arguments."); return true; } else { // Double transferamount = Double.parseDouble(args[2]); // 0 1 2 // /dp transfer player amount // final Player target = Bukkit.getPlayer(args[1].toLowerCase()); String sender = s.getName(); String target = args[1]; Double transferamount = Double.parseDouble(args[2]); if (!Methods.hasAccount(sender)) { s.sendMessage("�cYou don't have a DonationPoints account."); } if (!Methods.hasAccount(target)) { s.sendMessage("�cThat player does not have a DonationPoints account."); } if (target.equalsIgnoreCase(sender)) { s.sendMessage("�cYou can't transfer points to yourself."); } else { if (transferamount > Methods.getBalance(sender)) { s.sendMessage("�cYou don't have enough points to transfer."); return true; } if (transferamount == 0) { s.sendMessage("�cYou can't transfer 0 points."); return true; } } Methods.addPoints(transferamount, target); Methods.removePoints(transferamount, sender); s.sendMessage("�aYou have sent �3" + transferamount + " points �ato �3" + target.toLowerCase() + "."); for (Player player: Bukkit.getOnlinePlayers()) { if (player.getName().equalsIgnoreCase(args[1])) { player.sendMessage("�aYou have received �3" + transferamount + " points �afrom �3" + sender.toLowerCase() + "."); } } } } else if (args[0].equalsIgnoreCase("reload") && s.hasPermission("donationpoints.reload")) { plugin.reloadConfig(); try { plugin.firstRun(); } catch (Exception ex) { ex.printStackTrace(); } s.sendMessage("�aConfig / Packages reloaded."); } else if (args[0].equalsIgnoreCase("balance") && s.hasPermission("donationpoints.balance")) { if (args.length == 1) { if (!Methods.hasAccount(s.getName())) { s.sendMessage("�cYou don't have an account."); } else { Double balance = Methods.getBalance(s.getName()); s.sendMessage("�aYou currently have: �3" + balance + " points."); } } else if (args.length == 2 && s.hasPermission("donationpoints.balance.others")) { String string = args[1]; if (!Methods.hasAccount(string)) { s.sendMessage("�3" + string + "�c does not have an account."); } else { Double balance = Methods.getBalance(string); s.sendMessage("�3" + string + "�a has a balance of: �3" + balance + " points."); } } } else if (args[0].equalsIgnoreCase("create") && s.hasPermission("donationpoints.create")) { if (args.length == 1) { String string = s.getName(); if (!Methods.hasAccount(string)) { Methods.createAccount(string); s.sendMessage("�aAn account has been created."); } else { s.sendMessage("�cYou already have an account."); } } if (args.length == 2 && s.hasPermission("donationpoints.create.others")) { //ResultSet rs2 = DBConnection.sql.readQuery("SELECT player FROM points_players WHERE player = '" + args[1].toLowerCase() + "';"); String string = args[1]; if (!Methods.hasAccount(string)) { Methods.createAccount(string); s.sendMessage("�aAn account has been created for: �3" + string.toLowerCase()); } else if (Methods.hasAccount(string)) { s.sendMessage("�3" + string + "�c already has an account."); } } } else if (args[0].equalsIgnoreCase("give") && args.length == 3 && s.hasPermission("donationpoints.give")) { Double addamount = Double.parseDouble(args[2]); String target = args[1].toLowerCase(); Methods.addPoints(addamount, target); s.sendMessage("�aYou have given �3" + target + " �aa total of �3" + addamount + " �apoints."); } else if (args[0].equalsIgnoreCase("take") && args.length == 3 && s.hasPermission("donationpoints.take")) { Double takeamount = Double.parseDouble(args[2]); String target = args[1].toLowerCase(); Methods.removePoints(takeamount, target); s.sendMessage("�aYou have taken �3" + takeamount + "�a points from �3" + target); } else if (args[0].equalsIgnoreCase("confirm") && s.hasPermission("donationpoints.confirm")) { String sender = s.getName().toLowerCase(); if (PlayerListener.purchases.containsKey(sender)) { String pack2 = PlayerListener.purchases.get(s.getName().toLowerCase()); Double price2 = plugin.getConfig().getDouble("packages." + pack2 + ".price"); int limit = plugin.getConfig().getInt("packages." + pack2 + ".limit"); ResultSet numberpurchased = DBConnection.sql.readQuery("SELECT COUNT (*) AS size FROM points_transactions WHERE player = '" + s.getName().toLowerCase() + "' AND package = '" + pack2 + "';"); if (plugin.getConfig().getBoolean("General.UseLimits")) { try { int size = numberpurchased.getInt("size"); if (size >= limit) { s.sendMessage("�cYou can't purchase �3" + pack2 + "�c because you have reached the limit of �3" + limit); } else if (size < limit) { List<String> commands = plugin.getConfig().getStringList("packages." + pack2 + ".commands"); for (String cmd : commands) { plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), cmd.replace("%player", sender.toLowerCase())); } Methods.removePoints(price2, sender); s.sendMessage("�aYou have just purchased: �3" + pack2 + "�a for �3" + price2 + " points"); s.sendMessage("�aYour new balance is: " + Methods.getBalance(sender)); PlayerListener.purchases.remove(s.getName().toLowerCase()); if (plugin.getConfig().getBoolean("General.LogTransactions", true)) { Methods.logTransaction(sender, price2, pack2); DonationPoints.log.info(s.getName().toLowerCase() + " has made a purchase. It has been logged to the points_transactions table."); } else { DonationPoints.log.info(s.getName().toLowerCase() + " has purchased " + pack2); } } } catch (SQLException e) { e.printStackTrace(); } } else { List<String> commands = plugin.getConfig().getStringList("packages." + pack2 + ".commands"); for (String cmd : commands) { plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), cmd.replace("%player", sender.toLowerCase())); } Methods.removePoints(price2, sender); s.sendMessage("�aYou have just purchased: �3" + pack2 + "�a for �3" + price2 + " points."); s.sendMessage("�aYour new balance is: " + Methods.getBalance(sender)); PlayerListener.purchases.remove(s.getName().toLowerCase()); if (plugin.getConfig().getBoolean("General.LogTransactions", true)) { Methods.logTransaction(sender, price2, pack2); DonationPoints.log.info(s.getName().toLowerCase() + " has made a purchase. It has been logged to the points_transactions table."); } else { DonationPoints.log.info(s.getName().toLowerCase() + " has purchased " + pack2); } } } else { s.sendMessage("�cIt doesn't look like you've started a transaction."); } } else if (args[0].equalsIgnoreCase("set") && s.hasPermission("donationpoints.set")) { String target = args[1].toLowerCase(); Double amount = Double.parseDouble(args[2]); Methods.setPoints(amount, target); s.sendMessage("�aYou have set �3" + target + "'s �abalance to �3" + amount + " points."); } else if (args[0].equalsIgnoreCase("update")) { if (!s.hasPermission("donationpoints.update")) { s.sendMessage("�cYou don't have permission to do that!"); return true; } if (!plugin.getConfig().getBoolean("General.AutoCheckForUpdates")) { s.sendMessage("�cThis server does not have the Update Checker for DonationPoints enabled."); } else if (UpdateChecker.updateNeeded()) { s.sendMessage("�eYour server is not running the same version of DonationPoints as the latest file on Bukkit!"); s.sendMessage("�ePerhaps it's time to upgrade?"); } else if (!UpdateChecker.updateNeeded()) { s.sendMessage("�eYou are running the same DonationPoints version as the one on Bukkit!"); s.sendMessage("�eNo need for an update at this time. :)"); } } else if (args[0].equalsIgnoreCase("package") && args[1].equalsIgnoreCase("info") && s.hasPermission("donationpoints.package.info")) { String packName = args[2]; Double price = plugin.getConfig().getDouble("packages." + packName + ".price"); String description = plugin.getConfig().getString("packages." + packName + ".description"); s.sendMessage("-----�e" + packName + " Info�f-----"); s.sendMessage("�aPackage Name:�3 " + packName); s.sendMessage("�aPrice:�3 " + price + "0"); s.sendMessage("�aDescription:�3 " + description); } else if (args[0].equalsIgnoreCase("version") && s.hasPermission("donationpoints.version")) { s.sendMessage("�aThis server is running �eDonationPoints �aversion �3" + plugin.getDescription().getVersion()); } else { s.sendMessage("Not a valid DonationPoints command / Not Enough Permissions."); } return true; } }; donationpoints.setExecutor(exe); }
private void init() { PluginCommand donationpoints = plugin.getCommand("donationpoints"); CommandExecutor exe; exe = new CommandExecutor() { @Override public boolean onCommand(CommandSender s, Command c, String label, String[] args) { if (args.length < 1) { // Base Command s.sendMessage("-----�4DonationPoints Commands�f-----"); s.sendMessage("�3/dp basic�f - Show basic DonationPoints commands."); s.sendMessage("�3/dp packages�f - Show the DonationPoints packages commands."); s.sendMessage("�3/dp admin�f - Show the DonationPoints Admin Commands."); return true; // Packages Commands } else if (args[0].equalsIgnoreCase("packages")) { s.sendMessage("-----�4DonationPoints Package Commands�f-----"); if (s.hasPermission("donationpoints.package.info")) { s.sendMessage("�3/dp package info <packageName>�f - Shows package information."); } else { s.sendMessage("�cYou don't have permission to use any of the packages commands."); } // Admin Commands } else if (args[0].equalsIgnoreCase("admin")) { s.sendMessage("-----�4DonationPoints Admin Commands�f-----"); if (s.hasPermission("donationpoints.give")) { s.sendMessage("�3/dp give <player> <amount>�f - Give points to a player."); } if (s.hasPermission("donationpoints.take")) { s.sendMessage("�3/dp take <player> <amount>�f - Take points from a player."); } if (s.hasPermission("donationpoints.set")) { s.sendMessage("�3/dp set <player> <amount>�f - Set a player's balance."); } if (s.hasPermission("donationpoints.version")) { s.sendMessage("�3/dp version�f - Shows the version of the plugin you're running."); } if (s.hasPermission("donationpoints.update")) { s.sendMessage("�3/dp update�f - Checks if there is an update available."); } if (s.hasPermission("donationpoints.reload")) { s.sendMessage("�3/dp reload�f - Reloads the Configuration / Packages."); } else { s.sendMessage("�cYou don't have any permission for ANY DonationPoints Admin Commands."); } } else if (args[0].equalsIgnoreCase("basic")) { s.sendMessage("-----�4DonationPoints Basic Commands�f-----"); if (s.hasPermission("donationpoints.create")) { s.sendMessage("�3/dp create�f - Creates a points account for you."); } if (s.hasPermission("donationpoints.balance")) { s.sendMessage("�3/dp balance�f - Checks your points balance."); } if (s.hasPermission("donationpoints.transfer")) { s.sendMessage("�3/dp transfer <player> <amount>�f - Transfer Points."); } else { s.sendMessage("�cYou don't have permission for any DonationPoints Basic Commands."); } } else if (args[0].equalsIgnoreCase("transfer")) { if (!plugin.getConfig().getBoolean("General.Transferrable")) { s.sendMessage("�cThis server does not allow DonationPoints to be transferred."); return true; } if (!s.hasPermission("donationpoints.transfer")) { s.sendMessage("�cYou don't have permission to do that!"); return true; } if (!(s instanceof Player)) { s.sendMessage("�cThis command can only be performed by players."); return true; } if (args.length < 3) { s.sendMessage("�cNot enough arguments."); return true; } else { // Double transferamount = Double.parseDouble(args[2]); // 0 1 2 // /dp transfer player amount // final Player target = Bukkit.getPlayer(args[1].toLowerCase()); String sender = s.getName(); String target = args[1]; Double transferamount = Double.parseDouble(args[2]); if (!Methods.hasAccount(sender)) { s.sendMessage("�cYou don't have a DonationPoints account."); return true; } if (!Methods.hasAccount(target)) { s.sendMessage("�cThat player does not have a DonationPoints account."); return true; } if (target.equalsIgnoreCase(sender)) { s.sendMessage("�cYou can't transfer points to yourself."); return true; } else { if (transferamount > Methods.getBalance(sender)) { s.sendMessage("�cYou don't have enough points to transfer."); return true; } if (transferamount == 0) { s.sendMessage("�cYou can't transfer 0 points."); return true; } } Methods.addPoints(transferamount, target); Methods.removePoints(transferamount, sender); s.sendMessage("�aYou have sent �3" + transferamount + " points �ato �3" + target.toLowerCase() + "."); for (Player player: Bukkit.getOnlinePlayers()) { if (player.getName().equalsIgnoreCase(args[1])) { player.sendMessage("�aYou have received �3" + transferamount + " points �afrom �3" + sender.toLowerCase() + "."); } } } } else if (args[0].equalsIgnoreCase("reload") && s.hasPermission("donationpoints.reload")) { plugin.reloadConfig(); try { plugin.firstRun(); } catch (Exception ex) { ex.printStackTrace(); } s.sendMessage("�aConfig / Packages reloaded."); } else if (args[0].equalsIgnoreCase("balance") && s.hasPermission("donationpoints.balance")) { if (args.length == 1) { if (!Methods.hasAccount(s.getName())) { s.sendMessage("�cYou don't have an account."); } else { Double balance = Methods.getBalance(s.getName()); s.sendMessage("�aYou currently have: �3" + balance + " points."); } } else if (args.length == 2 && s.hasPermission("donationpoints.balance.others")) { String string = args[1]; if (!Methods.hasAccount(string)) { s.sendMessage("�3" + string + "�c does not have an account."); } else { Double balance = Methods.getBalance(string); s.sendMessage("�3" + string + "�a has a balance of: �3" + balance + " points."); } } } else if (args[0].equalsIgnoreCase("create") && s.hasPermission("donationpoints.create")) { if (args.length == 1) { String string = s.getName(); if (!Methods.hasAccount(string)) { Methods.createAccount(string); s.sendMessage("�aAn account has been created."); } else { s.sendMessage("�cYou already have an account."); } } if (args.length == 2 && s.hasPermission("donationpoints.create.others")) { //ResultSet rs2 = DBConnection.sql.readQuery("SELECT player FROM points_players WHERE player = '" + args[1].toLowerCase() + "';"); String string = args[1]; if (!Methods.hasAccount(string)) { Methods.createAccount(string); s.sendMessage("�aAn account has been created for: �3" + string.toLowerCase()); } else if (Methods.hasAccount(string)) { s.sendMessage("�3" + string + "�c already has an account."); } } } else if (args[0].equalsIgnoreCase("give") && args.length == 3 && s.hasPermission("donationpoints.give")) { Double addamount = Double.parseDouble(args[2]); String target = args[1].toLowerCase(); Methods.addPoints(addamount, target); s.sendMessage("�aYou have given �3" + target + " �aa total of �3" + addamount + " �apoints."); } else if (args[0].equalsIgnoreCase("take") && args.length == 3 && s.hasPermission("donationpoints.take")) { Double takeamount = Double.parseDouble(args[2]); String target = args[1].toLowerCase(); Methods.removePoints(takeamount, target); s.sendMessage("�aYou have taken �3" + takeamount + "�a points from �3" + target); } else if (args[0].equalsIgnoreCase("confirm") && s.hasPermission("donationpoints.confirm")) { String sender = s.getName().toLowerCase(); if (PlayerListener.purchases.containsKey(sender)) { String pack2 = PlayerListener.purchases.get(s.getName().toLowerCase()); Double price2 = plugin.getConfig().getDouble("packages." + pack2 + ".price"); int limit = plugin.getConfig().getInt("packages." + pack2 + ".limit"); ResultSet numberpurchased = DBConnection.sql.readQuery("SELECT COUNT (*) AS size FROM points_transactions WHERE player = '" + s.getName().toLowerCase() + "' AND package = '" + pack2 + "';"); if (plugin.getConfig().getBoolean("General.UseLimits")) { try { int size = numberpurchased.getInt("size"); if (size >= limit) { s.sendMessage("�cYou can't purchase �3" + pack2 + "�c because you have reached the limit of �3" + limit); } else if (size < limit) { List<String> commands = plugin.getConfig().getStringList("packages." + pack2 + ".commands"); for (String cmd : commands) { plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), cmd.replace("%player", sender.toLowerCase())); } Methods.removePoints(price2, sender); s.sendMessage("�aYou have just purchased: �3" + pack2 + "�a for �3" + price2 + " points"); s.sendMessage("�aYour new balance is: " + Methods.getBalance(sender)); PlayerListener.purchases.remove(s.getName().toLowerCase()); if (plugin.getConfig().getBoolean("General.LogTransactions", true)) { Methods.logTransaction(sender, price2, pack2); DonationPoints.log.info(s.getName().toLowerCase() + " has made a purchase. It has been logged to the points_transactions table."); } else { DonationPoints.log.info(s.getName().toLowerCase() + " has purchased " + pack2); } } } catch (SQLException e) { e.printStackTrace(); } } else { List<String> commands = plugin.getConfig().getStringList("packages." + pack2 + ".commands"); for (String cmd : commands) { plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), cmd.replace("%player", sender.toLowerCase())); } Methods.removePoints(price2, sender); s.sendMessage("�aYou have just purchased: �3" + pack2 + "�a for �3" + price2 + " points."); s.sendMessage("�aYour new balance is: " + Methods.getBalance(sender)); PlayerListener.purchases.remove(s.getName().toLowerCase()); if (plugin.getConfig().getBoolean("General.LogTransactions", true)) { Methods.logTransaction(sender, price2, pack2); DonationPoints.log.info(s.getName().toLowerCase() + " has made a purchase. It has been logged to the points_transactions table."); } else { DonationPoints.log.info(s.getName().toLowerCase() + " has purchased " + pack2); } } } else { s.sendMessage("�cIt doesn't look like you've started a transaction."); } } else if (args[0].equalsIgnoreCase("set") && s.hasPermission("donationpoints.set")) { String target = args[1].toLowerCase(); Double amount = Double.parseDouble(args[2]); Methods.setPoints(amount, target); s.sendMessage("�aYou have set �3" + target + "'s �abalance to �3" + amount + " points."); } else if (args[0].equalsIgnoreCase("update")) { if (!s.hasPermission("donationpoints.update")) { s.sendMessage("�cYou don't have permission to do that!"); return true; } if (!plugin.getConfig().getBoolean("General.AutoCheckForUpdates")) { s.sendMessage("�cThis server does not have the Update Checker for DonationPoints enabled."); } else if (UpdateChecker.updateNeeded()) { s.sendMessage("�eYour server is not running the same version of DonationPoints as the latest file on Bukkit!"); s.sendMessage("�ePerhaps it's time to upgrade?"); } else if (!UpdateChecker.updateNeeded()) { s.sendMessage("�eYou are running the same DonationPoints version as the one on Bukkit!"); s.sendMessage("�eNo need for an update at this time. :)"); } } else if (args[0].equalsIgnoreCase("package") && args[1].equalsIgnoreCase("info") && s.hasPermission("donationpoints.package.info")) { String packName = args[2]; Double price = plugin.getConfig().getDouble("packages." + packName + ".price"); String description = plugin.getConfig().getString("packages." + packName + ".description"); s.sendMessage("-----�e" + packName + " Info�f-----"); s.sendMessage("�aPackage Name:�3 " + packName); s.sendMessage("�aPrice:�3 " + price + "0"); s.sendMessage("�aDescription:�3 " + description); } else if (args[0].equalsIgnoreCase("version") && s.hasPermission("donationpoints.version")) { s.sendMessage("�aThis server is running �eDonationPoints �aversion �3" + plugin.getDescription().getVersion()); } else { s.sendMessage("Not a valid DonationPoints command / Not Enough Permissions."); } return true; } }; donationpoints.setExecutor(exe); }
diff --git a/deegree-core/deegree-core-base/src/main/java/org/deegree/gml/feature/GMLFeatureWriter.java b/deegree-core/deegree-core-base/src/main/java/org/deegree/gml/feature/GMLFeatureWriter.java index 3ab51fb48f..429a4a1153 100644 --- a/deegree-core/deegree-core-base/src/main/java/org/deegree/gml/feature/GMLFeatureWriter.java +++ b/deegree-core/deegree-core-base/src/main/java/org/deegree/gml/feature/GMLFeatureWriter.java @@ -1,726 +1,729 @@ //$HeadURL: svn+ssh://[email protected]/deegree/deegree3/commons/trunk/src/org/deegree/model/feature/Feature.java $ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: Department of Geography, University of Bonn and lat/lon GmbH 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 Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.gml.feature; import static org.deegree.commons.xml.CommonNamespaces.XLNNS; import static org.deegree.commons.xml.CommonNamespaces.XSINS; import static org.deegree.commons.xml.stax.StAXExportingHelper.writeAttribute; import static org.deegree.feature.types.property.ValueRepresentation.REMOTE; import static org.deegree.gml.GMLVersion.GML_2; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import org.apache.xerces.xs.XSElementDeclaration; import org.deegree.commons.tom.ElementNode; import org.deegree.commons.tom.TypedObjectNode; import org.deegree.commons.tom.array.TypedObjectNodeArray; import org.deegree.commons.tom.genericxml.GenericXMLElement; import org.deegree.commons.tom.gml.GMLObject; import org.deegree.commons.tom.gml.property.Property; import org.deegree.commons.tom.gml.property.PropertyType; import org.deegree.commons.tom.ows.CodeType; import org.deegree.commons.tom.ows.StringOrRef; import org.deegree.commons.tom.primitive.BaseType; import org.deegree.commons.tom.primitive.PrimitiveValue; import org.deegree.commons.uom.Length; import org.deegree.commons.uom.Measure; import org.deegree.cs.exceptions.TransformationException; import org.deegree.cs.exceptions.UnknownCRSException; import org.deegree.feature.Feature; import org.deegree.feature.FeatureCollection; import org.deegree.feature.GenericFeatureCollection; import org.deegree.feature.property.ExtraProps; import org.deegree.feature.property.GenericProperty; import org.deegree.feature.types.AppSchema; import org.deegree.feature.types.property.ArrayPropertyType; import org.deegree.feature.types.property.CodePropertyType; import org.deegree.feature.types.property.CustomPropertyType; import org.deegree.feature.types.property.EnvelopePropertyType; import org.deegree.feature.types.property.FeaturePropertyType; import org.deegree.feature.types.property.GeometryPropertyType; import org.deegree.feature.types.property.LengthPropertyType; import org.deegree.feature.types.property.MeasurePropertyType; import org.deegree.feature.types.property.ObjectPropertyType; import org.deegree.feature.types.property.SimplePropertyType; import org.deegree.feature.types.property.StringOrRefPropertyType; import org.deegree.feature.xpath.TypedObjectNodeXPathEvaluator; import org.deegree.filter.Filter; import org.deegree.filter.FilterEvaluationException; import org.deegree.filter.projection.ProjectionClause; import org.deegree.filter.projection.PropertyName; import org.deegree.filter.projection.TimeSliceProjection; import org.deegree.geometry.Envelope; import org.deegree.geometry.Geometry; import org.deegree.gml.GMLStreamWriter; import org.deegree.gml.commons.AbstractGMLObjectWriter; import org.deegree.gml.reference.FeatureReference; import org.deegree.gml.reference.GmlXlinkOptions; import org.deegree.gml.schema.GMLSchemaInfoSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Stream-based GML writer for {@link Feature} (and {@link FeatureCollection}) instances. * * @author <a href="mailto:[email protected]">Markus Schneider</a> * @author <a href="mailto:[email protected]">Andrei Ionita</a> * @author last edited by: $Author:$ * * @version $Revision:$, $Date:$ */ public class GMLFeatureWriter extends AbstractGMLObjectWriter { private static final Logger LOG = LoggerFactory.getLogger( GMLFeatureWriter.class ); private final QName fidAttr; private final String gmlNull; private final Map<QName, PropertyName> requestedPropertyNames = new HashMap<QName, PropertyName>(); private final List<Filter> timeSliceFilters = new ArrayList<Filter>(); private final boolean exportSf; private final boolean outputGeometries; private final boolean exportExtraProps; private final boolean exportBoundedBy; private final PropertyType boundedByPt; private AppSchema schema; private GMLSchemaInfoSet schemaInfoset; private static final QName XSI_NIL = new QName( XSINS, "nil", "xsi" ); /** * Creates a new {@link GMLFeatureWriter} instance. * * @param gmlStreamWriter * GML stream writer, must not be <code>null</code> */ public GMLFeatureWriter( GMLStreamWriter gmlStreamWriter ) { super( gmlStreamWriter ); if ( gmlStreamWriter.getProjections() != null ) { for ( ProjectionClause projection : gmlStreamWriter.getProjections() ) { if ( projection instanceof PropertyName ) { PropertyName propName = (PropertyName) projection; QName qName = propName.getPropertyName().getAsQName(); if ( qName != null ) { requestedPropertyNames.put( qName, propName ); } else { LOG.debug( "Only simple qualified element names are allowed for PropertyName projections. Ignoring '" + propName.getPropertyName() + "'" ); } } else if ( projection instanceof TimeSliceProjection ) { timeSliceFilters.add( ( (TimeSliceProjection) projection ).getTimeSliceFilter() ); } } } if ( !version.equals( GML_2 ) ) { fidAttr = new QName( gmlNs, "id" ); gmlNull = "Null"; } else { fidAttr = new QName( "", "fid" ); gmlNull = "null"; } this.outputGeometries = gmlStreamWriter.getOutputGeometries(); this.exportSf = false; this.exportExtraProps = gmlStreamWriter.getExportExtraProps(); this.boundedByPt = new EnvelopePropertyType( new QName( gmlNs, "boundedBy" ), 0, 1, null, null ); this.exportBoundedBy = gmlStreamWriter.getGenerateBoundedByForFeatures(); } /** * Exports the given {@link Feature} (or {@link FeatureCollection}). * * @param feature * feature to be exported, must not be <code>null</code> * @throws XMLStreamException * @throws UnknownCRSException * @throws TransformationException */ public void export( Feature feature ) throws XMLStreamException, UnknownCRSException, TransformationException { export( feature, referenceExportStrategy.getResolveOptions() ); } /** * Exports the given {@link Property}. * * @param prop * property to be exported, must not be <code>null</code> * @throws XMLStreamException * @throws UnknownCRSException * @throws TransformationException */ public void export( Property prop ) throws XMLStreamException, UnknownCRSException, TransformationException { export( prop, referenceExportStrategy.getResolveOptions() ); } public void export( TypedObjectNode node, GmlXlinkOptions resolveState ) throws XMLStreamException, UnknownCRSException, TransformationException { if ( node instanceof GMLObject ) { if ( node instanceof Feature ) { export( (Feature) node, resolveState ); } else if ( node instanceof Geometry ) { gmlStreamWriter.getGeometryWriter().export( (Geometry) node ); } else { throw new UnsupportedOperationException(); } } else if ( node instanceof PrimitiveValue ) { writer.writeCharacters( ( (PrimitiveValue) node ).getAsText() ); } else if ( node instanceof Property ) { export( (Property) node, resolveState ); } else if ( node instanceof ElementNode ) { ElementNode xmlContent = (ElementNode) node; exportGenericXmlElement( xmlContent, resolveState ); } else if ( node instanceof TypedObjectNodeArray<?> ) { for ( TypedObjectNode elem : ( (TypedObjectNodeArray<?>) node ).getElements() ) { export( elem, resolveState ); } } else if ( node == null ) { LOG.warn( "Null node encountered!?" ); } else { throw new RuntimeException( "Unhandled node type '" + node.getClass() + "'" ); } } private void export( Property property, GmlXlinkOptions resolveState ) throws XMLStreamException, UnknownCRSException, TransformationException { QName propName = property.getName(); PropertyType pt = property.getType(); if ( pt.getMinOccurs() == 0 ) { LOG.debug( "Optional property '" + propName + "', checking if it is requested." ); if ( !isPropertyRequested( propName ) ) { LOG.debug( "Skipping it." ); return; } // required for WMS: if ( !outputGeometries && pt instanceof GeometryPropertyType ) { LOG.debug( "Skipping it since geometries should not be output." ); return; } } if ( resolveState.getCurrentLevel() == 0 ) { resolveState = getResolveParams( property, resolveState ); } TypedObjectNode value = property.getValue(); // if ( value instanceof GenericXMLElement ) { // writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); // export( value, currentLevel, maxInlineLevels ); // writer.writeEndElement(); // return; // } // TODO check for GML 2 properties (gml:pointProperty, ...) and export // as "app:gml2PointProperty" for GML 3 boolean nilled = false; TypedObjectNode nil = property.getAttributes().get( XSI_NIL ); if ( nil instanceof PrimitiveValue ) { nilled = Boolean.TRUE.equals( ( (PrimitiveValue) nil ).getValue() ); } if ( pt instanceof FeaturePropertyType ) { if ( nilled ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XSINS, "nil", "true" ); endEmptyElement(); } else { exportFeatureProperty( (FeaturePropertyType) pt, (Feature) value, resolveState ); } } else if ( pt instanceof SimplePropertyType ) { if ( nilled ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XSINS, "nil", "true" ); endEmptyElement(); } else { // must be a primitive value PrimitiveValue pValue = (PrimitiveValue) value; writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( pValue != null ) { // TODO if ( pValue.getType().getBaseType() == BaseType.DECIMAL ) { writer.writeCharacters( pValue.getValue().toString() ); } else { writer.writeCharacters( pValue.getAsText() ); } } writer.writeEndElement(); } } else if ( pt instanceof GeometryPropertyType ) { if ( nilled ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XSINS, "nil", "true" ); endEmptyElement(); + } else if ( value == null ) { + writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); + endEmptyElement(); } else { Geometry gValue = (Geometry) value; if ( !exportSf && gValue.getId() != null && referenceExportStrategy.isObjectExported( gValue.getId() ) ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XLNNS, "href", "#" + gValue.getId() ); endEmptyElement(); } else { writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( gValue.getId() != null ) { // WFS CITE 1.1.0 test requirement (wfs:GetFeature.XLink-POST-XML-10) writer.writeComment( "Inlined geometry '" + gValue.getId() + "'" ); } gmlStreamWriter.getGeometryWriter().export( (Geometry) value ); writer.writeEndElement(); } } } else if ( pt instanceof CodePropertyType ) { writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( nilled ) { writeAttributeWithNS( XSINS, "nil", "true" ); } CodeType codeType = (CodeType) value; if ( codeType != null ) { if ( codeType.getCodeSpace() != null && codeType.getCodeSpace().length() > 0 ) { if ( GML_2 != version ) { writer.writeAttribute( "codeSpace", codeType.getCodeSpace() ); } } writer.writeCharacters( codeType.getCode() ); } writer.writeEndElement(); } else if ( pt instanceof EnvelopePropertyType ) { if ( nilled ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XSINS, "nil", "true" ); endEmptyElement(); } else { writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( value != null ) { gmlStreamWriter.getGeometryWriter().exportEnvelope( (Envelope) value ); } else { writeStartElementWithNS( gmlNs, gmlNull ); writer.writeCharacters( "missing" ); writer.writeEndElement(); } writer.writeEndElement(); } } else if ( pt instanceof LengthPropertyType ) { Length length = (Length) value; writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( GML_2 != version ) { if ( nilled ) { writeAttributeWithNS( XSINS, "nil", "true" ); } writer.writeAttribute( "uom", length.getUomUri() ); } if ( !nilled ) { writer.writeCharacters( String.valueOf( length.getValue() ) ); } writer.writeEndElement(); } else if ( pt instanceof MeasurePropertyType ) { Measure measure = (Measure) value; writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( GML_2 != version ) { writer.writeAttribute( "uom", measure.getUomUri() ); } writer.writeCharacters( String.valueOf( measure.getValue() ) ); writer.writeEndElement(); } else if ( pt instanceof StringOrRefPropertyType ) { StringOrRef stringOrRef = (StringOrRef) value; if ( stringOrRef.getString() == null || stringOrRef.getString().length() == 0 ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( stringOrRef.getRef() != null ) { writeAttributeWithNS( XLNNS, "href", stringOrRef.getRef() ); } if ( nilled ) { writeAttributeWithNS( XSINS, "nil", "true" ); } endEmptyElement(); } else { writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( nilled ) { writeAttributeWithNS( XSINS, "nil", "true" ); } if ( stringOrRef.getRef() != null ) { writeAttributeWithNS( XLNNS, "href", stringOrRef.getRef() ); } if ( !nilled && stringOrRef.getString() != null ) { writer.writeCharacters( stringOrRef.getString() ); } writer.writeEndElement(); } } else if ( pt instanceof CustomPropertyType ) { if ( !timeSliceFilters.isEmpty() ) { if ( excludeByTimeSliceFilter( property ) ) { return; } } writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( property.getAttributes() != null ) { for ( Entry<QName, PrimitiveValue> attr : property.getAttributes().entrySet() ) { writeAttribute( writer, attr.getKey(), attr.getValue().getAsText() ); } } if ( property.getChildren() != null ) { for ( TypedObjectNode childNode : property.getChildren() ) { export( childNode, resolveState ); } } writer.writeEndElement(); } else if ( pt instanceof ArrayPropertyType ) { if ( nilled ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XSINS, "nil", "true" ); endEmptyElement(); } else { writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); export( (TypedObjectNode) property.getValue(), resolveState ); writer.writeEndElement(); } } else { throw new RuntimeException( "Internal error. Unhandled property type '" + pt.getClass() + "'" ); } } private boolean excludeByTimeSliceFilter( Property property ) { XSElementDeclaration elDecl = property.getXSType(); if ( elDecl == null ) { return false; } if ( schemaInfoset.getTimeSlicePropertySemantics( elDecl ) == null ) { return false; } TypedObjectNode timeSlice = property.getValue(); // TODO will somebody *please* clean up getChildren() and getValue()! if ( timeSlice instanceof GenericXMLElement ) { GenericXMLElement el = (GenericXMLElement) timeSlice; if ( !el.getChildren().isEmpty() ) { timeSlice = el.getChildren().get( 0 ); } } for ( Filter timeSliceFilter : timeSliceFilters ) { TypedObjectNodeXPathEvaluator evaluator = new TypedObjectNodeXPathEvaluator(); try { if ( !timeSliceFilter.evaluate( timeSlice, evaluator ) ) { return true; } } catch ( FilterEvaluationException e ) { LOG.warn( "Unable to evaluate time slice projection filter: " + e.getMessage() ); } } return false; } private void exportBoundedBy( Envelope env, boolean indicateMissing ) throws XMLStreamException, UnknownCRSException, TransformationException { if ( env != null || indicateMissing ) { writer.writeStartElement( gmlNs, "boundedBy" ); if ( env != null ) { gmlStreamWriter.getGeometryWriter().exportEnvelope( env ); } else { writer.writeStartElement( gmlNs, gmlNull ); writer.writeCharacters( "missing" ); writer.writeEndElement(); } writer.writeEndElement(); } } private void export( Feature feature, GmlXlinkOptions resolveState ) throws XMLStreamException, UnknownCRSException, TransformationException { setSchema( feature ); if ( feature.getId() != null ) { referenceExportStrategy.addExportedId( feature.getId() ); } if ( feature instanceof GenericFeatureCollection ) { LOG.debug( "Exporting generic feature collection." ); writeStartElementWithNS( gmlNs, "FeatureCollection" ); if ( feature.getId() != null ) { if ( fidAttr.getNamespaceURI() == "" ) { writer.writeAttribute( fidAttr.getLocalPart(), feature.getId() ); } else { writeAttributeWithNS( fidAttr.getNamespaceURI(), fidAttr.getLocalPart(), feature.getId() ); } } exportBoundedBy( feature.getEnvelope(), false ); for ( Feature member : ( (FeatureCollection) feature ) ) { String memberFid = member.getId(); writeStartElementWithNS( gmlNs, "featureMember" ); if ( memberFid != null && referenceExportStrategy.isObjectExported( memberFid ) ) { writeAttributeWithNS( XLNNS, "href", "#" + memberFid ); } else { export( member, getResolveStateForNextLevel( resolveState ) ); } writer.writeEndElement(); } writer.writeEndElement(); } else { QName featureName = feature.getName(); LOG.debug( "Exporting Feature {} with ID {}", featureName, feature.getId() ); String namespaceURI = featureName.getNamespaceURI(); String localName = featureName.getLocalPart(); writeStartElementWithNS( namespaceURI, localName ); if ( feature.getId() != null ) { if ( fidAttr.getNamespaceURI() == "" ) { writer.writeAttribute( fidAttr.getLocalPart(), feature.getId() ); } else { writeAttributeWithNS( fidAttr.getNamespaceURI(), fidAttr.getLocalPart(), feature.getId() ); } } List<Property> props = feature.getProperties(); if ( exportBoundedBy ) { props = augmentBoundedBy( feature ); } for ( Property prop : props ) { export( prop, resolveState ); } if ( exportExtraProps ) { ExtraProps extraProps = feature.getExtraProperties(); if ( extraProps != null ) { for ( Property prop : extraProps.getProperties() ) { export( prop, resolveState ); } } } writer.writeEndElement(); } } private void setSchema( Feature feature ) { if ( schema == null ) { schema = feature.getType().getSchema(); if ( schema != null ) { schemaInfoset = schema.getGMLSchema(); } } } private List<Property> augmentBoundedBy( Feature f ) { LinkedList<Property> props = new LinkedList<Property>( f.getProperties() ); for ( int i = 0; i < props.size(); i++ ) { QName name = props.get( i ).getName(); if ( !gmlNs.equals( name.getNamespaceURI() ) || name.getLocalPart().equals( "location" ) ) { // not a GML property or gml:location -> gml:boundedBy must be included right before it Property boundedBy = getBoundedBy( f ); if ( boundedBy != null ) { props.add( i, boundedBy ); } break; } else if ( name.getLocalPart().equals( "boundedBy" ) ) { // already present -> don't include it break; } } return props; } private Property getBoundedBy( Feature f ) { Envelope env = f.getEnvelope(); if ( env == null ) { env = f.calcEnvelope(); } if ( env == null ) { return null; } return new GenericProperty( boundedByPt, env ); } private GmlXlinkOptions getResolveParams( Property prop, GmlXlinkOptions resolveState ) { PropertyName projection = requestedPropertyNames.get( prop.getName() ); if ( projection != null && projection.getResolveParams() != null ) { return new GmlXlinkOptions( projection.getResolveParams() ); } return resolveState; } private void exportFeatureProperty( FeaturePropertyType pt, Feature subFeature, GmlXlinkOptions resolveState ) throws XMLStreamException, UnknownCRSException, TransformationException { QName propName = pt.getName(); LOG.debug( "Exporting feature property '" + propName + "'" ); if ( subFeature == null ) { exportEmptyFeatureProperty( propName ); } else if ( subFeature instanceof FeatureReference ) { exportFeatureProperty( pt, (FeatureReference) subFeature, resolveState, propName ); } else { // normal feature String subFid = subFeature.getId(); if ( subFid == null ) { // no feature id -> no other chance, but inlining it writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writer.writeComment( "Inlined feature '" + subFid + "'" ); export( subFeature, getResolveStateForNextLevel( resolveState ) ); writer.writeEndElement(); } else { // has feature id if ( referenceExportStrategy.isObjectExported( subFid ) ) { exportAlreadyExportedFeaturePropertyByReference( subFeature, propName ); } else { exportFeaturePropertyByValue( propName, subFeature, resolveState ); } } } } private void exportEmptyFeatureProperty( QName propName ) throws XMLStreamException { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); endEmptyElement(); } private void exportFeatureProperty( FeaturePropertyType pt, FeatureReference ref, GmlXlinkOptions resolveState, QName propName ) throws XMLStreamException, UnknownCRSException, TransformationException { boolean includeNextLevelInOutput = includeNextLevelInOutput( resolveState ); if ( includeNextLevelInOutput ) { if ( pt.getAllowedRepresentation() == REMOTE ) { exportFeaturePropertyByReference( propName, ref, true, resolveState ); } else { if ( referenceExportStrategy.isObjectExported( ref.getId() ) ) { exportAlreadyExportedFeaturePropertyByReference( ref, propName ); } else { exportFeaturePropertyByValue( propName, ref, resolveState ); } } } else { exportFeaturePropertyByReference( propName, ref, false, resolveState ); } } private void exportAlreadyExportedFeaturePropertyByReference( Feature ref, QName propName ) throws XMLStreamException { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XLNNS, "href", "#" + ref.getId() ); endEmptyElement(); } private boolean includeNextLevelInOutput( GmlXlinkOptions resolveState ) { int maxInlineLevels = resolveState.getDepth(); int currentLevel = resolveState.getCurrentLevel(); return maxInlineLevels == -1 || ( maxInlineLevels > 0 && currentLevel < maxInlineLevels ); } private void exportFeaturePropertyByReference( QName propName, FeatureReference ref, boolean forceInclusionInDocument, GmlXlinkOptions resolveState ) throws XMLStreamException { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); String uri = null; if ( forceInclusionInDocument ) { resolveState = getResolveStateForNextLevel( resolveState ); uri = referenceExportStrategy.requireObject( ref, resolveState ); } else { uri = referenceExportStrategy.handleReference( ref ); } writeAttributeWithNS( XLNNS, "href", uri ); endEmptyElement(); } private void exportFeaturePropertyByValue( QName propName, Feature subFeature, GmlXlinkOptions resolveState ) throws XMLStreamException, UnknownCRSException, TransformationException { referenceExportStrategy.addExportedId( subFeature.getId() ); writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writer.writeComment( "Inlined feature '" + subFeature.getId() + "'" ); export( subFeature, getResolveStateForNextLevel( resolveState ) ); writer.writeEndElement(); } private void exportGenericXmlElement( ElementNode xmlContent, GmlXlinkOptions resolveState ) throws XMLStreamException, UnknownCRSException, TransformationException { QName elName = xmlContent.getName(); LOG.debug( "Exporting " + elName ); XSElementDeclaration elDecl = xmlContent.getXSType(); if ( elDecl != null && schemaInfoset != null ) { ObjectPropertyType gmlPropertyDecl = schemaInfoset.getGMLPropertyDecl( elDecl, elName, 0, 1, null ); if ( gmlPropertyDecl instanceof FeaturePropertyType ) { List<TypedObjectNode> children = xmlContent.getChildren(); if ( children.size() == 1 && children.get( 0 ) instanceof Feature ) { LOG.debug( "Exporting as nested feature property." ); exportFeatureProperty( (FeaturePropertyType) gmlPropertyDecl, (Feature) children.get( 0 ), resolveState ); return; } } } writeStartElementWithNS( elName.getNamespaceURI(), elName.getLocalPart() ); if ( xmlContent.getAttributes() != null ) { for ( Entry<QName, PrimitiveValue> attr : xmlContent.getAttributes().entrySet() ) { writeAttributeWithNS( attr.getKey().getNamespaceURI(), attr.getKey().getLocalPart(), attr.getValue().getAsText() ); } } if ( xmlContent.getChildren() != null ) { for ( TypedObjectNode childNode : xmlContent.getChildren() ) { export( childNode, resolveState ); } } writer.writeEndElement(); } private boolean isPropertyRequested( QName propName ) { return requestedPropertyNames.isEmpty() || requestedPropertyNames.containsKey( propName ); } }
true
true
private void export( Property property, GmlXlinkOptions resolveState ) throws XMLStreamException, UnknownCRSException, TransformationException { QName propName = property.getName(); PropertyType pt = property.getType(); if ( pt.getMinOccurs() == 0 ) { LOG.debug( "Optional property '" + propName + "', checking if it is requested." ); if ( !isPropertyRequested( propName ) ) { LOG.debug( "Skipping it." ); return; } // required for WMS: if ( !outputGeometries && pt instanceof GeometryPropertyType ) { LOG.debug( "Skipping it since geometries should not be output." ); return; } } if ( resolveState.getCurrentLevel() == 0 ) { resolveState = getResolveParams( property, resolveState ); } TypedObjectNode value = property.getValue(); // if ( value instanceof GenericXMLElement ) { // writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); // export( value, currentLevel, maxInlineLevels ); // writer.writeEndElement(); // return; // } // TODO check for GML 2 properties (gml:pointProperty, ...) and export // as "app:gml2PointProperty" for GML 3 boolean nilled = false; TypedObjectNode nil = property.getAttributes().get( XSI_NIL ); if ( nil instanceof PrimitiveValue ) { nilled = Boolean.TRUE.equals( ( (PrimitiveValue) nil ).getValue() ); } if ( pt instanceof FeaturePropertyType ) { if ( nilled ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XSINS, "nil", "true" ); endEmptyElement(); } else { exportFeatureProperty( (FeaturePropertyType) pt, (Feature) value, resolveState ); } } else if ( pt instanceof SimplePropertyType ) { if ( nilled ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XSINS, "nil", "true" ); endEmptyElement(); } else { // must be a primitive value PrimitiveValue pValue = (PrimitiveValue) value; writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( pValue != null ) { // TODO if ( pValue.getType().getBaseType() == BaseType.DECIMAL ) { writer.writeCharacters( pValue.getValue().toString() ); } else { writer.writeCharacters( pValue.getAsText() ); } } writer.writeEndElement(); } } else if ( pt instanceof GeometryPropertyType ) { if ( nilled ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XSINS, "nil", "true" ); endEmptyElement(); } else { Geometry gValue = (Geometry) value; if ( !exportSf && gValue.getId() != null && referenceExportStrategy.isObjectExported( gValue.getId() ) ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XLNNS, "href", "#" + gValue.getId() ); endEmptyElement(); } else { writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( gValue.getId() != null ) { // WFS CITE 1.1.0 test requirement (wfs:GetFeature.XLink-POST-XML-10) writer.writeComment( "Inlined geometry '" + gValue.getId() + "'" ); } gmlStreamWriter.getGeometryWriter().export( (Geometry) value ); writer.writeEndElement(); } } } else if ( pt instanceof CodePropertyType ) { writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( nilled ) { writeAttributeWithNS( XSINS, "nil", "true" ); } CodeType codeType = (CodeType) value; if ( codeType != null ) { if ( codeType.getCodeSpace() != null && codeType.getCodeSpace().length() > 0 ) { if ( GML_2 != version ) { writer.writeAttribute( "codeSpace", codeType.getCodeSpace() ); } } writer.writeCharacters( codeType.getCode() ); } writer.writeEndElement(); } else if ( pt instanceof EnvelopePropertyType ) { if ( nilled ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XSINS, "nil", "true" ); endEmptyElement(); } else { writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( value != null ) { gmlStreamWriter.getGeometryWriter().exportEnvelope( (Envelope) value ); } else { writeStartElementWithNS( gmlNs, gmlNull ); writer.writeCharacters( "missing" ); writer.writeEndElement(); } writer.writeEndElement(); } } else if ( pt instanceof LengthPropertyType ) { Length length = (Length) value; writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( GML_2 != version ) { if ( nilled ) { writeAttributeWithNS( XSINS, "nil", "true" ); } writer.writeAttribute( "uom", length.getUomUri() ); } if ( !nilled ) { writer.writeCharacters( String.valueOf( length.getValue() ) ); } writer.writeEndElement(); } else if ( pt instanceof MeasurePropertyType ) { Measure measure = (Measure) value; writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( GML_2 != version ) { writer.writeAttribute( "uom", measure.getUomUri() ); } writer.writeCharacters( String.valueOf( measure.getValue() ) ); writer.writeEndElement(); } else if ( pt instanceof StringOrRefPropertyType ) { StringOrRef stringOrRef = (StringOrRef) value; if ( stringOrRef.getString() == null || stringOrRef.getString().length() == 0 ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( stringOrRef.getRef() != null ) { writeAttributeWithNS( XLNNS, "href", stringOrRef.getRef() ); } if ( nilled ) { writeAttributeWithNS( XSINS, "nil", "true" ); } endEmptyElement(); } else { writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( nilled ) { writeAttributeWithNS( XSINS, "nil", "true" ); } if ( stringOrRef.getRef() != null ) { writeAttributeWithNS( XLNNS, "href", stringOrRef.getRef() ); } if ( !nilled && stringOrRef.getString() != null ) { writer.writeCharacters( stringOrRef.getString() ); } writer.writeEndElement(); } } else if ( pt instanceof CustomPropertyType ) { if ( !timeSliceFilters.isEmpty() ) { if ( excludeByTimeSliceFilter( property ) ) { return; } } writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( property.getAttributes() != null ) { for ( Entry<QName, PrimitiveValue> attr : property.getAttributes().entrySet() ) { writeAttribute( writer, attr.getKey(), attr.getValue().getAsText() ); } } if ( property.getChildren() != null ) { for ( TypedObjectNode childNode : property.getChildren() ) { export( childNode, resolveState ); } } writer.writeEndElement(); } else if ( pt instanceof ArrayPropertyType ) { if ( nilled ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XSINS, "nil", "true" ); endEmptyElement(); } else { writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); export( (TypedObjectNode) property.getValue(), resolveState ); writer.writeEndElement(); } } else { throw new RuntimeException( "Internal error. Unhandled property type '" + pt.getClass() + "'" ); } }
private void export( Property property, GmlXlinkOptions resolveState ) throws XMLStreamException, UnknownCRSException, TransformationException { QName propName = property.getName(); PropertyType pt = property.getType(); if ( pt.getMinOccurs() == 0 ) { LOG.debug( "Optional property '" + propName + "', checking if it is requested." ); if ( !isPropertyRequested( propName ) ) { LOG.debug( "Skipping it." ); return; } // required for WMS: if ( !outputGeometries && pt instanceof GeometryPropertyType ) { LOG.debug( "Skipping it since geometries should not be output." ); return; } } if ( resolveState.getCurrentLevel() == 0 ) { resolveState = getResolveParams( property, resolveState ); } TypedObjectNode value = property.getValue(); // if ( value instanceof GenericXMLElement ) { // writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); // export( value, currentLevel, maxInlineLevels ); // writer.writeEndElement(); // return; // } // TODO check for GML 2 properties (gml:pointProperty, ...) and export // as "app:gml2PointProperty" for GML 3 boolean nilled = false; TypedObjectNode nil = property.getAttributes().get( XSI_NIL ); if ( nil instanceof PrimitiveValue ) { nilled = Boolean.TRUE.equals( ( (PrimitiveValue) nil ).getValue() ); } if ( pt instanceof FeaturePropertyType ) { if ( nilled ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XSINS, "nil", "true" ); endEmptyElement(); } else { exportFeatureProperty( (FeaturePropertyType) pt, (Feature) value, resolveState ); } } else if ( pt instanceof SimplePropertyType ) { if ( nilled ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XSINS, "nil", "true" ); endEmptyElement(); } else { // must be a primitive value PrimitiveValue pValue = (PrimitiveValue) value; writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( pValue != null ) { // TODO if ( pValue.getType().getBaseType() == BaseType.DECIMAL ) { writer.writeCharacters( pValue.getValue().toString() ); } else { writer.writeCharacters( pValue.getAsText() ); } } writer.writeEndElement(); } } else if ( pt instanceof GeometryPropertyType ) { if ( nilled ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XSINS, "nil", "true" ); endEmptyElement(); } else if ( value == null ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); endEmptyElement(); } else { Geometry gValue = (Geometry) value; if ( !exportSf && gValue.getId() != null && referenceExportStrategy.isObjectExported( gValue.getId() ) ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XLNNS, "href", "#" + gValue.getId() ); endEmptyElement(); } else { writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( gValue.getId() != null ) { // WFS CITE 1.1.0 test requirement (wfs:GetFeature.XLink-POST-XML-10) writer.writeComment( "Inlined geometry '" + gValue.getId() + "'" ); } gmlStreamWriter.getGeometryWriter().export( (Geometry) value ); writer.writeEndElement(); } } } else if ( pt instanceof CodePropertyType ) { writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( nilled ) { writeAttributeWithNS( XSINS, "nil", "true" ); } CodeType codeType = (CodeType) value; if ( codeType != null ) { if ( codeType.getCodeSpace() != null && codeType.getCodeSpace().length() > 0 ) { if ( GML_2 != version ) { writer.writeAttribute( "codeSpace", codeType.getCodeSpace() ); } } writer.writeCharacters( codeType.getCode() ); } writer.writeEndElement(); } else if ( pt instanceof EnvelopePropertyType ) { if ( nilled ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XSINS, "nil", "true" ); endEmptyElement(); } else { writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( value != null ) { gmlStreamWriter.getGeometryWriter().exportEnvelope( (Envelope) value ); } else { writeStartElementWithNS( gmlNs, gmlNull ); writer.writeCharacters( "missing" ); writer.writeEndElement(); } writer.writeEndElement(); } } else if ( pt instanceof LengthPropertyType ) { Length length = (Length) value; writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( GML_2 != version ) { if ( nilled ) { writeAttributeWithNS( XSINS, "nil", "true" ); } writer.writeAttribute( "uom", length.getUomUri() ); } if ( !nilled ) { writer.writeCharacters( String.valueOf( length.getValue() ) ); } writer.writeEndElement(); } else if ( pt instanceof MeasurePropertyType ) { Measure measure = (Measure) value; writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( GML_2 != version ) { writer.writeAttribute( "uom", measure.getUomUri() ); } writer.writeCharacters( String.valueOf( measure.getValue() ) ); writer.writeEndElement(); } else if ( pt instanceof StringOrRefPropertyType ) { StringOrRef stringOrRef = (StringOrRef) value; if ( stringOrRef.getString() == null || stringOrRef.getString().length() == 0 ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( stringOrRef.getRef() != null ) { writeAttributeWithNS( XLNNS, "href", stringOrRef.getRef() ); } if ( nilled ) { writeAttributeWithNS( XSINS, "nil", "true" ); } endEmptyElement(); } else { writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( nilled ) { writeAttributeWithNS( XSINS, "nil", "true" ); } if ( stringOrRef.getRef() != null ) { writeAttributeWithNS( XLNNS, "href", stringOrRef.getRef() ); } if ( !nilled && stringOrRef.getString() != null ) { writer.writeCharacters( stringOrRef.getString() ); } writer.writeEndElement(); } } else if ( pt instanceof CustomPropertyType ) { if ( !timeSliceFilters.isEmpty() ) { if ( excludeByTimeSliceFilter( property ) ) { return; } } writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); if ( property.getAttributes() != null ) { for ( Entry<QName, PrimitiveValue> attr : property.getAttributes().entrySet() ) { writeAttribute( writer, attr.getKey(), attr.getValue().getAsText() ); } } if ( property.getChildren() != null ) { for ( TypedObjectNode childNode : property.getChildren() ) { export( childNode, resolveState ); } } writer.writeEndElement(); } else if ( pt instanceof ArrayPropertyType ) { if ( nilled ) { writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); writeAttributeWithNS( XSINS, "nil", "true" ); endEmptyElement(); } else { writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() ); export( (TypedObjectNode) property.getValue(), resolveState ); writer.writeEndElement(); } } else { throw new RuntimeException( "Internal error. Unhandled property type '" + pt.getClass() + "'" ); } }
diff --git a/src/org/saga/messages/StatsMessages.java b/src/org/saga/messages/StatsMessages.java index cb48aad..e61607e 100644 --- a/src/org/saga/messages/StatsMessages.java +++ b/src/org/saga/messages/StatsMessages.java @@ -1,369 +1,369 @@ package org.saga.messages; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import org.bukkit.ChatColor; import org.saga.abilities.Ability; import org.saga.abilities.AbilityDefinition; import org.saga.chunks.Bundle; import org.saga.chunks.BundleManager; import org.saga.config.AttributeConfiguration; import org.saga.config.ExperienceConfiguration; import org.saga.config.SettlementConfiguration; import org.saga.dependencies.EconomyDependency; import org.saga.factions.Faction; import org.saga.factions.FactionManager; import org.saga.messages.PlayerMessages.ColourLoop; import org.saga.player.GuardianRune; import org.saga.player.SagaPlayer; import org.saga.utility.text.RomanNumeral; import org.saga.utility.text.StringBook; import org.saga.utility.text.StringTable; import org.saga.utility.text.TextUtil; public class StatsMessages { public static ChatColor veryPositive = ChatColor.DARK_GREEN; public static ChatColor positive = ChatColor.GREEN; public static ChatColor negative = ChatColor.RED; public static ChatColor veryNegative = ChatColor.DARK_RED; public static ChatColor unavailable = ChatColor.DARK_GRAY; public static ChatColor announce = ChatColor.AQUA; public static ChatColor normal1 = ChatColor.GOLD; public static ChatColor normal2 = ChatColor.YELLOW; // Stats command: public static String stats(SagaPlayer sagaPlayer, Integer page) { StringBook book = new StringBook("stats", new ColourLoop().addColor(normal1).addColor(normal2)); // Attributes and levels: book.addTable(attributesLevels(sagaPlayer)); book.addLine(""); book.addTable(factionSettlement(sagaPlayer)); book.nextPage(); // Abilities: book.addTable(abilities(sagaPlayer)); book.nextPage(); // Invites: book.addTable(invites(sagaPlayer)); return book.framedPage(page); } private static StringTable attributesLevels(SagaPlayer sagaPlayer) { StringTable table = new StringTable(new ColourLoop().addColor(normal1).addColor(normal2)); DecimalFormat format = new DecimalFormat("00"); // Attributes: ArrayList<String> attrNames = AttributeConfiguration.config().getAttributeNames(); for (String attrName : attrNames) { Integer attrBonus = sagaPlayer.getAttrScoreBonus(attrName); Integer attrScore = sagaPlayer.getRawAttributeScore(attrName); String scoreCurr = format.format(attrScore + attrBonus); String scoreMax = format.format(AttributeConfiguration.config().maxAttributeScore + attrBonus); String score = scoreCurr + "/" + scoreMax; // Colours: if(attrBonus > 0){ score = positive + score; } else if(attrBonus < 0){ score = negative + score; } table.addLine(attrName, score, 0); } // Health: table.addLine("Health", TextUtil.round((double)sagaPlayer.getHealth(), 0) + "/" + TextUtil.round((double)sagaPlayer.getTotalHealth(), 0), 2); String attrPoints = sagaPlayer.getUsedAttributePoints() + "/" + sagaPlayer.getAvailableAttributePoints(); if(sagaPlayer.getRemainingAttributePoints() < 0){ attrPoints = ChatColor.DARK_RED + attrPoints; } else if (sagaPlayer.getRemainingAttributePoints() > 0) { attrPoints = ChatColor.DARK_GREEN + attrPoints; } table.addLine("Attributes", attrPoints, 2); // Exp: - table.addLine("Progress", (int)(100.0 * sagaPlayer.getRemainingExp() / ExperienceConfiguration.config().getAttributePointCost()) + "%", 2); + table.addLine("Progress", (int)(100.0 - 100.0 * sagaPlayer.getRemainingExp() / ExperienceConfiguration.config().getAttributePointCost()) + "%", 2); // Wallet: table.addLine("Wallet", EconomyMessages.coins(EconomyDependency.getCoins(sagaPlayer)), 2); // Guard rune: GuardianRune guardRune = sagaPlayer.getGuardRune(); String rune = ""; if(!guardRune.isEnabled()){ rune = "disabled"; }else{ if(guardRune.isCharged()){ rune= "charged"; }else{ rune= "discharged"; } } table.addLine("Guard rune", rune, 2); table.collapse(); return table; } private static StringTable factionSettlement(SagaPlayer sagaPlayer) { StringTable table = new StringTable(new ColourLoop().addColor(normal1).addColor(normal2)); // Faction and settlement: String faction = "none"; if(sagaPlayer.getFaction() != null) faction = sagaPlayer.getFaction().getName(); String settlement = "none"; if(sagaPlayer.getBundle() != null) settlement = sagaPlayer.getBundle().getName(); table.addLine("faction", faction, 0); table.addLine("settlement", settlement, 2); // Rank and role: String rank = "none"; if(sagaPlayer.getRank() != null) rank = sagaPlayer.getRank().getName(); String role = "none"; if(sagaPlayer.getRole() != null) role = sagaPlayer.getRole().getName(); table.addLine("rank", rank, 0); table.addLine("role", role, 2); // Style: table.collapse(); return table; } private static StringTable abilities(SagaPlayer sagaPlayer) { StringTable table = new StringTable(new ColourLoop().addColor(normal1).addColor(normal2)); HashSet<Ability> allAbilities = sagaPlayer.getAbilities(); // Add abilities: if(allAbilities.size() > 0){ for (Ability ability : allAbilities) { String name = ability.getName() + " " + RomanNumeral.binaryToRoman(ability.getScore()); String status = ""; if(ability.getScore() <= 0){ name = unavailable + name; status = unavailable + "(" + requirements(ability.getDefinition(), 1) + ")"; } else{ if(ability.getCooldown() <= 0){ status = "ready"; }else{ status = ability.getCooldown() + "s"; } } table.addLine(name, status, 0); } } // No abilities: else{ table.addLine("-"); } table.collapse(); return table; } public static String requirements(AbilityDefinition ability, Integer abilityScore) { StringBuffer result = new StringBuffer(); // Attributes: ArrayList<String> attributeNames = AttributeConfiguration.config().getAttributeNames(); for (String attribute : attributeNames) { Integer reqScore = ability.getAttrReq(attribute, abilityScore); if(reqScore <= 0) continue; if(result.length() > 0) result.append(", "); result.append(GeneralMessages.attrAbrev(attribute) + " " + reqScore); } // Buildings: Collection<String> bldgNames = SettlementConfiguration.config().getBuildingNames(); for (String bldgName : bldgNames) { Integer reqScore = ability.getBldgReq(bldgName, abilityScore); if(reqScore <= 0) continue; if(result.length() > 0) result.append(", "); result.append(bldgName + " " + RomanNumeral.binaryToRoman(reqScore)); } return result.toString(); } public static StringTable invites(SagaPlayer sagaPlayer) { StringTable table = new StringTable(new ColourLoop().addColor(normal1).addColor(normal2)); // Table size: ArrayList<Double> widths = new ArrayList<Double>(); widths.add(28.5); widths.add(28.5); table.setCustomWidths(widths); // Factions: table.addLine(GeneralMessages.columnTitle("faction invites"), 0); ArrayList<Faction> factions = getFactions(sagaPlayer.getFactionInvites()); for (Faction faction : factions) { table.addLine(faction.getName(), 0); } if(factions.size() == 0){ table.addLine("-", 0); } // Chunk groups: table.addLine(GeneralMessages.columnTitle("settlement invites"), 1); ArrayList<Bundle> bundles = getSettlements(sagaPlayer.getBundleInvites()); for (Bundle bundle : bundles) { table.addLine(bundle.getName(), 1); } if(bundles.size() == 0){ table.addLine("-", 1); } return table; } private static ArrayList<Faction> getFactions(ArrayList<Integer> ids) { // Faction invites: ArrayList<Faction> factions = new ArrayList<Faction>(); if(ids.size() > 0){ for (int i = 0; i < ids.size(); i++) { Faction faction = FactionManager.manager().getFaction(ids.get(i)); if( faction != null ){ factions.add(faction); }else{ ids.remove(i); i--; } } } return factions; } private static ArrayList<Bundle> getSettlements(ArrayList<Integer> ids) { // Faction invites: ArrayList<Bundle> bundles = new ArrayList<Bundle>(); if(ids.size() > 0){ for (int i = 0; i < ids.size(); i++) { Bundle faction = BundleManager.manager().getBundle(ids.get(i)); if( faction != null ){ bundles.add(faction); }else{ ids.remove(i); i--; } } } return bundles; } // Attribute points: public static String gaineAttributePoints(Integer amount) { return veryPositive + "Gained " + amount + " attribute points."; } }
true
true
private static StringTable attributesLevels(SagaPlayer sagaPlayer) { StringTable table = new StringTable(new ColourLoop().addColor(normal1).addColor(normal2)); DecimalFormat format = new DecimalFormat("00"); // Attributes: ArrayList<String> attrNames = AttributeConfiguration.config().getAttributeNames(); for (String attrName : attrNames) { Integer attrBonus = sagaPlayer.getAttrScoreBonus(attrName); Integer attrScore = sagaPlayer.getRawAttributeScore(attrName); String scoreCurr = format.format(attrScore + attrBonus); String scoreMax = format.format(AttributeConfiguration.config().maxAttributeScore + attrBonus); String score = scoreCurr + "/" + scoreMax; // Colours: if(attrBonus > 0){ score = positive + score; } else if(attrBonus < 0){ score = negative + score; } table.addLine(attrName, score, 0); } // Health: table.addLine("Health", TextUtil.round((double)sagaPlayer.getHealth(), 0) + "/" + TextUtil.round((double)sagaPlayer.getTotalHealth(), 0), 2); String attrPoints = sagaPlayer.getUsedAttributePoints() + "/" + sagaPlayer.getAvailableAttributePoints(); if(sagaPlayer.getRemainingAttributePoints() < 0){ attrPoints = ChatColor.DARK_RED + attrPoints; } else if (sagaPlayer.getRemainingAttributePoints() > 0) { attrPoints = ChatColor.DARK_GREEN + attrPoints; } table.addLine("Attributes", attrPoints, 2); // Exp: table.addLine("Progress", (int)(100.0 * sagaPlayer.getRemainingExp() / ExperienceConfiguration.config().getAttributePointCost()) + "%", 2); // Wallet: table.addLine("Wallet", EconomyMessages.coins(EconomyDependency.getCoins(sagaPlayer)), 2); // Guard rune: GuardianRune guardRune = sagaPlayer.getGuardRune(); String rune = ""; if(!guardRune.isEnabled()){ rune = "disabled"; }else{ if(guardRune.isCharged()){ rune= "charged"; }else{ rune= "discharged"; } } table.addLine("Guard rune", rune, 2); table.collapse(); return table; }
private static StringTable attributesLevels(SagaPlayer sagaPlayer) { StringTable table = new StringTable(new ColourLoop().addColor(normal1).addColor(normal2)); DecimalFormat format = new DecimalFormat("00"); // Attributes: ArrayList<String> attrNames = AttributeConfiguration.config().getAttributeNames(); for (String attrName : attrNames) { Integer attrBonus = sagaPlayer.getAttrScoreBonus(attrName); Integer attrScore = sagaPlayer.getRawAttributeScore(attrName); String scoreCurr = format.format(attrScore + attrBonus); String scoreMax = format.format(AttributeConfiguration.config().maxAttributeScore + attrBonus); String score = scoreCurr + "/" + scoreMax; // Colours: if(attrBonus > 0){ score = positive + score; } else if(attrBonus < 0){ score = negative + score; } table.addLine(attrName, score, 0); } // Health: table.addLine("Health", TextUtil.round((double)sagaPlayer.getHealth(), 0) + "/" + TextUtil.round((double)sagaPlayer.getTotalHealth(), 0), 2); String attrPoints = sagaPlayer.getUsedAttributePoints() + "/" + sagaPlayer.getAvailableAttributePoints(); if(sagaPlayer.getRemainingAttributePoints() < 0){ attrPoints = ChatColor.DARK_RED + attrPoints; } else if (sagaPlayer.getRemainingAttributePoints() > 0) { attrPoints = ChatColor.DARK_GREEN + attrPoints; } table.addLine("Attributes", attrPoints, 2); // Exp: table.addLine("Progress", (int)(100.0 - 100.0 * sagaPlayer.getRemainingExp() / ExperienceConfiguration.config().getAttributePointCost()) + "%", 2); // Wallet: table.addLine("Wallet", EconomyMessages.coins(EconomyDependency.getCoins(sagaPlayer)), 2); // Guard rune: GuardianRune guardRune = sagaPlayer.getGuardRune(); String rune = ""; if(!guardRune.isEnabled()){ rune = "disabled"; }else{ if(guardRune.isCharged()){ rune= "charged"; }else{ rune= "discharged"; } } table.addLine("Guard rune", rune, 2); table.collapse(); return table; }
diff --git a/src/com/fsck/k9/view/SingleMessageView.java b/src/com/fsck/k9/view/SingleMessageView.java index 5b84fc57..29e0d912 100644 --- a/src/com/fsck/k9/view/SingleMessageView.java +++ b/src/com/fsck/k9/view/SingleMessageView.java @@ -1,313 +1,316 @@ package com.fsck.k9.view; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.database.Cursor; import android.net.Uri; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import com.fsck.k9.Account; import com.fsck.k9.K9; import com.fsck.k9.R; import com.fsck.k9.controller.MessagingController; import com.fsck.k9.controller.MessagingListener; import com.fsck.k9.crypto.CryptoProvider; import com.fsck.k9.crypto.PgpData; import com.fsck.k9.helper.Contacts; import com.fsck.k9.helper.Utility; import com.fsck.k9.mail.*; import com.fsck.k9.mail.internet.MimeUtility; import com.fsck.k9.mail.store.LocalStore; import java.util.List; /** */ public class SingleMessageView extends LinearLayout { private boolean mScreenReaderEnabled; private MessageCryptoView mCryptoView; private MessageWebView mMessageContentView; private AccessibleWebView mAccessibleMessageContentView; private MessageHeader mHeaderContainer; private LinearLayout mAttachments; private View mShowPicturesSection; private boolean mShowPictures; private Button mDownloadRemainder; private LayoutInflater mInflater; private Contacts mContacts; private AttachmentView.AttachmentFileDownloadCallback attachmentCallback; public void initialize(Activity activity) { mMessageContentView = (MessageWebView) findViewById(R.id.message_content); mAccessibleMessageContentView = (AccessibleWebView) findViewById(R.id.accessible_message_content); mAttachments = (LinearLayout) findViewById(R.id.attachments); mHeaderContainer = (MessageHeader) findViewById(R.id.header_container); mCryptoView = (MessageCryptoView) findViewById(R.id.layout_decrypt); mCryptoView.setActivity(activity); mCryptoView.setupChildViews(); mShowPicturesSection = findViewById(R.id.show_pictures_section); mShowPictures = false; mContacts = Contacts.getInstance(activity); mInflater = activity.getLayoutInflater(); mDownloadRemainder = (Button) findViewById(R.id.download_remainder); mMessageContentView.configure(); mAttachments.setVisibility(View.GONE); if (isScreenReaderActive(activity)) { mAccessibleMessageContentView.setVisibility(View.VISIBLE); mMessageContentView.setVisibility(View.GONE); mScreenReaderEnabled = true; } else { mAccessibleMessageContentView.setVisibility(View.GONE); mMessageContentView.setVisibility(View.VISIBLE); mScreenReaderEnabled = false; } } public SingleMessageView(Context context, AttributeSet attrs) { super(context, attrs); } private boolean isScreenReaderActive(Activity activity) { final String SCREENREADER_INTENT_ACTION = "android.accessibilityservice.AccessibilityService"; final String SCREENREADER_INTENT_CATEGORY = "android.accessibilityservice.category.FEEDBACK_SPOKEN"; // Restrict the set of intents to only accessibility services that have // the category FEEDBACK_SPOKEN (aka, screen readers). Intent screenReaderIntent = new Intent(SCREENREADER_INTENT_ACTION); screenReaderIntent.addCategory(SCREENREADER_INTENT_CATEGORY); List<ResolveInfo> screenReaders = activity.getPackageManager().queryIntentServices( screenReaderIntent, 0); ContentResolver cr = activity.getContentResolver(); Cursor cursor = null; int status = 0; for (ResolveInfo screenReader : screenReaders) { // All screen readers are expected to implement a content provider // that responds to // content://<nameofpackage>.providers.StatusProvider cursor = cr.query(Uri.parse("content://" + screenReader.serviceInfo.packageName + ".providers.StatusProvider"), null, null, null, null); if (cursor != null) { cursor.moveToFirst(); // These content providers use a special cursor that only has // one element, // an integer that is 1 if the screen reader is running. status = cursor.getInt(0); cursor.close(); if (status == 1) { return true; } } } return false; } public boolean showPictures() { return mShowPictures; } public void setShowPictures(Boolean show) { mShowPictures = show; } /** * Enable/disable image loading of the WebView. But always hide the * "Show pictures" button! * * @param enable true, if (network) images should be loaded. * false, otherwise. */ public void setLoadPictures(boolean enable) { mMessageContentView.blockNetworkData(!enable); setShowPictures(enable); showShowPicturesSection(false); } public Button downloadRemainderButton() { return mDownloadRemainder; } public void showShowPicturesSection(boolean show) { mShowPicturesSection.setVisibility(show ? View.VISIBLE : View.GONE); } public void setHeaders(final Message message, Account account) { try { mHeaderContainer.populate(message, account); } catch (Exception me) { Log.e(K9.LOG_TAG, "setHeaders - error", me); } } public void setShowDownloadButton(Message message) { if (message.isSet(Flag.X_DOWNLOADED_FULL)) { mDownloadRemainder.setVisibility(View.GONE); } else { mDownloadRemainder.setEnabled(true); mDownloadRemainder.setVisibility(View.VISIBLE); } } public void setOnFlagListener(OnClickListener listener) { mHeaderContainer.setOnFlagListener(listener); } public void showAllHeaders() { mHeaderContainer.onShowAdditionalHeaders(); } public boolean additionalHeadersVisible() { return mHeaderContainer.additionalHeadersVisible(); } public void displayMessageBody(Account account, String folder, String uid, Message message, PgpData pgpData) throws MessagingException { // TODO - really this code path? this is an odd place to put it removeAllAttachments(); String type; String text = pgpData.getDecryptedData(); if (text != null) { type = "text/plain"; } else { // getTextForDisplay() always returns HTML-ified content. text = ((LocalStore.LocalMessage) message).getTextForDisplay(); type = "text/html"; } if (text != null) { final String emailText = text; final String contentType = type; loadBodyFromText(account.getCryptoProvider(), pgpData, message, emailText, contentType); // If the message contains external pictures and the "Show pictures" // button wasn't already pressed, see if the user's preferences has us // showing them anyway. if (Utility.hasExternalImages(text) && !showPictures()) { + Address[] from = message.getFrom(); if ((account.getShowPictures() == Account.ShowPictures.ALWAYS) || ((account.getShowPictures() == Account.ShowPictures.ONLY_FROM_CONTACTS) && - mContacts.isInContacts(message.getFrom()[0].getAddress()))) { + // Make sure we have at least one from address + (from != null && from.length > 0) && + mContacts.isInContacts(from[0].getAddress()))) { setLoadPictures(true); } else { showShowPicturesSection(true); } } } else { loadBodyFromUrl("file:///android_asset/empty.html"); } } public void loadBodyFromUrl(String url) { mMessageContentView.loadUrl(url); mCryptoView.hide(); } public void loadBodyFromText(CryptoProvider cryptoProvider, PgpData pgpData, Message message, String emailText, String contentType) { if (mScreenReaderEnabled) { mAccessibleMessageContentView.loadDataWithBaseURL("http://", emailText, contentType, "utf-8", null); } else { mMessageContentView.loadDataWithBaseURL("http://", emailText, contentType, "utf-8", null); mMessageContentView.scrollTo(0, 0); } updateCryptoLayout(cryptoProvider, pgpData, message); } public void updateCryptoLayout(CryptoProvider cp, PgpData pgpData, Message message) { mCryptoView.updateLayout(cp, pgpData, message); } public void setAttachmentsEnabled(boolean enabled) { for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) { AttachmentView attachment = (AttachmentView) mAttachments.getChildAt(i); attachment.viewButton.setEnabled(enabled); attachment.downloadButton.setEnabled(enabled); } } public void removeAllAttachments() { for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) { mAttachments.removeView(mAttachments.getChildAt(i)); } } public void renderAttachments(Part part, int depth, Message message, Account account, MessagingController controller, MessagingListener listener) throws MessagingException { if (part.getBody() instanceof Multipart) { Multipart mp = (Multipart) part.getBody(); for (int i = 0; i < mp.getCount(); i++) { renderAttachments(mp.getBodyPart(i), depth + 1, message, account, controller, listener); } } else if (part instanceof LocalStore.LocalAttachmentBodyPart) { String contentDisposition = MimeUtility.unfoldAndDecode(part.getDisposition()); // Inline parts with a content-id are almost certainly components of an HTML message // not attachments. Don't show attachment download buttons for them. if (contentDisposition != null && MimeUtility.getHeaderParameter(contentDisposition, null).matches("^(?i:inline)") && part.getHeader("Content-ID") != null) { return; } AttachmentView view = (AttachmentView)mInflater.inflate(R.layout.message_view_attachment, null); view.setCallback(attachmentCallback); if (view.populateFromPart(part, message, account, controller, listener)) { addAttachment(view); } } } public void addAttachment(View attachmentView) { mAttachments.addView(attachmentView); mAttachments.setVisibility(View.VISIBLE); } public void zoom(KeyEvent event) { if (mScreenReaderEnabled) { mAccessibleMessageContentView.zoomIn(); } else { if (event.isShiftPressed()) { mMessageContentView.zoomIn(); } else { mMessageContentView.zoomOut(); } } } public void beginSelectingText() { mMessageContentView.emulateShiftHeld(); } public void resetView() { setLoadPictures(false); mMessageContentView.scrollTo(0, 0); mHeaderContainer.setVisibility(View.GONE); mMessageContentView.clearView(); mAttachments.removeAllViews(); } public AttachmentView.AttachmentFileDownloadCallback getAttachmentCallback() { return attachmentCallback; } public void setAttachmentCallback( AttachmentView.AttachmentFileDownloadCallback attachmentCallback) { this.attachmentCallback = attachmentCallback; } }
false
true
public void displayMessageBody(Account account, String folder, String uid, Message message, PgpData pgpData) throws MessagingException { // TODO - really this code path? this is an odd place to put it removeAllAttachments(); String type; String text = pgpData.getDecryptedData(); if (text != null) { type = "text/plain"; } else { // getTextForDisplay() always returns HTML-ified content. text = ((LocalStore.LocalMessage) message).getTextForDisplay(); type = "text/html"; } if (text != null) { final String emailText = text; final String contentType = type; loadBodyFromText(account.getCryptoProvider(), pgpData, message, emailText, contentType); // If the message contains external pictures and the "Show pictures" // button wasn't already pressed, see if the user's preferences has us // showing them anyway. if (Utility.hasExternalImages(text) && !showPictures()) { if ((account.getShowPictures() == Account.ShowPictures.ALWAYS) || ((account.getShowPictures() == Account.ShowPictures.ONLY_FROM_CONTACTS) && mContacts.isInContacts(message.getFrom()[0].getAddress()))) { setLoadPictures(true); } else { showShowPicturesSection(true); } } } else { loadBodyFromUrl("file:///android_asset/empty.html"); } }
public void displayMessageBody(Account account, String folder, String uid, Message message, PgpData pgpData) throws MessagingException { // TODO - really this code path? this is an odd place to put it removeAllAttachments(); String type; String text = pgpData.getDecryptedData(); if (text != null) { type = "text/plain"; } else { // getTextForDisplay() always returns HTML-ified content. text = ((LocalStore.LocalMessage) message).getTextForDisplay(); type = "text/html"; } if (text != null) { final String emailText = text; final String contentType = type; loadBodyFromText(account.getCryptoProvider(), pgpData, message, emailText, contentType); // If the message contains external pictures and the "Show pictures" // button wasn't already pressed, see if the user's preferences has us // showing them anyway. if (Utility.hasExternalImages(text) && !showPictures()) { Address[] from = message.getFrom(); if ((account.getShowPictures() == Account.ShowPictures.ALWAYS) || ((account.getShowPictures() == Account.ShowPictures.ONLY_FROM_CONTACTS) && // Make sure we have at least one from address (from != null && from.length > 0) && mContacts.isInContacts(from[0].getAddress()))) { setLoadPictures(true); } else { showShowPicturesSection(true); } } } else { loadBodyFromUrl("file:///android_asset/empty.html"); } }
diff --git a/src/realms/welcome-admin/yanel/resources/show-realms/src/java/org/wyona/yanel/impl/resources/ShowRealms.java b/src/realms/welcome-admin/yanel/resources/show-realms/src/java/org/wyona/yanel/impl/resources/ShowRealms.java index eae7eb94b..0bb671c82 100644 --- a/src/realms/welcome-admin/yanel/resources/show-realms/src/java/org/wyona/yanel/impl/resources/ShowRealms.java +++ b/src/realms/welcome-admin/yanel/resources/show-realms/src/java/org/wyona/yanel/impl/resources/ShowRealms.java @@ -1,211 +1,212 @@ /* * Copyright 2006 Wyona * * 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.wyona.org/licenses/APACHE-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.wyona.yanel.impl.resources; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.util.Calendar; import java.io.StringBufferInputStream; //import java.io.StringReader; //import java.util.Enumeration; //import java.util.HashMap; //import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.log4j.Category; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceTypeDefinition; import org.wyona.yanel.core.ResourceTypeRegistry; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.map.Realm; import org.wyona.yanel.core.util.PathUtil; import org.wyona.yanel.core.util.ResourceAttributeHelper; import org.wyona.yarep.core.NoSuchNodeException; import org.wyona.yarep.core.Repository; import org.wyona.yarep.core.RepositoryFactory; import org.wyona.yanel.core.Yanel; import org.wyona.yarep.util.RepoPath; import org.wyona.yarep.util.YarepUtil; /** * */ public class ShowRealms extends Resource implements ViewableV2 { private static Category log = Category.getInstance(ShowRealms.class); /** * */ public ShowRealms() { } /** * */ public ViewDescriptor[] getViewDescriptors() { return null; } /** * */ public View getView(String viewId) throws Exception { View defaultView = new View(); defaultView.setMimeType("application/xml"); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); defaultView.setInputStream(new java.io.StringBufferInputStream(sb .toString())); String servletContext = request.getContextPath(); Repository contentRepo = getRealm().getRepository(); sb.append("<yanel-info>"); sb.append("<realms>"); Realm[] realms = yanel.getRealmConfiguration().getRealms(); for (int i = 0; i < realms.length; i++) { sb.append("<realm>"); sb.append("<name>" + realms[i].getName() + "</name>"); sb.append("<id>" + realms[i].getID() + "</id>"); sb.append("<mountpoint>" + realms[i].getMountPoint() + "</mountpoint>"); //sb.append("<description>" + realms[i].getDescription() + "</description>"); sb.append("</realm>"); } sb.append("</realms>"); sb.append("<resourcetypes>"); ResourceTypeRegistry rtr = new ResourceTypeRegistry(); ResourceTypeDefinition[] rtds = rtr.getResourceTypeDefinitions(); for (int i = 0; i < rtds.length; i++) { sb.append("<resourcetype>"); try { - String rtYanelHtdocPath = PathUtil.getGlobalHtdocsPath(this) + yanel.getReservedPrefix() + "/resource-types/" + rtds[i].getResourceTypeNamespace() + "::" + rtds[i].getResourceTypeLocalName() + "/" + yanel.getReservedPrefix() + "/"; + //String rtYanelHtdocPath = PathUtil.getGlobalHtdocsPath(this) + "/resource-types/" + rtds[i].getResourceTypeNamespace() + "::" + rtds[i].getResourceTypeLocalName() + "/" + yanel.getReservedPrefix() + "/"; + String rtYanelHtdocPath = PathUtil.getResourcesHtdocsPathURLencoded(this) + yanel.getReservedPrefix() + "/"; sb.append("<localname>" + rtds[i].getResourceTypeLocalName() + "</localname>"); sb.append("<description>" + rtds[i].getResourceTypeDescription() + "</description>"); sb.append("<icon alt=\"" + rtds[i].getResourceTypeLocalName() + " resource-type\">" + rtYanelHtdocPath + "icons/32x32/rt-icon.png" + "</icon>"); sb.append("<docu>" + rtYanelHtdocPath + "doc/index.html" + "</docu>"); } catch(Exception e) { log.error(e); } sb.append("</resourcetype>"); } sb.append("</resourcetypes>"); sb.append("</yanel-info>"); Transformer transformer = TransformerFactory.newInstance() .newTransformer(getXSLTStreamSource(getPath(), contentRepo)); transformer.setParameter("yanel.path.name", PathUtil.getName(getPath())); transformer.setParameter("servlet.context", servletContext); transformer.setParameter("yanel.path", getPath()); transformer.setParameter("yanel.back2context", backToRoot(getPath(), "")); transformer.setParameter("yarep.back2realm", backToRoot(getPath(), "")); // TODO: Is this the best way to generate an InputStream from an // OutputStream? java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); transformer.transform(new StreamSource(new java.io.StringBufferInputStream(sb.toString())), new StreamResult(baos)); defaultView.setInputStream(new java.io.ByteArrayInputStream(baos .toByteArray())); defaultView.setMimeType(getMimeType(getPath())); defaultView.setInputStream(new java.io.ByteArrayInputStream(baos .toByteArray())); defaultView.setMimeType("application/xhtml+xml"); return defaultView; } /** * */ private StreamSource getXSLTStreamSource(String path, Repository repo) throws Exception { String xsltPath = getXSLTPath(); if (xsltPath != null) { return new StreamSource(repo .getInputStream(new org.wyona.yarep.core.Path(getXSLTPath()))); } else { File xsltFile = org.wyona.commons.io.FileUtil.file(rtd .getConfigFile().getParentFile().getAbsolutePath(), "xslt" + File.separator + "info2xhtml.xsl"); log.error("DEBUG: XSLT file: " + xsltFile); return new StreamSource(xsltFile); } } /** * */ private String getXSLTPath() throws Exception { return getConfiguration().getProperty("xslt"); //return getRTI().getProperty("xslt"); } /** * */ public String getMimeType(String path) throws Exception { String mimeType = getConfiguration().getProperty("mime-type"); //String mimeType = getRTI().getProperty("mime-type"); if (mimeType == null) mimeType = "application/xhtml+xml"; return mimeType; } /** * */ private String backToRoot(String path, String backToRoot) { String parent = PathUtil.getParent(path); if (parent != null && !isRoot(parent)) { return backToRoot(parent, backToRoot + "../"); } return backToRoot; } /** * */ private boolean isRoot(String path) { if (path.equals(File.separator)) return true; return false; } public boolean exists() throws Exception { // TODO Auto-generated method stub return false; } public long getSize() throws Exception { // TODO Auto-generated method stub return 0; } }
true
true
public View getView(String viewId) throws Exception { View defaultView = new View(); defaultView.setMimeType("application/xml"); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); defaultView.setInputStream(new java.io.StringBufferInputStream(sb .toString())); String servletContext = request.getContextPath(); Repository contentRepo = getRealm().getRepository(); sb.append("<yanel-info>"); sb.append("<realms>"); Realm[] realms = yanel.getRealmConfiguration().getRealms(); for (int i = 0; i < realms.length; i++) { sb.append("<realm>"); sb.append("<name>" + realms[i].getName() + "</name>"); sb.append("<id>" + realms[i].getID() + "</id>"); sb.append("<mountpoint>" + realms[i].getMountPoint() + "</mountpoint>"); //sb.append("<description>" + realms[i].getDescription() + "</description>"); sb.append("</realm>"); } sb.append("</realms>"); sb.append("<resourcetypes>"); ResourceTypeRegistry rtr = new ResourceTypeRegistry(); ResourceTypeDefinition[] rtds = rtr.getResourceTypeDefinitions(); for (int i = 0; i < rtds.length; i++) { sb.append("<resourcetype>"); try { String rtYanelHtdocPath = PathUtil.getGlobalHtdocsPath(this) + yanel.getReservedPrefix() + "/resource-types/" + rtds[i].getResourceTypeNamespace() + "::" + rtds[i].getResourceTypeLocalName() + "/" + yanel.getReservedPrefix() + "/"; sb.append("<localname>" + rtds[i].getResourceTypeLocalName() + "</localname>"); sb.append("<description>" + rtds[i].getResourceTypeDescription() + "</description>"); sb.append("<icon alt=\"" + rtds[i].getResourceTypeLocalName() + " resource-type\">" + rtYanelHtdocPath + "icons/32x32/rt-icon.png" + "</icon>"); sb.append("<docu>" + rtYanelHtdocPath + "doc/index.html" + "</docu>"); } catch(Exception e) { log.error(e); } sb.append("</resourcetype>"); } sb.append("</resourcetypes>"); sb.append("</yanel-info>"); Transformer transformer = TransformerFactory.newInstance() .newTransformer(getXSLTStreamSource(getPath(), contentRepo)); transformer.setParameter("yanel.path.name", PathUtil.getName(getPath())); transformer.setParameter("servlet.context", servletContext); transformer.setParameter("yanel.path", getPath()); transformer.setParameter("yanel.back2context", backToRoot(getPath(), "")); transformer.setParameter("yarep.back2realm", backToRoot(getPath(), "")); // TODO: Is this the best way to generate an InputStream from an // OutputStream? java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); transformer.transform(new StreamSource(new java.io.StringBufferInputStream(sb.toString())), new StreamResult(baos)); defaultView.setInputStream(new java.io.ByteArrayInputStream(baos .toByteArray())); defaultView.setMimeType(getMimeType(getPath())); defaultView.setInputStream(new java.io.ByteArrayInputStream(baos .toByteArray())); defaultView.setMimeType("application/xhtml+xml"); return defaultView; }
public View getView(String viewId) throws Exception { View defaultView = new View(); defaultView.setMimeType("application/xml"); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); defaultView.setInputStream(new java.io.StringBufferInputStream(sb .toString())); String servletContext = request.getContextPath(); Repository contentRepo = getRealm().getRepository(); sb.append("<yanel-info>"); sb.append("<realms>"); Realm[] realms = yanel.getRealmConfiguration().getRealms(); for (int i = 0; i < realms.length; i++) { sb.append("<realm>"); sb.append("<name>" + realms[i].getName() + "</name>"); sb.append("<id>" + realms[i].getID() + "</id>"); sb.append("<mountpoint>" + realms[i].getMountPoint() + "</mountpoint>"); //sb.append("<description>" + realms[i].getDescription() + "</description>"); sb.append("</realm>"); } sb.append("</realms>"); sb.append("<resourcetypes>"); ResourceTypeRegistry rtr = new ResourceTypeRegistry(); ResourceTypeDefinition[] rtds = rtr.getResourceTypeDefinitions(); for (int i = 0; i < rtds.length; i++) { sb.append("<resourcetype>"); try { //String rtYanelHtdocPath = PathUtil.getGlobalHtdocsPath(this) + "/resource-types/" + rtds[i].getResourceTypeNamespace() + "::" + rtds[i].getResourceTypeLocalName() + "/" + yanel.getReservedPrefix() + "/"; String rtYanelHtdocPath = PathUtil.getResourcesHtdocsPathURLencoded(this) + yanel.getReservedPrefix() + "/"; sb.append("<localname>" + rtds[i].getResourceTypeLocalName() + "</localname>"); sb.append("<description>" + rtds[i].getResourceTypeDescription() + "</description>"); sb.append("<icon alt=\"" + rtds[i].getResourceTypeLocalName() + " resource-type\">" + rtYanelHtdocPath + "icons/32x32/rt-icon.png" + "</icon>"); sb.append("<docu>" + rtYanelHtdocPath + "doc/index.html" + "</docu>"); } catch(Exception e) { log.error(e); } sb.append("</resourcetype>"); } sb.append("</resourcetypes>"); sb.append("</yanel-info>"); Transformer transformer = TransformerFactory.newInstance() .newTransformer(getXSLTStreamSource(getPath(), contentRepo)); transformer.setParameter("yanel.path.name", PathUtil.getName(getPath())); transformer.setParameter("servlet.context", servletContext); transformer.setParameter("yanel.path", getPath()); transformer.setParameter("yanel.back2context", backToRoot(getPath(), "")); transformer.setParameter("yarep.back2realm", backToRoot(getPath(), "")); // TODO: Is this the best way to generate an InputStream from an // OutputStream? java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); transformer.transform(new StreamSource(new java.io.StringBufferInputStream(sb.toString())), new StreamResult(baos)); defaultView.setInputStream(new java.io.ByteArrayInputStream(baos .toByteArray())); defaultView.setMimeType(getMimeType(getPath())); defaultView.setInputStream(new java.io.ByteArrayInputStream(baos .toByteArray())); defaultView.setMimeType("application/xhtml+xml"); return defaultView; }
diff --git a/jython/src/org/python/core/PyModule.java b/jython/src/org/python/core/PyModule.java index 5ccef86c..643f3087 100644 --- a/jython/src/org/python/core/PyModule.java +++ b/jython/src/org/python/core/PyModule.java @@ -1,182 +1,185 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; import org.python.expose.ExposedDelete; import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; import org.python.expose.ExposedSet; import org.python.expose.ExposedType; /** * The Python Module object. * */ @ExposedType(name = "module") public class PyModule extends PyObject { private final PyObject moduleDoc = new PyString( "module(name[, doc])\n" + "\n" + "Create a module object.\n" + "The name must be a string; the optional doc argument can have any type."); /** The module's mutable dictionary */ @ExposedGet public PyObject __dict__; public PyModule() { super(); } public PyModule(PyType subType) { super(subType); } public PyModule(PyType subType, String name) { super(subType); module___init__(new PyString(name), Py.None); } public PyModule(String name) { this(name, null); } public PyModule(String name, PyObject dict) { super(); __dict__ = dict; module___init__(new PyString(name), Py.None); } @ExposedNew @ExposedMethod final void module___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("__init__", args, keywords, new String[] {"name", "doc"}); PyObject name = ap.getPyObject(0); PyObject docs = ap.getPyObject(1, Py.None); module___init__(name, docs); } private void module___init__(PyObject name, PyObject doc) { ensureDict(); __dict__.__setitem__("__name__", name); __dict__.__setitem__("__doc__", doc); } public PyObject fastGetDict() { return __dict__; } public PyObject getDict() { return __dict__; } @ExposedSet(name = "__dict__") public void setDict(PyObject newDict) { throw Py.TypeError("readonly attribute"); } @ExposedDelete(name = "__dict__") public void delDict() { throw Py.TypeError("readonly attribute"); } protected PyObject impAttr(String name) { + if (__dict__ == null) { + return null; + } PyObject path = __dict__.__finditem__("__path__"); PyObject pyName = __dict__.__finditem__("__name__"); if (path == null || pyName == null) { return null; } PyObject attr = null; String fullName = (pyName.__str__().toString() + '.' + name).intern(); if (path == Py.None) { // XXX: disabled //attr = imp.loadFromClassLoader(fullName, // Py.getSystemState().getClassLoader()); } else if (path instanceof PyList) { attr = imp.find_module(name, fullName, (PyList)path); } else { throw Py.TypeError("__path__ must be list or None"); } if (attr == null) { attr = PySystemState.packageManager.lookupName(fullName); } if (attr != null) { // Allow a package component to change its own meaning PyObject found = Py.getSystemState().modules.__finditem__(fullName); if (found != null) { attr = found; } __dict__.__setitem__(name, attr); return attr; } return null; } @Override public PyObject __findattr_ex__(String name) { PyObject attr=super.__findattr_ex__(name); if (attr!=null) return attr; return impAttr(name); } public void __setattr__(String name, PyObject value) { module___setattr__(name, value); } @ExposedMethod final void module___setattr__(String name, PyObject value) { if (name != "__dict__") { ensureDict(); } super.__setattr__(name, value); } public void __delattr__(String name) { module___delattr__(name); } @ExposedMethod final void module___delattr__(String name) { super.__delattr__(name); } public String toString() { return module_toString(); } @ExposedMethod(names = {"__repr__"}) final String module_toString() { PyObject name = null; PyObject filename = null; if (__dict__ != null) { name = __dict__.__finditem__("__name__"); filename = __dict__.__finditem__("__file__"); } if (name == null) { name = new PyString("?"); } if (filename == null) { return String.format("<module '%s' (built-in)>", name); } return String.format("<module '%s' from '%s'>", name, filename); } public PyObject __dir__() { if (__dict__ == null) { throw Py.TypeError("module.__dict__ is not a dictionary"); } return __dict__.invoke("keys"); } private void ensureDict() { if (__dict__ == null) { __dict__ = new PyStringMap(); } } }
true
true
protected PyObject impAttr(String name) { PyObject path = __dict__.__finditem__("__path__"); PyObject pyName = __dict__.__finditem__("__name__"); if (path == null || pyName == null) { return null; } PyObject attr = null; String fullName = (pyName.__str__().toString() + '.' + name).intern(); if (path == Py.None) { // XXX: disabled //attr = imp.loadFromClassLoader(fullName, // Py.getSystemState().getClassLoader()); } else if (path instanceof PyList) { attr = imp.find_module(name, fullName, (PyList)path); } else { throw Py.TypeError("__path__ must be list or None"); } if (attr == null) { attr = PySystemState.packageManager.lookupName(fullName); } if (attr != null) { // Allow a package component to change its own meaning PyObject found = Py.getSystemState().modules.__finditem__(fullName); if (found != null) { attr = found; } __dict__.__setitem__(name, attr); return attr; } return null; }
protected PyObject impAttr(String name) { if (__dict__ == null) { return null; } PyObject path = __dict__.__finditem__("__path__"); PyObject pyName = __dict__.__finditem__("__name__"); if (path == null || pyName == null) { return null; } PyObject attr = null; String fullName = (pyName.__str__().toString() + '.' + name).intern(); if (path == Py.None) { // XXX: disabled //attr = imp.loadFromClassLoader(fullName, // Py.getSystemState().getClassLoader()); } else if (path instanceof PyList) { attr = imp.find_module(name, fullName, (PyList)path); } else { throw Py.TypeError("__path__ must be list or None"); } if (attr == null) { attr = PySystemState.packageManager.lookupName(fullName); } if (attr != null) { // Allow a package component to change its own meaning PyObject found = Py.getSystemState().modules.__finditem__(fullName); if (found != null) { attr = found; } __dict__.__setitem__(name, attr); return attr; } return null; }
diff --git a/lucene/src/java/org/apache/lucene/search/FieldDoc.java b/lucene/src/java/org/apache/lucene/search/FieldDoc.java index d45ff268..faf54a07 100644 --- a/lucene/src/java/org/apache/lucene/search/FieldDoc.java +++ b/lucene/src/java/org/apache/lucene/search/FieldDoc.java @@ -1,75 +1,75 @@ package org.apache.lucene.search; /** * 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. */ /** * Expert: A ScoreDoc which also contains information about * how to sort the referenced document. In addition to the * document number and score, this object contains an array * of values for the document from the field(s) used to sort. * For example, if the sort criteria was to sort by fields * "a", "b" then "c", the <code>fields</code> object array * will have three elements, corresponding respectively to * the term values for the document in fields "a", "b" and "c". * The class of each element in the array will be either * Integer, Float or String depending on the type of values * in the terms of each field. * * <p>Created: Feb 11, 2004 1:23:38 PM * * @since lucene 1.4 * @see ScoreDoc * @see TopFieldDocs */ public class FieldDoc extends ScoreDoc { /** Expert: The values which are used to sort the referenced document. * The order of these will match the original sort criteria given by a * Sort object. Each Object will be either an Integer, Float or String, * depending on the type of values in the terms of the original field. * @see Sort * @see Searcher#search(Query,Filter,int,Sort) */ public Comparable[] fields; /** Expert: Creates one of these objects with empty sort information. */ public FieldDoc (int doc, float score) { super (doc, score); } /** Expert: Creates one of these objects with the given sort information. */ public FieldDoc (int doc, float score, Comparable[] fields) { super (doc, score); this.fields = fields; } // A convenience method for debugging. @Override public String toString() { // super.toString returns the doc and score information, so just add the // fields information StringBuilder sb = new StringBuilder(super.toString()); sb.append("["); for (int i = 0; i < fields.length; i++) { sb.append(fields[i]).append(", "); } sb.setLength(sb.length() - 2); // discard last ", " sb.append("]"); - return super.toString(); + return sb.toString(); } }
true
true
public String toString() { // super.toString returns the doc and score information, so just add the // fields information StringBuilder sb = new StringBuilder(super.toString()); sb.append("["); for (int i = 0; i < fields.length; i++) { sb.append(fields[i]).append(", "); } sb.setLength(sb.length() - 2); // discard last ", " sb.append("]"); return super.toString(); }
public String toString() { // super.toString returns the doc and score information, so just add the // fields information StringBuilder sb = new StringBuilder(super.toString()); sb.append("["); for (int i = 0; i < fields.length; i++) { sb.append(fields[i]).append(", "); } sb.setLength(sb.length() - 2); // discard last ", " sb.append("]"); return sb.toString(); }
diff --git a/flexodesktop/modules/flexoviewpointmodeler/src/main/java/org/openflexo/vpm/drawingshema/DrawEdgeControl.java b/flexodesktop/modules/flexoviewpointmodeler/src/main/java/org/openflexo/vpm/drawingshema/DrawEdgeControl.java index e972af83a..8f985e856 100644 --- a/flexodesktop/modules/flexoviewpointmodeler/src/main/java/org/openflexo/vpm/drawingshema/DrawEdgeControl.java +++ b/flexodesktop/modules/flexoviewpointmodeler/src/main/java/org/openflexo/vpm/drawingshema/DrawEdgeControl.java @@ -1,206 +1,206 @@ /* * (c) Copyright 2010-2011 AgileBirds * * This file is part of OpenFlexo. * * OpenFlexo 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. * * OpenFlexo 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 OpenFlexo. If not, see <http://www.gnu.org/licenses/>. * */ package org.openflexo.vpm.drawingshema; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.util.Vector; import java.util.logging.Logger; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import org.openflexo.fge.ConnectorGraphicalRepresentation; import org.openflexo.fge.GraphicalRepresentation; import org.openflexo.fge.connectors.Connector.ConnectorType; import org.openflexo.fge.controller.CustomDragControlAction; import org.openflexo.fge.controller.DrawingController; import org.openflexo.fge.controller.MouseDragControl; import org.openflexo.foundation.viewpoint.AddConnector; import org.openflexo.foundation.viewpoint.ConnectorPatternRole; import org.openflexo.foundation.viewpoint.EditionAction; import org.openflexo.foundation.viewpoint.ExampleDrawingConnector; import org.openflexo.foundation.viewpoint.LinkScheme; import org.openflexo.foundation.viewpoint.action.AddExampleDrawingConnector; import org.openflexo.localization.FlexoLocalization; public class DrawEdgeControl extends MouseDragControl { private static final Logger logger = Logger.getLogger(DrawEdgeControl.class.getPackage().getName()); protected Point currentDraggingLocationInDrawingView = null; protected boolean drawEdge = false; protected CalcDrawingShapeGR fromShape = null; protected CalcDrawingShapeGR toShape = null; public DrawEdgeControl() { super("Draw edge", MouseButton.LEFT, false, true, false, false); // CTRL DRAG action = new DrawEdgeAction(); } protected class DrawEdgeAction extends CustomDragControlAction { @Override public boolean handleMousePressed(GraphicalRepresentation<?> graphicalRepresentation, DrawingController<?> controller, MouseEvent event) { if (graphicalRepresentation instanceof CalcDrawingShapeGR) { drawEdge = true; fromShape = (CalcDrawingShapeGR) graphicalRepresentation; ((CalcDrawingShemaView) controller.getDrawingView()).setDrawEdgeAction(this); return true; } return false; } @Override public boolean handleMouseReleased(GraphicalRepresentation<?> graphicalRepresentation, final DrawingController<?> controller, MouseEvent event, boolean isSignificativeDrag) { if (drawEdge && toShape != null) { if (fromShape.getDrawable().getViewPoint() != null) { Vector<LinkScheme> availableConnectors = fromShape.getDrawable().getViewPoint().getAllConnectors(); if (availableConnectors.size() > 0) { JPopupMenu popup = new JPopupMenu(); for (final LinkScheme linkScheme : availableConnectors) { JMenuItem menuItem = new JMenuItem(FlexoLocalization.localizedForKey(linkScheme.getLabel() != null ? linkScheme .getLabel() : linkScheme.getName())); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { for (EditionAction a : linkScheme.getActions()) { if (a instanceof AddConnector) { ConnectorPatternRole patternRole = ((AddConnector) a).getPatternRole(); logger.warning("Implement this !!!"); - String text = (String) patternRole.getLabel().getBindingValue(null); + String text = patternRole.getLabel().getBinding().toString();// Value(null); performAddConnector(controller, (ConnectorGraphicalRepresentation<?>) patternRole.getGraphicalRepresentation(), text); return; } } performAddDefaultConnector(controller); } }); popup.add(menuItem); } JMenuItem menuItem = new JMenuItem(FlexoLocalization.localizedForKey("graphical_connector_only")); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { performAddDefaultConnector(controller); } }); popup.add(menuItem); popup.show(event.getComponent(), event.getX(), event.getY()); return false; } else { performAddDefaultConnector(controller); } } drawEdge = false; fromShape = null; toShape = null; ((CalcDrawingShemaView) controller.getDrawingView()).setDrawEdgeAction(null); } return false; } private void performAddDefaultConnector(DrawingController<?> controller) { AddExampleDrawingConnector action = AddExampleDrawingConnector.actionType.makeNewAction(fromShape.getDrawable(), null, ((CalcDrawingShemaController) controller).getCEDController().getEditor()); action.toShape = toShape.getDrawable(); ConnectorGraphicalRepresentation<?> connectorGR = new ConnectorGraphicalRepresentation<ExampleDrawingConnector>(); connectorGR.setConnectorType(ConnectorType.LINE); connectorGR.setIsSelectable(true); connectorGR.setIsFocusable(true); connectorGR.setIsReadOnly(false); connectorGR.setForeground(((CalcDrawingShemaController) controller).getCurrentForegroundStyle()); connectorGR.setTextStyle(((CalcDrawingShemaController) controller).getCurrentTextStyle()); action.graphicalRepresentation = connectorGR; action.doAction(); drawEdge = false; fromShape = null; toShape = null; ((CalcDrawingShemaView) controller.getDrawingView()).setDrawEdgeAction(null); } private void performAddConnector(DrawingController<?> controller, ConnectorGraphicalRepresentation<?> connectorGR, String text) { AddExampleDrawingConnector action = AddExampleDrawingConnector.actionType.makeNewAction(fromShape.getDrawable(), null, ((CalcDrawingShemaController) controller).getCEDController().getEditor()); action.toShape = toShape.getDrawable(); action.graphicalRepresentation = connectorGR; action.newConnectorName = text; action.doAction(); drawEdge = false; fromShape = null; toShape = null; ((CalcDrawingShemaView) controller.getDrawingView()).setDrawEdgeAction(null); } @Override public boolean handleMouseDragged(GraphicalRepresentation<?> graphicalRepresentation, DrawingController<?> controller, MouseEvent event) { if (drawEdge) { GraphicalRepresentation<?> gr = controller.getDrawingView().getFocusRetriever().getFocusedObject(event); if (gr instanceof CalcDrawingShapeGR && gr != fromShape && !fromShape.getAncestors().contains(gr.getDrawable())) { toShape = (CalcDrawingShapeGR) gr; } else { toShape = null; } currentDraggingLocationInDrawingView = SwingUtilities.convertPoint((Component) event.getSource(), event.getPoint(), controller.getDrawingView()); controller.getDrawingView().repaint(); return true; } return false; } public void paint(Graphics g, DrawingController<?> controller) { if (drawEdge && currentDraggingLocationInDrawingView != null) { Point from = controller.getDrawingGraphicalRepresentation().convertRemoteNormalizedPointToLocalViewCoordinates( fromShape.getShape().getShape().getCenter(), fromShape, controller.getScale()); Point to = currentDraggingLocationInDrawingView; if (toShape != null) { to = controller.getDrawingGraphicalRepresentation().convertRemoteNormalizedPointToLocalViewCoordinates( toShape.getShape().getShape().getCenter(), toShape, controller.getScale()); g.setColor(Color.BLUE); } else { g.setColor(Color.RED); } g.drawLine(from.x, from.y, to.x, to.y); } } } }
true
true
public boolean handleMouseReleased(GraphicalRepresentation<?> graphicalRepresentation, final DrawingController<?> controller, MouseEvent event, boolean isSignificativeDrag) { if (drawEdge && toShape != null) { if (fromShape.getDrawable().getViewPoint() != null) { Vector<LinkScheme> availableConnectors = fromShape.getDrawable().getViewPoint().getAllConnectors(); if (availableConnectors.size() > 0) { JPopupMenu popup = new JPopupMenu(); for (final LinkScheme linkScheme : availableConnectors) { JMenuItem menuItem = new JMenuItem(FlexoLocalization.localizedForKey(linkScheme.getLabel() != null ? linkScheme .getLabel() : linkScheme.getName())); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { for (EditionAction a : linkScheme.getActions()) { if (a instanceof AddConnector) { ConnectorPatternRole patternRole = ((AddConnector) a).getPatternRole(); logger.warning("Implement this !!!"); String text = (String) patternRole.getLabel().getBindingValue(null); performAddConnector(controller, (ConnectorGraphicalRepresentation<?>) patternRole.getGraphicalRepresentation(), text); return; } } performAddDefaultConnector(controller); } }); popup.add(menuItem); } JMenuItem menuItem = new JMenuItem(FlexoLocalization.localizedForKey("graphical_connector_only")); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { performAddDefaultConnector(controller); } }); popup.add(menuItem); popup.show(event.getComponent(), event.getX(), event.getY()); return false; } else { performAddDefaultConnector(controller); } } drawEdge = false; fromShape = null; toShape = null; ((CalcDrawingShemaView) controller.getDrawingView()).setDrawEdgeAction(null); } return false; }
public boolean handleMouseReleased(GraphicalRepresentation<?> graphicalRepresentation, final DrawingController<?> controller, MouseEvent event, boolean isSignificativeDrag) { if (drawEdge && toShape != null) { if (fromShape.getDrawable().getViewPoint() != null) { Vector<LinkScheme> availableConnectors = fromShape.getDrawable().getViewPoint().getAllConnectors(); if (availableConnectors.size() > 0) { JPopupMenu popup = new JPopupMenu(); for (final LinkScheme linkScheme : availableConnectors) { JMenuItem menuItem = new JMenuItem(FlexoLocalization.localizedForKey(linkScheme.getLabel() != null ? linkScheme .getLabel() : linkScheme.getName())); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { for (EditionAction a : linkScheme.getActions()) { if (a instanceof AddConnector) { ConnectorPatternRole patternRole = ((AddConnector) a).getPatternRole(); logger.warning("Implement this !!!"); String text = patternRole.getLabel().getBinding().toString();// Value(null); performAddConnector(controller, (ConnectorGraphicalRepresentation<?>) patternRole.getGraphicalRepresentation(), text); return; } } performAddDefaultConnector(controller); } }); popup.add(menuItem); } JMenuItem menuItem = new JMenuItem(FlexoLocalization.localizedForKey("graphical_connector_only")); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { performAddDefaultConnector(controller); } }); popup.add(menuItem); popup.show(event.getComponent(), event.getX(), event.getY()); return false; } else { performAddDefaultConnector(controller); } } drawEdge = false; fromShape = null; toShape = null; ((CalcDrawingShemaView) controller.getDrawingView()).setDrawEdgeAction(null); } return false; }
diff --git a/Labor2/Principal.java b/Labor2/Principal.java index 6e29f8f..b8c766a 100644 --- a/Labor2/Principal.java +++ b/Labor2/Principal.java @@ -1,25 +1,25 @@ public class Principal { /** * @param args */ public static void main(String arg[]) { - int result=0; + int r=0; int a1=10; int a2=21; result= a1 + a2; - System.out.println("La suma de 10 + 20 es: " + result ); + System.out.println("La suma de 10 + 20 es: " + r ); } }
false
true
public static void main(String arg[]) { int result=0; int a1=10; int a2=21; result= a1 + a2; System.out.println("La suma de 10 + 20 es: " + result ); }
public static void main(String arg[]) { int r=0; int a1=10; int a2=21; result= a1 + a2; System.out.println("La suma de 10 + 20 es: " + r ); }
diff --git a/src/edu/purdue/cs252/lab6/userapp/ActivityDirectory.java b/src/edu/purdue/cs252/lab6/userapp/ActivityDirectory.java index ccd3038..08898b0 100644 --- a/src/edu/purdue/cs252/lab6/userapp/ActivityDirectory.java +++ b/src/edu/purdue/cs252/lab6/userapp/ActivityDirectory.java @@ -1,245 +1,246 @@ package edu.purdue.cs252.lab6.userapp; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.concurrent.ConcurrentHashMap; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Spinner; import android.widget.AdapterView.OnItemSelectedListener; import edu.purdue.cs252.lab6.DirectoryCommand; import edu.purdue.cs252.lab6.User; import edu.purdue.cs252.lab6.UserList; /* * Class that contains the directory information after the user has logged in * The layout displayed is directory.xml */ public class ActivityDirectory extends ListActivity { public static final int RESULT_INTERRUPTED = 1; public static final int RESULT_FAILED = 2; private DirectoryClient dc; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.directory); final VoipApp appState = (VoipApp) getApplicationContext(); final User user = appState.getUser(); Log.d("Login", user.getUserName()); final ConcurrentHashMap<String,User> userMap = new ConcurrentHashMap<String,User>(); final ArrayList<String> usernameList = new ArrayList<String>(); final Spinner s = (Spinner)findViewById(R.id.sort_by); final ArrayAdapter<CharSequence> a = ArrayAdapter.createFromResource( this, R.array.sort_by, android.R.layout.simple_spinner_item); s.setAdapter(a); // Create an ArrayAdapter to user for our ListActivity Comparator<String> comparator = Collections.reverseOrder(); Collections.sort(usernameList,comparator); final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, usernameList); final ListActivity thisActivity = this; thisActivity.setListAdapter(adapter); s.setOnItemSelectedListener(new OnItemSelectedListener(){ public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { String str = parent.getItemAtPosition(pos).toString(); if(!str.equals("A-Z")){ Comparator<String> comparator = Collections.reverseOrder(); Collections.sort(usernameList,comparator); adapter.notifyDataSetChanged(); } if(!str.equals("Z-A")){ Collections.sort(usernameList); adapter.notifyDataSetChanged(); } } public void onNothingSelected(AdapterView<?> view) { // Do Nothing } }); // get the directory client dc = appState.getDirectoryClient(); Handler handler = new Handler() { public void handleMessage(Message msg) { Log.i("AH","adHandler"); if(msg.what == DirectoryCommand.S_DIRECTORY_SEND.getCode()) { userMap.clear(); //userMap.putAll((Map<String,User>)msg.obj); //ArrayList<User> users = (ArrayList<User>)msg.obj; UserList uList = (UserList)msg.obj; for(int i=0; i<uList.size(); i++) { User u = uList.get(i); userMap.put(u.getUserName(),u); } adapter.clear(); for(String username2 : userMap.keySet()) { if(!user.getUserName().equals(username2)) adapter.add(username2); Log.i("AD","directory: " + username2); } } else if(msg.what == DirectoryCommand.S_BC_USERLOGGEDIN.getCode()) { User user2 = (User)msg.obj; String username2 = user2.getUserName(); userMap.put(username2, user2); adapter.add(username2); } else if(msg.what == DirectoryCommand.S_BC_USERLOGGEDOUT.getCode()) { String username2 = (String)msg.obj; userMap.remove(username2); adapter.remove(username2); } else if(msg.what == DirectoryCommand.S_CALL_INCOMING.getCode()) { String username2 = (String)msg.obj; Call.setUsername2(username2); Call.setState(Call.State.INCOMING); Intent callIncomingIntent = new Intent(thisActivity.getBaseContext(), ActivityCallIncoming.class); callIncomingIntent.putExtra("username2",username2); startActivity(callIncomingIntent); } else { Log.e("AD","unrecognized message " + msg.what); // unrecognized message // TODO: handle error } } }; dc.setReadHandler(handler); dc.getDirectory(); final Button buttonCall = (Button) findViewById(R.id.ButtonLogout); buttonCall.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO: Logout try { dc.logout(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Intent intent = new Intent(); setResult(RESULT_OK, intent); - finish(); + Intent menuIntent = new Intent(thisActivity.getBaseContext(), ActivityHome.class); + startActivity(menuIntent); } }); /*Start ringer server //Intent rsIntent = new Intent(this, RingerServer.class); //startService(rsIntent); final Button buttonCall = (Button) findViewById(R.id.ButtonCall); buttonCall.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Switch to outgoing call activity Intent callOutgoingIntent = new Intent(v.getContext(), ActivityCallOutgoing.class); startActivityForResult(callOutgoingIntent, 0); } }); */ } /* * Summary: Function called when a user is selected on the list * Parameters: ListView, l, view v, int position, long id * Return: void */ @Override protected void onListItemClick(ListView l, View view, int position, long id) { super.onListItemClick(l, view, position, id); final View v = view; //Get the last item that was clicked and store it into keyword Object o = this.getListAdapter().getItem(position); final String username2 = o.toString(); //Build the Alert Box AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Are you sure you want to connect to " + username2 + "?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { //Clicking Yes on the dialog box public void onClick(DialogInterface dialog, int id) { //TODO : implement the connect to the next userf //Write to log to check if it is working Log.d("Connect", "to the next user"); Call.setUsername2(username2); Call.setState(Call.State.OUTGOING); Intent callOutgoingIntent = new Intent(v.getContext(), ActivityCallOutgoing.class); startActivity(callOutgoingIntent); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { //Clicking No on the dialog box public void onClick(DialogInterface dialog, int id) { //cancel dialog action dialog.cancel(); } }); //Create and show dialog box AlertDialog alert = builder.create(); alert.show(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { dc.logout(); } return super.onKeyDown(keyCode, event); } @Override public void onResume() { super.onResume(); /* // Capture ACTION_INCOMINGCALL broadcast IntentFilter intentFilter = new IntentFilter(RingerServer.ACTION_INCOMINGCALL); registerReceiver(new IncomingCallReceiver(),intentFilter);*/ } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // TODO: display notification if call fails } /*private class IncomingCallReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Switch to incoming call activity Intent callIncomingIntent = new Intent(context,ActivityCallIncoming.class); ((Activity) context).startActivityForResult(callIncomingIntent,0); } }*/ }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.directory); final VoipApp appState = (VoipApp) getApplicationContext(); final User user = appState.getUser(); Log.d("Login", user.getUserName()); final ConcurrentHashMap<String,User> userMap = new ConcurrentHashMap<String,User>(); final ArrayList<String> usernameList = new ArrayList<String>(); final Spinner s = (Spinner)findViewById(R.id.sort_by); final ArrayAdapter<CharSequence> a = ArrayAdapter.createFromResource( this, R.array.sort_by, android.R.layout.simple_spinner_item); s.setAdapter(a); // Create an ArrayAdapter to user for our ListActivity Comparator<String> comparator = Collections.reverseOrder(); Collections.sort(usernameList,comparator); final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, usernameList); final ListActivity thisActivity = this; thisActivity.setListAdapter(adapter); s.setOnItemSelectedListener(new OnItemSelectedListener(){ public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { String str = parent.getItemAtPosition(pos).toString(); if(!str.equals("A-Z")){ Comparator<String> comparator = Collections.reverseOrder(); Collections.sort(usernameList,comparator); adapter.notifyDataSetChanged(); } if(!str.equals("Z-A")){ Collections.sort(usernameList); adapter.notifyDataSetChanged(); } } public void onNothingSelected(AdapterView<?> view) { // Do Nothing } }); // get the directory client dc = appState.getDirectoryClient(); Handler handler = new Handler() { public void handleMessage(Message msg) { Log.i("AH","adHandler"); if(msg.what == DirectoryCommand.S_DIRECTORY_SEND.getCode()) { userMap.clear(); //userMap.putAll((Map<String,User>)msg.obj); //ArrayList<User> users = (ArrayList<User>)msg.obj; UserList uList = (UserList)msg.obj; for(int i=0; i<uList.size(); i++) { User u = uList.get(i); userMap.put(u.getUserName(),u); } adapter.clear(); for(String username2 : userMap.keySet()) { if(!user.getUserName().equals(username2)) adapter.add(username2); Log.i("AD","directory: " + username2); } } else if(msg.what == DirectoryCommand.S_BC_USERLOGGEDIN.getCode()) { User user2 = (User)msg.obj; String username2 = user2.getUserName(); userMap.put(username2, user2); adapter.add(username2); } else if(msg.what == DirectoryCommand.S_BC_USERLOGGEDOUT.getCode()) { String username2 = (String)msg.obj; userMap.remove(username2); adapter.remove(username2); } else if(msg.what == DirectoryCommand.S_CALL_INCOMING.getCode()) { String username2 = (String)msg.obj; Call.setUsername2(username2); Call.setState(Call.State.INCOMING); Intent callIncomingIntent = new Intent(thisActivity.getBaseContext(), ActivityCallIncoming.class); callIncomingIntent.putExtra("username2",username2); startActivity(callIncomingIntent); } else { Log.e("AD","unrecognized message " + msg.what); // unrecognized message // TODO: handle error } } }; dc.setReadHandler(handler); dc.getDirectory(); final Button buttonCall = (Button) findViewById(R.id.ButtonLogout); buttonCall.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO: Logout try { dc.logout(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Intent intent = new Intent(); setResult(RESULT_OK, intent); finish(); } }); /*Start ringer server //Intent rsIntent = new Intent(this, RingerServer.class); //startService(rsIntent); final Button buttonCall = (Button) findViewById(R.id.ButtonCall); buttonCall.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Switch to outgoing call activity Intent callOutgoingIntent = new Intent(v.getContext(), ActivityCallOutgoing.class); startActivityForResult(callOutgoingIntent, 0); } }); */ }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.directory); final VoipApp appState = (VoipApp) getApplicationContext(); final User user = appState.getUser(); Log.d("Login", user.getUserName()); final ConcurrentHashMap<String,User> userMap = new ConcurrentHashMap<String,User>(); final ArrayList<String> usernameList = new ArrayList<String>(); final Spinner s = (Spinner)findViewById(R.id.sort_by); final ArrayAdapter<CharSequence> a = ArrayAdapter.createFromResource( this, R.array.sort_by, android.R.layout.simple_spinner_item); s.setAdapter(a); // Create an ArrayAdapter to user for our ListActivity Comparator<String> comparator = Collections.reverseOrder(); Collections.sort(usernameList,comparator); final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, usernameList); final ListActivity thisActivity = this; thisActivity.setListAdapter(adapter); s.setOnItemSelectedListener(new OnItemSelectedListener(){ public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { String str = parent.getItemAtPosition(pos).toString(); if(!str.equals("A-Z")){ Comparator<String> comparator = Collections.reverseOrder(); Collections.sort(usernameList,comparator); adapter.notifyDataSetChanged(); } if(!str.equals("Z-A")){ Collections.sort(usernameList); adapter.notifyDataSetChanged(); } } public void onNothingSelected(AdapterView<?> view) { // Do Nothing } }); // get the directory client dc = appState.getDirectoryClient(); Handler handler = new Handler() { public void handleMessage(Message msg) { Log.i("AH","adHandler"); if(msg.what == DirectoryCommand.S_DIRECTORY_SEND.getCode()) { userMap.clear(); //userMap.putAll((Map<String,User>)msg.obj); //ArrayList<User> users = (ArrayList<User>)msg.obj; UserList uList = (UserList)msg.obj; for(int i=0; i<uList.size(); i++) { User u = uList.get(i); userMap.put(u.getUserName(),u); } adapter.clear(); for(String username2 : userMap.keySet()) { if(!user.getUserName().equals(username2)) adapter.add(username2); Log.i("AD","directory: " + username2); } } else if(msg.what == DirectoryCommand.S_BC_USERLOGGEDIN.getCode()) { User user2 = (User)msg.obj; String username2 = user2.getUserName(); userMap.put(username2, user2); adapter.add(username2); } else if(msg.what == DirectoryCommand.S_BC_USERLOGGEDOUT.getCode()) { String username2 = (String)msg.obj; userMap.remove(username2); adapter.remove(username2); } else if(msg.what == DirectoryCommand.S_CALL_INCOMING.getCode()) { String username2 = (String)msg.obj; Call.setUsername2(username2); Call.setState(Call.State.INCOMING); Intent callIncomingIntent = new Intent(thisActivity.getBaseContext(), ActivityCallIncoming.class); callIncomingIntent.putExtra("username2",username2); startActivity(callIncomingIntent); } else { Log.e("AD","unrecognized message " + msg.what); // unrecognized message // TODO: handle error } } }; dc.setReadHandler(handler); dc.getDirectory(); final Button buttonCall = (Button) findViewById(R.id.ButtonLogout); buttonCall.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO: Logout try { dc.logout(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Intent intent = new Intent(); setResult(RESULT_OK, intent); Intent menuIntent = new Intent(thisActivity.getBaseContext(), ActivityHome.class); startActivity(menuIntent); } }); /*Start ringer server //Intent rsIntent = new Intent(this, RingerServer.class); //startService(rsIntent); final Button buttonCall = (Button) findViewById(R.id.ButtonCall); buttonCall.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Switch to outgoing call activity Intent callOutgoingIntent = new Intent(v.getContext(), ActivityCallOutgoing.class); startActivityForResult(callOutgoingIntent, 0); } }); */ }
diff --git a/src/instructions/USI_END.java b/src/instructions/USI_END.java index 0a3834d..0706a3a 100644 --- a/src/instructions/USI_END.java +++ b/src/instructions/USI_END.java @@ -1,121 +1,121 @@ package instructions; import static assemblernator.ErrorReporting.makeError; import assemblernator.AbstractDirective; import assemblernator.ErrorReporting.ErrorHandler; import assemblernator.Instruction; import assemblernator.Module; import assemblernator.OperandChecker; /** * The END instruction. * * @author Generate.java * @date Apr 08, 2012; 08:26:19 * @specRef D7 */ public class USI_END extends AbstractDirective { /** * The operation identifier of this instruction; while comments should not * be treated as an instruction, specification says they must be included in * the user report. Hence, we will simply give this class a semicolon as its * instruction ID. */ private static final String opId = "END"; /** The static instance for this instruction. */ static USI_END staticInstance = new USI_END(true); /** @see assemblernator.Instruction#getNewLC(int, Module) */ @Override public int getNewLC(int lc, Module mod) { return lc; } /** * The type of operand specifying the source for this operation. */ String src = ""; /** @see assemblernator.Instruction#check(ErrorHandler) */ @Override public boolean check(ErrorHandler hErr) { return true; } /** @see assemblernator.Instruction#assemble() */ @Override public int[] assemble() { return null; // TODO: IMPLEMENT } /** @see assemblernator.Instruction#immediateCheck(assemblernator.ErrorReporting.ErrorHandler, Module) */ @Override public boolean immediateCheck(ErrorHandler hErr, Module module) { boolean isValid = true; //less than 1 operand error if(this.operands.size() < 1){ isValid=false; hErr.reportError(makeError("directiveMissingOp", this.getOpId(), "LR"), this.lineNum, -1); //checks for LR }else if (this.operands.size() == 1){ if(this.hasOperand("LR")){ src = "LR"; //range check - if(this.getOperand("LR") != module.programName){ + if(!this.getOperand("LR").equals(module.programName)){ hErr.reportError(makeError("matchLabel"), this.lineNum, -1); isValid=false; } if(this.label != null){ hErr.reportError(makeError("noLabel",this.getOpId()), this.lineNum, -1); isValid=false; } }else{ isValid=false; hErr.reportError(makeError("directiveMissingOp", this.getOpId(), "any operand other than LR"), this.lineNum, -1); } //more than 1 operand error }else{ isValid =false; hErr.reportError(makeError("extraOperandsDir", this.getOpId()), this.lineNum, -1); } return isValid; // TODO: IMPLEMENT } // ========================================================= // === Redundant code ====================================== // ========================================================= // === This code's the same in all instruction classes, ==== // === But Java lacks the mechanism to allow stuffing it === // === in super() where it belongs. ======================== // ========================================================= /** * @see Instruction * @return The static instance of this instruction. */ public static Instruction getInstance() { return staticInstance; } /** @see assemblernator.Instruction#getOpId() */ @Override public String getOpId() { return opId; } /** @see assemblernator.Instruction#getNewInstance() */ @Override public Instruction getNewInstance() { return new USI_END(); } /** * Calls the Instance(String,int) constructor to track this instruction. * * @param ignored * Unused parameter; used to distinguish the constructor for the * static instance. */ private USI_END(boolean ignored) { super(opId); } /** Default constructor; does nothing. */ private USI_END() {} }
true
true
@Override public boolean immediateCheck(ErrorHandler hErr, Module module) { boolean isValid = true; //less than 1 operand error if(this.operands.size() < 1){ isValid=false; hErr.reportError(makeError("directiveMissingOp", this.getOpId(), "LR"), this.lineNum, -1); //checks for LR }else if (this.operands.size() == 1){ if(this.hasOperand("LR")){ src = "LR"; //range check if(this.getOperand("LR") != module.programName){ hErr.reportError(makeError("matchLabel"), this.lineNum, -1); isValid=false; } if(this.label != null){ hErr.reportError(makeError("noLabel",this.getOpId()), this.lineNum, -1); isValid=false; } }else{ isValid=false; hErr.reportError(makeError("directiveMissingOp", this.getOpId(), "any operand other than LR"), this.lineNum, -1); } //more than 1 operand error }else{ isValid =false; hErr.reportError(makeError("extraOperandsDir", this.getOpId()), this.lineNum, -1); } return isValid; // TODO: IMPLEMENT }
@Override public boolean immediateCheck(ErrorHandler hErr, Module module) { boolean isValid = true; //less than 1 operand error if(this.operands.size() < 1){ isValid=false; hErr.reportError(makeError("directiveMissingOp", this.getOpId(), "LR"), this.lineNum, -1); //checks for LR }else if (this.operands.size() == 1){ if(this.hasOperand("LR")){ src = "LR"; //range check if(!this.getOperand("LR").equals(module.programName)){ hErr.reportError(makeError("matchLabel"), this.lineNum, -1); isValid=false; } if(this.label != null){ hErr.reportError(makeError("noLabel",this.getOpId()), this.lineNum, -1); isValid=false; } }else{ isValid=false; hErr.reportError(makeError("directiveMissingOp", this.getOpId(), "any operand other than LR"), this.lineNum, -1); } //more than 1 operand error }else{ isValid =false; hErr.reportError(makeError("extraOperandsDir", this.getOpId()), this.lineNum, -1); } return isValid; // TODO: IMPLEMENT }
diff --git a/core/src/visad/trunk/ss/SpreadSheet.java b/core/src/visad/trunk/ss/SpreadSheet.java index 900d8a44a..5e7260565 100644 --- a/core/src/visad/trunk/ss/SpreadSheet.java +++ b/core/src/visad/trunk/ss/SpreadSheet.java @@ -1,1156 +1,1156 @@ // // SpreadSheet.java // /* VisAD system for interactive analysis and visualization of numerical data. Copyright (C) 1996 - 1998 Bill Hibbard, Curtis Rueden, Tom Rink and Dave Glowacki. 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 1, 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 in file NOTICE 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ package visad.ss; // AWT packages import java.awt.*; import java.awt.event.*; // JFC packages import com.sun.java.swing.*; import com.sun.java.swing.border.*; import com.sun.java.swing.event.*; // I/O package import java.io.*; // Net class import java.net.URL; // RMI class import java.rmi.RemoteException; // Utility class import java.util.Vector; // VisAD packages import visad.*; import visad.java3d.*; // VisAD class import visad.data.BadFormException; /** SpreadSheet is a user interface for VisAD that supports multiple 3-D displays (FancySSCells).<P>*/ public class SpreadSheet extends JFrame implements ActionListener, AdjustmentListener, DisplayListener, KeyListener, ItemListener, MouseListener, MouseMotionListener { // starting size of the application, in percentage of screen size static final int WIDTH_PERCENT = 60; static final int HEIGHT_PERCENT = 75; // minimum VisAD display size, including display border static final int MIN_VIS_WIDTH = 120; static final int MIN_VIS_HEIGHT = 120; // spreadsheet letter order static final String Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // spreadsheet file dialog FileDialog SSFileDialog = null; // number of VisAD displays int NumVisX; int NumVisY; int NumVisDisplays; // whether this JVM supports Java3D (detected on SpreadSheet launch) boolean CanDo3D = true; // whether cells should automatically switch dimensions and detect mappings boolean AutoSwitch3D = true; boolean AutoMap = true; // display-related arrays and variables Panel DisplayPanel; JPanel ScrollPanel; ScrollPane SCPane; ScrollPane HorizLabels; ScrollPane VertLabels; JPanel[] HorizLabel, VertLabel; JPanel[] HorizDrag, VertDrag; FancySSCell[] DisplayCells; JTextField FormulaField; MenuItem EditPaste; JButton ToolPaste; JButton FormulaOk; CheckboxMenuItem CellDim3D3D, CellDim2D2D, CellDim2D3D; CheckboxMenuItem OptSwitch, OptAuto, OptFormula; int CurDisplay = 0; String Clipboard = null; File CurrentFile = null; public static void main(String[] argv) { int cols = 2; int rows = 2; if (argv.length > 1) { try { cols = Integer.parseInt(argv[0]); rows = Integer.parseInt(argv[1]); } catch (NumberFormatException exc) { } } if (cols > Letters.length()) cols = Letters.length(); if (cols < 1) cols = 1; if (rows < 1) rows = 1; SpreadSheet ss = new SpreadSheet(WIDTH_PERCENT, HEIGHT_PERCENT, cols, rows, "VisAD SpreadSheet"); } /** This is the constructor for the SpreadSheet class */ public SpreadSheet(int sWidth, int sHeight, int cols, int rows, String sTitle) { NumVisX = cols; NumVisY = rows; NumVisDisplays = NumVisX*NumVisY; MappingDialog.initDialog(); addKeyListener(this); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { quitProgram(); } }); setBackground(Color.white); // test for Java3D availability try { DisplayImplJ3D test = new DisplayImplJ3D("test"); } catch (UnsatisfiedLinkError err) { CanDo3D = false; } catch (VisADException exc) { CanDo3D = false; } catch (RemoteException exc) { CanDo3D = false; } // set up the content pane JPanel pane = new JPanel(); pane.setBackground(Color.white); pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); setContentPane(pane); // set up menus MenuBar menubar = new MenuBar(); setMenuBar(menubar); // file menu Menu file = new Menu("File"); menubar.add(file); MenuItem fileOpen = new MenuItem("Import data..."); fileOpen.addActionListener(this); fileOpen.setActionCommand("fileOpen"); file.add(fileOpen); MenuItem fileSave = new MenuItem("Export data to netCDF..."); fileSave.addActionListener(this); fileSave.setActionCommand("fileSave"); file.add(fileSave); file.addSeparator(); MenuItem fileExit = new MenuItem("Exit"); fileExit.addActionListener(this); fileExit.setActionCommand("fileExit"); file.add(fileExit); // edit menu Menu edit = new Menu("Edit"); menubar.add(edit); MenuItem editCut = new MenuItem("Cut"); editCut.addActionListener(this); editCut.setActionCommand("editCut"); edit.add(editCut); MenuItem editCopy = new MenuItem("Copy"); editCopy.addActionListener(this); editCopy.setActionCommand("editCopy"); edit.add(editCopy); EditPaste = new MenuItem("Paste"); EditPaste.addActionListener(this); EditPaste.setActionCommand("editPaste"); EditPaste.setEnabled(false); edit.add(EditPaste); MenuItem editClear = new MenuItem("Clear"); editClear.addActionListener(this); editClear.setActionCommand("editClear"); edit.add(editClear); // setup menu Menu setup = new Menu("Setup"); menubar.add(setup); MenuItem setupNew = new MenuItem("New spreadsheet file"); setupNew.addActionListener(this); setupNew.setActionCommand("setupNew"); setup.add(setupNew); MenuItem setupOpen = new MenuItem("Open spreadsheet file..."); setupOpen.addActionListener(this); setupOpen.setActionCommand("setupOpen"); setup.add(setupOpen); MenuItem setupSave = new MenuItem("Save spreadsheet file"); setupSave.addActionListener(this); setupSave.setActionCommand("setupSave"); setup.add(setupSave); MenuItem setupSaveas = new MenuItem("Save spreadsheet file as..."); setupSaveas.addActionListener(this); setupSaveas.setActionCommand("setupSaveas"); setup.add(setupSaveas); // display menu Menu disp = new Menu("Display"); menubar.add(disp); MenuItem dispEdit = new MenuItem("Edit mappings..."); dispEdit.addActionListener(this); dispEdit.setActionCommand("dispEdit"); disp.add(dispEdit); disp.addSeparator(); CellDim3D3D = new CheckboxMenuItem("3-D (Java3D)", CanDo3D); CellDim3D3D.addItemListener(this); CellDim3D3D.setEnabled(CanDo3D); disp.add(CellDim3D3D); CellDim2D2D = new CheckboxMenuItem("2-D (Java2D)", !CanDo3D); CellDim2D2D.addItemListener(this); disp.add(CellDim2D2D); CellDim2D3D = new CheckboxMenuItem("2-D (Java3D)", false); CellDim2D3D.addItemListener(this); - CellDim3D3D.setEnabled(CanDo3D); + CellDim2D3D.setEnabled(CanDo3D); disp.add(CellDim2D3D); // options menu Menu options = new Menu("Options"); menubar.add(options); OptSwitch = new CheckboxMenuItem("Auto-switch to 3-D", CanDo3D); OptSwitch.addItemListener(this); OptSwitch.setEnabled(CanDo3D); options.add(OptSwitch); OptAuto = new CheckboxMenuItem("Auto-detect mappings", true); OptAuto.addItemListener(this); options.add(OptAuto); OptFormula = new CheckboxMenuItem("Show formula error messages", true); OptFormula.addItemListener(this); options.add(OptFormula); options.addSeparator(); MenuItem optWidget = new MenuItem("Show VisAD controls"); optWidget.addActionListener(this); optWidget.setActionCommand("optWidget"); options.add(optWidget); // set up toolbar URL url; JToolBar toolbar = new JToolBar(); toolbar.setBackground(Color.lightGray); toolbar.setBorder(new EtchedBorder()); toolbar.setFloatable(false); pane.add(toolbar); // file menu toolbar icons url = SpreadSheet.class.getResource("open.gif"); ImageIcon toolFileOpen = new ImageIcon(url); if (toolFileOpen != null) { JButton b = new JButton(toolFileOpen); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Import data"); b.addActionListener(this); b.setActionCommand("fileOpen"); toolbar.add(b); } url = SpreadSheet.class.getResource("save.gif"); ImageIcon toolFileSave = new ImageIcon(url); if (toolFileSave != null) { JButton b = new JButton(toolFileSave); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Export data to netCDF"); b.addActionListener(this); b.setActionCommand("fileSave"); toolbar.add(b); } toolbar.addSeparator(); // edit menu toolbar icons url = SpreadSheet.class.getResource("cut.gif"); ImageIcon toolEditCut = new ImageIcon(url); if (toolEditCut != null) { JButton b = new JButton(toolEditCut); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Cut"); b.addActionListener(this); b.setActionCommand("editCut"); toolbar.add(b); } url = SpreadSheet.class.getResource("copy.gif"); ImageIcon toolEditCopy = new ImageIcon(url); if (toolEditCopy != null) { JButton b = new JButton(toolEditCopy); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Copy"); b.addActionListener(this); b.setActionCommand("editCopy"); toolbar.add(b); } url = SpreadSheet.class.getResource("paste.gif"); ImageIcon toolEditPaste = new ImageIcon(url); if (toolEditPaste != null) { ToolPaste = new JButton(toolEditPaste); ToolPaste.setAlignmentY(JButton.CENTER_ALIGNMENT); ToolPaste.setToolTipText("Paste"); ToolPaste.addActionListener(this); ToolPaste.setActionCommand("editPaste"); ToolPaste.setEnabled(false); toolbar.add(ToolPaste); } toolbar.addSeparator(); // mappings menu toolbar icons url = SpreadSheet.class.getResource("mappings.gif"); ImageIcon toolMappingsEdit = new ImageIcon(url); if (toolMappingsEdit != null) { JButton b = new JButton(toolMappingsEdit); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Edit mappings"); b.addActionListener(this); b.setActionCommand("dispEdit"); toolbar.add(b); } // window menu toolbar icons url = SpreadSheet.class.getResource("show.gif"); ImageIcon winShowControls = new ImageIcon(url); if (winShowControls != null) { JButton b = new JButton(winShowControls); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Show VisAD controls"); b.addActionListener(this); b.setActionCommand("optWidget"); toolbar.add(b); } toolbar.add(Box.createHorizontalGlue()); // set up formula bar JPanel formulaPanel = new JPanel(); formulaPanel.setBackground(Color.white); formulaPanel.setLayout(new BoxLayout(formulaPanel, BoxLayout.X_AXIS)); formulaPanel.setBorder(new EtchedBorder()); pane.add(formulaPanel); pane.add(Box.createRigidArea(new Dimension(0, 6))); url = SpreadSheet.class.getResource("cancel.gif"); ImageIcon cancelIcon = new ImageIcon(url); JButton formulaCancel = new JButton(cancelIcon); formulaCancel.setAlignmentY(JButton.CENTER_ALIGNMENT); formulaCancel.setToolTipText("Cancel formula entry"); formulaCancel.addActionListener(this); formulaCancel.setActionCommand("formulaCancel"); Dimension size = new Dimension(cancelIcon.getIconWidth()+4, cancelIcon.getIconHeight()+4); formulaCancel.setPreferredSize(size); formulaPanel.add(formulaCancel); url = SpreadSheet.class.getResource("ok.gif"); ImageIcon okIcon = new ImageIcon(url); FormulaOk = new JButton(okIcon); FormulaOk.setAlignmentY(JButton.CENTER_ALIGNMENT); FormulaOk.setToolTipText("Confirm formula entry"); FormulaOk.addActionListener(this); FormulaOk.setActionCommand("formulaOk"); size = new Dimension(okIcon.getIconWidth()+4, okIcon.getIconHeight()+4); FormulaOk.setPreferredSize(size); formulaPanel.add(FormulaOk); FormulaField = new JTextField(); FormulaField.setToolTipText("Enter a file name or formula"); FormulaField.addActionListener(this); FormulaField.setActionCommand("formulaChange"); formulaPanel.add(FormulaField); url = SpreadSheet.class.getResource("import.gif"); ImageIcon importIcon = new ImageIcon(url); JButton formulaImport = new JButton(importIcon); formulaImport.setAlignmentY(JButton.CENTER_ALIGNMENT); formulaImport.setToolTipText("Import data"); formulaImport.addActionListener(this); formulaImport.setActionCommand("fileOpen"); size = new Dimension(importIcon.getIconWidth()+4, importIcon.getIconHeight()+4); formulaImport.setPreferredSize(size); formulaPanel.add(formulaImport); // label constants final int LABEL_WIDTH = 30; final int LABEL_HEIGHT = 20; // set up horizontal spreadsheet cell labels JPanel horizShell = new JPanel(); horizShell.setBackground(Color.white); horizShell.setLayout(new BoxLayout(horizShell, BoxLayout.X_AXIS)); horizShell.add(Box.createRigidArea(new Dimension(LABEL_WIDTH+10, 0))); pane.add(horizShell); JPanel horizPanel = new JPanel() { public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); return new Dimension(d.width, LABEL_HEIGHT); } }; horizPanel.setLayout(new SSLayout(2*NumVisX-1, 1, MIN_VIS_WIDTH, LABEL_HEIGHT, 0, 0, true)); HorizLabel = new JPanel[NumVisX]; HorizDrag = new JPanel[NumVisX-1]; for (int i=0; i<NumVisX; i++) { String curLet = String.valueOf(Letters.charAt(i)); HorizLabel[i] = new JPanel(); HorizLabel[i].setBorder(new LineBorder(Color.black, 1)); HorizLabel[i].setLayout(new BorderLayout()); HorizLabel[i].setPreferredSize(new Dimension(MIN_VIS_WIDTH, LABEL_HEIGHT)); HorizLabel[i].add("Center", new JLabel(curLet, SwingConstants.CENTER)); horizPanel.add(HorizLabel[i]); if (i < NumVisX-1) { HorizDrag[i] = new JPanel() { public void paint(Graphics g) { Dimension s = getSize(); g.setColor(Color.black); g.drawRect(0, 0, s.width - 1, s.height - 1); g.setColor(Color.yellow); g.fillRect(1, 1, s.width - 2, s.height - 2); } }; HorizDrag[i].setPreferredSize(new Dimension(5, 0)); HorizDrag[i].addMouseListener(this); HorizDrag[i].addMouseMotionListener(this); horizPanel.add(HorizDrag[i]); } } ScrollPane hl = new ScrollPane(ScrollPane.SCROLLBARS_NEVER) { public Dimension getMinimumSize() { return new Dimension(0, LABEL_HEIGHT+4); } public Dimension getPreferredSize() { return new Dimension(0, LABEL_HEIGHT+4); } public Dimension getMaximumSize() { return new Dimension(Integer.MAX_VALUE, LABEL_HEIGHT+4); } }; HorizLabels = hl; HorizLabels.add(horizPanel); horizShell.add(HorizLabels); horizShell.add(Box.createRigidArea(new Dimension(6, 0))); // set up window's main panel JPanel mainPanel = new JPanel(); mainPanel.setBackground(Color.white); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS)); pane.add(mainPanel); pane.add(Box.createRigidArea(new Dimension(0, 6))); // set up vertical spreadsheet cell labels JPanel vertShell = new JPanel(); vertShell.setAlignmentY(JPanel.CENTER_ALIGNMENT); vertShell.setBackground(Color.white); vertShell.setLayout(new BoxLayout(vertShell, BoxLayout.X_AXIS)); mainPanel.add(Box.createRigidArea(new Dimension(6, 0))); mainPanel.add(vertShell); JPanel vertPanel = new JPanel() { public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); return new Dimension(LABEL_WIDTH, d.height); } }; vertPanel.setLayout(new SSLayout(1, 2*NumVisY-1, LABEL_WIDTH, MIN_VIS_HEIGHT, 0, 0, true)); VertLabel = new JPanel[NumVisY]; VertDrag = new JPanel[NumVisY-1]; for (int i=0; i<NumVisY; i++) { VertLabel[i] = new JPanel(); VertLabel[i].setBorder(new LineBorder(Color.black, 1)); VertLabel[i].setLayout(new BorderLayout()); VertLabel[i].setPreferredSize(new Dimension(LABEL_WIDTH, MIN_VIS_HEIGHT)); VertLabel[i].add("Center", new JLabel(""+(i+1), SwingConstants.CENTER)); vertPanel.add(VertLabel[i]); if (i < NumVisY-1) { VertDrag[i] = new JPanel() { public void paint(Graphics g) { Dimension s = getSize(); g.setColor(Color.black); g.drawRect(0, 0, s.width - 1, s.height - 1); g.setColor(Color.yellow); g.fillRect(1, 1, s.width - 2, s.height - 2); } }; VertDrag[i].setBackground(Color.white); VertDrag[i].setPreferredSize(new Dimension(0, 5)); VertDrag[i].addMouseListener(this); VertDrag[i].addMouseMotionListener(this); vertPanel.add(VertDrag[i]); } } ScrollPane vl = new ScrollPane(ScrollPane.SCROLLBARS_NEVER) { public Dimension getMinimumSize() { return new Dimension(LABEL_WIDTH+4, 0); } public Dimension getPreferredSize() { return new Dimension(LABEL_WIDTH+4, 0); } public Dimension getMaximumSize() { return new Dimension(LABEL_WIDTH+4, Integer.MAX_VALUE); } }; VertLabels = vl; VertLabels.add(vertPanel); vertShell.add(VertLabels); // set up scroll pane's panel ScrollPanel = new JPanel(); ScrollPanel.setBackground(Color.white); ScrollPanel.setLayout(new BoxLayout(ScrollPanel, BoxLayout.X_AXIS)); mainPanel.add(ScrollPanel); mainPanel.add(Box.createRigidArea(new Dimension(6, 0))); // set up scroll pane for VisAD Displays SCPane = new ScrollPane() { public Dimension getPreferredSize() { return new Dimension(0, 0); } }; Adjustable hadj = SCPane.getHAdjustable(); Adjustable vadj = SCPane.getVAdjustable(); hadj.setBlockIncrement(MIN_VIS_WIDTH); hadj.setUnitIncrement(MIN_VIS_WIDTH/4); hadj.addAdjustmentListener(this); vadj.setBlockIncrement(MIN_VIS_HEIGHT); vadj.setUnitIncrement(MIN_VIS_HEIGHT/4); vadj.addAdjustmentListener(this); ScrollPanel.add(SCPane); // set up display panel DisplayPanel = new Panel(); DisplayPanel.setBackground(Color.darkGray); DisplayPanel.setLayout(new SSLayout(NumVisX, NumVisY, MIN_VIS_WIDTH, MIN_VIS_HEIGHT, 5, 5, false)); SCPane.add(DisplayPanel); // set up display panel's individual VisAD displays DisplayCells = new FancySSCell[NumVisDisplays]; for (int i=0; i<NumVisDisplays; i++) { String name = String.valueOf(Letters.charAt(i % NumVisX)) + String.valueOf(i / NumVisX + 1); try { DisplayCells[i] = new FancySSCell(name, this); DisplayCells[i].addMouseListener(this); DisplayCells[i].setAutoSwitch(CanDo3D); DisplayCells[i].setDimension(!CanDo3D, !CanDo3D); DisplayCells[i].setDisplayListener(this); DisplayCells[i].setPreferredSize(new Dimension(MIN_VIS_WIDTH, MIN_VIS_HEIGHT)); if (i == 0) DisplayCells[i].setSelected(true); DisplayPanel.add(DisplayCells[i]); } catch (VisADException exc) { JOptionPane.showMessageDialog(this, "Cannot create displays.", "VisAD SpreadSheet error", JOptionPane.ERROR_MESSAGE); } catch (RemoteException exc) { JOptionPane.showMessageDialog(this, "Cannot create displays.", "VisAD SpreadSheet error", JOptionPane.ERROR_MESSAGE); } } // display window on screen setTitle(sTitle); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int appWidth = (int) (0.01*sWidth*screenSize.width); int appHeight = (int) (0.01*sHeight*screenSize.height); setSize(appWidth, appHeight); setLocation(screenSize.width/2 - appWidth/2, screenSize.height/2 - appHeight/2); setVisible(true); } /** Handles menubar/toolbar events */ public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); // file menu commands if (cmd.equals("fileOpen")) loadDataSet(); else if (cmd.equals("fileSave")) exportDataSet(); else if (cmd.equals("fileExit")) { DisplayCells[CurDisplay].hideWidgetFrame(); setVisible(false); quitProgram(); } // edit menu commands else if (cmd.equals("editCut")) cutCell(); else if (cmd.equals("editCopy")) copyCell(); else if (cmd.equals("editPaste")) pasteCell(); else if (cmd.equals("editClear")) clearCell(true); // setup menu commands else if (cmd.equals("setupNew")) newFile(); else if (cmd.equals("setupOpen")) openFile(); else if (cmd.equals("setupSave")) saveFile(); else if (cmd.equals("setupSaveas")) saveasFile(); // mappings menu commands else if (cmd.equals("dispEdit")) createMappings(); // window menu commands else if (cmd.equals("optWidget")) { DisplayCells[CurDisplay].showWidgetFrame(); } // formula bar commands else if (cmd.equals("formulaCancel")) refreshFormulaBar(); else if (cmd.equals("formulaOk")) updateFormula(); else if (cmd.equals("formulaChange")) { FormulaOk.requestFocus(); updateFormula(); } } /** Creates a new spreadsheet file */ void newFile() { // clear all cells for (int i=0; i<DisplayCells.length; i++) { try { DisplayCells[i].clearCell(); } catch (VisADException exc) { } catch (RemoteException exc) { } } CurrentFile = null; setTitle("VisAD SpreadSheet"); } /** Opens an existing spreadsheet file */ void openFile() { if (SSFileDialog == null) SSFileDialog = new FileDialog(this); SSFileDialog.setMode(FileDialog.LOAD); SSFileDialog.setVisible(true); // make sure file exists String file = SSFileDialog.getFile(); if (file == null) return; String dir = SSFileDialog.getDirectory(); if (dir == null) return; File f = new File(dir, file); if (!f.exists()) { JOptionPane.showMessageDialog(this, "The file "+file+" does not exist", "VisAD SpreadSheet error", JOptionPane.ERROR_MESSAGE); return; } // clear all cells newFile(); // load file String[] fileStrings = new String[DisplayCells.length]; try { FileReader fr = new FileReader(f); char[] buff = new char[1024]; int i = 0; while (fr.read(buff, 0, buff.length) != -1) { fileStrings[i++] = new String(buff); } fr.close(); } catch (IOException exc) { JOptionPane.showMessageDialog(this, "The file "+file+" could not be loaded", "VisAD SpreadSheet error", JOptionPane.ERROR_MESSAGE); return; } // reconstruct cells for (int i=0; i<DisplayCells.length; i++) { try { DisplayCells[i].setSSCellString(fileStrings[i]); } catch (VisADException exc) { JOptionPane.showMessageDialog(this, "Could not reconstruct spreadsheet", "VisAD SpreadSheet error", JOptionPane.ERROR_MESSAGE); newFile(); return; } catch (RemoteException exc) { } } CurrentFile = f; setTitle("VisAD SpreadSheet - "+f.getPath()); } /** Saves a spreadsheet file under its current name */ void saveFile() { if (CurrentFile == null) saveasFile(); else { try { FileWriter fw = new FileWriter(CurrentFile); for (int i=0; i<DisplayCells.length; i++) { String s = DisplayCells[i].getSSCellString(); char[] sc = new char[1024]; s.getChars(0, s.length(), sc, 0); fw.write(sc, 0, sc.length); } fw.close(); } catch (IOException exc) { JOptionPane.showMessageDialog(this, "Could not save file "+CurrentFile.getName(), "VisAD SpreadSheet error", JOptionPane.ERROR_MESSAGE); } } } /** Saves a spreadsheet file under a new name */ void saveasFile() { if (SSFileDialog == null) SSFileDialog = new FileDialog(this); SSFileDialog.setMode(FileDialog.SAVE); SSFileDialog.setVisible(true); // get file and make sure it is valid String file = SSFileDialog.getFile(); if (file == null) return; String dir = SSFileDialog.getDirectory(); if (dir == null) return; File f = new File(dir, file); CurrentFile = f; setTitle("VisAD SpreadSheet - "+f.getPath()); saveFile(); } /** Does any necessary clean-up, then quits the program */ void quitProgram() { // wait for files to finish saving Thread t = new Thread() { public void run() { boolean b = false; if (BasicSSCell.Saving > 0) b = true; JFrame f = new JFrame("Please wait"); if (b) { // display "please wait" message in new frame f.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); JPanel p = new JPanel(); f.setContentPane(p); p.setBorder(new EmptyBorder(10, 20, 10, 20)); p.setLayout(new BorderLayout()); p.add("Center", new JLabel("Please wait while the VisAD " +"SpreadSheet finishes saving files...")); f.setResizable(false); f.pack(); Dimension sSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension fSize = f.getSize(); f.setLocation(sSize.width/2 - fSize.width/2, sSize.height/2 - fSize.height/2); f.setVisible(true); } while (BasicSSCell.Saving > 0) { try { sleep(500); } catch (InterruptedException exc) { } } if (b) { f.setCursor(Cursor.getDefaultCursor()); f.setVisible(false); } System.exit(0); } }; t.start(); } /** Moves a cell from the screen to the clipboard */ void cutCell() { if (DisplayCells[CurDisplay].confirmClear()) { copyCell(); clearCell(false); } } /** Copies a cell from the screen to the clipboard */ void copyCell() { Clipboard = DisplayCells[CurDisplay].getSSCellString(); EditPaste.setEnabled(true); ToolPaste.setEnabled(true); } /** Copies a cell from the clipboard to the screen */ void pasteCell() { if (Clipboard != null) { try { DisplayCells[CurDisplay].setSSCellString(Clipboard); } catch (VisADException exc) { JOptionPane.showMessageDialog(this, "Could not paste cell: "+exc.toString(), "VisAD SpreadSheet error", JOptionPane.ERROR_MESSAGE); } catch (RemoteException exc) { } } } /** Clears the mappings and formula of the current cell */ void clearCell(boolean checkSafe) { try { if (checkSafe) DisplayCells[CurDisplay].smartClear(); else DisplayCells[CurDisplay].clearCell(); } catch (VisADException exc) { JOptionPane.showMessageDialog(this, "Cannot clear display mappings.", "VisAD SpreadSheet error", JOptionPane.ERROR_MESSAGE); } catch (RemoteException exc) { } refreshFormulaBar(); } /** Allows the user to specify mappings from Data to Display */ void createMappings() { DisplayCells[CurDisplay].addMapDialog(); } /** Allows the user to import a data set */ void loadDataSet() { DisplayCells[CurDisplay].loadDataDialog(); } /** Allows the user to export a data set to netCDF format */ void exportDataSet() { DisplayCells[CurDisplay].saveDataDialog(); } /** Makes sure the formula bar is displaying up-to-date info */ void refreshFormulaBar() { if (DisplayCells[CurDisplay].hasFormula()) { FormulaField.setText(DisplayCells[CurDisplay].getFormula()); } else { String f = DisplayCells[CurDisplay].getFilename(); if (f == null) f = ""; FormulaField.setText(f); } } /** Update formula based on formula entered in formula bar */ void updateFormula() { String newFormula = FormulaField.getText(); File f = new File(newFormula); if (f.exists()) { // check if filename has changed from last entry String oldFormula = DisplayCells[CurDisplay].getFilename(); if (oldFormula == null) oldFormula = ""; if (oldFormula.equals(newFormula)) return; // try to load the file DisplayCells[CurDisplay].loadDataFile(f); } else { // check if formula has changed from last entry String oldFormula = ""; if (DisplayCells[CurDisplay].hasFormula()) { oldFormula = DisplayCells[CurDisplay].getFormula(); } if (oldFormula.equalsIgnoreCase(newFormula)) return; // try to set the formula try { DisplayCells[CurDisplay].setFormula(newFormula); } catch (VisADException exc) { JOptionPane.showMessageDialog(this, exc.toString(), "VisAD SpreadSheet error", JOptionPane.ERROR_MESSAGE); } catch (RemoteException exc) { JOptionPane.showMessageDialog(this, exc.toString(), "VisAD SpreadSheet error", JOptionPane.ERROR_MESSAGE); } } } /** Update dimension checkbox menu items in Cell menu */ void refreshDisplayMenuItems() { // update dimension check marks int dim = DisplayCells[CurDisplay].getDimension(); if (dim == BasicSSCell.JAVA3D_3D) CellDim3D3D.setState(true); else CellDim3D3D.setState(false); if (dim == BasicSSCell.JAVA2D_2D) CellDim2D2D.setState(true); else CellDim2D2D.setState(false); if (dim == BasicSSCell.JAVA3D_2D) CellDim2D3D.setState(true); else CellDim2D3D.setState(false); // update auto-detect check mark OptAuto.setState(DisplayCells[CurDisplay].getAutoDetect()); } /** Handles checkbox menu item changes (dimension checkboxes) */ public void itemStateChanged(ItemEvent e) { String item = (String) e.getItem(); if (item.equals("Show formula error messages")) { for (int i=0; i<DisplayCells.length; i++) { DisplayCells[i].setShowFormulaErrors(e.getStateChange() == ItemEvent.SELECTED); } } try { if (item.equals("3-D (Java3D)")) { DisplayCells[CurDisplay].setDimension(false, false); } else if (item.equals("2-D (Java2D)")) { DisplayCells[CurDisplay].setDimension(true, true); } else if (item.equals("2-D (Java3D)")) { DisplayCells[CurDisplay].setDimension(true, false); } else if (item.equals("Auto-switch to 3-D")) { boolean b = e.getStateChange() == ItemEvent.SELECTED; for (int i=0; i<NumVisDisplays; i++) DisplayCells[i].setAutoSwitch(b); } else if (item.equals("Auto-detect mappings")) { boolean b = e.getStateChange() == ItemEvent.SELECTED; for (int i=0; i<NumVisDisplays; i++) DisplayCells[i].setAutoDetect(b); } refreshDisplayMenuItems(); } catch (VisADException exc) { JOptionPane.showMessageDialog(this, "Cannot alter display dimension.", "VisAD SpreadSheet error", JOptionPane.ERROR_MESSAGE); } catch (RemoteException exc) { } } /** Handles scrollbar changes */ public void adjustmentValueChanged(AdjustmentEvent e) { Adjustable a = e.getAdjustable(); int value = a.getValue(); if (a.getOrientation() == Adjustable.HORIZONTAL) { HorizLabels.setScrollPosition(value, 0); } else { // a.getOrientation() == Adjustable.VERTICAL VertLabels.setScrollPosition(0, value); } } /** Handles display changes */ public void displayChanged(DisplayEvent e) { FancySSCell fcell = (FancySSCell) BasicSSCell.getSSCellByDisplay(e.getDisplay()); int c = -1; for (int i=0; i<NumVisDisplays; i++) { if (fcell == DisplayCells[i]) c = i; } selectCell(c); } /** Selects the specified cell, updating screen info */ void selectCell(int cell) { if (cell < 0 || cell >= NumVisDisplays || cell == CurDisplay) return; // update blue border on screen DisplayCells[CurDisplay].setSelected(false); DisplayCells[cell].setSelected(true); CurDisplay = cell; // update spreadsheet info refreshFormulaBar(); refreshDisplayMenuItems(); } /** Handles key presses */ public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_RIGHT || key == KeyEvent.VK_LEFT || key == KeyEvent.VK_DOWN || key == KeyEvent.VK_UP) { int c = CurDisplay; if (key == KeyEvent.VK_RIGHT && (CurDisplay+1) % NumVisX != 0) { c = CurDisplay + 1; } if (key == KeyEvent.VK_LEFT && CurDisplay % NumVisX != 0) { c = CurDisplay - 1; } if (key == KeyEvent.VK_DOWN) c = CurDisplay + NumVisX; if (key == KeyEvent.VK_UP) c = CurDisplay - NumVisX; selectCell(c); } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } // used with cell resizing logic private int oldX; private int oldY; /** Handles mouse presses and cell resizing */ public void mousePressed(MouseEvent e) { Component c = e.getComponent(); for (int i=0; i<DisplayCells.length; i++) { if (c == DisplayCells[i]) selectCell(i); } oldX = e.getX(); oldY = e.getY(); } /** Handles cell resizing */ public void mouseReleased(MouseEvent e) { int x = e.getX(); int y = e.getY(); Component c = e.getComponent(); boolean change = false; for (int j=0; j<NumVisX-1; j++) { if (c == HorizDrag[j]) { change = true; break; } } for (int j=0; j<NumVisY-1; j++) { if (c == VertDrag[j]) { change = true; break; } } if (change) { // redisplay spreadsheet cells int h = VertLabel[0].getSize().height; for (int i=0; i<NumVisX; i++) { Dimension d = new Dimension(); d.width = HorizLabel[i].getSize().width; d.height = h; DisplayCells[i].setPreferredSize(d); } int w = HorizLabel[0].getSize().width; for (int i=0; i<NumVisY; i++) { Dimension d = new Dimension(); d.width = w; d.height = VertLabel[i].getSize().height; DisplayCells[NumVisX*i].setPreferredSize(d); } for (int i=0; i<NumVisX*NumVisY; i++) { Dimension d = new Dimension(); d.width = DisplayCells[i%NumVisX].getPreferredSize().width; d.height = DisplayCells[i/NumVisX].getPreferredSize().height; DisplayCells[i].setSize(d); } SCPane.invalidate(); SCPane.validate(); } } /** Handles cell resizing */ public void mouseDragged(MouseEvent e) { Component c = e.getComponent(); int x = e.getX(); int y = e.getY(); for (int j=0; j<NumVisX-1; j++) { if (c == HorizDrag[j]) { // resize columns (labels) Dimension s1 = HorizLabel[j].getSize(); Dimension s2 = HorizLabel[j+1].getSize(); int oldW = s1.width; s1.width += x - oldX; if (s1.width < MIN_VIS_WIDTH) s1.width = MIN_VIS_WIDTH; s2.width += oldW - s1.width; if (s2.width < MIN_VIS_WIDTH) { oldW = s2.width; s2.width = MIN_VIS_WIDTH; s1.width += oldW - s2.width; } HorizLabel[j].setSize(s1); HorizLabel[j+1].setSize(s2); for (int i=0; i<NumVisX; i++) { HorizLabel[i].setPreferredSize(HorizLabel[i].getSize()); } HorizLabels.invalidate(); HorizLabels.validate(); return; } } for (int j=0; j<NumVisY-1; j++) { if (c == VertDrag[j]) { // resize rows (labels) Dimension s1 = VertLabel[j].getSize(); Dimension s2 = VertLabel[j+1].getSize(); int oldH = s1.height; s1.height += y - oldY; if (s1.height < MIN_VIS_HEIGHT) s1.height = MIN_VIS_HEIGHT; s2.height += oldH - s1.height; if (s2.height < MIN_VIS_HEIGHT) { oldH = s2.height; s2.height = MIN_VIS_HEIGHT; s1.height += oldH - s2.height; } VertLabel[j].setSize(s1); VertLabel[j+1].setSize(s2); for (int i=0; i<NumVisY; i++) { VertLabel[i].setPreferredSize(VertLabel[i].getSize()); } VertLabels.invalidate(); VertLabels.validate(); return; } } } // unused MouseListener methods public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } // unused MouseMotionListener method public void mouseMoved(MouseEvent e) { } }
true
true
public SpreadSheet(int sWidth, int sHeight, int cols, int rows, String sTitle) { NumVisX = cols; NumVisY = rows; NumVisDisplays = NumVisX*NumVisY; MappingDialog.initDialog(); addKeyListener(this); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { quitProgram(); } }); setBackground(Color.white); // test for Java3D availability try { DisplayImplJ3D test = new DisplayImplJ3D("test"); } catch (UnsatisfiedLinkError err) { CanDo3D = false; } catch (VisADException exc) { CanDo3D = false; } catch (RemoteException exc) { CanDo3D = false; } // set up the content pane JPanel pane = new JPanel(); pane.setBackground(Color.white); pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); setContentPane(pane); // set up menus MenuBar menubar = new MenuBar(); setMenuBar(menubar); // file menu Menu file = new Menu("File"); menubar.add(file); MenuItem fileOpen = new MenuItem("Import data..."); fileOpen.addActionListener(this); fileOpen.setActionCommand("fileOpen"); file.add(fileOpen); MenuItem fileSave = new MenuItem("Export data to netCDF..."); fileSave.addActionListener(this); fileSave.setActionCommand("fileSave"); file.add(fileSave); file.addSeparator(); MenuItem fileExit = new MenuItem("Exit"); fileExit.addActionListener(this); fileExit.setActionCommand("fileExit"); file.add(fileExit); // edit menu Menu edit = new Menu("Edit"); menubar.add(edit); MenuItem editCut = new MenuItem("Cut"); editCut.addActionListener(this); editCut.setActionCommand("editCut"); edit.add(editCut); MenuItem editCopy = new MenuItem("Copy"); editCopy.addActionListener(this); editCopy.setActionCommand("editCopy"); edit.add(editCopy); EditPaste = new MenuItem("Paste"); EditPaste.addActionListener(this); EditPaste.setActionCommand("editPaste"); EditPaste.setEnabled(false); edit.add(EditPaste); MenuItem editClear = new MenuItem("Clear"); editClear.addActionListener(this); editClear.setActionCommand("editClear"); edit.add(editClear); // setup menu Menu setup = new Menu("Setup"); menubar.add(setup); MenuItem setupNew = new MenuItem("New spreadsheet file"); setupNew.addActionListener(this); setupNew.setActionCommand("setupNew"); setup.add(setupNew); MenuItem setupOpen = new MenuItem("Open spreadsheet file..."); setupOpen.addActionListener(this); setupOpen.setActionCommand("setupOpen"); setup.add(setupOpen); MenuItem setupSave = new MenuItem("Save spreadsheet file"); setupSave.addActionListener(this); setupSave.setActionCommand("setupSave"); setup.add(setupSave); MenuItem setupSaveas = new MenuItem("Save spreadsheet file as..."); setupSaveas.addActionListener(this); setupSaveas.setActionCommand("setupSaveas"); setup.add(setupSaveas); // display menu Menu disp = new Menu("Display"); menubar.add(disp); MenuItem dispEdit = new MenuItem("Edit mappings..."); dispEdit.addActionListener(this); dispEdit.setActionCommand("dispEdit"); disp.add(dispEdit); disp.addSeparator(); CellDim3D3D = new CheckboxMenuItem("3-D (Java3D)", CanDo3D); CellDim3D3D.addItemListener(this); CellDim3D3D.setEnabled(CanDo3D); disp.add(CellDim3D3D); CellDim2D2D = new CheckboxMenuItem("2-D (Java2D)", !CanDo3D); CellDim2D2D.addItemListener(this); disp.add(CellDim2D2D); CellDim2D3D = new CheckboxMenuItem("2-D (Java3D)", false); CellDim2D3D.addItemListener(this); CellDim3D3D.setEnabled(CanDo3D); disp.add(CellDim2D3D); // options menu Menu options = new Menu("Options"); menubar.add(options); OptSwitch = new CheckboxMenuItem("Auto-switch to 3-D", CanDo3D); OptSwitch.addItemListener(this); OptSwitch.setEnabled(CanDo3D); options.add(OptSwitch); OptAuto = new CheckboxMenuItem("Auto-detect mappings", true); OptAuto.addItemListener(this); options.add(OptAuto); OptFormula = new CheckboxMenuItem("Show formula error messages", true); OptFormula.addItemListener(this); options.add(OptFormula); options.addSeparator(); MenuItem optWidget = new MenuItem("Show VisAD controls"); optWidget.addActionListener(this); optWidget.setActionCommand("optWidget"); options.add(optWidget); // set up toolbar URL url; JToolBar toolbar = new JToolBar(); toolbar.setBackground(Color.lightGray); toolbar.setBorder(new EtchedBorder()); toolbar.setFloatable(false); pane.add(toolbar); // file menu toolbar icons url = SpreadSheet.class.getResource("open.gif"); ImageIcon toolFileOpen = new ImageIcon(url); if (toolFileOpen != null) { JButton b = new JButton(toolFileOpen); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Import data"); b.addActionListener(this); b.setActionCommand("fileOpen"); toolbar.add(b); } url = SpreadSheet.class.getResource("save.gif"); ImageIcon toolFileSave = new ImageIcon(url); if (toolFileSave != null) { JButton b = new JButton(toolFileSave); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Export data to netCDF"); b.addActionListener(this); b.setActionCommand("fileSave"); toolbar.add(b); } toolbar.addSeparator(); // edit menu toolbar icons url = SpreadSheet.class.getResource("cut.gif"); ImageIcon toolEditCut = new ImageIcon(url); if (toolEditCut != null) { JButton b = new JButton(toolEditCut); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Cut"); b.addActionListener(this); b.setActionCommand("editCut"); toolbar.add(b); } url = SpreadSheet.class.getResource("copy.gif"); ImageIcon toolEditCopy = new ImageIcon(url); if (toolEditCopy != null) { JButton b = new JButton(toolEditCopy); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Copy"); b.addActionListener(this); b.setActionCommand("editCopy"); toolbar.add(b); } url = SpreadSheet.class.getResource("paste.gif"); ImageIcon toolEditPaste = new ImageIcon(url); if (toolEditPaste != null) { ToolPaste = new JButton(toolEditPaste); ToolPaste.setAlignmentY(JButton.CENTER_ALIGNMENT); ToolPaste.setToolTipText("Paste"); ToolPaste.addActionListener(this); ToolPaste.setActionCommand("editPaste"); ToolPaste.setEnabled(false); toolbar.add(ToolPaste); } toolbar.addSeparator(); // mappings menu toolbar icons url = SpreadSheet.class.getResource("mappings.gif"); ImageIcon toolMappingsEdit = new ImageIcon(url); if (toolMappingsEdit != null) { JButton b = new JButton(toolMappingsEdit); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Edit mappings"); b.addActionListener(this); b.setActionCommand("dispEdit"); toolbar.add(b); } // window menu toolbar icons url = SpreadSheet.class.getResource("show.gif"); ImageIcon winShowControls = new ImageIcon(url); if (winShowControls != null) { JButton b = new JButton(winShowControls); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Show VisAD controls"); b.addActionListener(this); b.setActionCommand("optWidget"); toolbar.add(b); } toolbar.add(Box.createHorizontalGlue()); // set up formula bar JPanel formulaPanel = new JPanel(); formulaPanel.setBackground(Color.white); formulaPanel.setLayout(new BoxLayout(formulaPanel, BoxLayout.X_AXIS)); formulaPanel.setBorder(new EtchedBorder()); pane.add(formulaPanel); pane.add(Box.createRigidArea(new Dimension(0, 6))); url = SpreadSheet.class.getResource("cancel.gif"); ImageIcon cancelIcon = new ImageIcon(url); JButton formulaCancel = new JButton(cancelIcon); formulaCancel.setAlignmentY(JButton.CENTER_ALIGNMENT); formulaCancel.setToolTipText("Cancel formula entry"); formulaCancel.addActionListener(this); formulaCancel.setActionCommand("formulaCancel"); Dimension size = new Dimension(cancelIcon.getIconWidth()+4, cancelIcon.getIconHeight()+4); formulaCancel.setPreferredSize(size); formulaPanel.add(formulaCancel); url = SpreadSheet.class.getResource("ok.gif"); ImageIcon okIcon = new ImageIcon(url); FormulaOk = new JButton(okIcon); FormulaOk.setAlignmentY(JButton.CENTER_ALIGNMENT); FormulaOk.setToolTipText("Confirm formula entry"); FormulaOk.addActionListener(this); FormulaOk.setActionCommand("formulaOk"); size = new Dimension(okIcon.getIconWidth()+4, okIcon.getIconHeight()+4); FormulaOk.setPreferredSize(size); formulaPanel.add(FormulaOk); FormulaField = new JTextField(); FormulaField.setToolTipText("Enter a file name or formula"); FormulaField.addActionListener(this); FormulaField.setActionCommand("formulaChange"); formulaPanel.add(FormulaField); url = SpreadSheet.class.getResource("import.gif"); ImageIcon importIcon = new ImageIcon(url); JButton formulaImport = new JButton(importIcon); formulaImport.setAlignmentY(JButton.CENTER_ALIGNMENT); formulaImport.setToolTipText("Import data"); formulaImport.addActionListener(this); formulaImport.setActionCommand("fileOpen"); size = new Dimension(importIcon.getIconWidth()+4, importIcon.getIconHeight()+4); formulaImport.setPreferredSize(size); formulaPanel.add(formulaImport); // label constants final int LABEL_WIDTH = 30; final int LABEL_HEIGHT = 20; // set up horizontal spreadsheet cell labels JPanel horizShell = new JPanel(); horizShell.setBackground(Color.white); horizShell.setLayout(new BoxLayout(horizShell, BoxLayout.X_AXIS)); horizShell.add(Box.createRigidArea(new Dimension(LABEL_WIDTH+10, 0))); pane.add(horizShell); JPanel horizPanel = new JPanel() { public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); return new Dimension(d.width, LABEL_HEIGHT); } }; horizPanel.setLayout(new SSLayout(2*NumVisX-1, 1, MIN_VIS_WIDTH, LABEL_HEIGHT, 0, 0, true)); HorizLabel = new JPanel[NumVisX]; HorizDrag = new JPanel[NumVisX-1]; for (int i=0; i<NumVisX; i++) { String curLet = String.valueOf(Letters.charAt(i)); HorizLabel[i] = new JPanel(); HorizLabel[i].setBorder(new LineBorder(Color.black, 1)); HorizLabel[i].setLayout(new BorderLayout()); HorizLabel[i].setPreferredSize(new Dimension(MIN_VIS_WIDTH, LABEL_HEIGHT)); HorizLabel[i].add("Center", new JLabel(curLet, SwingConstants.CENTER)); horizPanel.add(HorizLabel[i]); if (i < NumVisX-1) { HorizDrag[i] = new JPanel() { public void paint(Graphics g) { Dimension s = getSize(); g.setColor(Color.black); g.drawRect(0, 0, s.width - 1, s.height - 1); g.setColor(Color.yellow); g.fillRect(1, 1, s.width - 2, s.height - 2); } }; HorizDrag[i].setPreferredSize(new Dimension(5, 0)); HorizDrag[i].addMouseListener(this); HorizDrag[i].addMouseMotionListener(this); horizPanel.add(HorizDrag[i]); } } ScrollPane hl = new ScrollPane(ScrollPane.SCROLLBARS_NEVER) { public Dimension getMinimumSize() { return new Dimension(0, LABEL_HEIGHT+4); } public Dimension getPreferredSize() { return new Dimension(0, LABEL_HEIGHT+4); } public Dimension getMaximumSize() { return new Dimension(Integer.MAX_VALUE, LABEL_HEIGHT+4); } }; HorizLabels = hl; HorizLabels.add(horizPanel); horizShell.add(HorizLabels); horizShell.add(Box.createRigidArea(new Dimension(6, 0))); // set up window's main panel JPanel mainPanel = new JPanel(); mainPanel.setBackground(Color.white); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS)); pane.add(mainPanel); pane.add(Box.createRigidArea(new Dimension(0, 6))); // set up vertical spreadsheet cell labels JPanel vertShell = new JPanel(); vertShell.setAlignmentY(JPanel.CENTER_ALIGNMENT); vertShell.setBackground(Color.white); vertShell.setLayout(new BoxLayout(vertShell, BoxLayout.X_AXIS)); mainPanel.add(Box.createRigidArea(new Dimension(6, 0))); mainPanel.add(vertShell); JPanel vertPanel = new JPanel() { public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); return new Dimension(LABEL_WIDTH, d.height); } }; vertPanel.setLayout(new SSLayout(1, 2*NumVisY-1, LABEL_WIDTH, MIN_VIS_HEIGHT, 0, 0, true)); VertLabel = new JPanel[NumVisY]; VertDrag = new JPanel[NumVisY-1]; for (int i=0; i<NumVisY; i++) { VertLabel[i] = new JPanel(); VertLabel[i].setBorder(new LineBorder(Color.black, 1)); VertLabel[i].setLayout(new BorderLayout()); VertLabel[i].setPreferredSize(new Dimension(LABEL_WIDTH, MIN_VIS_HEIGHT)); VertLabel[i].add("Center", new JLabel(""+(i+1), SwingConstants.CENTER)); vertPanel.add(VertLabel[i]); if (i < NumVisY-1) { VertDrag[i] = new JPanel() { public void paint(Graphics g) { Dimension s = getSize(); g.setColor(Color.black); g.drawRect(0, 0, s.width - 1, s.height - 1); g.setColor(Color.yellow); g.fillRect(1, 1, s.width - 2, s.height - 2); } }; VertDrag[i].setBackground(Color.white); VertDrag[i].setPreferredSize(new Dimension(0, 5)); VertDrag[i].addMouseListener(this); VertDrag[i].addMouseMotionListener(this); vertPanel.add(VertDrag[i]); } } ScrollPane vl = new ScrollPane(ScrollPane.SCROLLBARS_NEVER) { public Dimension getMinimumSize() { return new Dimension(LABEL_WIDTH+4, 0); } public Dimension getPreferredSize() { return new Dimension(LABEL_WIDTH+4, 0); } public Dimension getMaximumSize() { return new Dimension(LABEL_WIDTH+4, Integer.MAX_VALUE); } }; VertLabels = vl; VertLabels.add(vertPanel); vertShell.add(VertLabels); // set up scroll pane's panel ScrollPanel = new JPanel(); ScrollPanel.setBackground(Color.white); ScrollPanel.setLayout(new BoxLayout(ScrollPanel, BoxLayout.X_AXIS)); mainPanel.add(ScrollPanel); mainPanel.add(Box.createRigidArea(new Dimension(6, 0))); // set up scroll pane for VisAD Displays SCPane = new ScrollPane() { public Dimension getPreferredSize() { return new Dimension(0, 0); } }; Adjustable hadj = SCPane.getHAdjustable(); Adjustable vadj = SCPane.getVAdjustable(); hadj.setBlockIncrement(MIN_VIS_WIDTH); hadj.setUnitIncrement(MIN_VIS_WIDTH/4); hadj.addAdjustmentListener(this); vadj.setBlockIncrement(MIN_VIS_HEIGHT); vadj.setUnitIncrement(MIN_VIS_HEIGHT/4); vadj.addAdjustmentListener(this); ScrollPanel.add(SCPane); // set up display panel DisplayPanel = new Panel(); DisplayPanel.setBackground(Color.darkGray); DisplayPanel.setLayout(new SSLayout(NumVisX, NumVisY, MIN_VIS_WIDTH, MIN_VIS_HEIGHT, 5, 5, false)); SCPane.add(DisplayPanel); // set up display panel's individual VisAD displays DisplayCells = new FancySSCell[NumVisDisplays]; for (int i=0; i<NumVisDisplays; i++) { String name = String.valueOf(Letters.charAt(i % NumVisX)) + String.valueOf(i / NumVisX + 1); try { DisplayCells[i] = new FancySSCell(name, this); DisplayCells[i].addMouseListener(this); DisplayCells[i].setAutoSwitch(CanDo3D); DisplayCells[i].setDimension(!CanDo3D, !CanDo3D); DisplayCells[i].setDisplayListener(this); DisplayCells[i].setPreferredSize(new Dimension(MIN_VIS_WIDTH, MIN_VIS_HEIGHT)); if (i == 0) DisplayCells[i].setSelected(true); DisplayPanel.add(DisplayCells[i]); } catch (VisADException exc) { JOptionPane.showMessageDialog(this, "Cannot create displays.", "VisAD SpreadSheet error", JOptionPane.ERROR_MESSAGE); } catch (RemoteException exc) { JOptionPane.showMessageDialog(this, "Cannot create displays.", "VisAD SpreadSheet error", JOptionPane.ERROR_MESSAGE); } } // display window on screen setTitle(sTitle); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int appWidth = (int) (0.01*sWidth*screenSize.width); int appHeight = (int) (0.01*sHeight*screenSize.height); setSize(appWidth, appHeight); setLocation(screenSize.width/2 - appWidth/2, screenSize.height/2 - appHeight/2); setVisible(true); }
public SpreadSheet(int sWidth, int sHeight, int cols, int rows, String sTitle) { NumVisX = cols; NumVisY = rows; NumVisDisplays = NumVisX*NumVisY; MappingDialog.initDialog(); addKeyListener(this); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { quitProgram(); } }); setBackground(Color.white); // test for Java3D availability try { DisplayImplJ3D test = new DisplayImplJ3D("test"); } catch (UnsatisfiedLinkError err) { CanDo3D = false; } catch (VisADException exc) { CanDo3D = false; } catch (RemoteException exc) { CanDo3D = false; } // set up the content pane JPanel pane = new JPanel(); pane.setBackground(Color.white); pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); setContentPane(pane); // set up menus MenuBar menubar = new MenuBar(); setMenuBar(menubar); // file menu Menu file = new Menu("File"); menubar.add(file); MenuItem fileOpen = new MenuItem("Import data..."); fileOpen.addActionListener(this); fileOpen.setActionCommand("fileOpen"); file.add(fileOpen); MenuItem fileSave = new MenuItem("Export data to netCDF..."); fileSave.addActionListener(this); fileSave.setActionCommand("fileSave"); file.add(fileSave); file.addSeparator(); MenuItem fileExit = new MenuItem("Exit"); fileExit.addActionListener(this); fileExit.setActionCommand("fileExit"); file.add(fileExit); // edit menu Menu edit = new Menu("Edit"); menubar.add(edit); MenuItem editCut = new MenuItem("Cut"); editCut.addActionListener(this); editCut.setActionCommand("editCut"); edit.add(editCut); MenuItem editCopy = new MenuItem("Copy"); editCopy.addActionListener(this); editCopy.setActionCommand("editCopy"); edit.add(editCopy); EditPaste = new MenuItem("Paste"); EditPaste.addActionListener(this); EditPaste.setActionCommand("editPaste"); EditPaste.setEnabled(false); edit.add(EditPaste); MenuItem editClear = new MenuItem("Clear"); editClear.addActionListener(this); editClear.setActionCommand("editClear"); edit.add(editClear); // setup menu Menu setup = new Menu("Setup"); menubar.add(setup); MenuItem setupNew = new MenuItem("New spreadsheet file"); setupNew.addActionListener(this); setupNew.setActionCommand("setupNew"); setup.add(setupNew); MenuItem setupOpen = new MenuItem("Open spreadsheet file..."); setupOpen.addActionListener(this); setupOpen.setActionCommand("setupOpen"); setup.add(setupOpen); MenuItem setupSave = new MenuItem("Save spreadsheet file"); setupSave.addActionListener(this); setupSave.setActionCommand("setupSave"); setup.add(setupSave); MenuItem setupSaveas = new MenuItem("Save spreadsheet file as..."); setupSaveas.addActionListener(this); setupSaveas.setActionCommand("setupSaveas"); setup.add(setupSaveas); // display menu Menu disp = new Menu("Display"); menubar.add(disp); MenuItem dispEdit = new MenuItem("Edit mappings..."); dispEdit.addActionListener(this); dispEdit.setActionCommand("dispEdit"); disp.add(dispEdit); disp.addSeparator(); CellDim3D3D = new CheckboxMenuItem("3-D (Java3D)", CanDo3D); CellDim3D3D.addItemListener(this); CellDim3D3D.setEnabled(CanDo3D); disp.add(CellDim3D3D); CellDim2D2D = new CheckboxMenuItem("2-D (Java2D)", !CanDo3D); CellDim2D2D.addItemListener(this); disp.add(CellDim2D2D); CellDim2D3D = new CheckboxMenuItem("2-D (Java3D)", false); CellDim2D3D.addItemListener(this); CellDim2D3D.setEnabled(CanDo3D); disp.add(CellDim2D3D); // options menu Menu options = new Menu("Options"); menubar.add(options); OptSwitch = new CheckboxMenuItem("Auto-switch to 3-D", CanDo3D); OptSwitch.addItemListener(this); OptSwitch.setEnabled(CanDo3D); options.add(OptSwitch); OptAuto = new CheckboxMenuItem("Auto-detect mappings", true); OptAuto.addItemListener(this); options.add(OptAuto); OptFormula = new CheckboxMenuItem("Show formula error messages", true); OptFormula.addItemListener(this); options.add(OptFormula); options.addSeparator(); MenuItem optWidget = new MenuItem("Show VisAD controls"); optWidget.addActionListener(this); optWidget.setActionCommand("optWidget"); options.add(optWidget); // set up toolbar URL url; JToolBar toolbar = new JToolBar(); toolbar.setBackground(Color.lightGray); toolbar.setBorder(new EtchedBorder()); toolbar.setFloatable(false); pane.add(toolbar); // file menu toolbar icons url = SpreadSheet.class.getResource("open.gif"); ImageIcon toolFileOpen = new ImageIcon(url); if (toolFileOpen != null) { JButton b = new JButton(toolFileOpen); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Import data"); b.addActionListener(this); b.setActionCommand("fileOpen"); toolbar.add(b); } url = SpreadSheet.class.getResource("save.gif"); ImageIcon toolFileSave = new ImageIcon(url); if (toolFileSave != null) { JButton b = new JButton(toolFileSave); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Export data to netCDF"); b.addActionListener(this); b.setActionCommand("fileSave"); toolbar.add(b); } toolbar.addSeparator(); // edit menu toolbar icons url = SpreadSheet.class.getResource("cut.gif"); ImageIcon toolEditCut = new ImageIcon(url); if (toolEditCut != null) { JButton b = new JButton(toolEditCut); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Cut"); b.addActionListener(this); b.setActionCommand("editCut"); toolbar.add(b); } url = SpreadSheet.class.getResource("copy.gif"); ImageIcon toolEditCopy = new ImageIcon(url); if (toolEditCopy != null) { JButton b = new JButton(toolEditCopy); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Copy"); b.addActionListener(this); b.setActionCommand("editCopy"); toolbar.add(b); } url = SpreadSheet.class.getResource("paste.gif"); ImageIcon toolEditPaste = new ImageIcon(url); if (toolEditPaste != null) { ToolPaste = new JButton(toolEditPaste); ToolPaste.setAlignmentY(JButton.CENTER_ALIGNMENT); ToolPaste.setToolTipText("Paste"); ToolPaste.addActionListener(this); ToolPaste.setActionCommand("editPaste"); ToolPaste.setEnabled(false); toolbar.add(ToolPaste); } toolbar.addSeparator(); // mappings menu toolbar icons url = SpreadSheet.class.getResource("mappings.gif"); ImageIcon toolMappingsEdit = new ImageIcon(url); if (toolMappingsEdit != null) { JButton b = new JButton(toolMappingsEdit); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Edit mappings"); b.addActionListener(this); b.setActionCommand("dispEdit"); toolbar.add(b); } // window menu toolbar icons url = SpreadSheet.class.getResource("show.gif"); ImageIcon winShowControls = new ImageIcon(url); if (winShowControls != null) { JButton b = new JButton(winShowControls); b.setAlignmentY(JButton.CENTER_ALIGNMENT); b.setToolTipText("Show VisAD controls"); b.addActionListener(this); b.setActionCommand("optWidget"); toolbar.add(b); } toolbar.add(Box.createHorizontalGlue()); // set up formula bar JPanel formulaPanel = new JPanel(); formulaPanel.setBackground(Color.white); formulaPanel.setLayout(new BoxLayout(formulaPanel, BoxLayout.X_AXIS)); formulaPanel.setBorder(new EtchedBorder()); pane.add(formulaPanel); pane.add(Box.createRigidArea(new Dimension(0, 6))); url = SpreadSheet.class.getResource("cancel.gif"); ImageIcon cancelIcon = new ImageIcon(url); JButton formulaCancel = new JButton(cancelIcon); formulaCancel.setAlignmentY(JButton.CENTER_ALIGNMENT); formulaCancel.setToolTipText("Cancel formula entry"); formulaCancel.addActionListener(this); formulaCancel.setActionCommand("formulaCancel"); Dimension size = new Dimension(cancelIcon.getIconWidth()+4, cancelIcon.getIconHeight()+4); formulaCancel.setPreferredSize(size); formulaPanel.add(formulaCancel); url = SpreadSheet.class.getResource("ok.gif"); ImageIcon okIcon = new ImageIcon(url); FormulaOk = new JButton(okIcon); FormulaOk.setAlignmentY(JButton.CENTER_ALIGNMENT); FormulaOk.setToolTipText("Confirm formula entry"); FormulaOk.addActionListener(this); FormulaOk.setActionCommand("formulaOk"); size = new Dimension(okIcon.getIconWidth()+4, okIcon.getIconHeight()+4); FormulaOk.setPreferredSize(size); formulaPanel.add(FormulaOk); FormulaField = new JTextField(); FormulaField.setToolTipText("Enter a file name or formula"); FormulaField.addActionListener(this); FormulaField.setActionCommand("formulaChange"); formulaPanel.add(FormulaField); url = SpreadSheet.class.getResource("import.gif"); ImageIcon importIcon = new ImageIcon(url); JButton formulaImport = new JButton(importIcon); formulaImport.setAlignmentY(JButton.CENTER_ALIGNMENT); formulaImport.setToolTipText("Import data"); formulaImport.addActionListener(this); formulaImport.setActionCommand("fileOpen"); size = new Dimension(importIcon.getIconWidth()+4, importIcon.getIconHeight()+4); formulaImport.setPreferredSize(size); formulaPanel.add(formulaImport); // label constants final int LABEL_WIDTH = 30; final int LABEL_HEIGHT = 20; // set up horizontal spreadsheet cell labels JPanel horizShell = new JPanel(); horizShell.setBackground(Color.white); horizShell.setLayout(new BoxLayout(horizShell, BoxLayout.X_AXIS)); horizShell.add(Box.createRigidArea(new Dimension(LABEL_WIDTH+10, 0))); pane.add(horizShell); JPanel horizPanel = new JPanel() { public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); return new Dimension(d.width, LABEL_HEIGHT); } }; horizPanel.setLayout(new SSLayout(2*NumVisX-1, 1, MIN_VIS_WIDTH, LABEL_HEIGHT, 0, 0, true)); HorizLabel = new JPanel[NumVisX]; HorizDrag = new JPanel[NumVisX-1]; for (int i=0; i<NumVisX; i++) { String curLet = String.valueOf(Letters.charAt(i)); HorizLabel[i] = new JPanel(); HorizLabel[i].setBorder(new LineBorder(Color.black, 1)); HorizLabel[i].setLayout(new BorderLayout()); HorizLabel[i].setPreferredSize(new Dimension(MIN_VIS_WIDTH, LABEL_HEIGHT)); HorizLabel[i].add("Center", new JLabel(curLet, SwingConstants.CENTER)); horizPanel.add(HorizLabel[i]); if (i < NumVisX-1) { HorizDrag[i] = new JPanel() { public void paint(Graphics g) { Dimension s = getSize(); g.setColor(Color.black); g.drawRect(0, 0, s.width - 1, s.height - 1); g.setColor(Color.yellow); g.fillRect(1, 1, s.width - 2, s.height - 2); } }; HorizDrag[i].setPreferredSize(new Dimension(5, 0)); HorizDrag[i].addMouseListener(this); HorizDrag[i].addMouseMotionListener(this); horizPanel.add(HorizDrag[i]); } } ScrollPane hl = new ScrollPane(ScrollPane.SCROLLBARS_NEVER) { public Dimension getMinimumSize() { return new Dimension(0, LABEL_HEIGHT+4); } public Dimension getPreferredSize() { return new Dimension(0, LABEL_HEIGHT+4); } public Dimension getMaximumSize() { return new Dimension(Integer.MAX_VALUE, LABEL_HEIGHT+4); } }; HorizLabels = hl; HorizLabels.add(horizPanel); horizShell.add(HorizLabels); horizShell.add(Box.createRigidArea(new Dimension(6, 0))); // set up window's main panel JPanel mainPanel = new JPanel(); mainPanel.setBackground(Color.white); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS)); pane.add(mainPanel); pane.add(Box.createRigidArea(new Dimension(0, 6))); // set up vertical spreadsheet cell labels JPanel vertShell = new JPanel(); vertShell.setAlignmentY(JPanel.CENTER_ALIGNMENT); vertShell.setBackground(Color.white); vertShell.setLayout(new BoxLayout(vertShell, BoxLayout.X_AXIS)); mainPanel.add(Box.createRigidArea(new Dimension(6, 0))); mainPanel.add(vertShell); JPanel vertPanel = new JPanel() { public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); return new Dimension(LABEL_WIDTH, d.height); } }; vertPanel.setLayout(new SSLayout(1, 2*NumVisY-1, LABEL_WIDTH, MIN_VIS_HEIGHT, 0, 0, true)); VertLabel = new JPanel[NumVisY]; VertDrag = new JPanel[NumVisY-1]; for (int i=0; i<NumVisY; i++) { VertLabel[i] = new JPanel(); VertLabel[i].setBorder(new LineBorder(Color.black, 1)); VertLabel[i].setLayout(new BorderLayout()); VertLabel[i].setPreferredSize(new Dimension(LABEL_WIDTH, MIN_VIS_HEIGHT)); VertLabel[i].add("Center", new JLabel(""+(i+1), SwingConstants.CENTER)); vertPanel.add(VertLabel[i]); if (i < NumVisY-1) { VertDrag[i] = new JPanel() { public void paint(Graphics g) { Dimension s = getSize(); g.setColor(Color.black); g.drawRect(0, 0, s.width - 1, s.height - 1); g.setColor(Color.yellow); g.fillRect(1, 1, s.width - 2, s.height - 2); } }; VertDrag[i].setBackground(Color.white); VertDrag[i].setPreferredSize(new Dimension(0, 5)); VertDrag[i].addMouseListener(this); VertDrag[i].addMouseMotionListener(this); vertPanel.add(VertDrag[i]); } } ScrollPane vl = new ScrollPane(ScrollPane.SCROLLBARS_NEVER) { public Dimension getMinimumSize() { return new Dimension(LABEL_WIDTH+4, 0); } public Dimension getPreferredSize() { return new Dimension(LABEL_WIDTH+4, 0); } public Dimension getMaximumSize() { return new Dimension(LABEL_WIDTH+4, Integer.MAX_VALUE); } }; VertLabels = vl; VertLabels.add(vertPanel); vertShell.add(VertLabels); // set up scroll pane's panel ScrollPanel = new JPanel(); ScrollPanel.setBackground(Color.white); ScrollPanel.setLayout(new BoxLayout(ScrollPanel, BoxLayout.X_AXIS)); mainPanel.add(ScrollPanel); mainPanel.add(Box.createRigidArea(new Dimension(6, 0))); // set up scroll pane for VisAD Displays SCPane = new ScrollPane() { public Dimension getPreferredSize() { return new Dimension(0, 0); } }; Adjustable hadj = SCPane.getHAdjustable(); Adjustable vadj = SCPane.getVAdjustable(); hadj.setBlockIncrement(MIN_VIS_WIDTH); hadj.setUnitIncrement(MIN_VIS_WIDTH/4); hadj.addAdjustmentListener(this); vadj.setBlockIncrement(MIN_VIS_HEIGHT); vadj.setUnitIncrement(MIN_VIS_HEIGHT/4); vadj.addAdjustmentListener(this); ScrollPanel.add(SCPane); // set up display panel DisplayPanel = new Panel(); DisplayPanel.setBackground(Color.darkGray); DisplayPanel.setLayout(new SSLayout(NumVisX, NumVisY, MIN_VIS_WIDTH, MIN_VIS_HEIGHT, 5, 5, false)); SCPane.add(DisplayPanel); // set up display panel's individual VisAD displays DisplayCells = new FancySSCell[NumVisDisplays]; for (int i=0; i<NumVisDisplays; i++) { String name = String.valueOf(Letters.charAt(i % NumVisX)) + String.valueOf(i / NumVisX + 1); try { DisplayCells[i] = new FancySSCell(name, this); DisplayCells[i].addMouseListener(this); DisplayCells[i].setAutoSwitch(CanDo3D); DisplayCells[i].setDimension(!CanDo3D, !CanDo3D); DisplayCells[i].setDisplayListener(this); DisplayCells[i].setPreferredSize(new Dimension(MIN_VIS_WIDTH, MIN_VIS_HEIGHT)); if (i == 0) DisplayCells[i].setSelected(true); DisplayPanel.add(DisplayCells[i]); } catch (VisADException exc) { JOptionPane.showMessageDialog(this, "Cannot create displays.", "VisAD SpreadSheet error", JOptionPane.ERROR_MESSAGE); } catch (RemoteException exc) { JOptionPane.showMessageDialog(this, "Cannot create displays.", "VisAD SpreadSheet error", JOptionPane.ERROR_MESSAGE); } } // display window on screen setTitle(sTitle); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int appWidth = (int) (0.01*sWidth*screenSize.width); int appHeight = (int) (0.01*sHeight*screenSize.height); setSize(appWidth, appHeight); setLocation(screenSize.width/2 - appWidth/2, screenSize.height/2 - appHeight/2); setVisible(true); }
diff --git a/src/Conference/MucContact.java b/src/Conference/MucContact.java index e7bc0d38..cce23251 100644 --- a/src/Conference/MucContact.java +++ b/src/Conference/MucContact.java @@ -1,271 +1,272 @@ /* * MucContact.java * * Created on 2.05.2006, 14:05 * Copyright (c) 2005-2008, Eugene Stahov (evgs), http://bombus-im.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * You can also redistribute and/or modify this program under the * terms of the Psi License, specified in the accompanied COPYING * file, as published by the Psi Project; either dated January 1st, * 2005, 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 library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package Conference; import Client.Contact; import Client.Jid; import Client.StaticData; import com.alsutton.jabber.JabberDataBlock; import com.alsutton.jabber.datablocks.Presence; import images.RosterIcons; import locale.SR; import Client.Msg; import util.StringUtils; /** * * @author root */ public class MucContact extends Contact { public final static short AFFILIATION_OUTCAST=-1; public final static short AFFILIATION_NONE=0; public final static short AFFILIATION_MEMBER=1; public final static short AFFILIATION_ADMIN=2; public final static short AFFILIATION_OWNER=3; public final static short ROLE_VISITOR=-1; public final static short ROLE_PARTICIPANT=0; public final static short ROLE_MODERATOR=1; public final static short GROUP_VISITOR=4; public final static short GROUP_MEMBER=3; public final static short GROUP_PARTICIPANT=2; public final static short GROUP_MODERATOR=1; public Jid realJid; public String affiliation; public String role; public short roleCode; public short affiliationCode; public boolean commonPresence=true; public long lastMessageTime; /** Creates a new instance of MucContact * @param nick * @param jid */ public MucContact(String nick, String jid) { super(nick, jid, Presence.PRESENCE_OFFLINE, "muc"); offline_type=Presence.PRESENCE_OFFLINE; } public String processPresence(JabberDataBlock xmuc, Presence presence) { String from=jid.toString(); int presenceType=presence.getTypeIndex(); if (presenceType==Presence.PRESENCE_ERROR) { StaticData.getInstance().roster.roomOffline(group); return StringUtils.processError(presence, presenceType, (ConferenceGroup) group, this); } JabberDataBlock item=xmuc.getChildBlock("item"); String tempRole=item.getAttribute("role"); if (tempRole.equals("visitor")) roleCode=ROLE_VISITOR; else if (tempRole.equals("participant")) roleCode=ROLE_PARTICIPANT; else if (tempRole.equals("moderator")) roleCode=ROLE_MODERATOR; String tempAffiliation=item.getAttribute("affiliation"); if (tempAffiliation.equals("owner")) affiliationCode=AFFILIATION_OWNER; else if (tempAffiliation.equals("admin")) affiliationCode=AFFILIATION_ADMIN; else if (tempAffiliation.equals("member")) affiliationCode=AFFILIATION_MEMBER; else if (tempAffiliation.equals("none")) affiliationCode=AFFILIATION_NONE; boolean roleChanged= !tempRole.equals(role); boolean affiliationChanged=!tempAffiliation.equals(affiliation); role=tempRole; affiliation=tempAffiliation; setSortKey(nick); switch (roleCode) { case ROLE_MODERATOR: transport=RosterIcons.ICON_MODERATOR_INDEX; key0=GROUP_MODERATOR; break; case ROLE_VISITOR: transport=RosterIcons.getInstance().getTransportIndex("muc#vis"); key0=GROUP_VISITOR; break; default: transport=(affiliation.equals("member"))? 0: RosterIcons.getInstance().getTransportIndex("muc#vis"); key0=(affiliation.equals("member"))?GROUP_MEMBER:GROUP_PARTICIPANT; } int statusCode = 0; JabberDataBlock statusBlock = xmuc.getChildBlock("status"); if (statusBlock != null) { try { statusCode = Integer.parseInt(statusBlock.getAttribute("code")); } catch (NumberFormatException e) { } } StringBuffer b=new StringBuffer(); Msg.appendNick(b,nick); String statusText=presence.getChildBlockText("status"); - Jid tempRealJid=new Jid(item.getAttribute("jid")); + String aJid = item.getAttribute("jid"); + Jid tempRealJid = aJid == null ? null : new Jid(aJid); if (statusCode==201) { //todo: fix this nasty hack, it will not work if multiple status codes are nested in presence) b=new StringBuffer(); b.append(SR.MS_NEW_ROOM_CREATED); } else if (presenceType==Presence.PRESENCE_OFFLINE) { key0=3; String reason=item.getChildBlockText("reason"); switch (statusCode) { case 303: b.append(SR.MS_IS_NOW_KNOWN_AS); String chNick=item.getAttribute("nick"); Msg.appendNick(b,chNick); String newJid=from.substring(0, from.indexOf('/')+1)+chNick; jid.setJid(newJid); bareJid=newJid; from=newJid; nick=chNick; break; case 301: //ban presenceType=Presence.PRESENCE_ERROR; case 307: //kick b.append((statusCode==301)? SR.MS_WAS_BANNED : SR.MS_WAS_KICKED ); //#ifdef POPUPS //# if (((ConferenceGroup)group).selfContact == this ) { //# StaticData.getInstance().roster.setWobble(3, this.getJid().toString(), ((statusCode==301)? SR.MS_WAS_BANNED : SR.MS_WAS_KICKED)+((!reason.equals(""))?"\n"+reason:"")); //# } //#endif if (!reason.equals("")) b.append("(").append(reason).append(")"); testMeOffline(); break; case 321: case 322: b.append((statusCode==321)?SR.MS_HAS_BEEN_UNAFFILIATED_AND_KICKED_FROM_MEMBERS_ONLY_ROOM:SR.MS_HAS_BEEN_KICKED_BECAUSE_ROOM_BECAME_MEMBERS_ONLY); testMeOffline(); break; default: if (tempRealJid!=null) b.append(" (").append(tempRealJid).append(")"); //else if (from!=null) // b.append(" (").append(from).append(")"); b.append(SR.MS_HAS_LEFT_CHANNEL); if (statusText.length()>0) b.append(" (").append(statusText).append(")"); testMeOffline(); } } else { if (this.status==Presence.PRESENCE_OFFLINE) { if (tempRealJid!=null) { realJid=tempRealJid; //for moderating purposes b.append(" (").append(tempRealJid).append(')'); } b.append(SR.MS_HAS_JOINED_THE_CHANNEL_AS); if (affiliationCode==AFFILIATION_MEMBER && roleCode==ROLE_PARTICIPANT) { b.append(getAffiliationLocale(affiliationCode)); } else { b.append(getRoleLocale(roleCode)); if (affiliationCode!=AFFILIATION_NONE) { b.append(SR.MS_AND) .append(getAffiliationLocale(affiliationCode)); } } if (statusText.length()>0) b.append(" (").append(statusText).append(")"); } else { b.append(SR.MS_IS_NOW); if (roleChanged) { b.append(getRoleLocale(roleCode)); String reason = item.getChildBlockText("reason"); if (!reason.equals("")) b.append("(").append(reason).append(")"); } if (affiliationChanged) { if (roleChanged) b.append(SR.MS_AND); b.append(getAffiliationLocale(affiliationCode)); } if (!roleChanged && !affiliationChanged) b.append(presence.getPresenceTxt()); } } setStatus(presenceType); return b.toString(); } public static String getRoleLocale(int rol) { switch (rol) { case ROLE_VISITOR: return SR.MS_ROLE_VISITOR; case ROLE_PARTICIPANT: return SR.MS_ROLE_PARTICIPANT; case ROLE_MODERATOR: return SR.MS_ROLE_MODERATOR; } return null; } public static String getAffiliationLocale(int aff) { switch (aff) { case AFFILIATION_NONE: return SR.MS_AFFILIATION_NONE; case AFFILIATION_MEMBER: return SR.MS_AFFILIATION_MEMBER; case AFFILIATION_ADMIN: return SR.MS_AFFILIATION_ADMIN; case AFFILIATION_OWNER: return SR.MS_AFFILIATION_OWNER; } return null; } public void testMeOffline(){ ConferenceGroup gr=(ConferenceGroup)group; if ( gr.selfContact == this ) StaticData.getInstance().roster.roomOffline(gr); } public void addMessage(Msg m) { super.addMessage(m); switch (m.messageType) { case Msg.MESSAGE_TYPE_IN: case Msg.MESSAGE_TYPE_OUT: case Msg.MESSAGE_TYPE_HISTORY: break; default: return; } lastMessageTime=m.dateGmt; } }
true
true
public String processPresence(JabberDataBlock xmuc, Presence presence) { String from=jid.toString(); int presenceType=presence.getTypeIndex(); if (presenceType==Presence.PRESENCE_ERROR) { StaticData.getInstance().roster.roomOffline(group); return StringUtils.processError(presence, presenceType, (ConferenceGroup) group, this); } JabberDataBlock item=xmuc.getChildBlock("item"); String tempRole=item.getAttribute("role"); if (tempRole.equals("visitor")) roleCode=ROLE_VISITOR; else if (tempRole.equals("participant")) roleCode=ROLE_PARTICIPANT; else if (tempRole.equals("moderator")) roleCode=ROLE_MODERATOR; String tempAffiliation=item.getAttribute("affiliation"); if (tempAffiliation.equals("owner")) affiliationCode=AFFILIATION_OWNER; else if (tempAffiliation.equals("admin")) affiliationCode=AFFILIATION_ADMIN; else if (tempAffiliation.equals("member")) affiliationCode=AFFILIATION_MEMBER; else if (tempAffiliation.equals("none")) affiliationCode=AFFILIATION_NONE; boolean roleChanged= !tempRole.equals(role); boolean affiliationChanged=!tempAffiliation.equals(affiliation); role=tempRole; affiliation=tempAffiliation; setSortKey(nick); switch (roleCode) { case ROLE_MODERATOR: transport=RosterIcons.ICON_MODERATOR_INDEX; key0=GROUP_MODERATOR; break; case ROLE_VISITOR: transport=RosterIcons.getInstance().getTransportIndex("muc#vis"); key0=GROUP_VISITOR; break; default: transport=(affiliation.equals("member"))? 0: RosterIcons.getInstance().getTransportIndex("muc#vis"); key0=(affiliation.equals("member"))?GROUP_MEMBER:GROUP_PARTICIPANT; } int statusCode = 0; JabberDataBlock statusBlock = xmuc.getChildBlock("status"); if (statusBlock != null) { try { statusCode = Integer.parseInt(statusBlock.getAttribute("code")); } catch (NumberFormatException e) { } } StringBuffer b=new StringBuffer(); Msg.appendNick(b,nick); String statusText=presence.getChildBlockText("status"); Jid tempRealJid=new Jid(item.getAttribute("jid")); if (statusCode==201) { //todo: fix this nasty hack, it will not work if multiple status codes are nested in presence) b=new StringBuffer(); b.append(SR.MS_NEW_ROOM_CREATED); } else if (presenceType==Presence.PRESENCE_OFFLINE) { key0=3; String reason=item.getChildBlockText("reason"); switch (statusCode) { case 303: b.append(SR.MS_IS_NOW_KNOWN_AS); String chNick=item.getAttribute("nick"); Msg.appendNick(b,chNick); String newJid=from.substring(0, from.indexOf('/')+1)+chNick; jid.setJid(newJid); bareJid=newJid; from=newJid; nick=chNick; break; case 301: //ban presenceType=Presence.PRESENCE_ERROR; case 307: //kick b.append((statusCode==301)? SR.MS_WAS_BANNED : SR.MS_WAS_KICKED ); //#ifdef POPUPS //# if (((ConferenceGroup)group).selfContact == this ) { //# StaticData.getInstance().roster.setWobble(3, this.getJid().toString(), ((statusCode==301)? SR.MS_WAS_BANNED : SR.MS_WAS_KICKED)+((!reason.equals(""))?"\n"+reason:"")); //# } //#endif if (!reason.equals("")) b.append("(").append(reason).append(")"); testMeOffline(); break; case 321: case 322: b.append((statusCode==321)?SR.MS_HAS_BEEN_UNAFFILIATED_AND_KICKED_FROM_MEMBERS_ONLY_ROOM:SR.MS_HAS_BEEN_KICKED_BECAUSE_ROOM_BECAME_MEMBERS_ONLY); testMeOffline(); break; default: if (tempRealJid!=null) b.append(" (").append(tempRealJid).append(")"); //else if (from!=null) // b.append(" (").append(from).append(")"); b.append(SR.MS_HAS_LEFT_CHANNEL); if (statusText.length()>0) b.append(" (").append(statusText).append(")"); testMeOffline(); } } else { if (this.status==Presence.PRESENCE_OFFLINE) { if (tempRealJid!=null) { realJid=tempRealJid; //for moderating purposes b.append(" (").append(tempRealJid).append(')'); } b.append(SR.MS_HAS_JOINED_THE_CHANNEL_AS); if (affiliationCode==AFFILIATION_MEMBER && roleCode==ROLE_PARTICIPANT) { b.append(getAffiliationLocale(affiliationCode)); } else { b.append(getRoleLocale(roleCode)); if (affiliationCode!=AFFILIATION_NONE) { b.append(SR.MS_AND) .append(getAffiliationLocale(affiliationCode)); } } if (statusText.length()>0) b.append(" (").append(statusText).append(")"); } else { b.append(SR.MS_IS_NOW); if (roleChanged) { b.append(getRoleLocale(roleCode)); String reason = item.getChildBlockText("reason"); if (!reason.equals("")) b.append("(").append(reason).append(")"); } if (affiliationChanged) { if (roleChanged) b.append(SR.MS_AND); b.append(getAffiliationLocale(affiliationCode)); } if (!roleChanged && !affiliationChanged) b.append(presence.getPresenceTxt()); } } setStatus(presenceType); return b.toString(); }
public String processPresence(JabberDataBlock xmuc, Presence presence) { String from=jid.toString(); int presenceType=presence.getTypeIndex(); if (presenceType==Presence.PRESENCE_ERROR) { StaticData.getInstance().roster.roomOffline(group); return StringUtils.processError(presence, presenceType, (ConferenceGroup) group, this); } JabberDataBlock item=xmuc.getChildBlock("item"); String tempRole=item.getAttribute("role"); if (tempRole.equals("visitor")) roleCode=ROLE_VISITOR; else if (tempRole.equals("participant")) roleCode=ROLE_PARTICIPANT; else if (tempRole.equals("moderator")) roleCode=ROLE_MODERATOR; String tempAffiliation=item.getAttribute("affiliation"); if (tempAffiliation.equals("owner")) affiliationCode=AFFILIATION_OWNER; else if (tempAffiliation.equals("admin")) affiliationCode=AFFILIATION_ADMIN; else if (tempAffiliation.equals("member")) affiliationCode=AFFILIATION_MEMBER; else if (tempAffiliation.equals("none")) affiliationCode=AFFILIATION_NONE; boolean roleChanged= !tempRole.equals(role); boolean affiliationChanged=!tempAffiliation.equals(affiliation); role=tempRole; affiliation=tempAffiliation; setSortKey(nick); switch (roleCode) { case ROLE_MODERATOR: transport=RosterIcons.ICON_MODERATOR_INDEX; key0=GROUP_MODERATOR; break; case ROLE_VISITOR: transport=RosterIcons.getInstance().getTransportIndex("muc#vis"); key0=GROUP_VISITOR; break; default: transport=(affiliation.equals("member"))? 0: RosterIcons.getInstance().getTransportIndex("muc#vis"); key0=(affiliation.equals("member"))?GROUP_MEMBER:GROUP_PARTICIPANT; } int statusCode = 0; JabberDataBlock statusBlock = xmuc.getChildBlock("status"); if (statusBlock != null) { try { statusCode = Integer.parseInt(statusBlock.getAttribute("code")); } catch (NumberFormatException e) { } } StringBuffer b=new StringBuffer(); Msg.appendNick(b,nick); String statusText=presence.getChildBlockText("status"); String aJid = item.getAttribute("jid"); Jid tempRealJid = aJid == null ? null : new Jid(aJid); if (statusCode==201) { //todo: fix this nasty hack, it will not work if multiple status codes are nested in presence) b=new StringBuffer(); b.append(SR.MS_NEW_ROOM_CREATED); } else if (presenceType==Presence.PRESENCE_OFFLINE) { key0=3; String reason=item.getChildBlockText("reason"); switch (statusCode) { case 303: b.append(SR.MS_IS_NOW_KNOWN_AS); String chNick=item.getAttribute("nick"); Msg.appendNick(b,chNick); String newJid=from.substring(0, from.indexOf('/')+1)+chNick; jid.setJid(newJid); bareJid=newJid; from=newJid; nick=chNick; break; case 301: //ban presenceType=Presence.PRESENCE_ERROR; case 307: //kick b.append((statusCode==301)? SR.MS_WAS_BANNED : SR.MS_WAS_KICKED ); //#ifdef POPUPS //# if (((ConferenceGroup)group).selfContact == this ) { //# StaticData.getInstance().roster.setWobble(3, this.getJid().toString(), ((statusCode==301)? SR.MS_WAS_BANNED : SR.MS_WAS_KICKED)+((!reason.equals(""))?"\n"+reason:"")); //# } //#endif if (!reason.equals("")) b.append("(").append(reason).append(")"); testMeOffline(); break; case 321: case 322: b.append((statusCode==321)?SR.MS_HAS_BEEN_UNAFFILIATED_AND_KICKED_FROM_MEMBERS_ONLY_ROOM:SR.MS_HAS_BEEN_KICKED_BECAUSE_ROOM_BECAME_MEMBERS_ONLY); testMeOffline(); break; default: if (tempRealJid!=null) b.append(" (").append(tempRealJid).append(")"); //else if (from!=null) // b.append(" (").append(from).append(")"); b.append(SR.MS_HAS_LEFT_CHANNEL); if (statusText.length()>0) b.append(" (").append(statusText).append(")"); testMeOffline(); } } else { if (this.status==Presence.PRESENCE_OFFLINE) { if (tempRealJid!=null) { realJid=tempRealJid; //for moderating purposes b.append(" (").append(tempRealJid).append(')'); } b.append(SR.MS_HAS_JOINED_THE_CHANNEL_AS); if (affiliationCode==AFFILIATION_MEMBER && roleCode==ROLE_PARTICIPANT) { b.append(getAffiliationLocale(affiliationCode)); } else { b.append(getRoleLocale(roleCode)); if (affiliationCode!=AFFILIATION_NONE) { b.append(SR.MS_AND) .append(getAffiliationLocale(affiliationCode)); } } if (statusText.length()>0) b.append(" (").append(statusText).append(")"); } else { b.append(SR.MS_IS_NOW); if (roleChanged) { b.append(getRoleLocale(roleCode)); String reason = item.getChildBlockText("reason"); if (!reason.equals("")) b.append("(").append(reason).append(")"); } if (affiliationChanged) { if (roleChanged) b.append(SR.MS_AND); b.append(getAffiliationLocale(affiliationCode)); } if (!roleChanged && !affiliationChanged) b.append(presence.getPresenceTxt()); } } setStatus(presenceType); return b.toString(); }
diff --git a/atlas-dao/src/main/java/uk/ac/ebi/gxa/dao/AbstractDAO.java b/atlas-dao/src/main/java/uk/ac/ebi/gxa/dao/AbstractDAO.java index f3ef5c3de..e08f21948 100644 --- a/atlas-dao/src/main/java/uk/ac/ebi/gxa/dao/AbstractDAO.java +++ b/atlas-dao/src/main/java/uk/ac/ebi/gxa/dao/AbstractDAO.java @@ -1,78 +1,78 @@ package uk.ac.ebi.gxa.dao; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.HibernateTemplate; import uk.ac.ebi.gxa.dao.exceptions.RecordNotFoundException; import java.util.List; public abstract class AbstractDAO<T> { protected final HibernateTemplate template; private final Class<T> clazz; /** * @return the name of column used as name for {@link #getByName} method */ protected abstract String getNameColumn(); /** * @return false by default - case should match as is by default in getByName() queries */ protected boolean lowerCaseNameMatch() { return false; } protected AbstractDAO(SessionFactory sessionFactory, Class<T> clazz) { this.clazz = clazz; this.template = new HibernateTemplate(sessionFactory); } public T getById(long id) { return clazz.cast(template.get(clazz, id)); } @SuppressWarnings("unchecked") public List<T> getAll() { return template.find("from " + clazz.getName()); } public void save(T object) { template.saveOrUpdate(object); } /** * @param name * @return instance of class T that matches name * @throws uk.ac.ebi.gxa.dao.exceptions.RecordNotFoundException * */ public T getByName(String name) throws RecordNotFoundException { return getByName(name, getNameColumn()); } /** * @param name * @param colName * @return instance of class T that matches name, searching through colName * @throws uk.ac.ebi.gxa.dao.exceptions.RecordNotFoundException * */ public T getByName(String name, String colName) throws RecordNotFoundException { @SuppressWarnings("unchecked") final List<T> results = template.find("from " + clazz.getSimpleName() + " where " + colName + " = ?", (lowerCaseNameMatch() ? name.toLowerCase() : name)); return getOnly(results); } /** * @param objects * @return first element of objects * @throws uk.ac.ebi.gxa.dao.exceptions.RecordNotFoundException * if objects' length == 0 */ protected T getOnly(List<T> objects) throws RecordNotFoundException { if (objects.size() == 1) return objects.get(0); else - throw new RecordNotFoundException(clazz.getName() + ": " + objects.size() + "objects returned; expected 1)"); + throw new RecordNotFoundException(clazz.getName() + ": " + objects.size() + " objects returned; expected 1)"); } }
true
true
protected T getOnly(List<T> objects) throws RecordNotFoundException { if (objects.size() == 1) return objects.get(0); else throw new RecordNotFoundException(clazz.getName() + ": " + objects.size() + "objects returned; expected 1)"); }
protected T getOnly(List<T> objects) throws RecordNotFoundException { if (objects.size() == 1) return objects.get(0); else throw new RecordNotFoundException(clazz.getName() + ": " + objects.size() + " objects returned; expected 1)"); }
diff --git a/cotrix/cotrix-io/src/main/java/org/cotrix/io/sdmx/map/Codelist2Sdmx.java b/cotrix/cotrix-io/src/main/java/org/cotrix/io/sdmx/map/Codelist2Sdmx.java index 0849f51c..455d9deb 100644 --- a/cotrix/cotrix-io/src/main/java/org/cotrix/io/sdmx/map/Codelist2Sdmx.java +++ b/cotrix/cotrix-io/src/main/java/org/cotrix/io/sdmx/map/Codelist2Sdmx.java @@ -1,240 +1,241 @@ package org.cotrix.io.sdmx.map; import static org.cotrix.common.Log.*; import static org.cotrix.common.Report.*; import static org.cotrix.common.Report.Item.Type.*; import static org.sdmxsource.sdmx.api.constants.TERTIARY_BOOL.*; import java.text.ParseException; import java.util.Calendar; import org.cotrix.common.Report; import org.cotrix.domain.attributes.Attribute; import org.cotrix.domain.codelist.Code; import org.cotrix.domain.codelist.Codelist; import org.cotrix.domain.links.Link; import org.cotrix.domain.trait.Described; import org.cotrix.domain.trait.Named; import org.cotrix.domain.utils.DomainUtils; import org.cotrix.io.impl.MapTask; import org.cotrix.io.sdmx.SdmxElement; import org.cotrix.io.sdmx.map.Codelist2SdmxDirectives.GetClause; import org.sdmxsource.sdmx.api.exception.SdmxSemmanticException; import org.sdmxsource.sdmx.api.model.beans.codelist.CodelistBean; import org.sdmxsource.sdmx.api.model.mutable.base.AnnotationMutableBean; import org.sdmxsource.sdmx.api.model.mutable.base.NameableMutableBean; import org.sdmxsource.sdmx.api.model.mutable.codelist.CodeMutableBean; import org.sdmxsource.sdmx.api.model.mutable.codelist.CodelistMutableBean; import org.sdmxsource.sdmx.sdmxbeans.model.mutable.base.AnnotationMutableBeanImpl; import org.sdmxsource.sdmx.sdmxbeans.model.mutable.codelist.CodeMutableBeanImpl; import org.sdmxsource.sdmx.sdmxbeans.model.mutable.codelist.CodelistMutableBeanImpl; import org.sdmxsource.sdmx.util.date.DateUtil; /** * Transforms {@link Codelist}s in {@link CodelistBean}s. * <p> * * * @author Fabio Simeoni * */ /* defaults: * * (local) names -> ids (and names if no other are specified) * version -> version * agency -> default agency * status > undefined * * * */ public class Codelist2Sdmx implements MapTask<Codelist,CodelistBean,Codelist2SdmxDirectives> { @Override public Class<Codelist2SdmxDirectives> directedBy() { return Codelist2SdmxDirectives.class; } /** * Applies the transformation to a given {@link Codelist} with given directives. * @param codelist the codelist * @params directives the directives * @return the result of the transformation * @throws Exception if the given codelist cannot be transformed */ public CodelistBean map(Codelist codelist, Codelist2SdmxDirectives directives) throws Exception { double time = System.currentTimeMillis(); report().log(item("transforming codelist "+codelist.qname()+"("+codelist.id()+") to SDMX")).as(INFO) .log(item(Calendar.getInstance().getTime().toString())).as(INFO); String id = directives.id()==null?codelist.qname().getLocalPart():directives.id(); CodelistMutableBean codelistbean = new CodelistMutableBeanImpl(); codelistbean.setAgencyId(directives.agency()); codelistbean.setId(id); codelistbean.setVersion(directives.version()==null?codelist.version():directives.version()); codelistbean.setFinalStructure(directives.isFinal()==null?UNSET:directives.isFinal()==true?TRUE:FALSE); mapCodelistAttributes(codelist,codelistbean,directives); if (codelistbean.getNames()==null) codelistbean.addName("en",codelistbean.getId()); for (Code code : codelist.codes()) { CodeMutableBean codebean = new CodeMutableBeanImpl(); if (code.qname()==null) { report().log(item(code.id()+" has no name ")).as(ERROR); continue; } codebean.setId(code.qname().getLocalPart()); mapAttributes(code,codebean,directives.forCodes()); mapCodelinks(code, codebean, directives.forCodes()); //default name if (codebean.getNames()==null) codebean.addName("en",codebean.getId()); codelistbean.addItem(codebean); } String msg = "transformed codelist "+codelist.qname()+"("+codelist.id()+") to SDMX in "+(System.currentTimeMillis()-time)/1000; report().log(item(msg)).as(INFO); try { return codelistbean.getImmutableInstance(); } catch(SdmxSemmanticException e) {//hilarious, check the spelling... - throw new RuntimeException("invalid sdmx result: "+unwrapErrorDescription(e),e); + report().log("SDMX validation error: "+unwrapErrorDescription(e)).as(ERROR); + return null; } } //helpers private String unwrapErrorDescription(Throwable t) { while (t.getCause()!=null && t.getCause() instanceof SdmxSemmanticException) t = t.getCause(); return t.getMessage(); } private void mapCodelistAttributes(Codelist list, CodelistMutableBean bean, Codelist2SdmxDirectives directives) { //name-based pass for (Attribute a : list.attributes()) { String val = a.value(); SdmxElement element = directives.forCodelist().get(a); if (element!=null) switch(element) { case VALID_FROM: try { bean.setStartDate(DateUtil.getDateTimeFormat().parse(val)); } catch(ParseException e) { Report.report().log(item("unparseable start date: "+a.value())).as(WARN); } break; case VALID_TO: try { bean.setEndDate(DateUtil.getDateTimeFormat().parse(val)); } catch(ParseException e) { Report.report().log(item("unparseable end date: "+a.value())).as(WARN); } break; default: } } mapAttributes(list, bean,directives.forCodelist()); } private <T extends Described & Named> void mapAttributes(T attributed, NameableMutableBean bean, GetClause directives) { for (Attribute a : attributed.attributes()) { String val = a.value(); String lang = a.language()==null?"en":a.language(); SdmxElement element = directives.get(a); if (element!=null) switch(element) { case NAME: bean.addName(lang,val); break; case DESCRIPTION: bean.addDescription(lang,val); break; case ANNOTATION: AnnotationMutableBean annotation = new AnnotationMutableBeanImpl(); annotation.setTitle(a.qname().getLocalPart()); annotation.addText(lang, val); bean.addAnnotation(annotation); break; default: } } } private void mapCodelinks(Code code, NameableMutableBean bean, GetClause directives) { for (Link link : code.links()) { String val = link.valueAsString(); String lang = DomainUtils.languageOf(link.definition()); SdmxElement element = directives.get(link); if (element!=null) switch(element) { case NAME: bean.addName(lang,val); break; case DESCRIPTION: bean.addDescription(lang,val); break; case ANNOTATION: AnnotationMutableBean annotation = new AnnotationMutableBeanImpl(); annotation.setTitle(link.qname().getLocalPart()); annotation.addText(lang, val); bean.addAnnotation(annotation); break; default: } } } @Override public String toString() { return "codelist-2-sdmx"; } }
true
true
public CodelistBean map(Codelist codelist, Codelist2SdmxDirectives directives) throws Exception { double time = System.currentTimeMillis(); report().log(item("transforming codelist "+codelist.qname()+"("+codelist.id()+") to SDMX")).as(INFO) .log(item(Calendar.getInstance().getTime().toString())).as(INFO); String id = directives.id()==null?codelist.qname().getLocalPart():directives.id(); CodelistMutableBean codelistbean = new CodelistMutableBeanImpl(); codelistbean.setAgencyId(directives.agency()); codelistbean.setId(id); codelistbean.setVersion(directives.version()==null?codelist.version():directives.version()); codelistbean.setFinalStructure(directives.isFinal()==null?UNSET:directives.isFinal()==true?TRUE:FALSE); mapCodelistAttributes(codelist,codelistbean,directives); if (codelistbean.getNames()==null) codelistbean.addName("en",codelistbean.getId()); for (Code code : codelist.codes()) { CodeMutableBean codebean = new CodeMutableBeanImpl(); if (code.qname()==null) { report().log(item(code.id()+" has no name ")).as(ERROR); continue; } codebean.setId(code.qname().getLocalPart()); mapAttributes(code,codebean,directives.forCodes()); mapCodelinks(code, codebean, directives.forCodes()); //default name if (codebean.getNames()==null) codebean.addName("en",codebean.getId()); codelistbean.addItem(codebean); } String msg = "transformed codelist "+codelist.qname()+"("+codelist.id()+") to SDMX in "+(System.currentTimeMillis()-time)/1000; report().log(item(msg)).as(INFO); try { return codelistbean.getImmutableInstance(); } catch(SdmxSemmanticException e) {//hilarious, check the spelling... throw new RuntimeException("invalid sdmx result: "+unwrapErrorDescription(e),e); } }
public CodelistBean map(Codelist codelist, Codelist2SdmxDirectives directives) throws Exception { double time = System.currentTimeMillis(); report().log(item("transforming codelist "+codelist.qname()+"("+codelist.id()+") to SDMX")).as(INFO) .log(item(Calendar.getInstance().getTime().toString())).as(INFO); String id = directives.id()==null?codelist.qname().getLocalPart():directives.id(); CodelistMutableBean codelistbean = new CodelistMutableBeanImpl(); codelistbean.setAgencyId(directives.agency()); codelistbean.setId(id); codelistbean.setVersion(directives.version()==null?codelist.version():directives.version()); codelistbean.setFinalStructure(directives.isFinal()==null?UNSET:directives.isFinal()==true?TRUE:FALSE); mapCodelistAttributes(codelist,codelistbean,directives); if (codelistbean.getNames()==null) codelistbean.addName("en",codelistbean.getId()); for (Code code : codelist.codes()) { CodeMutableBean codebean = new CodeMutableBeanImpl(); if (code.qname()==null) { report().log(item(code.id()+" has no name ")).as(ERROR); continue; } codebean.setId(code.qname().getLocalPart()); mapAttributes(code,codebean,directives.forCodes()); mapCodelinks(code, codebean, directives.forCodes()); //default name if (codebean.getNames()==null) codebean.addName("en",codebean.getId()); codelistbean.addItem(codebean); } String msg = "transformed codelist "+codelist.qname()+"("+codelist.id()+") to SDMX in "+(System.currentTimeMillis()-time)/1000; report().log(item(msg)).as(INFO); try { return codelistbean.getImmutableInstance(); } catch(SdmxSemmanticException e) {//hilarious, check the spelling... report().log("SDMX validation error: "+unwrapErrorDescription(e)).as(ERROR); return null; } }
diff --git a/src/jmxsh/SetCmd.java b/src/jmxsh/SetCmd.java index 3a5f5a1..a1fffea 100755 --- a/src/jmxsh/SetCmd.java +++ b/src/jmxsh/SetCmd.java @@ -1,163 +1,163 @@ /* * $URL$ * * $Revision$ * * $LastChangedDate$ * * $LastChangedBy$ * * 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 jmxsh; import org.apache.commons.cli.*; //import org.apache.log4j.Logger; import tcl.lang.*; class SetCmd implements Command { private final static SetCmd instance = new SetCmd(); static SetCmd getInstance() { return instance; } private SetCmd() { opts = new Options(); opts.addOption( OptionBuilder.withLongOpt("server") .withDescription("Server containing mbean.") .withArgName("SERVER") .hasArg() .create("s") ); opts.addOption( OptionBuilder.withLongOpt("mbean") .withDescription("MBean containing attribute.") .withArgName("MBEAN") .hasArg() .create("m") ); opts.addOption( OptionBuilder.withLongOpt("help") .withDescription("Display usage help.") .hasArg(false) .create("?") ); } private CommandLine parseCommandLine(TclObject argv[]) throws ParseException { String[] args = new String[argv.length - 1]; for(int i = 0; i < argv.length - 1; i++) args[i] = argv[i + 1].toString(); CommandLine cl = (new PosixParser()).parse(opts, args); return cl; } private void getDefaults(Interp interp) { server = null; //domain = null; mbean = null; attrop = null; try { server = interp.getVar("SERVER", TCL.GLOBAL_ONLY).toString(); //domain = interp.getVar("DOMAIN", TCL.GLOBAL_ONLY).toString(); mbean = interp.getVar("MBEAN", TCL.GLOBAL_ONLY).toString(); attrop = interp.getVar("ATTROP", TCL.GLOBAL_ONLY).toString(); } catch (TclException e) { /* If one doesn't exist, it will just be null. */ } } public void cmdProc(Interp interp, TclObject argv[]) throws TclException { try { CommandLine cl = parseCommandLine(argv); String args[] = cl.getArgs(); String attribute = null; TclObject newvalue = null; if (cl.hasOption("help")) { new HelpFormatter().printHelp ( "jmx_set [-?] [-s server] [-m mbean] [ATTRIBUTE] NEW_VALUE", "======================================================================", opts, "======================================================================", false ); System.out.println("jmx_set updates the current value of the given attribute."); System.out.println("If you do not specify server, mbean, or ATTRIBUTE, then the"); System.out.println("values in the global variables SERVER, MBEAN, and ATTROP,"); System.out.println("respectively, will be used."); return; } getDefaults(interp); server = cl.getOptionValue("server", server); mbean = cl.getOptionValue("mbean", mbean); attrop = cl.getOptionValue("attrop", attrop); if (args.length > 1) { attribute = args[0]; newvalue = argv[argv.length-args.length+1]; } else { attribute = attrop; newvalue = argv[argv.length-args.length]; } if (server == null) { throw new TclException(interp, "No server specified; please set SERVER variable or use -s option.", TCL.ERROR); } if (mbean == null) { throw new TclException(interp, "No mbean specified; please set MBEAN variable or use -m option.", TCL.ERROR); } - if (attrop == null) { + if (attribute == null) { throw new TclException(interp, "No attribute specified; please set ATTROP variable or add it to the command line.", TCL.ERROR); } if (newvalue == null) { throw new TclException(interp, "No new value provided for the attribute.", TCL.ERROR); } Jmx.getInstance().setAttribute(server, mbean, attribute, newvalue); } catch(ParseException e) { throw new TclException(interp, e.getMessage(), 1); } catch(RuntimeException e) { - throw new TclException(interp, "Cannot convert result to a string.", 1); + throw new TclException(interp, e.getMessage(), 1); } } private String server; //private String domain; private String mbean; private String attrop; //private static Logger logger = Logger.getLogger(SetCmd.class); private Options opts; }
false
true
public void cmdProc(Interp interp, TclObject argv[]) throws TclException { try { CommandLine cl = parseCommandLine(argv); String args[] = cl.getArgs(); String attribute = null; TclObject newvalue = null; if (cl.hasOption("help")) { new HelpFormatter().printHelp ( "jmx_set [-?] [-s server] [-m mbean] [ATTRIBUTE] NEW_VALUE", "======================================================================", opts, "======================================================================", false ); System.out.println("jmx_set updates the current value of the given attribute."); System.out.println("If you do not specify server, mbean, or ATTRIBUTE, then the"); System.out.println("values in the global variables SERVER, MBEAN, and ATTROP,"); System.out.println("respectively, will be used."); return; } getDefaults(interp); server = cl.getOptionValue("server", server); mbean = cl.getOptionValue("mbean", mbean); attrop = cl.getOptionValue("attrop", attrop); if (args.length > 1) { attribute = args[0]; newvalue = argv[argv.length-args.length+1]; } else { attribute = attrop; newvalue = argv[argv.length-args.length]; } if (server == null) { throw new TclException(interp, "No server specified; please set SERVER variable or use -s option.", TCL.ERROR); } if (mbean == null) { throw new TclException(interp, "No mbean specified; please set MBEAN variable or use -m option.", TCL.ERROR); } if (attrop == null) { throw new TclException(interp, "No attribute specified; please set ATTROP variable or add it to the command line.", TCL.ERROR); } if (newvalue == null) { throw new TclException(interp, "No new value provided for the attribute.", TCL.ERROR); } Jmx.getInstance().setAttribute(server, mbean, attribute, newvalue); } catch(ParseException e) { throw new TclException(interp, e.getMessage(), 1); } catch(RuntimeException e) { throw new TclException(interp, "Cannot convert result to a string.", 1); } }
public void cmdProc(Interp interp, TclObject argv[]) throws TclException { try { CommandLine cl = parseCommandLine(argv); String args[] = cl.getArgs(); String attribute = null; TclObject newvalue = null; if (cl.hasOption("help")) { new HelpFormatter().printHelp ( "jmx_set [-?] [-s server] [-m mbean] [ATTRIBUTE] NEW_VALUE", "======================================================================", opts, "======================================================================", false ); System.out.println("jmx_set updates the current value of the given attribute."); System.out.println("If you do not specify server, mbean, or ATTRIBUTE, then the"); System.out.println("values in the global variables SERVER, MBEAN, and ATTROP,"); System.out.println("respectively, will be used."); return; } getDefaults(interp); server = cl.getOptionValue("server", server); mbean = cl.getOptionValue("mbean", mbean); attrop = cl.getOptionValue("attrop", attrop); if (args.length > 1) { attribute = args[0]; newvalue = argv[argv.length-args.length+1]; } else { attribute = attrop; newvalue = argv[argv.length-args.length]; } if (server == null) { throw new TclException(interp, "No server specified; please set SERVER variable or use -s option.", TCL.ERROR); } if (mbean == null) { throw new TclException(interp, "No mbean specified; please set MBEAN variable or use -m option.", TCL.ERROR); } if (attribute == null) { throw new TclException(interp, "No attribute specified; please set ATTROP variable or add it to the command line.", TCL.ERROR); } if (newvalue == null) { throw new TclException(interp, "No new value provided for the attribute.", TCL.ERROR); } Jmx.getInstance().setAttribute(server, mbean, attribute, newvalue); } catch(ParseException e) { throw new TclException(interp, e.getMessage(), 1); } catch(RuntimeException e) { throw new TclException(interp, e.getMessage(), 1); } }
diff --git a/integrar-t-android/src/main/java/org/utn/proyecto/helpful/integrart/integrar_t_android/menu/ItemDetailActivity.java b/integrar-t-android/src/main/java/org/utn/proyecto/helpful/integrart/integrar_t_android/menu/ItemDetailActivity.java index f200178..cadf6cd 100644 --- a/integrar-t-android/src/main/java/org/utn/proyecto/helpful/integrart/integrar_t_android/menu/ItemDetailActivity.java +++ b/integrar-t-android/src/main/java/org/utn/proyecto/helpful/integrart/integrar_t_android/menu/ItemDetailActivity.java @@ -1,40 +1,41 @@ package org.utn.proyecto.helpful.integrart.integrar_t_android.menu; import org.utn.proyecto.helpful.integrart.integrar_t_android.R; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.*; import android.view.MenuItem; public class ItemDetailActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mam_activity_item_list); + setContentView(R.layout.mam_activity_item_detail); getActionBar().setDisplayHomeAsUpEnabled(true); if (savedInstanceState == null) { Bundle arguments = new Bundle(); arguments.putString(ItemDetailFragment.ARG_ITEM_ID, getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID)); ItemDetailFragment fragment = new ItemDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .add(R.id.item_detail_container, fragment) .commit(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { NavUtils.navigateUpTo(this, new Intent(this, ItemListActivity.class)); return true; } return super.onOptionsItemSelected(item); } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mam_activity_item_list); getActionBar().setDisplayHomeAsUpEnabled(true); if (savedInstanceState == null) { Bundle arguments = new Bundle(); arguments.putString(ItemDetailFragment.ARG_ITEM_ID, getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID)); ItemDetailFragment fragment = new ItemDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .add(R.id.item_detail_container, fragment) .commit(); } }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mam_activity_item_list); setContentView(R.layout.mam_activity_item_detail); getActionBar().setDisplayHomeAsUpEnabled(true); if (savedInstanceState == null) { Bundle arguments = new Bundle(); arguments.putString(ItemDetailFragment.ARG_ITEM_ID, getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID)); ItemDetailFragment fragment = new ItemDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .add(R.id.item_detail_container, fragment) .commit(); } }
diff --git a/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/Weapons/ProjectileWeapon.java b/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/Weapons/ProjectileWeapon.java index e4ed090..f532156 100644 --- a/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/Weapons/ProjectileWeapon.java +++ b/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/Weapons/ProjectileWeapon.java @@ -1,95 +1,95 @@ /* * The MIT License * * Copyright 2013 Manuel Gauto. * * 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 org.mgenterprises.java.bukkit.gmcfps.Core.Weapons; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.inventory.ItemStack; import org.mgenterprises.java.bukkit.gmcfps.Core.InternalEvents.Events.WeaponFiredEvent; /** * * @author Manuel Gauto */ public abstract class ProjectileWeapon extends Weapon { private Material ammoMaterial; private EntityType projectileType; private int fireDelay; public ProjectileWeapon(WeaponManager wm, String name, Material m, Material ammoType, EntityType projectileType, int fireDelay) { super(wm, name, m); this.ammoMaterial = ammoType; this.fireDelay = fireDelay; this.projectileType = projectileType; } public Material getAmmunitionType() { return this.ammoMaterial; } public abstract void onWeaponFire(Player p); @Override public void onWeaponRightClick(WeaponFiredEvent event) { //System.out.println(event); if(super.getWeaponManager().waiting.contains(event.getPlayer().getName())){ return; } boolean hasAmmoLeft = event.getPlayer().getInventory().contains(ammoMaterial); if (hasAmmoLeft) { - int slot = event.getPlayer().getInventory().first(ammoUsed); + int slot = event.getPlayer().getInventory().first(ammoMaterial); if(slot > -1){ ItemStack itemStack = event.getPlayer().getInventory().getItem(slot); itemStack.setAmount(itemStack.getAmount()-1); - event.getPlayer().getInventory().setItem(itemStack); + event.getPlayer().getInventory().setItem(slot,itemStack); onWeaponFire(event.getPlayer()); scheduleDelay(event.getPlayer()); } } } @Override public boolean isThrowable() { return false; } @Override public boolean isProjectile() { return true; } public EntityType getProjectileType(){ return this.projectileType; } public abstract void onProjectileHit(EntityDamageByEntityEvent event); private void scheduleDelay(Player p) { Bukkit.getScheduler().scheduleSyncDelayedTask(super.getWeaponManager().getFPSCore().getPluginReference(), new DelayRunnable(super.getWeaponManager().getFPSCore(), p), this.fireDelay); } }
false
true
public void onWeaponRightClick(WeaponFiredEvent event) { //System.out.println(event); if(super.getWeaponManager().waiting.contains(event.getPlayer().getName())){ return; } boolean hasAmmoLeft = event.getPlayer().getInventory().contains(ammoMaterial); if (hasAmmoLeft) { int slot = event.getPlayer().getInventory().first(ammoUsed); if(slot > -1){ ItemStack itemStack = event.getPlayer().getInventory().getItem(slot); itemStack.setAmount(itemStack.getAmount()-1); event.getPlayer().getInventory().setItem(itemStack); onWeaponFire(event.getPlayer()); scheduleDelay(event.getPlayer()); } } }
public void onWeaponRightClick(WeaponFiredEvent event) { //System.out.println(event); if(super.getWeaponManager().waiting.contains(event.getPlayer().getName())){ return; } boolean hasAmmoLeft = event.getPlayer().getInventory().contains(ammoMaterial); if (hasAmmoLeft) { int slot = event.getPlayer().getInventory().first(ammoMaterial); if(slot > -1){ ItemStack itemStack = event.getPlayer().getInventory().getItem(slot); itemStack.setAmount(itemStack.getAmount()-1); event.getPlayer().getInventory().setItem(slot,itemStack); onWeaponFire(event.getPlayer()); scheduleDelay(event.getPlayer()); } } }
diff --git a/javasrc/src/org/ccnx/ccn/impl/support/DaemonOutput.java b/javasrc/src/org/ccnx/ccn/impl/support/DaemonOutput.java index ec446f91d..2db637067 100644 --- a/javasrc/src/org/ccnx/ccn/impl/support/DaemonOutput.java +++ b/javasrc/src/org/ccnx/ccn/impl/support/DaemonOutput.java @@ -1,51 +1,63 @@ /* * Part of the CCNx Java Library. * * Copyright (C) 2008, 2009 Palo Alto Research Center, Inc. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. * 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., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA. */ package org.ccnx.ccn.impl.support; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Routes output from the daemon stdout/stderr to a file */ public class DaemonOutput extends Thread { private InputStream _is; private OutputStream _os; public DaemonOutput(InputStream is, OutputStream os) throws FileNotFoundException { _is = is; _os = os; this.start(); } public void run() { byte [] buffer = new byte[8196]; while (true) { try { - // this will block until somethings ready. - int size = _is.read(buffer); - _os.write(buffer, 0, size); - _os.flush(); + if( _is.available() > 0 ) { + // this will block until somethings ready. + int size = _is.read(buffer); +// System.out.println("read bytes: " + size); + if( size > 0 ) { +// String x = new String(buffer); +// System.out.println("buffer: " + x); + _os.write(buffer, 0, size); + _os.flush(); + } + } else { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + } + } } catch (IOException e) { return; } } } }
true
true
public void run() { byte [] buffer = new byte[8196]; while (true) { try { // this will block until somethings ready. int size = _is.read(buffer); _os.write(buffer, 0, size); _os.flush(); } catch (IOException e) { return; } } }
public void run() { byte [] buffer = new byte[8196]; while (true) { try { if( _is.available() > 0 ) { // this will block until somethings ready. int size = _is.read(buffer); // System.out.println("read bytes: " + size); if( size > 0 ) { // String x = new String(buffer); // System.out.println("buffer: " + x); _os.write(buffer, 0, size); _os.flush(); } } else { try { Thread.sleep(1000); } catch (InterruptedException e) { } } } catch (IOException e) { return; } } }
diff --git a/src/fr/crafter/tickleman/realplugin/RealConfig.java b/src/fr/crafter/tickleman/realplugin/RealConfig.java index d961987..464bf74 100644 --- a/src/fr/crafter/tickleman/realplugin/RealConfig.java +++ b/src/fr/crafter/tickleman/realplugin/RealConfig.java @@ -1,149 +1,150 @@ package fr.crafter.tickleman.realplugin; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.lang.reflect.Field; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import org.bukkit.plugin.java.JavaPlugin; //###################################################################################### RealConfig public class RealConfig { private final String fileName; public boolean debug = false; public String language = "en"; public String permissionsPlugin = "none"; private JavaPlugin plugin; public boolean pluginLog = false; private Set<Field> volatileFields = new HashSet<Field>(); //---------------------------------------------------------------------------------------- Config public RealConfig(final JavaPlugin plugin) { this(plugin, "config"); } //---------------------------------------------------------------------------------------- Config public RealConfig(final JavaPlugin plugin, String fileName) { this.plugin = plugin; this.fileName = getPlugin().getDataFolder().getPath() + "/" + fileName + ".txt"; } //---------------------------------------------------------------------------------------- Config public RealConfig(final JavaPlugin plugin, String fileName, RealConfig mainConfig) { this(plugin, fileName); copyFrom(mainConfig); setVolatileFields(mainConfig.getClass()); } //----------------------------------------------------------------------------------------- clone private void copyFrom(RealConfig config) { for (Field field : getClass().getFields()) { try { field.set(this, field.get(config)); } catch (Exception e) { } } } //------------------------------------------------------------------------------------- getPlugin protected JavaPlugin getPlugin() { return plugin; } //------------------------------------------------------------------------------------------ load public RealConfig load() { try { BufferedReader reader = new BufferedReader(new FileReader(fileName)); String buffer; while ((buffer = reader.readLine()) != null) { + buffer = buffer.replace("\r", ""); if (buffer.charAt(0) != '#') { String[] line = buffer.split("="); if (line.length >= 2) { String key = line[0].trim(); String value = line[1].trim(); Field field = getClass().getField(key); if ((field == null) || volatileFields.contains(field)) { getPlugin().getServer().getLogger().log( Level.WARNING, "[" + getPlugin().getDescription().getName() + "] " + " ignore configuration option " + key + " in " + fileName + " (unknown keyword)" ); } else { String fieldClass = field.getType().getName(); try { if ((fieldClass.equals("boolean")) || (fieldClass.equals("java.lang.Boolean"))) { field.set(this, RealVarTools.parseBoolean(value)); } else if ((fieldClass.equals("double")) || (fieldClass.equals("java.lang.Double"))) { field.set(this, Double.parseDouble(value)); } else if ((fieldClass.equals("int")) || (fieldClass.equals("java.lang.Integer"))) { field.set(this, Integer.parseInt(value)); } else { field.set(this, value); } } catch (Exception e) { getPlugin().getServer().getLogger().log( Level.SEVERE, "[" + getPlugin().getDescription().getName() + "] " + " ignore configuration option " + key + " in " + fileName + " (" + e.getMessage() + ")" ); } } } } } reader.close(); } catch (Exception e) { getPlugin().getServer().getLogger().log( Level.WARNING, "[" + getPlugin().getDescription().getName() + "] " + " auto-create default " + fileName ); save(); } return this; } //------------------------------------------------------------------------------------------ save public void save() { try { BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); for (Field field : getClass().getFields()) { if (!volatileFields.contains(field)) { String value = ((field.get(this) == null) ? "null" : field.get(this).toString()); writer.write(field.getName() + "=" + value + "\n"); } } writer.flush(); writer.close(); } catch (Exception e) { getPlugin().getServer().getLogger().log( Level.SEVERE, "[" + getPlugin().getDescription().getName() + "]" + " file save error " + fileName + " (" + e.getMessage() + ")" ); } } //----------------------------------------------------------------------------- setVolatileFields private void setVolatileFields(Class<?> applyClass) { volatileFields.clear(); for (Field field : applyClass.getFields()) { volatileFields.add(field); } } }
true
true
public RealConfig load() { try { BufferedReader reader = new BufferedReader(new FileReader(fileName)); String buffer; while ((buffer = reader.readLine()) != null) { if (buffer.charAt(0) != '#') { String[] line = buffer.split("="); if (line.length >= 2) { String key = line[0].trim(); String value = line[1].trim(); Field field = getClass().getField(key); if ((field == null) || volatileFields.contains(field)) { getPlugin().getServer().getLogger().log( Level.WARNING, "[" + getPlugin().getDescription().getName() + "] " + " ignore configuration option " + key + " in " + fileName + " (unknown keyword)" ); } else { String fieldClass = field.getType().getName(); try { if ((fieldClass.equals("boolean")) || (fieldClass.equals("java.lang.Boolean"))) { field.set(this, RealVarTools.parseBoolean(value)); } else if ((fieldClass.equals("double")) || (fieldClass.equals("java.lang.Double"))) { field.set(this, Double.parseDouble(value)); } else if ((fieldClass.equals("int")) || (fieldClass.equals("java.lang.Integer"))) { field.set(this, Integer.parseInt(value)); } else { field.set(this, value); } } catch (Exception e) { getPlugin().getServer().getLogger().log( Level.SEVERE, "[" + getPlugin().getDescription().getName() + "] " + " ignore configuration option " + key + " in " + fileName + " (" + e.getMessage() + ")" ); } } } } } reader.close(); } catch (Exception e) { getPlugin().getServer().getLogger().log( Level.WARNING, "[" + getPlugin().getDescription().getName() + "] " + " auto-create default " + fileName ); save(); } return this; }
public RealConfig load() { try { BufferedReader reader = new BufferedReader(new FileReader(fileName)); String buffer; while ((buffer = reader.readLine()) != null) { buffer = buffer.replace("\r", ""); if (buffer.charAt(0) != '#') { String[] line = buffer.split("="); if (line.length >= 2) { String key = line[0].trim(); String value = line[1].trim(); Field field = getClass().getField(key); if ((field == null) || volatileFields.contains(field)) { getPlugin().getServer().getLogger().log( Level.WARNING, "[" + getPlugin().getDescription().getName() + "] " + " ignore configuration option " + key + " in " + fileName + " (unknown keyword)" ); } else { String fieldClass = field.getType().getName(); try { if ((fieldClass.equals("boolean")) || (fieldClass.equals("java.lang.Boolean"))) { field.set(this, RealVarTools.parseBoolean(value)); } else if ((fieldClass.equals("double")) || (fieldClass.equals("java.lang.Double"))) { field.set(this, Double.parseDouble(value)); } else if ((fieldClass.equals("int")) || (fieldClass.equals("java.lang.Integer"))) { field.set(this, Integer.parseInt(value)); } else { field.set(this, value); } } catch (Exception e) { getPlugin().getServer().getLogger().log( Level.SEVERE, "[" + getPlugin().getDescription().getName() + "] " + " ignore configuration option " + key + " in " + fileName + " (" + e.getMessage() + ")" ); } } } } } reader.close(); } catch (Exception e) { getPlugin().getServer().getLogger().log( Level.WARNING, "[" + getPlugin().getDescription().getName() + "] " + " auto-create default " + fileName ); save(); } return this; }
diff --git a/srcj/com/sun/electric/tool/routing/Router.java b/srcj/com/sun/electric/tool/routing/Router.java index 2febfde88..49ad1060c 100644 --- a/srcj/com/sun/electric/tool/routing/Router.java +++ b/srcj/com/sun/electric/tool/routing/Router.java @@ -1,540 +1,541 @@ /* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: Router.java * * Copyright (c) 2003 Sun Microsystems and Static Free Software * * Electric(tm) 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. * * Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.routing; import com.sun.electric.database.geometry.Dimension2D; import com.sun.electric.database.hierarchy.Cell; import com.sun.electric.database.hierarchy.EDatabase; import com.sun.electric.database.hierarchy.Export; import com.sun.electric.database.prototype.NodeProto; import com.sun.electric.database.prototype.PortProto; import com.sun.electric.database.text.TextUtils; import com.sun.electric.database.topology.ArcInst; import com.sun.electric.database.topology.Connection; import com.sun.electric.database.topology.NodeInst; import com.sun.electric.database.topology.PortInst; import com.sun.electric.database.variable.EditWindow_; import com.sun.electric.database.variable.UserInterface; import com.sun.electric.technology.ArcProto; import com.sun.electric.technology.Technology; import com.sun.electric.technology.technologies.Generic; import com.sun.electric.tool.Job; import com.sun.electric.tool.JobException; import com.sun.electric.tool.Tool; import com.sun.electric.tool.user.CircuitChangeJobs; import com.sun.electric.tool.user.User; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Parent Class for all Routers. I really have no idea what this * should look like because I've never written a real router, * but I've started it off with a few basics. * <p> * A Route is a List of RouteElements. See RouteElement for details * of the elements. * <p> * User: gainsley * Date: Mar 1, 2004 * Time: 2:48:46 PM */ public abstract class Router { /** set to tell user short info on what was done */ protected boolean verbose = false; /** the tool that is making routes */ protected Tool tool; // ------------------ Abstract Router Methods ----------------- /** * Plan a route from startRE to endRE. * startRE in this case will be route.getEndRE(). This builds upon whatever * route is already in 'route'. * @param route the list of RouteElements describing route to be modified * @param cell the cell in which to create the route * @param endRE the RouteElementPort that will be the new end of the route * @param startLoc the location to attach an arc to on startRE * @param endLoc the location to attach an arc to on endRE * @param hint can be used as a hint to the router for determining route. * Ignored if null * @return false on error, route should be ignored. */ // protected abstract boolean planRoute(Route route, Cell cell, RouteElementPort endRE, // Point2D startLoc, Point2D endLoc, Point2D hint); /** Return a string describing the Router */ //public abstract String toString(); // --------------------------- Public Methods --------------------------- /** * Create the route within a Job. * @param route the route to create * @param cell the cell in which to create the route */ public void createRoute(Route route, Cell cell) { new CreateRouteJob(toString(), route, cell, verbose, tool); } /** * Method to create the route. * Does not wrap Job around it * (useful if already being called from a Job). This still * must be called from within a Job context, however. * @param route the route to create * @param cell the cell in which to create the route * @param highlightRouteEnd highlights end of route (last object) if true, otherwise leaves * highlights alone. * @param arcsCreatedMap a map of arcs to integers which is updated to indicate the number of each arc type created. * @param nodesCreatedMap a map of nodes to integers which is updated to indicate the number of each node type created. */ public static PortInst createRouteNoJob(Route route, Cell cell, boolean highlightRouteEnd, Map<ArcProto,Integer> arcsCreatedMap, Map<NodeProto,Integer> nodesCreatedMap) { EDatabase.serverDatabase().checkChanging(); // check if we can edit this cell if (CircuitChangeJobs.cantEdit(cell, null, true, true) != 0) return null; // pass 1: build all newNodes for (RouteElement e : route) { if (e.getAction() == RouteElement.RouteElementAction.newNode) { if (e.isDone()) continue; e.doAction(); RouteElementPort rep = (RouteElementPort)e; Integer i = nodesCreatedMap.get(rep.getPortProto().getParent()); if (i == null) i = new Integer(0); i = new Integer(i.intValue() + 1); nodesCreatedMap.put(rep.getPortProto().getParent(), i); } } // pass 2: do all other actions (deletes, newArcs) for (RouteElement e : route) { e.doAction(); if (e.getAction() == RouteElement.RouteElementAction.newArc) { RouteElementArc rea = (RouteElementArc)e; Integer i = arcsCreatedMap.get(rea.getArcProto()); if (i == null) i = new Integer(0); i = new Integer(i.intValue() + 1); arcsCreatedMap.put(rea.getArcProto(), i); } } if (arcsCreatedMap.get(Generic.tech.unrouted_arc) == null) { // update current unrouted arcs - PortInst pi = route.getStart().getPortInst(); - if (pi != null) + RouteElementPort rep = route.getStart(); + if (rep != null && rep.getPortInst() != null) { + PortInst pi = rep.getPortInst(); for (Iterator<Connection> it = pi.getConnections(); it.hasNext(); ) { Connection conn = it.next(); ArcInst ai = conn.getArc(); if (ai.getProto() == Generic.tech.unrouted_arc) { Connection oconn = (ai.getHead() == conn ? ai.getTail() : ai.getHead()); // make new unrouted arc from end of route to arc end point, // otherwise just get rid of it if (oconn.getPortInst() != route.getEnd().getPortInst()) { RouteElementPort newEnd = RouteElementPort.existingPortInst(oconn.getPortInst(), oconn.getLocation()); RouteElementArc newArc = RouteElementArc.newArc(cell, Generic.tech.unrouted_arc, Generic.tech.unrouted_arc.getDefaultWidth(), route.getEnd(), newEnd, route.getEnd().getLocation(), newEnd.getLocation(), null, ai.getTextDescriptor(ArcInst.ARC_NAME), ai, true, true, null); newArc.doAction(); } if (conn.getArc().isLinked()) conn.getArc().kill(); } } } } PortInst created = null; if (highlightRouteEnd) { RouteElementPort finalRE = route.getEnd(); if (finalRE != null) created = finalRE.getPortInst(); } return created; } public static void reportRoutingResults(String prefix, Map<ArcProto,Integer> arcsCreatedMap, Map<NodeProto,Integer> nodesCreatedMap) { List<ArcProto> arcEntries = new ArrayList<ArcProto>(arcsCreatedMap.keySet()); List<NodeProto> nodeEntries = new ArrayList<NodeProto>(nodesCreatedMap.keySet()); if (arcEntries.size() == 0 && nodeEntries.size() == 0) { System.out.println(prefix + ": nothing added"); } else { System.out.print(prefix + " added: "); Collections.sort(arcEntries, new TextUtils.ObjectsByToString()); Collections.sort(nodeEntries, new TextUtils.ObjectsByToString()); int total = arcEntries.size() + nodeEntries.size(); int sofar = 0; for (ArcProto ap : arcEntries) { Integer i = arcsCreatedMap.get(ap); sofar++; if (sofar > 1 && total > 1) { if (sofar < total) System.out.print(", "); else System.out.print(" and "); } System.out.print(i.intValue() + " " + ap.describe()); if (i.intValue() > 1) System.out.print(" arcs"); else System.out.print(" arc"); } for (NodeProto np : nodeEntries) { Integer i = nodesCreatedMap.get(np); sofar++; if (sofar > 1 && total > 1) { if (sofar < total) System.out.print(", "); else System.out.print(" and "); } System.out.print(i.intValue() + " " + np.describe(false)); if (i.intValue() > 1) System.out.print(" nodes"); else System.out.print(" node"); } System.out.println(); User.playSound(); } } /** Method to set the tool associated with this router */ public void setTool(Tool tool) { this.tool = tool; } // -------------------------- Job to build route ------------------------ /** * Job to create the route. * Highlights the end of the Route after it creates it. */ protected static class CreateRouteJob extends Job { /** route to build */ protected Route route; /** print message on what was done */ private boolean verbose; /** cell in which to build route */ private Cell cell; /** port to highlight */ private PortInst portToHighlight; /** Constructor */ protected CreateRouteJob(String what, Route route, Cell cell, boolean verbose, Tool tool) { super(what, tool, Job.Type.CHANGE, null, null, Job.Priority.USER); this.route = route; this.verbose = verbose; this.cell = cell; startJob(); } public boolean doIt() throws JobException { if (CircuitChangeJobs.cantEdit(cell, null, true, true) != 0) return false; Map<ArcProto,Integer> arcsCreatedMap = new HashMap<ArcProto,Integer>(); Map<NodeProto,Integer> nodesCreatedMap = new HashMap<NodeProto,Integer>(); portToHighlight = createRouteNoJob(route, cell, verbose, arcsCreatedMap, nodesCreatedMap); reportRoutingResults("Wiring", arcsCreatedMap, nodesCreatedMap); fieldVariableChanged("portToHighlight"); return true; } public void terminateOK() { if (portToHighlight != null) { UserInterface ui = Job.getUserInterface(); EditWindow_ wnd = ui.getCurrentEditWindow_(); if (wnd != null) { wnd.clearHighlighting(); wnd.addElectricObject(portToHighlight, cell); wnd.finishedHighlighting(); } } } } // ------------------------ Protected Utility Methods --------------------- /** * Determine which arc type to use to connect two ports * NOTE: for safety, will NOT return a Generic.tech.universal_arc, * Generic.tech.invisible_arc, or Generic.tech.unrouted_arc, * unless it is the currently selected arc. Will instead return null * if no other arc can be found to work. * @param port1 one end point of arc (ignored if null) * @param port2 other end point of arc (ignored if null) * @return the arc type (an ArcProto). null if none or error. */ public static ArcProto getArcToUse(PortProto port1, PortProto port2) { // current user selected arc ArcProto curAp = User.getUserTool().getCurrentArcProto(); ArcProto uni = Generic.tech.universal_arc; ArcProto invis = Generic.tech.invisible_arc; ArcProto unr = Generic.tech.unrouted_arc; PortProto pp1 = null, pp2 = null; // Note: this makes it so either port1 or port2 can be null, // but only pp2 can be null down below if (port1 == null) pp1 = port2; else { pp1 = port1; pp2 = port2; } if (pp1 == null && pp2 == null) return null; // Ignore pp2 if it is null if (pp2 == null) { // see if current arcproto works if (pp1.connectsTo(curAp)) return curAp; // otherwise, find one that does Technology tech = pp1.getParent().getTechnology(); for(Iterator<ArcProto> it = tech.getArcs(); it.hasNext(); ) { ArcProto ap = it.next(); if (pp1.connectsTo(ap) && ap != uni && ap != invis && ap != unr) return ap; } // none in current technology: try any technology for(Iterator<Technology> it = Technology.getTechnologies(); it.hasNext(); ) { Technology anyTech = it.next(); for(Iterator<ArcProto> aIt = anyTech.getArcs(); aIt.hasNext(); ) { ArcProto ap = aIt.next(); if (pp1.connectsTo(ap) && ap != uni && ap != invis && ap != unr) return ap; } } } else { // pp2 is not null, include it in search // see if current arcproto workds if (pp1.connectsTo(curAp) && pp2.connectsTo(curAp)) return curAp; // find one that works if current doesn't Technology tech = pp1.getParent().getTechnology(); for(Iterator<ArcProto> it = tech.getArcs(); it.hasNext(); ) { ArcProto ap = it.next(); if (pp1.connectsTo(ap) && pp2.connectsTo(ap) && ap != uni && ap != invis && ap != unr) return ap; } // none in current technology: try any technology for(Iterator<Technology> it = Technology.getTechnologies(); it.hasNext(); ) { Technology anyTech = it.next(); for(Iterator<ArcProto> aIt = anyTech.getArcs(); aIt.hasNext(); ) { ArcProto ap = aIt.next(); if (pp1.connectsTo(ap) && pp2.connectsTo(ap) && ap != uni && ap != invis && ap != unr) return ap; } } } return null; } /** * Convert all new arcs of type 'ap' in route to use width of widest * arc of that type. */ protected static void useWidestWire(Route route, ArcProto ap) { // get widest wire connected to anything in route double width = getArcWidthToUse(route, ap); // set all new arcs of that type to use that width for (RouteElement re : route) { if (re instanceof RouteElementArc) { RouteElementArc reArc = (RouteElementArc)re; if (reArc.getArcProto() == ap) reArc.setArcWidth(width); } } } /** * Get arc width to use by searching for largest arc of passed type * connected to any elements in the route. * @param route the route to be searched * @param ap the arc type * @return the largest width */ protected static double getArcWidthToUse(Route route, ArcProto ap) { double widest = ap.getDefaultWidth(); for (RouteElement re : route) { double width = getArcWidthToUse(re, ap); if (width > widest) widest = width; } return widest; } /** * Get arc width to use to connect to PortInst pi. Arc type * is ap. Uses the largest width of arc type ap already connected * to pi, or the default width of ap if none found.<p> * You may specify pi as null, in which case it just returns * ap.getDefaultWidth(). * @param pi the PortInst to connect to * @param ap the Arc type to connect with * @return the width to use to connect */ public static double getArcWidthToUse(PortInst pi, ArcProto ap) { // if pi null, just return default width of ap if (pi == null) return ap.getDefaultWidth(); // get all ArcInsts on pi, find largest double width = ap.getDefaultWidth(); for (Iterator<Connection> it = pi.getConnections(); it.hasNext(); ) { Connection c = it.next(); ArcInst ai = c.getArc(); if (ai.getProto() != ap) continue; double newWidth = c.getArc().getWidth() - c.getArc().getProto().getWidthOffset(); if (width < newWidth) width = newWidth; } // check any wires that connect to the export of this portinst in the // prototype, if this is a cell instance NodeInst ni = pi.getNodeInst(); if (ni.isCellInstance()) { Cell cell = (Cell)ni.getProto(); Export export = cell.findExport(pi.getPortProto().getName()); PortInst exportedInst = export.getOriginalPort(); double width2 = getArcWidthToUse(exportedInst, ap); if (width2 > width) width = width2; } return width; } /** * Get arc width to use to connect to RouteElement re. Uses largest * width of arc already connected to re. * @param re the RouteElement to connect to * @param ap the arc type (for default width) * @return the width of the arc to use to connect */ protected static double getArcWidthToUse(RouteElement re, ArcProto ap) { double width = ap.getDefaultWidth(); double connectedWidth = width; if (re instanceof RouteElementPort) { RouteElementPort rePort = (RouteElementPort)re; connectedWidth = rePort.getWidestConnectingArc(ap); if (rePort.getPortInst() != null) { // check if prototype connection to export has larger wire double width2 = getArcWidthToUse(rePort.getPortInst(), ap); if (width2 > connectedWidth) connectedWidth = width2; } } if (re instanceof RouteElementArc) { RouteElementArc reArc = (RouteElementArc)re; connectedWidth = reArc.getOffsetArcWidth(); } if (width > connectedWidth) return width; else return connectedWidth; } /** * Get the dimensions of a contact that will connect between startRE and endRE. */ protected static Dimension2D getContactSize(RouteElement startRE, RouteElement endRE) { Dimension2D start = getContactSize(startRE); Dimension2D end = getContactSize(endRE); // use the largest of the dimensions Dimension2D dim = new Dimension2D.Double(start); if (end.getWidth() > dim.getWidth()) dim.setSize(end.getWidth(), dim.getHeight()); if (end.getHeight() > dim.getHeight()) dim.setSize(dim.getWidth(), end.getHeight()); return dim; } protected static Dimension2D getContactSize(RouteElement re) { double width = -1, height = -1; // if RE is an arc, use its arc width if (re instanceof RouteElementArc) { RouteElementArc reArc = (RouteElementArc)re; if (reArc.isArcVertical()) { if (reArc.getOffsetArcWidth() > width) width = reArc.getOffsetArcWidth(); } if (reArc.isArcHorizontal()) { if (reArc.getOffsetArcWidth() > height) height = reArc.getOffsetArcWidth(); } } // special case: if this is a contact cut, use the size of the contact cut /* if (re.getPortProto() != null) { if (re.getPortProto().getParent().getFunction() == PrimitiveNode.Function.CONTACT) { return re.getNodeSize(); } } */ // if RE is an existingPortInst, use width of arcs connected to it. if (re.getAction() == RouteElement.RouteElementAction.existingPortInst) { RouteElementPort rePort = (RouteElementPort)re; PortInst pi = rePort.getPortInst(); for (Iterator<Connection> it = pi.getConnections(); it.hasNext(); ) { Connection conn = it.next(); ArcInst arc = conn.getArc(); Point2D head = arc.getHeadLocation(); Point2D tail = arc.getTailLocation(); // use width of widest arc double newWidth = arc.getWidth() - arc.getProto().getWidthOffset(); if (head.getX() == tail.getX()) { if (newWidth > width) width = newWidth; } if (head.getY() == tail.getY()) { if (newWidth > height) height = newWidth; } } } // if RE is a new Node, check it's arcs if (re.getAction() == RouteElement.RouteElementAction.newNode) { RouteElementPort rePort = (RouteElementPort)re; Dimension2D dim = null; for (Iterator<RouteElement> it = rePort.getNewArcs(); it.hasNext(); ) { RouteElement newArcRE = it.next(); Dimension2D d = getContactSize(newArcRE); if (dim == null) dim = d; // use LARGEST of all dimensions if (d.getWidth() > dim.getWidth()) dim.setSize(d.getWidth(), dim.getHeight()); if (d.getHeight() > dim.getHeight()) dim.setSize(dim.getWidth(), d.getHeight()); } if (dim == null) dim = new Dimension2D.Double(-1, -1); return dim; } return new Dimension2D.Double(width, height); } }
false
true
public static PortInst createRouteNoJob(Route route, Cell cell, boolean highlightRouteEnd, Map<ArcProto,Integer> arcsCreatedMap, Map<NodeProto,Integer> nodesCreatedMap) { EDatabase.serverDatabase().checkChanging(); // check if we can edit this cell if (CircuitChangeJobs.cantEdit(cell, null, true, true) != 0) return null; // pass 1: build all newNodes for (RouteElement e : route) { if (e.getAction() == RouteElement.RouteElementAction.newNode) { if (e.isDone()) continue; e.doAction(); RouteElementPort rep = (RouteElementPort)e; Integer i = nodesCreatedMap.get(rep.getPortProto().getParent()); if (i == null) i = new Integer(0); i = new Integer(i.intValue() + 1); nodesCreatedMap.put(rep.getPortProto().getParent(), i); } } // pass 2: do all other actions (deletes, newArcs) for (RouteElement e : route) { e.doAction(); if (e.getAction() == RouteElement.RouteElementAction.newArc) { RouteElementArc rea = (RouteElementArc)e; Integer i = arcsCreatedMap.get(rea.getArcProto()); if (i == null) i = new Integer(0); i = new Integer(i.intValue() + 1); arcsCreatedMap.put(rea.getArcProto(), i); } } if (arcsCreatedMap.get(Generic.tech.unrouted_arc) == null) { // update current unrouted arcs PortInst pi = route.getStart().getPortInst(); if (pi != null) { for (Iterator<Connection> it = pi.getConnections(); it.hasNext(); ) { Connection conn = it.next(); ArcInst ai = conn.getArc(); if (ai.getProto() == Generic.tech.unrouted_arc) { Connection oconn = (ai.getHead() == conn ? ai.getTail() : ai.getHead()); // make new unrouted arc from end of route to arc end point, // otherwise just get rid of it if (oconn.getPortInst() != route.getEnd().getPortInst()) { RouteElementPort newEnd = RouteElementPort.existingPortInst(oconn.getPortInst(), oconn.getLocation()); RouteElementArc newArc = RouteElementArc.newArc(cell, Generic.tech.unrouted_arc, Generic.tech.unrouted_arc.getDefaultWidth(), route.getEnd(), newEnd, route.getEnd().getLocation(), newEnd.getLocation(), null, ai.getTextDescriptor(ArcInst.ARC_NAME), ai, true, true, null); newArc.doAction(); } if (conn.getArc().isLinked()) conn.getArc().kill(); } } } } PortInst created = null; if (highlightRouteEnd) { RouteElementPort finalRE = route.getEnd(); if (finalRE != null) created = finalRE.getPortInst(); } return created; }
public static PortInst createRouteNoJob(Route route, Cell cell, boolean highlightRouteEnd, Map<ArcProto,Integer> arcsCreatedMap, Map<NodeProto,Integer> nodesCreatedMap) { EDatabase.serverDatabase().checkChanging(); // check if we can edit this cell if (CircuitChangeJobs.cantEdit(cell, null, true, true) != 0) return null; // pass 1: build all newNodes for (RouteElement e : route) { if (e.getAction() == RouteElement.RouteElementAction.newNode) { if (e.isDone()) continue; e.doAction(); RouteElementPort rep = (RouteElementPort)e; Integer i = nodesCreatedMap.get(rep.getPortProto().getParent()); if (i == null) i = new Integer(0); i = new Integer(i.intValue() + 1); nodesCreatedMap.put(rep.getPortProto().getParent(), i); } } // pass 2: do all other actions (deletes, newArcs) for (RouteElement e : route) { e.doAction(); if (e.getAction() == RouteElement.RouteElementAction.newArc) { RouteElementArc rea = (RouteElementArc)e; Integer i = arcsCreatedMap.get(rea.getArcProto()); if (i == null) i = new Integer(0); i = new Integer(i.intValue() + 1); arcsCreatedMap.put(rea.getArcProto(), i); } } if (arcsCreatedMap.get(Generic.tech.unrouted_arc) == null) { // update current unrouted arcs RouteElementPort rep = route.getStart(); if (rep != null && rep.getPortInst() != null) { PortInst pi = rep.getPortInst(); for (Iterator<Connection> it = pi.getConnections(); it.hasNext(); ) { Connection conn = it.next(); ArcInst ai = conn.getArc(); if (ai.getProto() == Generic.tech.unrouted_arc) { Connection oconn = (ai.getHead() == conn ? ai.getTail() : ai.getHead()); // make new unrouted arc from end of route to arc end point, // otherwise just get rid of it if (oconn.getPortInst() != route.getEnd().getPortInst()) { RouteElementPort newEnd = RouteElementPort.existingPortInst(oconn.getPortInst(), oconn.getLocation()); RouteElementArc newArc = RouteElementArc.newArc(cell, Generic.tech.unrouted_arc, Generic.tech.unrouted_arc.getDefaultWidth(), route.getEnd(), newEnd, route.getEnd().getLocation(), newEnd.getLocation(), null, ai.getTextDescriptor(ArcInst.ARC_NAME), ai, true, true, null); newArc.doAction(); } if (conn.getArc().isLinked()) conn.getArc().kill(); } } } } PortInst created = null; if (highlightRouteEnd) { RouteElementPort finalRE = route.getEnd(); if (finalRE != null) created = finalRE.getPortInst(); } return created; }
diff --git a/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java index 2e3b6bf51..bed70e99b 100644 --- a/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java +++ b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java @@ -1,418 +1,419 @@ /* * Copyright (c) 2002-2008 Gargoyle Software Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The end-user documentation included with the redistribution, if any, must * include the following acknowledgment: * * "This product includes software developed by Gargoyle Software Inc. * (http://www.GargoyleSoftware.com/)." * * Alternately, this acknowledgment may appear in the software itself, if * and wherever such third-party acknowledgments normally appear. * 4. The name "Gargoyle Software" must not be used to endorse or promote * products derived from this software without prior written permission. * For written permission, please contact [email protected]. * 5. Products derived from this software may not be called "HtmlUnit", nor may * "HtmlUnit" appear in their name, without prior written permission of * Gargoyle Software Inc. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARGOYLE * SOFTWARE INC. 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 com.gargoylesoftware.htmlunit.javascript; import static org.junit.Assert.fail; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.commons.lang.ClassUtils; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import com.gargoylesoftware.htmlunit.BrowserRunner; import com.gargoylesoftware.htmlunit.CollectingAlertHandler; import com.gargoylesoftware.htmlunit.MockWebConnection; import com.gargoylesoftware.htmlunit.ScriptException; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.WebTestCase; import com.gargoylesoftware.htmlunit.BrowserRunner.Alerts; import com.gargoylesoftware.htmlunit.BrowserRunner.Browser; import com.gargoylesoftware.htmlunit.BrowserRunner.Browsers; import com.gargoylesoftware.htmlunit.BrowserRunner.NotYetImplemented; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfiguration; /** * Tests for {@link SimpleScriptable}. * * @version $Revision$ * @author <a href="mailto:[email protected]">Mike Bowler</a> * @author <a href="mailto:[email protected]">Barnaby Court</a> * @author David K. Taylor * @author <a href="mailto:[email protected]">Ben Curren</a> * @author Marc Guillemot * @author Chris Erskine * @author Ahmed Ashour */ @RunWith(BrowserRunner.class) public class SimpleScriptableTest extends WebTestCase { /** * @throws Exception if the test fails */ @Test public void callInheritedFunction() throws Exception { final WebClient client = getWebClient(); final MockWebConnection webConnection = new MockWebConnection(client); final String content = "<html><head><title>foo</title><script>\n" + "function doTest() {\n" + " document.form1.textfield1.focus();\n" + " alert('past focus');\n" + "}\n" + "</script></head><body onload='doTest()'>\n" + "<p>hello world</p>\n" + "<form name='form1'>\n" + " <input type='text' name='textfield1' id='textfield1' value='foo'/>\n" + "</form>\n" + "</body></html>"; webConnection.setDefaultResponse(content); client.setWebConnection(webConnection); final List<String> expectedAlerts = Collections.singletonList("past focus"); createTestPageForRealBrowserIfNeeded(content, expectedAlerts); final List<String> collectedAlerts = new ArrayList<String>(); client.setAlertHandler(new CollectingAlertHandler(collectedAlerts)); final HtmlPage page = (HtmlPage) client.getPage(URL_GARGOYLE); assertEquals("foo", page.getTitleText()); Assert.assertEquals("focus not changed to textfield1", page.getFormByName("form1").getInputByName("textfield1"), page.getFocusedElement()); assertEquals(expectedAlerts, collectedAlerts); } /** * Test. */ @Test @Browsers(Browser.NONE) public void htmlJavaScriptMapping_AllJavaScriptClassesArePresent() { final Map<Class < ? extends HtmlElement>, Class < ? extends SimpleScriptable>> map = JavaScriptConfiguration.getHtmlJavaScriptMapping(); final String directoryName = "../../../src/main/java/com/gargoylesoftware/htmlunit/javascript/host"; final Set<String> names = getFileNames(directoryName.replace('/', File.separatorChar)); // Now pull out those names that we know don't have HTML equivalents names.remove("ActiveXObject"); names.remove("BoxObject"); names.remove("ComputedCSSStyleDeclaration"); + names.remove("CSSRuleList"); names.remove("CSSStyleDeclaration"); names.remove("Document"); names.remove("DOMImplementation"); names.remove("DOMParser"); names.remove("Event"); names.remove("EventNode"); names.remove("EventHandler"); names.remove("EventListenersContainer"); names.remove("FormField"); names.remove("History"); names.remove("HTMLCollection"); names.remove("HTMLCollectionTags"); names.remove("HTMLOptionsCollection"); names.remove("JavaScriptBackgroundJob"); names.remove("Location"); names.remove("MimeType"); names.remove("MimeTypeArray"); names.remove("MouseEvent"); names.remove("Navigator"); names.remove("Node"); names.remove("Plugin"); names.remove("PluginArray"); names.remove("Popup"); names.remove("Range"); names.remove("RowContainer"); names.remove("Screen"); names.remove("ScoperFunctionObject"); names.remove("Selection"); names.remove("SimpleArray"); names.remove("Stylesheet"); names.remove("StyleSheetList"); names.remove("TextRange"); names.remove("TextRectangle"); names.remove("UIEvent"); names.remove("Window"); names.remove("XMLDocument"); names.remove("XMLDOMParseError"); names.remove("XMLHttpRequest"); names.remove("XMLSerializer"); names.remove("XPathNSResolver"); names.remove("XPathResult"); names.remove("XSLTProcessor"); names.remove("XSLTemplate"); final Collection<String> hostClassNames = new ArrayList<String>(); for (final Class< ? extends SimpleScriptable> clazz : map.values()) { hostClassNames.add(ClassUtils.getShortClassName(clazz)); } assertEquals(new TreeSet<String>(names), new TreeSet<String>(hostClassNames)); } private Set<String> getFileNames(final String directoryName) { File directory = new File("." + File.separatorChar + directoryName); if (!directory.exists()) { directory = new File("./src/main/java/".replace('/', File.separatorChar) + directoryName); } assertTrue("directory exists", directory.exists()); assertTrue("is a directory", directory.isDirectory()); final Set<String> collection = new HashSet<String>(); for (final String name : directory.list()) { if (name.endsWith(".java")) { collection.add(name.substring(0, name.length() - 5)); } } return collection; } /** * This test fails on IE and FF but not by HtmlUnit because according to Ecma standard, * attempts to set read only properties should be silently ignored. * Furthermore document.body = document.body will work on FF but not on IE * @throws Exception if the test fails */ @Test @NotYetImplemented public void setNonWritableProperty() throws Exception { final String content = "<html><head><title>foo</title></head><body onload='document.body=123456'>" + "</body></html>"; try { loadPage(getBrowserVersion(), content, null); fail("Exception should have been thrown"); } catch (final ScriptException e) { // it's ok } } /** * Works since Rhino 1.7. * @throws Exception if the test fails */ @Test @Alerts("[object Object]") public void arguments_toString() throws Exception { final String html = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " alert(arguments);\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; loadPageWithAlerts(html); } /** * @throws Exception if the test fails */ @Test @Alerts("3") public void stringWithExclamationMark() throws Exception { final String html = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " var x = '<!>';\n" + " alert(x.length);\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; loadPageWithAlerts(html); } /** * Test the host class names match the Firefox (w3c names). * @see <a * href="http://java.sun.com/j2se/1.5.0/docs/guide/plugin/dom/org/w3c/dom/html/package-summary.html">DOM API</a> * @throws Exception if the test fails */ @Test @Browsers(Browser.FIREFOX_2) @NotYetImplemented public void hostClassNames() throws Exception { testHostClassNames("HTMLAnchorElement"); } private void testHostClassNames(final String className) throws Exception { final String content = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " alert(" + className + ");\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; final String[] expectedAlerts = {'[' + className + ']'}; final List<String> collectedAlerts = new ArrayList<String>(); loadPage(getBrowserVersion(), content, collectedAlerts); assertEquals(expectedAlerts, collectedAlerts); } /** * Blocked by Rhino bug 419090 (https://bugzilla.mozilla.org/show_bug.cgi?id=419090). * @throws Exception if the test fails */ @Test @Alerts({ "x1", "x2", "x3", "x4", "x5" }) @NotYetImplemented public void arrayedMap() throws Exception { final String html = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " var map = {};\n" + " map['x1'] = 'y1';\n" + " map['x2'] = 'y2';\n" + " map['x3'] = 'y3';\n" + " map['x4'] = 'y4';\n" + " map['x5'] = 'y5';\n" + " for (var i in map) {\n" + " alert(i);\n" + " }" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; loadPageWithAlerts(html); } /** * @throws Exception if the test fails */ @Test @Browsers(Browser.FIREFOX_2) public void isParentOf() throws Exception { isParentOf("Node", "Element", true); isParentOf("Document", "XMLDocument", true); isParentOf("Node", "XPathResult", false); isParentOf("Element", "HTMLElement", true); isParentOf("HTMLElement", "HTMLHtmlElement", true); isParentOf("CSSStyleDeclaration", "ComputedCSSStyleDeclaration", true); //although Image != HTMLImageElement, they seem to be synonyms!!! isParentOf("Image", "HTMLImageElement", true); isParentOf("HTMLImageElement", "Image", true); } private void isParentOf(final String object1, final String object2, final boolean status) throws Exception { final String html = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " alert(isParentOf(" + object1 + ", " + object2 + "));\n" + " }\n" + " /**\n" + " * Returns true if o1 prototype is parent/grandparent of o2 prototype\n" + " */\n" + " function isParentOf(o1, o2) {\n" + " o1.prototype.myCustomFunction = function() {};\n" + " return o2.prototype.myCustomFunction != undefined;\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; final String[] expectedAlerts = {Boolean.toString(status)}; final List<String> collectedAlerts = new ArrayList<String>(); loadPage(getBrowserVersion(), html, collectedAlerts); assertEquals(expectedAlerts, collectedAlerts); } /** * @throws Exception if the test fails */ @Test @Browsers(Browser.FIREFOX_2) public void windowPropertyToString() throws Exception { final String content = "<html id='myId'><head><title>foo</title><script>\n" + " function test() {\n" + " alert(document.getElementById('myId'));\n" + " alert(HTMLHtmlElement);\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; final String[] expectedAlerts = {"[object HTMLHtmlElement]", "[HTMLHtmlElement]"}; createTestPageForRealBrowserIfNeeded(content, expectedAlerts); final List<String> collectedAlerts = new ArrayList<String>(); loadPage(getBrowserVersion(), content, collectedAlerts); assertEquals(expectedAlerts, collectedAlerts); } /** * This is related to HtmlUnitContextFactory.hasFeature(Context.FEATURE_PARENT_PROTO_PROPERTIES). * @throws Exception if the test fails */ @Test @Alerts(IE = "false", FF = "true") public void parentProtoFeature() throws Exception { final String html = "<html><head><title>First</title><script>\n" + "function test() {\n" + " alert(document.createElement('div').__proto__ != undefined);\n" + "}\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; loadPageWithAlerts(html); } /** * Test for * <a href="https://sourceforge.net/tracker/index.php?func=detail&aid=1933943&group_id=47038&atid=448266">bug</a>. * @throws Exception if the test fails */ @Test @Alerts("1") @NotYetImplemented public void passFunctionAsParameter() throws Exception { final String html = "<html><head><title>First</title><script>\n" + " function run(fun) {\n" + " fun('alert(1)');\n" + " }\n" + "\n" + " function test() {\n" + " run(eval);\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; loadPageWithAlerts(html); } }
true
true
public void htmlJavaScriptMapping_AllJavaScriptClassesArePresent() { final Map<Class < ? extends HtmlElement>, Class < ? extends SimpleScriptable>> map = JavaScriptConfiguration.getHtmlJavaScriptMapping(); final String directoryName = "../../../src/main/java/com/gargoylesoftware/htmlunit/javascript/host"; final Set<String> names = getFileNames(directoryName.replace('/', File.separatorChar)); // Now pull out those names that we know don't have HTML equivalents names.remove("ActiveXObject"); names.remove("BoxObject"); names.remove("ComputedCSSStyleDeclaration"); names.remove("CSSStyleDeclaration"); names.remove("Document"); names.remove("DOMImplementation"); names.remove("DOMParser"); names.remove("Event"); names.remove("EventNode"); names.remove("EventHandler"); names.remove("EventListenersContainer"); names.remove("FormField"); names.remove("History"); names.remove("HTMLCollection"); names.remove("HTMLCollectionTags"); names.remove("HTMLOptionsCollection"); names.remove("JavaScriptBackgroundJob"); names.remove("Location"); names.remove("MimeType"); names.remove("MimeTypeArray"); names.remove("MouseEvent"); names.remove("Navigator"); names.remove("Node"); names.remove("Plugin"); names.remove("PluginArray"); names.remove("Popup"); names.remove("Range"); names.remove("RowContainer"); names.remove("Screen"); names.remove("ScoperFunctionObject"); names.remove("Selection"); names.remove("SimpleArray"); names.remove("Stylesheet"); names.remove("StyleSheetList"); names.remove("TextRange"); names.remove("TextRectangle"); names.remove("UIEvent"); names.remove("Window"); names.remove("XMLDocument"); names.remove("XMLDOMParseError"); names.remove("XMLHttpRequest"); names.remove("XMLSerializer"); names.remove("XPathNSResolver"); names.remove("XPathResult"); names.remove("XSLTProcessor"); names.remove("XSLTemplate"); final Collection<String> hostClassNames = new ArrayList<String>(); for (final Class< ? extends SimpleScriptable> clazz : map.values()) { hostClassNames.add(ClassUtils.getShortClassName(clazz)); } assertEquals(new TreeSet<String>(names), new TreeSet<String>(hostClassNames)); }
public void htmlJavaScriptMapping_AllJavaScriptClassesArePresent() { final Map<Class < ? extends HtmlElement>, Class < ? extends SimpleScriptable>> map = JavaScriptConfiguration.getHtmlJavaScriptMapping(); final String directoryName = "../../../src/main/java/com/gargoylesoftware/htmlunit/javascript/host"; final Set<String> names = getFileNames(directoryName.replace('/', File.separatorChar)); // Now pull out those names that we know don't have HTML equivalents names.remove("ActiveXObject"); names.remove("BoxObject"); names.remove("ComputedCSSStyleDeclaration"); names.remove("CSSRuleList"); names.remove("CSSStyleDeclaration"); names.remove("Document"); names.remove("DOMImplementation"); names.remove("DOMParser"); names.remove("Event"); names.remove("EventNode"); names.remove("EventHandler"); names.remove("EventListenersContainer"); names.remove("FormField"); names.remove("History"); names.remove("HTMLCollection"); names.remove("HTMLCollectionTags"); names.remove("HTMLOptionsCollection"); names.remove("JavaScriptBackgroundJob"); names.remove("Location"); names.remove("MimeType"); names.remove("MimeTypeArray"); names.remove("MouseEvent"); names.remove("Navigator"); names.remove("Node"); names.remove("Plugin"); names.remove("PluginArray"); names.remove("Popup"); names.remove("Range"); names.remove("RowContainer"); names.remove("Screen"); names.remove("ScoperFunctionObject"); names.remove("Selection"); names.remove("SimpleArray"); names.remove("Stylesheet"); names.remove("StyleSheetList"); names.remove("TextRange"); names.remove("TextRectangle"); names.remove("UIEvent"); names.remove("Window"); names.remove("XMLDocument"); names.remove("XMLDOMParseError"); names.remove("XMLHttpRequest"); names.remove("XMLSerializer"); names.remove("XPathNSResolver"); names.remove("XPathResult"); names.remove("XSLTProcessor"); names.remove("XSLTemplate"); final Collection<String> hostClassNames = new ArrayList<String>(); for (final Class< ? extends SimpleScriptable> clazz : map.values()) { hostClassNames.add(ClassUtils.getShortClassName(clazz)); } assertEquals(new TreeSet<String>(names), new TreeSet<String>(hostClassNames)); }
diff --git a/plugins/org.eclipse.birt.report.engine.emitter.wpml/src/org/eclipse/birt/report/engine/emitter/wpml/AbstractEmitterImpl.java b/plugins/org.eclipse.birt.report.engine.emitter.wpml/src/org/eclipse/birt/report/engine/emitter/wpml/AbstractEmitterImpl.java index e2fcd3044..e3ed1c02e 100644 --- a/plugins/org.eclipse.birt.report.engine.emitter.wpml/src/org/eclipse/birt/report/engine/emitter/wpml/AbstractEmitterImpl.java +++ b/plugins/org.eclipse.birt.report.engine.emitter.wpml/src/org/eclipse/birt/report/engine/emitter/wpml/AbstractEmitterImpl.java @@ -1,1187 +1,1191 @@ /******************************************************************************* * Copyright (c) 2008 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.engine.emitter.wpml; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.Stack; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.report.engine.api.EngineException; import org.eclipse.birt.report.engine.api.HTMLRenderOption; import org.eclipse.birt.report.engine.api.IHTMLActionHandler; import org.eclipse.birt.report.engine.api.IRenderOption; import org.eclipse.birt.report.engine.api.IReportRunnable; import org.eclipse.birt.report.engine.api.InstanceID; import org.eclipse.birt.report.engine.api.RenderOption; import org.eclipse.birt.report.engine.api.script.IReportContext; import org.eclipse.birt.report.engine.content.IAutoTextContent; import org.eclipse.birt.report.engine.content.IBandContent; import org.eclipse.birt.report.engine.content.ICellContent; import org.eclipse.birt.report.engine.content.IColumn; import org.eclipse.birt.report.engine.content.IContainerContent; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.content.IDataContent; import org.eclipse.birt.report.engine.content.IElement; import org.eclipse.birt.report.engine.content.IForeignContent; import org.eclipse.birt.report.engine.content.IGroupContent; import org.eclipse.birt.report.engine.content.IHyperlinkAction; import org.eclipse.birt.report.engine.content.IImageContent; import org.eclipse.birt.report.engine.content.ILabelContent; import org.eclipse.birt.report.engine.content.IListBandContent; import org.eclipse.birt.report.engine.content.IListContent; import org.eclipse.birt.report.engine.content.IListGroupContent; import org.eclipse.birt.report.engine.content.IPageContent; import org.eclipse.birt.report.engine.content.IReportContent; import org.eclipse.birt.report.engine.content.IRowContent; import org.eclipse.birt.report.engine.content.IStyle; import org.eclipse.birt.report.engine.content.ITableBandContent; import org.eclipse.birt.report.engine.content.ITableContent; import org.eclipse.birt.report.engine.content.ITableGroupContent; import org.eclipse.birt.report.engine.content.ITextContent; import org.eclipse.birt.report.engine.content.impl.TextContent; import org.eclipse.birt.report.engine.css.engine.StyleConstants; import org.eclipse.birt.report.engine.css.engine.value.DataFormatValue; import org.eclipse.birt.report.engine.css.engine.value.birt.BIRTConstants; import org.eclipse.birt.report.engine.emitter.EmitterUtil; import org.eclipse.birt.report.engine.emitter.IEmitterServices; import org.eclipse.birt.report.engine.i18n.EngineResourceHandle; import org.eclipse.birt.report.engine.i18n.MessageConstants; import org.eclipse.birt.report.engine.ir.DimensionType; import org.eclipse.birt.report.engine.ir.EngineIRConstants; import org.eclipse.birt.report.engine.ir.SimpleMasterPageDesign; import org.eclipse.birt.report.engine.layout.emitter.Image; import org.eclipse.birt.report.engine.layout.pdf.font.FontInfo; import org.eclipse.birt.report.engine.layout.pdf.font.FontMappingManager; import org.eclipse.birt.report.engine.layout.pdf.font.FontMappingManagerFactory; import org.eclipse.birt.report.engine.layout.pdf.font.FontSplitter; import org.eclipse.birt.report.engine.layout.pdf.text.Chunk; import org.eclipse.birt.report.engine.layout.pdf.util.PropertyUtil; import org.eclipse.birt.report.engine.presentation.ContentEmitterVisitor; import org.eclipse.birt.report.engine.util.FlashFile; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.core.IModuleModel; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.w3c.dom.css.CSSValue; import com.ibm.icu.util.ULocale; public abstract class AbstractEmitterImpl { public final static int NORMAL = -1; public static enum InlineFlag { FIRST_INLINE, MIDDLE_INLINE, BLOCK }; public static enum TextFlag { START, MIDDLE, END, WHOLE }; private static Set<Integer> nonInherityStyles = new HashSet<Integer>( ); static { nonInherityStyles.add( IStyle.STYLE_BORDER_BOTTOM_COLOR ); nonInherityStyles.add( IStyle.STYLE_BORDER_BOTTOM_STYLE ); nonInherityStyles.add( IStyle.STYLE_BORDER_BOTTOM_WIDTH ); nonInherityStyles.add( IStyle.STYLE_BORDER_TOP_COLOR ); nonInherityStyles.add( IStyle.STYLE_BORDER_TOP_STYLE ); nonInherityStyles.add( IStyle.STYLE_BORDER_TOP_WIDTH ); nonInherityStyles.add( IStyle.STYLE_BORDER_LEFT_COLOR ); nonInherityStyles.add( IStyle.STYLE_BORDER_LEFT_STYLE ); nonInherityStyles.add( IStyle.STYLE_BORDER_LEFT_WIDTH ); nonInherityStyles.add( IStyle.STYLE_BORDER_RIGHT_COLOR ); nonInherityStyles.add( IStyle.STYLE_BORDER_RIGHT_STYLE ); nonInherityStyles.add( IStyle.STYLE_BORDER_RIGHT_WIDTH ); } private static Logger logger = Logger.getLogger( AbstractEmitterImpl.class .getName( ) ); protected OutputStream out = null; protected ContentEmitterVisitor contentVisitor; protected IWordWriter wordWriter = null; protected EmitterContext context = null; protected IPageContent previousPage = null; protected IReportContent reportContent; protected Stack<IStyle> styles = new Stack<IStyle>( ); private int pageWidth = 0; private int pageHeight = 0; protected int contentWidth = 0; private int headerHeight = 0; private int footerHeight = 0; private int topMargin = 0; private int bottomMargin = 0; private int leftMargin = 0; private int rightMargin = 0; private String orientation = "portrait"; private HashSet<String> bookmarks = new HashSet<String>( ); private boolean rowFilledFlag = false; private ArrayList<InstanceID> groupIdList = new ArrayList<InstanceID>( ); private int tocLevel = 1; private List<TocInfo> tableTocs = new ArrayList<TocInfo>( ); private IReportRunnable reportRunnable; private IHTMLActionHandler actionHandler; private IReportContext reportContext; private String messageFlashObjectNotSupported; private String layoutPreference = null; private boolean fixedLayout; public void initialize( IEmitterServices service ) throws EngineException { if ( service != null ) { this.out = EmitterUtil.getOuputStream( service, "report." + getOutputFormat( ) ); this.reportRunnable = service.getReportRunnable( ); this.actionHandler = (IHTMLActionHandler) service .getOption( RenderOption.ACTION_HANDLER ); reportContext = service.getReportContext( ); ULocale locale = null; if ( reportContext != null ) { locale = ULocale.forLocale( reportContext.getLocale( ) ); } if ( locale == null ) { locale = ULocale.getDefault( ); } EngineResourceHandle resourceHandle = new EngineResourceHandle( locale ); messageFlashObjectNotSupported = resourceHandle .getMessage( MessageConstants.FLASH_OBJECT_NOT_SUPPORTED_PROMPT ); IRenderOption renderOption = service.getRenderOption( ); if ( renderOption != null ) { HTMLRenderOption htmlOption = new HTMLRenderOption( renderOption ); layoutPreference = htmlOption.getLayoutPreference( ); } } context = new EmitterContext( ); } public void start( IReportContent report ) { this.reportContent = report; if ( null == layoutPreference ) { ReportDesignHandle designHandle = report.getDesign( ) .getReportDesign( ); if ( designHandle != null ) { String reportLayoutPreference = designHandle .getLayoutPreference( ); if ( DesignChoiceConstants.REPORT_LAYOUT_PREFERENCE_FIXED_LAYOUT .equals( reportLayoutPreference ) ) { layoutPreference = HTMLRenderOption.LAYOUT_PREFERENCE_FIXED; } else if ( DesignChoiceConstants.REPORT_LAYOUT_PREFERENCE_AUTO_LAYOUT .equals( reportLayoutPreference ) ) { layoutPreference = HTMLRenderOption.LAYOUT_PREFERENCE_AUTO; } } fixedLayout = HTMLRenderOption.LAYOUT_PREFERENCE_FIXED .equals( layoutPreference ); } } public void startPage( IPageContent page ) throws IOException, BirtException { if ( previousPage != null ) { outputPrePageProperties( ); previousPage = page; context.resetWidth( ); } else { previousPage = page; boolean isRtl = false; String creator = null; String title = null; String description = null; if ( reportContent != null ) { ReportDesignHandle designHandle = reportContent.getDesign( ) .getReportDesign( ); creator = designHandle.getAuthor( ); title = designHandle .getStringProperty( IModuleModel.TITLE_PROP ); description = designHandle.getDescription( ); IContent rootContent = reportContent.getRoot( ); isRtl = rootContent != null && rootContent.isRTL( ); } wordWriter.start( isRtl, creator, title, description ); drawDocumentBackground( ); } computePageProperties( page ); context.addWidth( contentWidth ); wordWriter.startPage( ); } private void outputPrePageProperties( ) throws IOException, BirtException { adjustInline( ); writeSectionInP( ); wordWriter.endPage( ); } public void end( IReportContent report ) throws IOException, BirtException { adjustInline( ); writeSectionInBody( ); wordWriter.endPage( ); wordWriter.end( ); } public void endContainer( IContainerContent container ) { // Do nothing. } public void startContainer( IContainerContent container ) { // Do nothing. } public abstract void endTable( ITableContent table ); public abstract void startForeign( IForeignContent foreign ) throws BirtException; protected abstract void writeContent( int type, String txt, IContent content ); public abstract String getOutputFormat( ); public void computePageProperties( IPageContent page ) { pageWidth = WordUtil.convertTo( page.getPageWidth( ), 0 ); // 11 inch * 1440 pageHeight = WordUtil.convertTo( page.getPageHeight( ), 0 ); footerHeight = WordUtil.convertTo( page.getFooterHeight( ), 0 ); headerHeight = WordUtil.convertTo( page.getHeaderHeight( ), 0 ); topMargin = WordUtil.convertTo( page.getMarginTop( ), 0 ); bottomMargin = WordUtil.convertTo( page.getMarginBottom( ), 0 ); leftMargin = WordUtil.convertTo( page.getMarginLeft( ), 0 ); rightMargin = WordUtil.convertTo( page.getMarginRight( ), 0 ); contentWidth = pageWidth - leftMargin - rightMargin; orientation = page.getOrientation( ); } public void startAutoText( IAutoTextContent autoText ) { writeContent( autoText.getType( ), autoText.getText( ), autoText ); } public void startData( IDataContent data ) { writeContent( AbstractEmitterImpl.NORMAL, data.getText( ), data ); } public void startLabel( ILabelContent label ) { String txt = label.getText( ) == null ? label.getLabelText( ) : label .getText( ); txt = txt == null ? "" : txt; writeContent( AbstractEmitterImpl.NORMAL, txt, label ); } public void startText( ITextContent text ) { writeContent( AbstractEmitterImpl.NORMAL, text.getText( ), text ); } public void startList( IListContent list ) { adjustInline( ); styles.push( list.getComputedStyle( ) ); writeBookmark( list ); Object listToc = list.getTOC( ); if ( listToc != null ) { tableTocs.add( new TocInfo( listToc.toString( ), tocLevel ) ); } increaseTOCLevel( list ); if ( context.isLastTable( ) ) { wordWriter.insertHiddenParagraph( ); } wordWriter.startTable( list.getComputedStyle( ), context .getCurrentWidth( ) ); } public void startListBand( IListBandContent listBand ) { context.startCell( ); wordWriter.startTableRow( -1 ); IStyle style = computeStyle( listBand.getComputedStyle( ) ); wordWriter.startTableCell( context.getCurrentWidth( ), style, null ); writeTableToc( ); } public void startListGroup( IListGroupContent group ) { setGroupToc( group ); } public void startRow( IRowContent row ) { if ( !isHidden( row ) ) { writeBookmark( row ); rowFilledFlag = false; boolean isHeader = false; styles.push( row.getComputedStyle( ) ); if ( row.getBand( ) != null && row.getBand( ).getBandType( ) == IBandContent.BAND_HEADER ) { isHeader = true; } double height = WordUtil.convertTo( row.getHeight( ) ); wordWriter.startTableRow( height, isHeader, row.getTable( ) .isHeaderRepeat( ), fixedLayout ); context.newRow( ); } } public void startContent( IContent content ) { } public void startGroup( IGroupContent group ) { setGroupToc( group ); } public void startCell( ICellContent cell ) { rowFilledFlag = true; context.startCell( ); writeBookmark( cell ); int columnId = cell.getColumn( ); List<SpanInfo> spans = context.getSpans( columnId ); if ( spans != null ) { for ( int i = 0; i < spans.size( ); i++ ) { wordWriter.writeSpanCell( spans.get( i ) ); } } int columnSpan = cell.getColSpan( ); int rowSpan = cell.getRowSpan( ); int cellWidth = context.getCellWidth( columnId, columnSpan ); IStyle style = computeStyle( cell.getComputedStyle( ) ); if ( rowSpan > 1 ) { context.addSpan( columnId, columnSpan, cellWidth, rowSpan, style ); } SpanInfo info = null; if ( columnSpan > 1 || rowSpan > 1 ) { info = new SpanInfo( columnId, columnSpan, cellWidth, true, style ); } wordWriter.startTableCell( cellWidth, style, info ); context.addWidth( getCellWidth( cellWidth, style ) ); writeTableToc( ); if ( cell.getDiagonalNumber( ) != 0 && cell.getDiagonalStyle( ) != null && !"none".equalsIgnoreCase( cell.getDiagonalStyle( ) ) ) { drawDiagonalLine( cell, WordUtil.twipToPt( cellWidth ) ); } } private void drawDiagonalLine( ICellContent cell, double cellWidth ) { if ( cellWidth == 0 ) return; int cellHeight = WordUtil.convertTo( getCellHeight( cell ), 0 ) / 20; if ( cellHeight == 0 ) return; DiagonalLineInfo diagonalLineInfo = new DiagonalLineInfo( ); int diagonalWidth = PropertyUtil.getDimensionValue( cell, cell .getDiagonalWidth( ), (int) cellWidth ) / 1000; diagonalLineInfo.setDiagonalLine( cell.getDiagonalNumber( ), cell .getDiagonalStyle( ), diagonalWidth ); diagonalLineInfo.setAntidiagonalLine( 0, null, 0 ); diagonalLineInfo.setCoordinateSize( cellWidth, cellHeight ); String lineColor = null; if ( cell.getDiagonalColor( ) != null ) { lineColor = WordUtil.parseColor( cell.getDiagonalColor( ) ); } else { lineColor = WordUtil.parseColor( cell.getComputedStyle( ) .getColor( ) ); } diagonalLineInfo.setColor( lineColor ); wordWriter.drawDiagonalLine( diagonalLineInfo ); } protected DimensionType getCellHeight( ICellContent cell ) { IElement parent = cell.getParent( ); while ( !( parent instanceof IRowContent ) ) { parent = parent.getParent( ); } return ( (IRowContent) parent ).getHeight( ); } public void startTable( ITableContent table ) { adjustInline( ); styles.push( table.getComputedStyle( ) ); writeBookmark( table ); Object tableToc = table.getTOC( ); if ( tableToc != null ) { tableTocs.add( new TocInfo( tableToc.toString( ), tocLevel ) ); } increaseTOCLevel( table ); String caption = table.getCaption( ); if ( caption != null ) { wordWriter.writeCaption( caption ); } if ( context.isLastTable( ) ) { wordWriter.insertHiddenParagraph( ); } int width = WordUtil.convertTo( table.getWidth( ), context .getCurrentWidth( ) ); width = Math.min( width, context.getCurrentWidth( ) ); int[] cols = computeTblColumnWidths( table, width ); wordWriter .startTable( table.getComputedStyle( ), getTableWidth( cols ) ); wordWriter.writeColumn( cols ); context.addTable( cols, table.getComputedStyle( ) ); } private int getTableWidth( int[] cols ) { int tableWidth = 0; for ( int i = 0; i < cols.length; i++ ) { tableWidth += cols[i]; } return tableWidth; } public void startTableBand( ITableBandContent band ) { } public void startTableGroup( ITableGroupContent group ) { setGroupToc( group ); } private void setGroupToc( IGroupContent group ) { if ( group != null ) { InstanceID groupId = group.getInstanceID( ); if ( !groupIdList.contains( groupId ) ) { groupIdList.add( groupId ); Object groupToc = group.getTOC( ); if ( groupToc != null ) { tableTocs .add( new TocInfo( groupToc.toString( ), tocLevel ) ); } } increaseTOCLevel( group ); } } private void writeTableToc( ) { if ( !tableTocs.isEmpty( ) ) { for ( TocInfo toc : tableTocs ) { if ( !"".equals( toc.tocValue ) ) { wordWriter.writeTOC( toc.tocValue, toc.tocLevel ); } } tableTocs.clear( ); } } public void endCell( ICellContent cell ) { adjustInline( ); context.removeWidth( ); wordWriter.endTableCell( context.needEmptyP( ) ); context.endCell( ); } public void endContent( IContent content ) { } public void endGroup( IGroupContent group ) { decreaseTOCLevel( group ); } public void endList( IListContent list ) { if ( !styles.isEmpty( ) ) { styles.pop( ); } context.addContainer( true ); wordWriter.endTable( ); context.setLastIsTable( true ); decreaseTOCLevel( list ); } public void endListBand( IListBandContent listBand ) { adjustInline( ); context.endCell( ); wordWriter.endTableCell( true ); wordWriter.endTableRow( ); } public void endListGroup( IListGroupContent group ) { decreaseTOCLevel( group ); } public void endRow( IRowContent row ) { if ( !isHidden( row ) ) { if ( !styles.isEmpty( ) ) { styles.pop( ); } int col = context.getCurrentTableColmns( ).length - 1; List<SpanInfo> spans = context.getSpans( col ); if ( spans != null ) { int spanSize = spans.size( ); if ( spanSize > 0 ) { rowFilledFlag = true; } for ( int i = 0; i < spanSize; i++ ) { wordWriter.writeSpanCell( spans.get( i ) ); } } if ( !rowFilledFlag ) { wordWriter.writeEmptyCell( ); rowFilledFlag = true; } wordWriter.endTableRow( ); } } public void endTableBand( ITableBandContent band ) { } public void endTableGroup( ITableGroupContent group ) { decreaseTOCLevel( group ); } public void endPage( IPageContent page ) { } public void startImage( IImageContent image ) { IStyle style = image.getComputedStyle( ); InlineFlag inlineFlag = getInlineFlag( style ); String uri = image.getURI( ); String mimeType = image.getMIMEType( ); String extension = image.getExtension( ); String altText = image.getAltText( ); + double height = WordUtil.convertImageSize( image.getHeight( ), 0 ); + double width = WordUtil.convertImageSize( image.getWidth( ), 0 ); context.addContainer( false ); if ( FlashFile.isFlash( mimeType, uri, extension ) ) { if ( altText == null ) { altText = messageFlashObjectNotSupported; } - wordWriter.drawImage( null, 0.0, 0.0, null, style, inlineFlag, + wordWriter.drawImage( null, height, width, null, style, inlineFlag, altText, uri ); return; } try { Image imageInfo = EmitterUtil.parseImage( image, image .getImageSource( ), uri, mimeType, extension ); byte[] data = imageInfo.getData( ); if ( data == null || data.length == 0 ) { wordWriter.drawImage( null, 0.0, 0.0, null, style, inlineFlag, altText, uri ); return; } - double height = WordUtil.convertImageSize( image.getHeight( ), + height = WordUtil.convertImageSize( image.getHeight( ), imageInfo.getHeight( ) ); - double width = WordUtil.convertImageSize( image.getWidth( ), + width = WordUtil.convertImageSize( image.getWidth( ), imageInfo.getWidth( ) ); writeBookmark( image ); writeToc( image ); HyperlinkInfo hyper = getHyperlink( image ); wordWriter.drawImage( data, height, width, hyper, style, inlineFlag, altText, uri ); } catch ( IOException e ) { logger.log( Level.WARNING, e.getLocalizedMessage( ) ); + wordWriter.drawImage( null, height, width, null, style, inlineFlag, + altText, uri ); } } protected void endTable( ) { context.addContainer( true ); if ( !styles.isEmpty( ) ) { styles.pop( ); } wordWriter.endTable( ); context.setLastIsTable( true ); context.removeTable( ); } protected void increaseTOCLevel( IContent content ) { if ( content != null && content.getTOC( ) != null ) { tocLevel += 1; } } protected void decreaseTOCLevel( IContent content ) { if ( content != null && content.getTOC( ) != null ) { tocLevel -= 1; } } protected void adjustInline( ) { if ( !context.isFirstInline( ) ) { wordWriter.endParagraph( ); context.endInline( ); } } protected void writeSectionInP( ) throws IOException, BirtException { wordWriter.startSectionInParagraph( ); writeHeaderFooter( ); wordWriter.writePageProperties( pageHeight, pageWidth, headerHeight, footerHeight, topMargin, bottomMargin, leftMargin, rightMargin, orientation ); wordWriter.writePageBorders( previousPage.getComputedStyle( ), topMargin, bottomMargin, leftMargin, rightMargin ); wordWriter.endSectionInParagraph( ); } protected void writeSectionInBody( ) throws IOException, BirtException { wordWriter.startSection( ); writeHeaderFooter( ); wordWriter.writePageProperties( pageHeight, pageWidth, headerHeight, footerHeight, topMargin, bottomMargin, leftMargin, rightMargin, orientation ); wordWriter.writePageBorders( previousPage.getComputedStyle( ), topMargin, bottomMargin, leftMargin, rightMargin ); wordWriter.endSection( ); } // TOC must not contain space,word may not process TOC with // space protected void writeToc( IContent content ) { if ( content != null ) { Object tocObj = content.getTOC( ); if ( tocObj != null ) { String toc = tocObj.toString( ); toc = toc.trim( ); if ( !"".equals( toc ) ) { wordWriter.writeTOC( toc, tocLevel ); } } } } private InlineFlag getInlineFlag( IStyle style ) { InlineFlag inlineFlag = InlineFlag.BLOCK; if ( "inline".equalsIgnoreCase( style.getDisplay( ) ) ) { if ( context.isFirstInline( ) ) { context.startInline( ); inlineFlag = InlineFlag.FIRST_INLINE; } else inlineFlag = InlineFlag.MIDDLE_INLINE; } else { adjustInline( ); } return inlineFlag; } protected void writeBookmark( IContent content ) { String bookmark = content.getBookmark( ); // birt use __TOC_X_X as bookmark for toc and thus it is not a // really bookmark if ( bookmark == null || bookmark.startsWith( "_TOC" ) ) { return; } if ( bookmarks.contains( bookmark ) ) { return; } bookmark = bookmark.replaceAll( " ", "_" ); wordWriter.writeBookmark( bookmark ); bookmarks.add( bookmark ); } protected HyperlinkInfo getHyperlink( IContent content ) { HyperlinkInfo hyperlink = null; IHyperlinkAction linkAction = content.getHyperlinkAction( ); if ( linkAction != null ) { String tooltip = linkAction.getTooltip( ); String bookmark = linkAction.getBookmark( ); switch ( linkAction.getType( ) ) { case IHyperlinkAction.ACTION_BOOKMARK : bookmark = bookmark.replaceAll( " ", "_" ); hyperlink = new HyperlinkInfo( HyperlinkInfo.BOOKMARK, bookmark, tooltip ); break; case IHyperlinkAction.ACTION_HYPERLINK : case IHyperlinkAction.ACTION_DRILLTHROUGH : String url = EmitterUtil .getHyperlinkUrl( linkAction, reportRunnable, actionHandler, reportContext ); hyperlink = new HyperlinkInfo( HyperlinkInfo.HYPERLINK, url, tooltip ); break; } } return hyperlink; } protected void writeText( int type, String txt, IContent content, InlineFlag inlineFlag, IStyle computedStyle, IStyle inlineStyle ) { HyperlinkInfo hyper = getHyperlink( content ); int paragraphWidth = (int) WordUtil .twipToPt( context.getCurrentWidth( ) ); if ( content instanceof TextContent ) { TextFlag textFlag = TextFlag.START; String fontFamily = null; if ( "".equals( txt ) || txt == null || WordUtil.isField( content ) ) { wordWriter.writeContent( type, txt, computedStyle, inlineStyle, fontFamily, hyper, inlineFlag, textFlag, paragraphWidth ); } else { FontSplitter fontSplitter = getFontSplitter( content ); while ( fontSplitter.hasMore( ) ) { Chunk ch = fontSplitter.getNext( ); int offset = ch.getOffset( ); int length = ch.getLength( ); fontFamily = getFontFamily( computedStyle, ch ); wordWriter.writeContent( type, txt.substring( offset, offset + length ), computedStyle, inlineStyle, fontFamily, hyper, inlineFlag, textFlag, paragraphWidth ); textFlag = fontSplitter.hasMore( ) ? TextFlag.MIDDLE : TextFlag.END; } } if ( inlineFlag == InlineFlag.BLOCK ) { wordWriter.writeContent( type, null, computedStyle, inlineStyle, fontFamily, hyper, inlineFlag, TextFlag.END, paragraphWidth ); } } else { wordWriter.writeContent( type, txt, computedStyle, inlineStyle, computedStyle.getFontFamily( ), hyper, inlineFlag, TextFlag.WHOLE, paragraphWidth ); } } private String getFontFamily( IStyle c_style, Chunk ch ) { String fontFamily = null; FontInfo info = ch.getFontInfo( ); if ( info != null ) { fontFamily = info.getFontName( ); } else { fontFamily = c_style.getFontFamily( ); } return fontFamily; } private FontSplitter getFontSplitter( IContent content ) { FontMappingManager fontManager = FontMappingManagerFactory .getInstance( ).getFontMappingManager( "doc", Locale.getDefault( ) ); String text = ( (TextContent) content ).getText( ); FontSplitter fontSplitter = new FontSplitter( fontManager, new Chunk( text ), (TextContent) content, true ); return fontSplitter; } private boolean isHidden( IContent content ) { if ( content != null ) { IStyle style = content.getStyle( ); if ( !IStyle.NONE_VALUE.equals( style .getProperty( IStyle.STYLE_DISPLAY ) ) ) { return isHiddenByVisibility( content ); } return true; } return false; } /** * if the content is hidden * * @return */ private boolean isHiddenByVisibility( IContent content ) { assert content != null; IStyle style = content.getStyle( ); String formats = style.getVisibleFormat( ); return contains( formats, getOutputFormat( ) ); } private boolean contains( String formats, String format ) { if ( formats != null && ( formats.indexOf( EngineIRConstants.FORMAT_TYPE_VIEWER ) >= 0 || formats.indexOf( BIRTConstants.BIRT_ALL_VALUE ) >= 0 || formats .indexOf( format ) >= 0 ) ) { return true; } return false; } protected IStyle computeStyle( IStyle style ) { if ( styles.size( ) == 0 ) { return style; } for ( int i = 0; i < StyleConstants.NUMBER_OF_STYLE; i++ ) { if ( isInherityProperty( i ) ) { if ( isNullValue( style.getProperty( i ) ) ) { style.setProperty( i, null ); for ( int p = styles.size( ) - 1; p >= 0; p-- ) { IStyle parent = styles.get( p ); if ( !isNullValue( parent.getProperty( i ) ) ) { style.setProperty( i, parent.getProperty( i ) ); break; } } } } } return style; } protected boolean isNullValue( CSSValue value ) { if ( value == null ) { return true; } if ( value instanceof DataFormatValue ) { return true; } String cssText = value.getCssText( ); return "none".equalsIgnoreCase( cssText ) || "transparent".equalsIgnoreCase( cssText ); } private void writeHeaderFooter( ) throws IOException, BirtException { IStyle style = previousPage.getStyle( ); String backgroundHeight = style.getBackgroundHeight( ); String backgroundWidth = style.getBackgroundWidth( ); if ( previousPage.getPageHeader( ) != null || backgroundHeight != null || backgroundWidth != null ) { SimpleMasterPageDesign master = (SimpleMasterPageDesign) previousPage .getGenerateBy( ); wordWriter.startHeader( !master.isShowHeaderOnFirst( ), headerHeight, contentWidth ); if ( backgroundHeight != null || backgroundWidth != null ) { String backgroundImageUrl = EmitterUtil.getBackgroundImageUrl( style, reportContent.getDesign( ).getReportDesign( ), reportContext.getAppContext( ) ); wordWriter.drawDocumentBackgroundImage( backgroundImageUrl, backgroundHeight, backgroundWidth, WordUtil.twipToPt( topMargin ), WordUtil .twipToPt( leftMargin ), WordUtil .twipToPt( pageHeight ), WordUtil .twipToPt( pageWidth ) ); } contentVisitor.visitChildren( previousPage.getPageHeader( ), null ); wordWriter.endHeader( ); } if ( previousPage.getPageFooter( ) != null ) { wordWriter.startFooter( footerHeight, contentWidth ); contentVisitor.visitChildren( previousPage.getPageFooter( ), null ); wordWriter.endFooter( ); } } /** * Transfer background for current page to Doc format. Now, the exported * file will apply the first background properties, and followed background * will ignore. * * In addition, Since the Word only support fill-in background, the * background attach, pos, posX, posY and repeat are not mapped to Word * easyly. At present, ignore those properties. * * @throws IOException * * @TODO support background properties. attach, pos, posx, posy and repeat. */ protected void drawDocumentBackground( ) throws IOException { // Set the first page background which is not null to DOC IStyle style = previousPage.getStyle( ); String backgroundColor = style.getBackgroundColor( ); String backgroundImageUrl = EmitterUtil.getBackgroundImageUrl( style, reportContent.getDesign( ).getReportDesign( ), reportContext .getAppContext( ) ); String height = style.getBackgroundHeight( ); String width = style.getBackgroundWidth( ); wordWriter.drawDocumentBackground( backgroundColor, backgroundImageUrl, height, width ); } private boolean isInherityProperty( int propertyIndex ) { return !nonInherityStyles.contains( propertyIndex ); } private int getCellWidth( int cellWidth, IStyle style ) { float leftPadding = getPadding( style.getPaddingLeft( ) ); float rightPadding = getPadding( style.getPaddingRight( ) ); if ( leftPadding > cellWidth ) { leftPadding = 0; } if ( rightPadding > cellWidth ) { rightPadding = 0; } if ( ( leftPadding + rightPadding ) > cellWidth ) { rightPadding = 0; } return (int) ( cellWidth - leftPadding - rightPadding ); } private float getPadding( String padding ) { float value = 0; // Percentage value will be omitted try { value = Float.parseFloat( padding ) / 50; } catch ( Exception e ) { logger.log( Level.WARNING, e.getMessage( ), e ); } return value; } private int[] computeTblColumnWidths( ITableContent table, int tblWidth ) { int colCount = table.getColumnCount( ); int[] tblColumns = new int[colCount]; int count = 0; int total = 0; for ( int i = 0; i < colCount; i++ ) { IColumn col = table.getColumn( i ); if ( col.getWidth( ) == null ) { tblColumns[i] = -1; count++; } else { tblColumns[i] = WordUtil.convertTo( col.getWidth( ), tblWidth ); total += tblColumns[i]; } } if ( table.getWidth( ) == null && count == 0 ) { return tblColumns; } return EmitterUtil.resizeTableColumn( tblWidth, tblColumns, count, total ); } class TocInfo { String tocValue; int tocLevel; TocInfo( String tocValue, int tocLevel ) { this.tocValue = tocValue; this.tocLevel = tocLevel; } } }
false
true
public void startImage( IImageContent image ) { IStyle style = image.getComputedStyle( ); InlineFlag inlineFlag = getInlineFlag( style ); String uri = image.getURI( ); String mimeType = image.getMIMEType( ); String extension = image.getExtension( ); String altText = image.getAltText( ); context.addContainer( false ); if ( FlashFile.isFlash( mimeType, uri, extension ) ) { if ( altText == null ) { altText = messageFlashObjectNotSupported; } wordWriter.drawImage( null, 0.0, 0.0, null, style, inlineFlag, altText, uri ); return; } try { Image imageInfo = EmitterUtil.parseImage( image, image .getImageSource( ), uri, mimeType, extension ); byte[] data = imageInfo.getData( ); if ( data == null || data.length == 0 ) { wordWriter.drawImage( null, 0.0, 0.0, null, style, inlineFlag, altText, uri ); return; } double height = WordUtil.convertImageSize( image.getHeight( ), imageInfo.getHeight( ) ); double width = WordUtil.convertImageSize( image.getWidth( ), imageInfo.getWidth( ) ); writeBookmark( image ); writeToc( image ); HyperlinkInfo hyper = getHyperlink( image ); wordWriter.drawImage( data, height, width, hyper, style, inlineFlag, altText, uri ); } catch ( IOException e ) { logger.log( Level.WARNING, e.getLocalizedMessage( ) ); } }
public void startImage( IImageContent image ) { IStyle style = image.getComputedStyle( ); InlineFlag inlineFlag = getInlineFlag( style ); String uri = image.getURI( ); String mimeType = image.getMIMEType( ); String extension = image.getExtension( ); String altText = image.getAltText( ); double height = WordUtil.convertImageSize( image.getHeight( ), 0 ); double width = WordUtil.convertImageSize( image.getWidth( ), 0 ); context.addContainer( false ); if ( FlashFile.isFlash( mimeType, uri, extension ) ) { if ( altText == null ) { altText = messageFlashObjectNotSupported; } wordWriter.drawImage( null, height, width, null, style, inlineFlag, altText, uri ); return; } try { Image imageInfo = EmitterUtil.parseImage( image, image .getImageSource( ), uri, mimeType, extension ); byte[] data = imageInfo.getData( ); if ( data == null || data.length == 0 ) { wordWriter.drawImage( null, 0.0, 0.0, null, style, inlineFlag, altText, uri ); return; } height = WordUtil.convertImageSize( image.getHeight( ), imageInfo.getHeight( ) ); width = WordUtil.convertImageSize( image.getWidth( ), imageInfo.getWidth( ) ); writeBookmark( image ); writeToc( image ); HyperlinkInfo hyper = getHyperlink( image ); wordWriter.drawImage( data, height, width, hyper, style, inlineFlag, altText, uri ); } catch ( IOException e ) { logger.log( Level.WARNING, e.getLocalizedMessage( ) ); wordWriter.drawImage( null, height, width, null, style, inlineFlag, altText, uri ); } }
diff --git a/src/com/android/email/activity/setup/AccountSetupExchange.java b/src/com/android/email/activity/setup/AccountSetupExchange.java index fcfbc8ff..bafca357 100644 --- a/src/com/android/email/activity/setup/AccountSetupExchange.java +++ b/src/com/android/email/activity/setup/AccountSetupExchange.java @@ -1,355 +1,359 @@ /* * 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.email.activity.setup; import com.android.email.R; import com.android.email.Utility; import com.android.email.provider.EmailContent; import com.android.email.provider.EmailContent.Account; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.CompoundButton.OnCheckedChangeListener; import java.net.URI; import java.net.URISyntaxException; /** * Provides generic setup for Exchange accounts. The following fields are supported: * * Email Address (from previous setup screen) * Server * Domain * Requires SSL? * User (login) * Password */ public class AccountSetupExchange extends Activity implements OnClickListener, OnCheckedChangeListener { private static final String EXTRA_ACCOUNT = "account"; private static final String EXTRA_MAKE_DEFAULT = "makeDefault"; private static final String EXTRA_EAS_FLOW = "easFlow"; private final static int DIALOG_DUPLICATE_ACCOUNT = 1; private EditText mUsernameView; private EditText mPasswordView; private EditText mServerView; private CheckBox mSslSecurityView; private CheckBox mTrustCertificatesView; private Button mNextButton; private Account mAccount; private boolean mMakeDefault; private String mCacheLoginCredential; private String mDuplicateAccountName; public static void actionIncomingSettings(Activity fromActivity, Account account, boolean makeDefault, boolean easFlowMode) { Intent i = new Intent(fromActivity, AccountSetupExchange.class); i.putExtra(EXTRA_ACCOUNT, account); i.putExtra(EXTRA_MAKE_DEFAULT, makeDefault); i.putExtra(EXTRA_EAS_FLOW, easFlowMode); fromActivity.startActivity(i); } public static void actionEditIncomingSettings(Activity fromActivity, Account account) { Intent i = new Intent(fromActivity, AccountSetupExchange.class); i.setAction(Intent.ACTION_EDIT); i.putExtra(EXTRA_ACCOUNT, account); fromActivity.startActivity(i); } /** * For now, we'll simply replicate outgoing, for the purpose of satisfying the * account settings flow. */ public static void actionEditOutgoingSettings(Activity fromActivity, Account account) { Intent i = new Intent(fromActivity, AccountSetupExchange.class); i.setAction(Intent.ACTION_EDIT); i.putExtra(EXTRA_ACCOUNT, account); fromActivity.startActivity(i); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.account_setup_exchange); mUsernameView = (EditText) findViewById(R.id.account_username); mPasswordView = (EditText) findViewById(R.id.account_password); mServerView = (EditText) findViewById(R.id.account_server); mSslSecurityView = (CheckBox) findViewById(R.id.account_ssl); mSslSecurityView.setOnCheckedChangeListener(this); mTrustCertificatesView = (CheckBox) findViewById(R.id.account_trust_certificates); mNextButton = (Button)findViewById(R.id.next); mNextButton.setOnClickListener(this); /* * Calls validateFields() which enables or disables the Next button * based on the fields' validity. */ TextWatcher validationTextWatcher = new TextWatcher() { public void afterTextChanged(Editable s) { validateFields(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }; mUsernameView.addTextChangedListener(validationTextWatcher); mPasswordView.addTextChangedListener(validationTextWatcher); mServerView.addTextChangedListener(validationTextWatcher); mAccount = (EmailContent.Account) getIntent().getParcelableExtra(EXTRA_ACCOUNT); mMakeDefault = getIntent().getBooleanExtra(EXTRA_MAKE_DEFAULT, false); /* * If we're being reloaded we override the original account with the one * we saved */ if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_ACCOUNT)) { mAccount = (EmailContent.Account) savedInstanceState.getParcelable(EXTRA_ACCOUNT); } try { URI uri = new URI(mAccount.getStoreUri(this)); String username = null; String password = null; if (uri.getUserInfo() != null) { String[] userInfoParts = uri.getUserInfo().split(":", 2); username = userInfoParts[0]; if (userInfoParts.length > 1) { password = userInfoParts[1]; } } if (username != null) { - // Add a backslash to the start of the username as an affordance - mUsernameView.setText("\\" + username); + // Add a backslash to the start of the username, but only if the username has no + // backslash in it. + if (username.indexOf('\\') < 0) { + username = "\\" + username; + } + mUsernameView.setText(username); } if (password != null) { mPasswordView.setText(password); } if (uri.getScheme().startsWith("eas")) { // any other setup from mAccount can go here } else { throw new Error("Unknown account type: " + mAccount.getStoreUri(this)); } if (uri.getHost() != null) { mServerView.setText(uri.getHost()); } boolean ssl = uri.getScheme().contains("ssl"); mSslSecurityView.setChecked(ssl); mTrustCertificatesView.setChecked(uri.getScheme().contains("tssl")); mTrustCertificatesView.setVisibility(ssl ? View.VISIBLE : View.GONE); } catch (URISyntaxException use) { /* * We should always be able to parse our own settings. */ throw new Error(use); } validateFields(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(EXTRA_ACCOUNT, mAccount); } private boolean usernameFieldValid(EditText usernameView) { return Utility.requiredFieldValid(usernameView) && !usernameView.getText().toString().equals("\\"); } /** * Prepare a cached dialog with current values (e.g. account name) */ @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_DUPLICATE_ACCOUNT: return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.account_duplicate_dlg_title) .setMessage(getString(R.string.account_duplicate_dlg_message_fmt, mDuplicateAccountName)) .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dismissDialog(DIALOG_DUPLICATE_ACCOUNT); } }) .create(); } return null; } /** * Update a cached dialog with current values (e.g. account name) */ @Override public void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_DUPLICATE_ACCOUNT: if (mDuplicateAccountName != null) { AlertDialog alert = (AlertDialog) dialog; alert.setMessage(getString(R.string.account_duplicate_dlg_message_fmt, mDuplicateAccountName)); } break; } } /** * Check the values in the fields and decide if it makes sense to enable the "next" button * NOTE: Does it make sense to extract & combine with similar code in AccountSetupIncoming? */ private void validateFields() { boolean enabled = usernameFieldValid(mUsernameView) && Utility.requiredFieldValid(mPasswordView) && Utility.requiredFieldValid(mServerView); if (enabled) { try { URI uri = getUri(); } catch (URISyntaxException use) { enabled = false; } } mNextButton.setEnabled(enabled); Utility.setCompoundDrawablesAlpha(mNextButton, enabled ? 255 : 128); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (Intent.ACTION_EDIT.equals(getIntent().getAction())) { // TODO Review carefully to make sure this is bulletproof if (mAccount.isSaved()) { mAccount.update(this, mAccount.toContentValues()); } else { mAccount.save(this); } finish(); } else { // Go directly to end - there is no 2nd screen for incoming settings boolean easFlowMode = getIntent().getBooleanExtra(EXTRA_EAS_FLOW, false); AccountSetupOptions.actionOptions(this, mAccount, mMakeDefault, easFlowMode); finish(); } } } /** * Attempt to create a URI from the fields provided. Throws URISyntaxException if there's * a problem with the user input. * @return a URI built from the account setup fields */ private URI getUri() throws URISyntaxException { boolean sslRequired = mSslSecurityView.isChecked(); boolean trustCertificates = mTrustCertificatesView.isChecked(); String scheme = (sslRequired) ? (trustCertificates ? "eas+tssl+" : "eas+ssl+") : "eas"; String userName = mUsernameView.getText().toString().trim(); // Remove a leading backslash, if there is one, since we now automatically put one at // the start of the username field if (userName.startsWith("\\")) { userName = userName.substring(1); } mCacheLoginCredential = userName; String userInfo = userName + ":" + mPasswordView.getText().toString().trim(); String host = mServerView.getText().toString().trim(); String path = null; URI uri = new URI( scheme, userInfo, host, 0, path, null, null); return uri; } /** * Note, in EAS, store & sender are the same, so we always populate them together */ private void onNext() { try { URI uri = getUri(); mAccount.setStoreUri(this, uri.toString()); mAccount.setSenderUri(this, uri.toString()); // Stop here if the login credentials duplicate an existing account // (unless they duplicate the existing account, as they of course will) mDuplicateAccountName = Utility.findDuplicateAccount(this, mAccount.mId, uri.getHost(), mCacheLoginCredential); if (mDuplicateAccountName != null) { this.showDialog(DIALOG_DUPLICATE_ACCOUNT); return; } } catch (URISyntaxException use) { /* * It's unrecoverable if we cannot create a URI from components that * we validated to be safe. */ throw new Error(use); } AccountSetupCheckSettings.actionCheckSettings(this, mAccount, true, false); } public void onClick(View v) { switch (v.getId()) { case R.id.next: onNext(); break; } } public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (buttonView.getId() == R.id.account_ssl) { mTrustCertificatesView.setVisibility(isChecked ? View.VISIBLE : View.GONE); } } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.account_setup_exchange); mUsernameView = (EditText) findViewById(R.id.account_username); mPasswordView = (EditText) findViewById(R.id.account_password); mServerView = (EditText) findViewById(R.id.account_server); mSslSecurityView = (CheckBox) findViewById(R.id.account_ssl); mSslSecurityView.setOnCheckedChangeListener(this); mTrustCertificatesView = (CheckBox) findViewById(R.id.account_trust_certificates); mNextButton = (Button)findViewById(R.id.next); mNextButton.setOnClickListener(this); /* * Calls validateFields() which enables or disables the Next button * based on the fields' validity. */ TextWatcher validationTextWatcher = new TextWatcher() { public void afterTextChanged(Editable s) { validateFields(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }; mUsernameView.addTextChangedListener(validationTextWatcher); mPasswordView.addTextChangedListener(validationTextWatcher); mServerView.addTextChangedListener(validationTextWatcher); mAccount = (EmailContent.Account) getIntent().getParcelableExtra(EXTRA_ACCOUNT); mMakeDefault = getIntent().getBooleanExtra(EXTRA_MAKE_DEFAULT, false); /* * If we're being reloaded we override the original account with the one * we saved */ if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_ACCOUNT)) { mAccount = (EmailContent.Account) savedInstanceState.getParcelable(EXTRA_ACCOUNT); } try { URI uri = new URI(mAccount.getStoreUri(this)); String username = null; String password = null; if (uri.getUserInfo() != null) { String[] userInfoParts = uri.getUserInfo().split(":", 2); username = userInfoParts[0]; if (userInfoParts.length > 1) { password = userInfoParts[1]; } } if (username != null) { // Add a backslash to the start of the username as an affordance mUsernameView.setText("\\" + username); } if (password != null) { mPasswordView.setText(password); } if (uri.getScheme().startsWith("eas")) { // any other setup from mAccount can go here } else { throw new Error("Unknown account type: " + mAccount.getStoreUri(this)); } if (uri.getHost() != null) { mServerView.setText(uri.getHost()); } boolean ssl = uri.getScheme().contains("ssl"); mSslSecurityView.setChecked(ssl); mTrustCertificatesView.setChecked(uri.getScheme().contains("tssl")); mTrustCertificatesView.setVisibility(ssl ? View.VISIBLE : View.GONE); } catch (URISyntaxException use) { /* * We should always be able to parse our own settings. */ throw new Error(use); } validateFields(); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.account_setup_exchange); mUsernameView = (EditText) findViewById(R.id.account_username); mPasswordView = (EditText) findViewById(R.id.account_password); mServerView = (EditText) findViewById(R.id.account_server); mSslSecurityView = (CheckBox) findViewById(R.id.account_ssl); mSslSecurityView.setOnCheckedChangeListener(this); mTrustCertificatesView = (CheckBox) findViewById(R.id.account_trust_certificates); mNextButton = (Button)findViewById(R.id.next); mNextButton.setOnClickListener(this); /* * Calls validateFields() which enables or disables the Next button * based on the fields' validity. */ TextWatcher validationTextWatcher = new TextWatcher() { public void afterTextChanged(Editable s) { validateFields(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }; mUsernameView.addTextChangedListener(validationTextWatcher); mPasswordView.addTextChangedListener(validationTextWatcher); mServerView.addTextChangedListener(validationTextWatcher); mAccount = (EmailContent.Account) getIntent().getParcelableExtra(EXTRA_ACCOUNT); mMakeDefault = getIntent().getBooleanExtra(EXTRA_MAKE_DEFAULT, false); /* * If we're being reloaded we override the original account with the one * we saved */ if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_ACCOUNT)) { mAccount = (EmailContent.Account) savedInstanceState.getParcelable(EXTRA_ACCOUNT); } try { URI uri = new URI(mAccount.getStoreUri(this)); String username = null; String password = null; if (uri.getUserInfo() != null) { String[] userInfoParts = uri.getUserInfo().split(":", 2); username = userInfoParts[0]; if (userInfoParts.length > 1) { password = userInfoParts[1]; } } if (username != null) { // Add a backslash to the start of the username, but only if the username has no // backslash in it. if (username.indexOf('\\') < 0) { username = "\\" + username; } mUsernameView.setText(username); } if (password != null) { mPasswordView.setText(password); } if (uri.getScheme().startsWith("eas")) { // any other setup from mAccount can go here } else { throw new Error("Unknown account type: " + mAccount.getStoreUri(this)); } if (uri.getHost() != null) { mServerView.setText(uri.getHost()); } boolean ssl = uri.getScheme().contains("ssl"); mSslSecurityView.setChecked(ssl); mTrustCertificatesView.setChecked(uri.getScheme().contains("tssl")); mTrustCertificatesView.setVisibility(ssl ? View.VISIBLE : View.GONE); } catch (URISyntaxException use) { /* * We should always be able to parse our own settings. */ throw new Error(use); } validateFields(); }
diff --git a/src/net/grinder/plugin/http/tcpproxyfilter/RegularExpressionsImplementation.java b/src/net/grinder/plugin/http/tcpproxyfilter/RegularExpressionsImplementation.java index 0026ce11..29b03439 100755 --- a/src/net/grinder/plugin/http/tcpproxyfilter/RegularExpressionsImplementation.java +++ b/src/net/grinder/plugin/http/tcpproxyfilter/RegularExpressionsImplementation.java @@ -1,144 +1,144 @@ // Copyright (C) 2006 Philip Aston // All rights reserved. // // This file is part of The Grinder software distribution. Refer to // the file LICENSE which is part of The Grinder distribution for // licensing details. The Grinder distribution is available on the // Internet at http://grinder.sourceforge.net/ // // 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 // REGENTS 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 net.grinder.plugin.http.tcpproxyfilter; import java.util.regex.Pattern; /** * Compiled regular expressions. * * @author Philip Aston * @version $Revision$ */ public final class RegularExpressionsImplementation implements RegularExpressions { private final Pattern m_basicAuthorizationHeaderPattern; private final Pattern m_headerPattern; private final Pattern m_messageBodyPattern; private final Pattern m_requestLinePattern; private final Pattern m_responseLinePattern; private final Pattern m_lastPathElementPathPattern; /** * Constructor. */ public RegularExpressionsImplementation() { // We're generally flexible about SP and CRLF, see RFC 2616, 19.3. // From RFC 2616: // // Request-Line = Method SP Request-URI SP HTTP-Version CRLF // HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT // http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]] // m_requestLinePattern = Pattern.compile( "^([A-Z]+)[ \\t]+" + // Method. "(?:https?://[^/]+)?" + // Ignore scheme, host, port. "(.+)" + // Path, query string, fragment. "[ \\t]+HTTP/\\d.\\d[ \\t]*\\r?\\n", Pattern.MULTILINE | Pattern.UNIX_LINES); // RFC 2616, 6.1: // // Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF m_responseLinePattern = Pattern.compile( "^HTTP/\\d.\\d[ \\t]+" + "(\\d+)" + // Status-Code "[ \\t]+" + "(.*)" + // Reason-Phrase "[ \\t]*\\r?\\n"); m_messageBodyPattern = Pattern.compile("\\r\\n\\r\\n(.*)", Pattern.DOTALL); m_headerPattern = Pattern.compile( "^([^:\\r\\n]*)[ \\t]*:[ \\t]*(.*?)\\r?\\n", Pattern.MULTILINE | Pattern.UNIX_LINES); m_basicAuthorizationHeaderPattern = Pattern.compile( "^Authorization[ \\t]*:[ \\t]*Basic[ \\t]*([a-zA-Z0-9+/]*=*).*?\\r?\\n", Pattern.MULTILINE | Pattern.UNIX_LINES); - // Ignore maximum amount of stuff that's not a '?', ';', or '#' followed by - // a '/', then grab the next until the first '?', ';', or '#'. - m_lastPathElementPathPattern = Pattern.compile("^[^\\?;#]*/([^\\?;#]*)"); + // Ignore maximum amount of stuff that's not a '?', or '#' followed by + // a '/', then grab the next until the first ';', '?', or '#'. + m_lastPathElementPathPattern = Pattern.compile("^[^\\?#]*/([^\\?;#]*)"); } /** * A pattern that matches the first line of an HTTP request. * * @return The pattern. */ public Pattern getRequestLinePattern() { return m_requestLinePattern; } /** * A pattern that matches the first line of an HTTP response. * * @return The pattern. */ public Pattern getResponseLinePattern() { return m_responseLinePattern; } /** * A pattern that matches an HTTP message body. * * @return The pattern. */ public Pattern getMessageBodyPattern() { return m_messageBodyPattern; } /** * A pattern that matches an HTTP header. * * @return The pattern */ public Pattern getHeaderPattern() { return m_headerPattern; } /** * A pattern that matches an HTTP Basic Authorization header. * * @return The pattern */ public Pattern getBasicAuthorizationHeaderPattern() { return m_basicAuthorizationHeaderPattern; } /** * A pattern that matches the last element in a path. * * @return The pattern */ public Pattern getLastPathElementPathPattern() { return m_lastPathElementPathPattern; } }
true
true
public RegularExpressionsImplementation() { // We're generally flexible about SP and CRLF, see RFC 2616, 19.3. // From RFC 2616: // // Request-Line = Method SP Request-URI SP HTTP-Version CRLF // HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT // http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]] // m_requestLinePattern = Pattern.compile( "^([A-Z]+)[ \\t]+" + // Method. "(?:https?://[^/]+)?" + // Ignore scheme, host, port. "(.+)" + // Path, query string, fragment. "[ \\t]+HTTP/\\d.\\d[ \\t]*\\r?\\n", Pattern.MULTILINE | Pattern.UNIX_LINES); // RFC 2616, 6.1: // // Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF m_responseLinePattern = Pattern.compile( "^HTTP/\\d.\\d[ \\t]+" + "(\\d+)" + // Status-Code "[ \\t]+" + "(.*)" + // Reason-Phrase "[ \\t]*\\r?\\n"); m_messageBodyPattern = Pattern.compile("\\r\\n\\r\\n(.*)", Pattern.DOTALL); m_headerPattern = Pattern.compile( "^([^:\\r\\n]*)[ \\t]*:[ \\t]*(.*?)\\r?\\n", Pattern.MULTILINE | Pattern.UNIX_LINES); m_basicAuthorizationHeaderPattern = Pattern.compile( "^Authorization[ \\t]*:[ \\t]*Basic[ \\t]*([a-zA-Z0-9+/]*=*).*?\\r?\\n", Pattern.MULTILINE | Pattern.UNIX_LINES); // Ignore maximum amount of stuff that's not a '?', ';', or '#' followed by // a '/', then grab the next until the first '?', ';', or '#'. m_lastPathElementPathPattern = Pattern.compile("^[^\\?;#]*/([^\\?;#]*)"); }
public RegularExpressionsImplementation() { // We're generally flexible about SP and CRLF, see RFC 2616, 19.3. // From RFC 2616: // // Request-Line = Method SP Request-URI SP HTTP-Version CRLF // HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT // http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]] // m_requestLinePattern = Pattern.compile( "^([A-Z]+)[ \\t]+" + // Method. "(?:https?://[^/]+)?" + // Ignore scheme, host, port. "(.+)" + // Path, query string, fragment. "[ \\t]+HTTP/\\d.\\d[ \\t]*\\r?\\n", Pattern.MULTILINE | Pattern.UNIX_LINES); // RFC 2616, 6.1: // // Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF m_responseLinePattern = Pattern.compile( "^HTTP/\\d.\\d[ \\t]+" + "(\\d+)" + // Status-Code "[ \\t]+" + "(.*)" + // Reason-Phrase "[ \\t]*\\r?\\n"); m_messageBodyPattern = Pattern.compile("\\r\\n\\r\\n(.*)", Pattern.DOTALL); m_headerPattern = Pattern.compile( "^([^:\\r\\n]*)[ \\t]*:[ \\t]*(.*?)\\r?\\n", Pattern.MULTILINE | Pattern.UNIX_LINES); m_basicAuthorizationHeaderPattern = Pattern.compile( "^Authorization[ \\t]*:[ \\t]*Basic[ \\t]*([a-zA-Z0-9+/]*=*).*?\\r?\\n", Pattern.MULTILINE | Pattern.UNIX_LINES); // Ignore maximum amount of stuff that's not a '?', or '#' followed by // a '/', then grab the next until the first ';', '?', or '#'. m_lastPathElementPathPattern = Pattern.compile("^[^\\?#]*/([^\\?;#]*)"); }
diff --git a/trunk/src/java/org/apache/commons/dbcp2/managed/PoolableManagedConnectionFactory.java b/trunk/src/java/org/apache/commons/dbcp2/managed/PoolableManagedConnectionFactory.java index c847630..dc70821 100644 --- a/trunk/src/java/org/apache/commons/dbcp2/managed/PoolableManagedConnectionFactory.java +++ b/trunk/src/java/org/apache/commons/dbcp2/managed/PoolableManagedConnectionFactory.java @@ -1,80 +1,80 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.dbcp2.managed; import java.sql.Connection; import org.apache.commons.dbcp2.PoolableConnectionFactory; import org.apache.commons.dbcp2.PoolingConnection; import org.apache.commons.pool2.KeyedObjectPool; import org.apache.commons.pool2.impl.GenericKeyedObjectPool; import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig; import org.apache.commons.pool2.impl.WhenExhaustedAction; /** * A {@link PoolableConnectionFactory} that creates {@link PoolableManagedConnection}s. * * @version $Revision$ $Date$ */ public class PoolableManagedConnectionFactory extends PoolableConnectionFactory { /** Transaction registry associated with connections created by this factory */ private final TransactionRegistry transactionRegistry; /** * Create a PoolableManagedConnectionFactory and attach it to a connection pool. * * @param connFactory XAConnectionFactory */ public PoolableManagedConnectionFactory(XAConnectionFactory connFactory) { super(connFactory); this.transactionRegistry = connFactory.getTransactionRegistry(); } /** * Uses the configured XAConnectionFactory to create a {@link PoolableManagedConnection}. * Throws <code>IllegalStateException</code> if the connection factory returns null. * Also initializes the connection using configured initialization sql (if provided) * and sets up a prepared statement pool associated with the PoolableManagedConnection * if statement pooling is enabled. */ @Override - synchronized public Object makeObject() throws Exception { + synchronized public Connection makeObject() throws Exception { Connection conn = _connFactory.createConnection(); if (conn == null) { throw new IllegalStateException("Connection factory returned null from createConnection"); } initializeConnection(conn); if(poolStatements) { conn = new PoolingConnection(conn); GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig(); config.setMaxTotalPerKey(-1); config.setWhenExhaustedAction(WhenExhaustedAction.FAIL); config.setMaxWait(0); config.setMaxIdlePerKey(1); config.setMaxTotal(maxOpenPreparedStatements); KeyedObjectPool stmtPool = new GenericKeyedObjectPool((PoolingConnection)conn, config); ((PoolingConnection)conn).setStatementPool(stmtPool); ((PoolingConnection) conn).setCacheState(_cacheState); } return new PoolableManagedConnection(transactionRegistry, conn, _pool, _config); } }
true
true
synchronized public Object makeObject() throws Exception { Connection conn = _connFactory.createConnection(); if (conn == null) { throw new IllegalStateException("Connection factory returned null from createConnection"); } initializeConnection(conn); if(poolStatements) { conn = new PoolingConnection(conn); GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig(); config.setMaxTotalPerKey(-1); config.setWhenExhaustedAction(WhenExhaustedAction.FAIL); config.setMaxWait(0); config.setMaxIdlePerKey(1); config.setMaxTotal(maxOpenPreparedStatements); KeyedObjectPool stmtPool = new GenericKeyedObjectPool((PoolingConnection)conn, config); ((PoolingConnection)conn).setStatementPool(stmtPool); ((PoolingConnection) conn).setCacheState(_cacheState); } return new PoolableManagedConnection(transactionRegistry, conn, _pool, _config); }
synchronized public Connection makeObject() throws Exception { Connection conn = _connFactory.createConnection(); if (conn == null) { throw new IllegalStateException("Connection factory returned null from createConnection"); } initializeConnection(conn); if(poolStatements) { conn = new PoolingConnection(conn); GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig(); config.setMaxTotalPerKey(-1); config.setWhenExhaustedAction(WhenExhaustedAction.FAIL); config.setMaxWait(0); config.setMaxIdlePerKey(1); config.setMaxTotal(maxOpenPreparedStatements); KeyedObjectPool stmtPool = new GenericKeyedObjectPool((PoolingConnection)conn, config); ((PoolingConnection)conn).setStatementPool(stmtPool); ((PoolingConnection) conn).setCacheState(_cacheState); } return new PoolableManagedConnection(transactionRegistry, conn, _pool, _config); }
diff --git a/tools/remotetools/org.eclipse.ptp.remotetools.core/src/org/eclipse/ptp/remotetools/internal/ssh/UploadExecution.java b/tools/remotetools/org.eclipse.ptp.remotetools.core/src/org/eclipse/ptp/remotetools/internal/ssh/UploadExecution.java index 7cab51cf7..3f4c16032 100755 --- a/tools/remotetools/org.eclipse.ptp.remotetools.core/src/org/eclipse/ptp/remotetools/internal/ssh/UploadExecution.java +++ b/tools/remotetools/org.eclipse.ptp.remotetools.core/src/org/eclipse/ptp/remotetools/internal/ssh/UploadExecution.java @@ -1,85 +1,85 @@ /****************************************************************************** * Copyright (c) 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - Initial Implementation * *****************************************************************************/ package org.eclipse.ptp.remotetools.internal.ssh; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.eclipse.ptp.remotetools.core.IRemotePathTools; import org.eclipse.ptp.remotetools.core.IRemoteUploadExecution; import org.eclipse.ptp.remotetools.exception.RemoteConnectionException; import org.eclipse.ptp.remotetools.internal.common.Debug; import com.jcraft.jsch.ChannelExec; public class UploadExecution extends KillableExecution implements IRemoteUploadExecution { String remoteFile; InputStream sourceStream; ByteArrayOutputStream errorStream; OutputStream outputStream; public UploadExecution(ExecutionManager executionManager, String remoteFile, InputStream source) throws RemoteConnectionException { super(executionManager); this.sourceStream = source; this.remoteFile = remoteFile; errorStream = new ByteArrayOutputStream(); } public OutputStream getOutputStreamToProcessRemoteFile() { if (sourceStream != null) { throw new IllegalStateException(); } return outputStream; } public void startExecution() throws RemoteConnectionException { ChannelExec channel = createChannel(false); IRemotePathTools pathTool = getExecutionManager().getRemotePathTools(); setCommandLine("cat >" + pathTool.quote(remoteFile, true)); //$NON-NLS-1$ if (sourceStream != null) { channel.setInputStream(sourceStream); outputStream = null; } else { try { outputStream = channel.getOutputStream(); } catch (IOException e) { throw new RemoteConnectionException(Messages.UploadExecution_StartExecution_FailedCreateUpload, e); } } channel.setErrStream(errorStream); super.startExecution(); Debug.println("Uploading " + remoteFile); //$NON-NLS-1$ // Must wait the channel to open or we can have a racing on process // trying to manipulate non-existent files (e.g. set file attributes after // the upload) - while(channel.isClosed() || !channel.isConnected()) { + while(!channel.isClosed() && !channel.isConnected()) { synchronized (this) { try { this.wait(10); } catch (InterruptedException e) { // Ignore } } } } public String getErrorMessage() { return errorStream.toString(); } }
true
true
public void startExecution() throws RemoteConnectionException { ChannelExec channel = createChannel(false); IRemotePathTools pathTool = getExecutionManager().getRemotePathTools(); setCommandLine("cat >" + pathTool.quote(remoteFile, true)); //$NON-NLS-1$ if (sourceStream != null) { channel.setInputStream(sourceStream); outputStream = null; } else { try { outputStream = channel.getOutputStream(); } catch (IOException e) { throw new RemoteConnectionException(Messages.UploadExecution_StartExecution_FailedCreateUpload, e); } } channel.setErrStream(errorStream); super.startExecution(); Debug.println("Uploading " + remoteFile); //$NON-NLS-1$ // Must wait the channel to open or we can have a racing on process // trying to manipulate non-existent files (e.g. set file attributes after // the upload) while(channel.isClosed() || !channel.isConnected()) { synchronized (this) { try { this.wait(10); } catch (InterruptedException e) { // Ignore } } } }
public void startExecution() throws RemoteConnectionException { ChannelExec channel = createChannel(false); IRemotePathTools pathTool = getExecutionManager().getRemotePathTools(); setCommandLine("cat >" + pathTool.quote(remoteFile, true)); //$NON-NLS-1$ if (sourceStream != null) { channel.setInputStream(sourceStream); outputStream = null; } else { try { outputStream = channel.getOutputStream(); } catch (IOException e) { throw new RemoteConnectionException(Messages.UploadExecution_StartExecution_FailedCreateUpload, e); } } channel.setErrStream(errorStream); super.startExecution(); Debug.println("Uploading " + remoteFile); //$NON-NLS-1$ // Must wait the channel to open or we can have a racing on process // trying to manipulate non-existent files (e.g. set file attributes after // the upload) while(!channel.isClosed() && !channel.isConnected()) { synchronized (this) { try { this.wait(10); } catch (InterruptedException e) { // Ignore } } } }
diff --git a/src/main/java/net/pterodactylus/sone/web/OptionsPage.java b/src/main/java/net/pterodactylus/sone/web/OptionsPage.java index 39cacc6e..bbc10848 100644 --- a/src/main/java/net/pterodactylus/sone/web/OptionsPage.java +++ b/src/main/java/net/pterodactylus/sone/web/OptionsPage.java @@ -1,99 +1,102 @@ /* * Sone - OptionsPage.java - Copyright © 2010 David Roden * * 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. * * 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 net.pterodactylus.sone.web; import net.pterodactylus.sone.core.Core.Preferences; import net.pterodactylus.sone.data.Sone; import net.pterodactylus.sone.web.page.Page.Request.Method; import net.pterodactylus.util.number.Numbers; import net.pterodactylus.util.template.Template; import net.pterodactylus.util.template.TemplateContext; /** * This page lets the user edit the options of the Sone plugin. * * @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a> */ public class OptionsPage extends SoneTemplatePage { /** * Creates a new options page. * * @param template * The template to render * @param webInterface * The Sone web interface */ public OptionsPage(Template template, WebInterface webInterface) { super("options.html", template, "Page.Options.Title", webInterface, false); } // // TEMPLATEPAGE METHODS // /** * {@inheritDoc} */ @Override protected void processTemplate(Request request, TemplateContext templateContext) throws RedirectException { super.processTemplate(request, templateContext); Preferences preferences = webInterface.getCore().getPreferences(); Sone currentSone = webInterface.getCurrentSone(request.getToadletContext(), false); if (request.getMethod() == Method.POST) { if (currentSone != null) { boolean autoFollow = request.getHttpRequest().isPartSet("auto-follow"); currentSone.getOptions().getBooleanOption("AutoFollow").set(autoFollow); webInterface.getCore().saveSone(currentSone); } Integer insertionDelay = Numbers.safeParseInteger(request.getHttpRequest().getPartAsStringFailsafe("insertion-delay", 16)); preferences.setInsertionDelay(insertionDelay); Integer postsPerPage = Numbers.safeParseInteger(request.getHttpRequest().getPartAsStringFailsafe("posts-per-page", 4), null); preferences.setPostsPerPage(postsPerPage); + boolean requireFullAccess = request.getHttpRequest().isPartSet("require-full-access"); + preferences.setRequireFullAccess(requireFullAccess); Integer positiveTrust = Numbers.safeParseInteger(request.getHttpRequest().getPartAsStringFailsafe("positive-trust", 3)); preferences.setPositiveTrust(positiveTrust); Integer negativeTrust = Numbers.safeParseInteger(request.getHttpRequest().getPartAsStringFailsafe("negative-trust", 4)); preferences.setNegativeTrust(negativeTrust); String trustComment = request.getHttpRequest().getPartAsStringFailsafe("trust-comment", 256); if (trustComment.trim().length() == 0) { trustComment = null; } preferences.setTrustComment(trustComment); boolean soneRescueMode = Boolean.parseBoolean(request.getHttpRequest().getPartAsStringFailsafe("sone-rescue-mode", 5)); preferences.setSoneRescueMode(soneRescueMode); boolean clearOnNextRestart = Boolean.parseBoolean(request.getHttpRequest().getPartAsStringFailsafe("clear-on-next-restart", 5)); preferences.setClearOnNextRestart(clearOnNextRestart); boolean reallyClearOnNextRestart = Boolean.parseBoolean(request.getHttpRequest().getPartAsStringFailsafe("really-clear-on-next-restart", 5)); preferences.setReallyClearOnNextRestart(reallyClearOnNextRestart); webInterface.getCore().saveConfiguration(); throw new RedirectException(getPath()); } if (currentSone != null) { templateContext.set("auto-follow", currentSone.getOptions().getBooleanOption("AutoFollow").get()); } templateContext.set("insertion-delay", preferences.getInsertionDelay()); templateContext.set("posts-per-page", preferences.getPostsPerPage()); + templateContext.set("require-full-access", preferences.isRequireFullAccess()); templateContext.set("positive-trust", preferences.getPositiveTrust()); templateContext.set("negative-trust", preferences.getNegativeTrust()); templateContext.set("trust-comment", preferences.getTrustComment()); templateContext.set("sone-rescue-mode", preferences.isSoneRescueMode()); templateContext.set("clear-on-next-restart", preferences.isClearOnNextRestart()); templateContext.set("really-clear-on-next-restart", preferences.isReallyClearOnNextRestart()); } }
false
true
protected void processTemplate(Request request, TemplateContext templateContext) throws RedirectException { super.processTemplate(request, templateContext); Preferences preferences = webInterface.getCore().getPreferences(); Sone currentSone = webInterface.getCurrentSone(request.getToadletContext(), false); if (request.getMethod() == Method.POST) { if (currentSone != null) { boolean autoFollow = request.getHttpRequest().isPartSet("auto-follow"); currentSone.getOptions().getBooleanOption("AutoFollow").set(autoFollow); webInterface.getCore().saveSone(currentSone); } Integer insertionDelay = Numbers.safeParseInteger(request.getHttpRequest().getPartAsStringFailsafe("insertion-delay", 16)); preferences.setInsertionDelay(insertionDelay); Integer postsPerPage = Numbers.safeParseInteger(request.getHttpRequest().getPartAsStringFailsafe("posts-per-page", 4), null); preferences.setPostsPerPage(postsPerPage); Integer positiveTrust = Numbers.safeParseInteger(request.getHttpRequest().getPartAsStringFailsafe("positive-trust", 3)); preferences.setPositiveTrust(positiveTrust); Integer negativeTrust = Numbers.safeParseInteger(request.getHttpRequest().getPartAsStringFailsafe("negative-trust", 4)); preferences.setNegativeTrust(negativeTrust); String trustComment = request.getHttpRequest().getPartAsStringFailsafe("trust-comment", 256); if (trustComment.trim().length() == 0) { trustComment = null; } preferences.setTrustComment(trustComment); boolean soneRescueMode = Boolean.parseBoolean(request.getHttpRequest().getPartAsStringFailsafe("sone-rescue-mode", 5)); preferences.setSoneRescueMode(soneRescueMode); boolean clearOnNextRestart = Boolean.parseBoolean(request.getHttpRequest().getPartAsStringFailsafe("clear-on-next-restart", 5)); preferences.setClearOnNextRestart(clearOnNextRestart); boolean reallyClearOnNextRestart = Boolean.parseBoolean(request.getHttpRequest().getPartAsStringFailsafe("really-clear-on-next-restart", 5)); preferences.setReallyClearOnNextRestart(reallyClearOnNextRestart); webInterface.getCore().saveConfiguration(); throw new RedirectException(getPath()); } if (currentSone != null) { templateContext.set("auto-follow", currentSone.getOptions().getBooleanOption("AutoFollow").get()); } templateContext.set("insertion-delay", preferences.getInsertionDelay()); templateContext.set("posts-per-page", preferences.getPostsPerPage()); templateContext.set("positive-trust", preferences.getPositiveTrust()); templateContext.set("negative-trust", preferences.getNegativeTrust()); templateContext.set("trust-comment", preferences.getTrustComment()); templateContext.set("sone-rescue-mode", preferences.isSoneRescueMode()); templateContext.set("clear-on-next-restart", preferences.isClearOnNextRestart()); templateContext.set("really-clear-on-next-restart", preferences.isReallyClearOnNextRestart()); }
protected void processTemplate(Request request, TemplateContext templateContext) throws RedirectException { super.processTemplate(request, templateContext); Preferences preferences = webInterface.getCore().getPreferences(); Sone currentSone = webInterface.getCurrentSone(request.getToadletContext(), false); if (request.getMethod() == Method.POST) { if (currentSone != null) { boolean autoFollow = request.getHttpRequest().isPartSet("auto-follow"); currentSone.getOptions().getBooleanOption("AutoFollow").set(autoFollow); webInterface.getCore().saveSone(currentSone); } Integer insertionDelay = Numbers.safeParseInteger(request.getHttpRequest().getPartAsStringFailsafe("insertion-delay", 16)); preferences.setInsertionDelay(insertionDelay); Integer postsPerPage = Numbers.safeParseInteger(request.getHttpRequest().getPartAsStringFailsafe("posts-per-page", 4), null); preferences.setPostsPerPage(postsPerPage); boolean requireFullAccess = request.getHttpRequest().isPartSet("require-full-access"); preferences.setRequireFullAccess(requireFullAccess); Integer positiveTrust = Numbers.safeParseInteger(request.getHttpRequest().getPartAsStringFailsafe("positive-trust", 3)); preferences.setPositiveTrust(positiveTrust); Integer negativeTrust = Numbers.safeParseInteger(request.getHttpRequest().getPartAsStringFailsafe("negative-trust", 4)); preferences.setNegativeTrust(negativeTrust); String trustComment = request.getHttpRequest().getPartAsStringFailsafe("trust-comment", 256); if (trustComment.trim().length() == 0) { trustComment = null; } preferences.setTrustComment(trustComment); boolean soneRescueMode = Boolean.parseBoolean(request.getHttpRequest().getPartAsStringFailsafe("sone-rescue-mode", 5)); preferences.setSoneRescueMode(soneRescueMode); boolean clearOnNextRestart = Boolean.parseBoolean(request.getHttpRequest().getPartAsStringFailsafe("clear-on-next-restart", 5)); preferences.setClearOnNextRestart(clearOnNextRestart); boolean reallyClearOnNextRestart = Boolean.parseBoolean(request.getHttpRequest().getPartAsStringFailsafe("really-clear-on-next-restart", 5)); preferences.setReallyClearOnNextRestart(reallyClearOnNextRestart); webInterface.getCore().saveConfiguration(); throw new RedirectException(getPath()); } if (currentSone != null) { templateContext.set("auto-follow", currentSone.getOptions().getBooleanOption("AutoFollow").get()); } templateContext.set("insertion-delay", preferences.getInsertionDelay()); templateContext.set("posts-per-page", preferences.getPostsPerPage()); templateContext.set("require-full-access", preferences.isRequireFullAccess()); templateContext.set("positive-trust", preferences.getPositiveTrust()); templateContext.set("negative-trust", preferences.getNegativeTrust()); templateContext.set("trust-comment", preferences.getTrustComment()); templateContext.set("sone-rescue-mode", preferences.isSoneRescueMode()); templateContext.set("clear-on-next-restart", preferences.isClearOnNextRestart()); templateContext.set("really-clear-on-next-restart", preferences.isReallyClearOnNextRestart()); }
diff --git a/servicemix-http/src/main/java/org/apache/servicemix/http/processors/ProviderProcessor.java b/servicemix-http/src/main/java/org/apache/servicemix/http/processors/ProviderProcessor.java index bce0072a6..d98a124c4 100644 --- a/servicemix-http/src/main/java/org/apache/servicemix/http/processors/ProviderProcessor.java +++ b/servicemix-http/src/main/java/org/apache/servicemix/http/processors/ProviderProcessor.java @@ -1,319 +1,321 @@ /* * 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.servicemix.http.processors; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.jbi.component.ComponentLifeCycle; import javax.jbi.messaging.DeliveryChannel; import javax.jbi.messaging.ExchangeStatus; import javax.jbi.messaging.Fault; import javax.jbi.messaging.InOnly; import javax.jbi.messaging.InOptionalOut; import javax.jbi.messaging.InOut; import javax.jbi.messaging.MessageExchange; import javax.jbi.messaging.NormalizedMessage; import javax.servlet.http.HttpServletRequest; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpHost; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.URI; import org.apache.commons.httpclient.methods.ByteArrayRequestEntity; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.servicemix.JbiConstants; import org.apache.servicemix.common.ExchangeProcessor; import org.apache.servicemix.http.HttpConfiguration; import org.apache.servicemix.http.HttpEndpoint; import org.apache.servicemix.http.HttpLifeCycle; import org.apache.servicemix.soap.Context; import org.apache.servicemix.soap.SoapHelper; import org.apache.servicemix.soap.marshalers.SoapMessage; import org.apache.servicemix.soap.marshalers.SoapReader; import org.apache.servicemix.soap.marshalers.SoapWriter; import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap; /** * * @author Guillaume Nodet * @version $Revision: 370186 $ * @since 3.0 */ public class ProviderProcessor implements ExchangeProcessor { protected HttpEndpoint endpoint; protected HostConfiguration host; protected SoapHelper soapHelper; protected DeliveryChannel channel; private String relUri; private Map methods; public ProviderProcessor(HttpEndpoint endpoint) { this.endpoint = endpoint; this.soapHelper = new SoapHelper(endpoint); java.net.URI uri = java.net.URI.create(endpoint.getLocationURI()); relUri = uri.getPath(); if (!relUri.startsWith("/")) { relUri = "/" + relUri; } if (uri.getQuery() != null) { relUri += "?" + uri.getQuery(); } if (uri.getFragment() != null) { relUri += "#" + uri.getFragment(); } this.methods = new ConcurrentHashMap(); } public void process(MessageExchange exchange) throws Exception { if (exchange.getStatus() == ExchangeStatus.DONE || exchange.getStatus() == ExchangeStatus.ERROR) { PostMethod method = (PostMethod) methods.remove(exchange.getExchangeId()); if (method != null) { method.releaseConnection(); } return; } boolean txSync = exchange.isTransacted() && Boolean.TRUE.equals(exchange.getProperty(JbiConstants.SEND_SYNC)); NormalizedMessage nm = exchange.getMessage("in"); if (nm == null) { throw new IllegalStateException("Exchange has no input message"); } PostMethod method = new PostMethod(relUri); SoapMessage soapMessage = new SoapMessage(); soapHelper.getJBIMarshaler().fromNMS(soapMessage, nm); Context context = soapHelper.createContext(soapMessage); soapHelper.onSend(context); SoapWriter writer = soapHelper.getSoapMarshaler().createWriter(soapMessage); Map headers = (Map) nm.getProperty(JbiConstants.PROTOCOL_HEADERS); if (headers != null) { for (Iterator it = headers.keySet().iterator(); it.hasNext();) { String name = (String) it.next(); String value = (String) headers.get(name); method.addRequestHeader(name, value); } } RequestEntity entity = writeMessage(writer); // remove content-type header that may have been part of the in message method.removeRequestHeader(Constants.HEADER_CONTENT_TYPE); method.addRequestHeader(Constants.HEADER_CONTENT_TYPE, entity.getContentType()); if (entity.getContentLength() < 0) { method.removeRequestHeader(Constants.HEADER_CONTENT_LENGTH); } else { method.setRequestHeader(Constants.HEADER_CONTENT_LENGTH, Long.toString(entity.getContentLength())); } if (endpoint.isSoap() && method.getRequestHeader(Constants.HEADER_SOAP_ACTION) == null) { if (endpoint.getSoapAction() != null) { method.setRequestHeader(Constants.HEADER_SOAP_ACTION, endpoint.getSoapAction()); } else { method.setRequestHeader(Constants.HEADER_SOAP_ACTION, "\"\""); } } method.setRequestEntity(entity); boolean close = true; try { // Uncomment to avoid the http request being sent several times. // Can be useful when debugging //================================ //method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new HttpMethodRetryHandler() { // public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) { // return false; // } //}); if (endpoint.getBasicAuthentication() != null) { endpoint.getBasicAuthentication().applyCredentials( getClient() ); } int response = getClient().executeMethod(host, method); if (response != HttpStatus.SC_OK && response != HttpStatus.SC_ACCEPTED) { if (exchange instanceof InOnly == false) { SoapReader reader = soapHelper.getSoapMarshaler().createReader(); Header contentType = method.getResponseHeader(Constants.HEADER_CONTENT_TYPE); soapMessage = reader.read(method.getResponseBodyAsStream(), contentType != null ? contentType.getValue() : null); context.setFaultMessage(soapMessage); soapHelper.onAnswer(context); Fault fault = exchange.createFault(); fault.setProperty(JbiConstants.PROTOCOL_HEADERS, getHeaders(method)); soapHelper.getJBIMarshaler().toNMS(fault, soapMessage); exchange.setFault(fault); if (txSync) { channel.sendSync(exchange); } else { + methods.put(exchange.getExchangeId(), method); channel.send(exchange); + close = false; } return; } else { throw new Exception("Invalid status response: " + response); } } if (exchange instanceof InOut) { NormalizedMessage msg = exchange.createMessage(); SoapReader reader = soapHelper.getSoapMarshaler().createReader(); Header contentType = method.getResponseHeader(Constants.HEADER_CONTENT_TYPE); soapMessage = reader.read(method.getResponseBodyAsStream(), contentType != null ? contentType.getValue() : null); context.setOutMessage(soapMessage); soapHelper.onAnswer(context); msg.setProperty(JbiConstants.PROTOCOL_HEADERS, getHeaders(method)); soapHelper.getJBIMarshaler().toNMS(msg, soapMessage); ((InOut) exchange).setOutMessage(msg); if (txSync) { channel.sendSync(exchange); } else { methods.put(exchange.getExchangeId(), method); channel.send(exchange); close = false; } } else if (exchange instanceof InOptionalOut) { if (method.getResponseContentLength() == 0) { exchange.setStatus(ExchangeStatus.DONE); channel.send(exchange); } else { NormalizedMessage msg = exchange.createMessage(); SoapReader reader = soapHelper.getSoapMarshaler().createReader(); soapMessage = reader.read(method.getResponseBodyAsStream(), method.getResponseHeader(Constants.HEADER_CONTENT_TYPE).getValue()); context.setOutMessage(soapMessage); soapHelper.onAnswer(context); msg.setProperty(JbiConstants.PROTOCOL_HEADERS, getHeaders(method)); soapHelper.getJBIMarshaler().toNMS(msg, soapMessage); ((InOptionalOut) exchange).setOutMessage(msg); if (txSync) { channel.sendSync(exchange); } else { methods.put(exchange.getExchangeId(), method); channel.send(exchange); close = false; } } } else { exchange.setStatus(ExchangeStatus.DONE); channel.send(exchange); } } finally { if (close) { method.releaseConnection(); } } } public void start() throws Exception { URI uri = new URI(endpoint.getLocationURI(), false); if (uri.getScheme().equals("https")) { ProtocolSocketFactory sf = new CommonsHttpSSLSocketFactory( endpoint.getSsl(), endpoint.getKeystoreManager()); Protocol protocol = new Protocol("https", sf, 443); HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), protocol); this.host = new HostConfiguration(); this.host.setHost(host); } else { this.host = new HostConfiguration(); this.host.setHost(uri.getHost(), uri.getPort()); } channel = endpoint.getServiceUnit().getComponent().getComponentContext().getDeliveryChannel(); } protected HttpConfiguration getConfiguration(HttpEndpoint endpoint) { ComponentLifeCycle lf = endpoint.getServiceUnit().getComponent().getLifeCycle(); return ((HttpLifeCycle) lf).getConfiguration(); } public void stop() throws Exception { } protected Map getHeaders(HttpServletRequest request) { Map headers = new HashMap(); Enumeration enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String name = (String) enumeration.nextElement(); String value = request.getHeader(name); headers.put(name, value); } return headers; } protected Map getHeaders(HttpMethod method) { Map headers = new HashMap(); Header[] h = method.getResponseHeaders(); for (int i = 0; i < h.length; i++) { headers.put(h[i].getName(), h[i].getValue()); } return headers; } protected RequestEntity writeMessage(SoapWriter writer) throws Exception { HttpLifeCycle lf = (HttpLifeCycle) endpoint.getServiceUnit().getComponent().getLifeCycle(); if (lf.getConfiguration().isStreamingEnabled()) { return new StreamingRequestEntity(writer); } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); writer.write(baos); return new ByteArrayRequestEntity(baos.toByteArray(), writer.getContentType()); } } protected HttpClient getClient() { HttpLifeCycle lf = (HttpLifeCycle) endpoint.getServiceUnit().getComponent().getLifeCycle(); return lf.getClient(); } public static class StreamingRequestEntity implements RequestEntity { private SoapWriter writer; public StreamingRequestEntity(SoapWriter writer) { this.writer = writer; } public boolean isRepeatable() { return false; } public void writeRequest(OutputStream out) throws IOException { try { writer.write(out); out.flush(); } catch (Exception e) { throw (IOException) new IOException("Could not write request").initCause(e); } } public long getContentLength() { // not known so we send negative value return -1; } public String getContentType() { return writer.getContentType(); } } }
false
true
public void process(MessageExchange exchange) throws Exception { if (exchange.getStatus() == ExchangeStatus.DONE || exchange.getStatus() == ExchangeStatus.ERROR) { PostMethod method = (PostMethod) methods.remove(exchange.getExchangeId()); if (method != null) { method.releaseConnection(); } return; } boolean txSync = exchange.isTransacted() && Boolean.TRUE.equals(exchange.getProperty(JbiConstants.SEND_SYNC)); NormalizedMessage nm = exchange.getMessage("in"); if (nm == null) { throw new IllegalStateException("Exchange has no input message"); } PostMethod method = new PostMethod(relUri); SoapMessage soapMessage = new SoapMessage(); soapHelper.getJBIMarshaler().fromNMS(soapMessage, nm); Context context = soapHelper.createContext(soapMessage); soapHelper.onSend(context); SoapWriter writer = soapHelper.getSoapMarshaler().createWriter(soapMessage); Map headers = (Map) nm.getProperty(JbiConstants.PROTOCOL_HEADERS); if (headers != null) { for (Iterator it = headers.keySet().iterator(); it.hasNext();) { String name = (String) it.next(); String value = (String) headers.get(name); method.addRequestHeader(name, value); } } RequestEntity entity = writeMessage(writer); // remove content-type header that may have been part of the in message method.removeRequestHeader(Constants.HEADER_CONTENT_TYPE); method.addRequestHeader(Constants.HEADER_CONTENT_TYPE, entity.getContentType()); if (entity.getContentLength() < 0) { method.removeRequestHeader(Constants.HEADER_CONTENT_LENGTH); } else { method.setRequestHeader(Constants.HEADER_CONTENT_LENGTH, Long.toString(entity.getContentLength())); } if (endpoint.isSoap() && method.getRequestHeader(Constants.HEADER_SOAP_ACTION) == null) { if (endpoint.getSoapAction() != null) { method.setRequestHeader(Constants.HEADER_SOAP_ACTION, endpoint.getSoapAction()); } else { method.setRequestHeader(Constants.HEADER_SOAP_ACTION, "\"\""); } } method.setRequestEntity(entity); boolean close = true; try { // Uncomment to avoid the http request being sent several times. // Can be useful when debugging //================================ //method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new HttpMethodRetryHandler() { // public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) { // return false; // } //}); if (endpoint.getBasicAuthentication() != null) { endpoint.getBasicAuthentication().applyCredentials( getClient() ); } int response = getClient().executeMethod(host, method); if (response != HttpStatus.SC_OK && response != HttpStatus.SC_ACCEPTED) { if (exchange instanceof InOnly == false) { SoapReader reader = soapHelper.getSoapMarshaler().createReader(); Header contentType = method.getResponseHeader(Constants.HEADER_CONTENT_TYPE); soapMessage = reader.read(method.getResponseBodyAsStream(), contentType != null ? contentType.getValue() : null); context.setFaultMessage(soapMessage); soapHelper.onAnswer(context); Fault fault = exchange.createFault(); fault.setProperty(JbiConstants.PROTOCOL_HEADERS, getHeaders(method)); soapHelper.getJBIMarshaler().toNMS(fault, soapMessage); exchange.setFault(fault); if (txSync) { channel.sendSync(exchange); } else { channel.send(exchange); } return; } else { throw new Exception("Invalid status response: " + response); } } if (exchange instanceof InOut) { NormalizedMessage msg = exchange.createMessage(); SoapReader reader = soapHelper.getSoapMarshaler().createReader(); Header contentType = method.getResponseHeader(Constants.HEADER_CONTENT_TYPE); soapMessage = reader.read(method.getResponseBodyAsStream(), contentType != null ? contentType.getValue() : null); context.setOutMessage(soapMessage); soapHelper.onAnswer(context); msg.setProperty(JbiConstants.PROTOCOL_HEADERS, getHeaders(method)); soapHelper.getJBIMarshaler().toNMS(msg, soapMessage); ((InOut) exchange).setOutMessage(msg); if (txSync) { channel.sendSync(exchange); } else { methods.put(exchange.getExchangeId(), method); channel.send(exchange); close = false; } } else if (exchange instanceof InOptionalOut) { if (method.getResponseContentLength() == 0) { exchange.setStatus(ExchangeStatus.DONE); channel.send(exchange); } else { NormalizedMessage msg = exchange.createMessage(); SoapReader reader = soapHelper.getSoapMarshaler().createReader(); soapMessage = reader.read(method.getResponseBodyAsStream(), method.getResponseHeader(Constants.HEADER_CONTENT_TYPE).getValue()); context.setOutMessage(soapMessage); soapHelper.onAnswer(context); msg.setProperty(JbiConstants.PROTOCOL_HEADERS, getHeaders(method)); soapHelper.getJBIMarshaler().toNMS(msg, soapMessage); ((InOptionalOut) exchange).setOutMessage(msg); if (txSync) { channel.sendSync(exchange); } else { methods.put(exchange.getExchangeId(), method); channel.send(exchange); close = false; } } } else { exchange.setStatus(ExchangeStatus.DONE); channel.send(exchange); } } finally { if (close) { method.releaseConnection(); } } }
public void process(MessageExchange exchange) throws Exception { if (exchange.getStatus() == ExchangeStatus.DONE || exchange.getStatus() == ExchangeStatus.ERROR) { PostMethod method = (PostMethod) methods.remove(exchange.getExchangeId()); if (method != null) { method.releaseConnection(); } return; } boolean txSync = exchange.isTransacted() && Boolean.TRUE.equals(exchange.getProperty(JbiConstants.SEND_SYNC)); NormalizedMessage nm = exchange.getMessage("in"); if (nm == null) { throw new IllegalStateException("Exchange has no input message"); } PostMethod method = new PostMethod(relUri); SoapMessage soapMessage = new SoapMessage(); soapHelper.getJBIMarshaler().fromNMS(soapMessage, nm); Context context = soapHelper.createContext(soapMessage); soapHelper.onSend(context); SoapWriter writer = soapHelper.getSoapMarshaler().createWriter(soapMessage); Map headers = (Map) nm.getProperty(JbiConstants.PROTOCOL_HEADERS); if (headers != null) { for (Iterator it = headers.keySet().iterator(); it.hasNext();) { String name = (String) it.next(); String value = (String) headers.get(name); method.addRequestHeader(name, value); } } RequestEntity entity = writeMessage(writer); // remove content-type header that may have been part of the in message method.removeRequestHeader(Constants.HEADER_CONTENT_TYPE); method.addRequestHeader(Constants.HEADER_CONTENT_TYPE, entity.getContentType()); if (entity.getContentLength() < 0) { method.removeRequestHeader(Constants.HEADER_CONTENT_LENGTH); } else { method.setRequestHeader(Constants.HEADER_CONTENT_LENGTH, Long.toString(entity.getContentLength())); } if (endpoint.isSoap() && method.getRequestHeader(Constants.HEADER_SOAP_ACTION) == null) { if (endpoint.getSoapAction() != null) { method.setRequestHeader(Constants.HEADER_SOAP_ACTION, endpoint.getSoapAction()); } else { method.setRequestHeader(Constants.HEADER_SOAP_ACTION, "\"\""); } } method.setRequestEntity(entity); boolean close = true; try { // Uncomment to avoid the http request being sent several times. // Can be useful when debugging //================================ //method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new HttpMethodRetryHandler() { // public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) { // return false; // } //}); if (endpoint.getBasicAuthentication() != null) { endpoint.getBasicAuthentication().applyCredentials( getClient() ); } int response = getClient().executeMethod(host, method); if (response != HttpStatus.SC_OK && response != HttpStatus.SC_ACCEPTED) { if (exchange instanceof InOnly == false) { SoapReader reader = soapHelper.getSoapMarshaler().createReader(); Header contentType = method.getResponseHeader(Constants.HEADER_CONTENT_TYPE); soapMessage = reader.read(method.getResponseBodyAsStream(), contentType != null ? contentType.getValue() : null); context.setFaultMessage(soapMessage); soapHelper.onAnswer(context); Fault fault = exchange.createFault(); fault.setProperty(JbiConstants.PROTOCOL_HEADERS, getHeaders(method)); soapHelper.getJBIMarshaler().toNMS(fault, soapMessage); exchange.setFault(fault); if (txSync) { channel.sendSync(exchange); } else { methods.put(exchange.getExchangeId(), method); channel.send(exchange); close = false; } return; } else { throw new Exception("Invalid status response: " + response); } } if (exchange instanceof InOut) { NormalizedMessage msg = exchange.createMessage(); SoapReader reader = soapHelper.getSoapMarshaler().createReader(); Header contentType = method.getResponseHeader(Constants.HEADER_CONTENT_TYPE); soapMessage = reader.read(method.getResponseBodyAsStream(), contentType != null ? contentType.getValue() : null); context.setOutMessage(soapMessage); soapHelper.onAnswer(context); msg.setProperty(JbiConstants.PROTOCOL_HEADERS, getHeaders(method)); soapHelper.getJBIMarshaler().toNMS(msg, soapMessage); ((InOut) exchange).setOutMessage(msg); if (txSync) { channel.sendSync(exchange); } else { methods.put(exchange.getExchangeId(), method); channel.send(exchange); close = false; } } else if (exchange instanceof InOptionalOut) { if (method.getResponseContentLength() == 0) { exchange.setStatus(ExchangeStatus.DONE); channel.send(exchange); } else { NormalizedMessage msg = exchange.createMessage(); SoapReader reader = soapHelper.getSoapMarshaler().createReader(); soapMessage = reader.read(method.getResponseBodyAsStream(), method.getResponseHeader(Constants.HEADER_CONTENT_TYPE).getValue()); context.setOutMessage(soapMessage); soapHelper.onAnswer(context); msg.setProperty(JbiConstants.PROTOCOL_HEADERS, getHeaders(method)); soapHelper.getJBIMarshaler().toNMS(msg, soapMessage); ((InOptionalOut) exchange).setOutMessage(msg); if (txSync) { channel.sendSync(exchange); } else { methods.put(exchange.getExchangeId(), method); channel.send(exchange); close = false; } } } else { exchange.setStatus(ExchangeStatus.DONE); channel.send(exchange); } } finally { if (close) { method.releaseConnection(); } } }
diff --git a/uk.ac.gda.dls.client/src/uk/ac/gda/dls/client/views/EnumPositionerCompositeFactory.java b/uk.ac.gda.dls.client/src/uk/ac/gda/dls/client/views/EnumPositionerCompositeFactory.java index 787e09e79..389044576 100644 --- a/uk.ac.gda.dls.client/src/uk/ac/gda/dls/client/views/EnumPositionerCompositeFactory.java +++ b/uk.ac.gda.dls.client/src/uk/ac/gda/dls/client/views/EnumPositionerCompositeFactory.java @@ -1,260 +1,259 @@ /*- * Copyright © 2011 Diamond Light Source Ltd. * * This file is part of GDA. * * GDA 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. * * GDA 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 GDA. If not, see <http://www.gnu.org/licenses/>. */ package uk.ac.gda.dls.client.views; import gda.device.DeviceException; import gda.device.EnumPositioner; import gda.device.enumpositioner.DummyPositioner; import gda.factory.FactoryException; import gda.observable.IObserver; import gda.rcp.views.CompositeFactory; import java.util.Arrays; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchPartSite; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.StringUtils; import swing2swt.layout.BorderLayout; import uk.ac.gda.common.rcp.util.EclipseWidgetUtils; import uk.ac.gda.ui.utils.SWTUtils; public class EnumPositionerCompositeFactory implements CompositeFactory, InitializingBean { private String label; private EnumPositioner positioner; private Integer labelWidth; private Integer contentWidth; public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public EnumPositioner getPositioner() { return positioner; } public void setPositioner(EnumPositioner positioner) { this.positioner = positioner; } public Integer getLabelWidth() { return labelWidth; } public Integer getContentWidth() { return contentWidth; } public void setContentWidth(Integer contentWidth) { this.contentWidth = contentWidth; } public void setLabelWidth(Integer labelWidth) { this.labelWidth = labelWidth; } @Override public Composite createComposite(Composite parent, int style, IWorkbenchPartSite iWorkbenchPartSite) { return new EnumPositionerComposite(parent, style, iWorkbenchPartSite.getShell().getDisplay(), positioner, label, labelWidth, contentWidth); } public static void main(String... args) { Display display = new Display(); Shell shell = new Shell(display); shell.setLayout(new BorderLayout()); DummyPositioner dummy = new DummyPositioner(); dummy.setName("dummy"); try { dummy.configure(); } catch (FactoryException e1) { // TODO Auto-generated catch block } dummy.setPositions(new String[]{"position1", "position2", "position3"}); try { dummy.moveTo(1); } catch (DeviceException e) { System.out.println("Can not move dummy to position 1"); } final EnumPositionerComposite comp = new EnumPositionerComposite(shell, SWT.NONE, display, dummy, "", new Integer(100), new Integer(200)); comp.setLayoutData(BorderLayout.NORTH); comp.setVisible(true); shell.pack(); shell.setSize(400, 400); SWTUtils.showCenteredShell(shell); } @Override public void afterPropertiesSet() throws Exception { if (positioner == null) throw new IllegalArgumentException("positioner is null"); } } class EnumPositionerComposite extends Composite { private static final Logger logger = LoggerFactory.getLogger(EnumPositionerComposite.class); private Combo pcom; EnumPositioner positioner; IObserver observer; int selectionIndex=-1; String positions[]; Integer labelWidth; Integer contentWidth; Display display; private Runnable setComboRunnable; String [] formats; EnumPositionerComposite(Composite parent, int style, final Display display, EnumPositioner positioner, String label, Integer labelWidth, Integer contentWidth ) { super(parent, style); this.display = display; this.positioner = positioner; this.labelWidth=labelWidth; this.contentWidth=contentWidth; formats = positioner.getOutputFormat(); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(this); GridDataFactory.fillDefaults().applyTo(this); // GridDataFactory.fillDefaults().align(GridData.FILL, SWT.FILL).applyTo(this); // Label lbl = new Label(this, SWT.RIGHT |SWT.WRAP | SWT.BORDER); Label lbl = new Label(this, SWT.RIGHT |SWT.WRAP); lbl.setText(StringUtils.hasLength(label) ? label : positioner.getName()); GridData labelGridData = new GridData(GridData.HORIZONTAL_ALIGN_END); if(labelWidth != null) labelGridData.widthHint = labelWidth.intValue(); lbl.setLayoutData(labelGridData); try { positions = this.positioner.getPositions(); } catch (DeviceException e) { - // TODO Auto-generated catch block - logger.error("TODO put description of error here", e); + logger.error("Error getting position for " + this.positioner.getName(), e); } pcom = new Combo(this, SWT.SINGLE|SWT.BORDER|SWT.CENTER|SWT.READ_ONLY); pcom.setItems(positions); // pcom.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false)); GridData textGridData = new GridData(GridData.FILL_HORIZONTAL); textGridData.horizontalAlignment = GridData.HORIZONTAL_ALIGN_BEGINNING; if(contentWidth != null) textGridData.widthHint = contentWidth.intValue(); pcom.setLayoutData(textGridData); pcom.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { valueChanged((Combo)e.widget); } }); setComboRunnable = new Runnable() { @Override public void run() { if(selectionIndex != -1){ pcom.select(selectionIndex); } EclipseWidgetUtils.forceLayoutOfTopParent(EnumPositionerComposite.this); } }; observer = new IObserver() { @Override public void update(Object source, Object arg) { logger.info("Got the who knows what type event!"); displayValue(); } }; displayValue(); positioner.addIObserver(observer); } void displayValue() { try { String a=(String) positioner.getPosition(); selectionIndex=Arrays.asList(this.positions).indexOf(a); } catch (DeviceException e) { selectionIndex=-1; logger.error("Error getting position for " + positioner.getName(), e); } if(!isDisposed()){ display.asyncExec(setComboRunnable); } } /** * To change the positioner position when the input text fields changes. * * @param c * the event source */ public void valueChanged(Combo c) { // if (!c.isFocusControl()) // return; try { int npi=c.getSelectionIndex(); this.positioner.asynchronousMoveTo( positions[npi] ); logger.info("New value '" + positions[npi] + "' send to " + positioner.getName() + "."); selectionIndex = npi; } catch (NumberFormatException e) { logger.error("Invalid number format: " + c.getText()); } catch (DeviceException e) { logger.error("EnumPositioner device " + positioner.getName() + " move failed", e); } } @Override public void dispose() { positioner.deleteIObserver(observer); super.dispose(); } }
true
true
EnumPositionerComposite(Composite parent, int style, final Display display, EnumPositioner positioner, String label, Integer labelWidth, Integer contentWidth ) { super(parent, style); this.display = display; this.positioner = positioner; this.labelWidth=labelWidth; this.contentWidth=contentWidth; formats = positioner.getOutputFormat(); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(this); GridDataFactory.fillDefaults().applyTo(this); // GridDataFactory.fillDefaults().align(GridData.FILL, SWT.FILL).applyTo(this); // Label lbl = new Label(this, SWT.RIGHT |SWT.WRAP | SWT.BORDER); Label lbl = new Label(this, SWT.RIGHT |SWT.WRAP); lbl.setText(StringUtils.hasLength(label) ? label : positioner.getName()); GridData labelGridData = new GridData(GridData.HORIZONTAL_ALIGN_END); if(labelWidth != null) labelGridData.widthHint = labelWidth.intValue(); lbl.setLayoutData(labelGridData); try { positions = this.positioner.getPositions(); } catch (DeviceException e) { // TODO Auto-generated catch block logger.error("TODO put description of error here", e); } pcom = new Combo(this, SWT.SINGLE|SWT.BORDER|SWT.CENTER|SWT.READ_ONLY); pcom.setItems(positions); // pcom.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false)); GridData textGridData = new GridData(GridData.FILL_HORIZONTAL); textGridData.horizontalAlignment = GridData.HORIZONTAL_ALIGN_BEGINNING; if(contentWidth != null) textGridData.widthHint = contentWidth.intValue(); pcom.setLayoutData(textGridData); pcom.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { valueChanged((Combo)e.widget); } }); setComboRunnable = new Runnable() { @Override public void run() { if(selectionIndex != -1){ pcom.select(selectionIndex); } EclipseWidgetUtils.forceLayoutOfTopParent(EnumPositionerComposite.this); } }; observer = new IObserver() { @Override public void update(Object source, Object arg) { logger.info("Got the who knows what type event!"); displayValue(); } }; displayValue(); positioner.addIObserver(observer); }
EnumPositionerComposite(Composite parent, int style, final Display display, EnumPositioner positioner, String label, Integer labelWidth, Integer contentWidth ) { super(parent, style); this.display = display; this.positioner = positioner; this.labelWidth=labelWidth; this.contentWidth=contentWidth; formats = positioner.getOutputFormat(); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(this); GridDataFactory.fillDefaults().applyTo(this); // GridDataFactory.fillDefaults().align(GridData.FILL, SWT.FILL).applyTo(this); // Label lbl = new Label(this, SWT.RIGHT |SWT.WRAP | SWT.BORDER); Label lbl = new Label(this, SWT.RIGHT |SWT.WRAP); lbl.setText(StringUtils.hasLength(label) ? label : positioner.getName()); GridData labelGridData = new GridData(GridData.HORIZONTAL_ALIGN_END); if(labelWidth != null) labelGridData.widthHint = labelWidth.intValue(); lbl.setLayoutData(labelGridData); try { positions = this.positioner.getPositions(); } catch (DeviceException e) { logger.error("Error getting position for " + this.positioner.getName(), e); } pcom = new Combo(this, SWT.SINGLE|SWT.BORDER|SWT.CENTER|SWT.READ_ONLY); pcom.setItems(positions); // pcom.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false)); GridData textGridData = new GridData(GridData.FILL_HORIZONTAL); textGridData.horizontalAlignment = GridData.HORIZONTAL_ALIGN_BEGINNING; if(contentWidth != null) textGridData.widthHint = contentWidth.intValue(); pcom.setLayoutData(textGridData); pcom.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { valueChanged((Combo)e.widget); } }); setComboRunnable = new Runnable() { @Override public void run() { if(selectionIndex != -1){ pcom.select(selectionIndex); } EclipseWidgetUtils.forceLayoutOfTopParent(EnumPositionerComposite.this); } }; observer = new IObserver() { @Override public void update(Object source, Object arg) { logger.info("Got the who knows what type event!"); displayValue(); } }; displayValue(); positioner.addIObserver(observer); }
diff --git a/src/edu/berkeley/cs160/smartnature/EditView.java b/src/edu/berkeley/cs160/smartnature/EditView.java index b9049ab..ab98494 100644 --- a/src/edu/berkeley/cs160/smartnature/EditView.java +++ b/src/edu/berkeley/cs160/smartnature/EditView.java @@ -1,250 +1,254 @@ package edu.berkeley.cs160.smartnature; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RectShape; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.Toast; public class EditView extends View implements View.OnClickListener, View.OnTouchListener { EditScreen context; Garden garden; /** plot that is currently pressed */ Plot focusedPlot; /** the entire transformation matrix applied to the canvas */ Matrix m = new Matrix(); /** translation matrix applied to the canvas */ Matrix dragMatrix = new Matrix(); /** translation matrix applied to the background */ Matrix bgDragMatrix = new Matrix(); Drawable bg; Paint textPaint; int zoomLevel; float prevX, prevY, downX, downY, x, y, zoomScale = 1; float textSize; boolean portraitMode, dragMode; private int status; private final static int START_DRAGGING = 0; private final static int STOP_DRAGGING = 1; public EditView(Context context, AttributeSet attrs) { super(context, attrs); this.context = (EditScreen) context; textSize = 15.5f * getResources().getDisplayMetrics().scaledDensity; initPaint(); bg = getResources().getDrawable(R.drawable.tile); initPaint(); initMockData(); setOnClickListener(this); setOnTouchListener(this); } public void initMockData() { garden = this.context.mockGarden; for (Plot plot : garden.getPlots()) { Paint p = plot.getShape().getPaint(); p.setStyle(Paint.Style.STROKE); p.setStrokeWidth(3); p.setStrokeCap(Paint.Cap.ROUND); p.setStrokeJoin(Paint.Join.ROUND); } } public void initPaint() { textPaint = new Paint(Paint.ANTI_ALIAS_FLAG|Paint.FAKE_BOLD_TEXT_FLAG|Paint.DEV_KERN_TEXT_FLAG); textPaint.setTextSize(textSize); textPaint.setTextScaleX(1.2f); textPaint.setTextAlign(Paint.Align.CENTER); } /** called when user clicks "zoom to fit" */ public void reset() { zoomLevel = 0; zoomScale = 1; textPaint.setTextSize(textSize); textPaint.setTextScaleX(1.2f); dragMatrix.reset(); bgDragMatrix.reset(); invalidate(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int width = getWidth(), height = getHeight(); portraitMode = width < height; canvas.save(); canvas.concat(bgDragMatrix); bg.setBounds(canvas.getClipBounds()); bg.draw(canvas); //canvas.drawRGB(255, 255, 255); canvas.restore(); m.reset(); RectF gardenBounds = context.showFullScreen ? garden.getBounds() : garden.getBounds(portraitMode); m.setRectToRect(gardenBounds, getBounds(), Matrix.ScaleToFit.CENTER); if (portraitMode) { m.postRotate(90); m.postTranslate(width, 0); } m.postConcat(dragMatrix); if (zoomLevel != 0) { float zoomShift = (1 - zoomScale) / 2; m.postScale(zoomScale, zoomScale); m.postTranslate(zoomShift * width, zoomShift * height); } canvas.save(); canvas.concat(m); for (Plot p: garden.getPlots()) { if (p != context.newPlot) { canvas.save(); Rect shapeBounds = p.getShape().getBounds(); canvas.rotate(p.getAngle(), shapeBounds.centerX(), shapeBounds.centerY()); p.getShape().draw(canvas); canvas.restore(); } } // "shade" over everything canvas.restore(); canvas.drawARGB(100, 0, 0, 0); // draw plot being edited canvas.save(); canvas.concat(m); Rect shapeBounds = context.newPlot.getShape().getBounds(); canvas.rotate(context.newPlot.getAngle(), shapeBounds.centerX(), shapeBounds.centerY()); context.newPlot.getShape().draw(canvas); canvas.restore(); if (context.showLabels) for (Plot p: garden.getPlots()) { Rect bounds = p.getShape().getBounds(); float[] labelLoc = portraitMode ? new float[] {bounds.left - 10, bounds.centerY()} : new float[] {bounds.centerX(), bounds.top - 10}; m.mapPoints(labelLoc); canvas.drawText(p.getName().toUpperCase(), labelLoc[0], labelLoc[1], textPaint); } } public RectF getBounds() { if (portraitMode) return new RectF(getLeft(), getTop(), getBottom(), getRight()); else return new RectF(getLeft(), getTop(), getRight(), getBottom()); } @Override public void onAnimationEnd() { zoomLevel = context.zoomLevel; zoomScale = (float) Math.pow(1.5, zoomLevel); textPaint.setTextSize(Math.max(10, textSize * zoomScale)); invalidate(); } @Override public void onClick(View view) { if (focusedPlot != null) Toast.makeText(context, "clicked " + focusedPlot.getName(), Toast.LENGTH_SHORT).show(); } @Override public boolean onTouch(View view, MotionEvent event) { context.handleZoom(); x = event.getX(); y = event.getY(); if (context.getDragPlot()) { switch(event.getAction()) { case(MotionEvent.ACTION_DOWN): - focusedPlot = garden.plotAt(x, y, m); - if (focusedPlot == context.newPlot) { + Matrix inv = new Matrix(); + m.invert(inv); + float[] xy = { x, y }; + inv.mapPoints(xy); + if (context.newPlot.contains(xy[0], xy[1])) { + focusedPlot = context.newPlot; // set focused plot appearance focusedPlot.getShape().getPaint().setColor(0xFF7BB518); focusedPlot.getShape().getPaint().setStrokeWidth(5); status = START_DRAGGING; } break; case(MotionEvent.ACTION_UP): status = STOP_DRAGGING; if(focusedPlot != null) { focusedPlot.getShape().getPaint().setColor(Color.BLACK); focusedPlot.getShape().getPaint().setStrokeWidth(3); } break; case(MotionEvent.ACTION_MOVE): if(status == START_DRAGGING && focusedPlot != null) { //focusedPlot.getShape().getPaint().setColor(0xFF7BB518); //focusedPlot.getShape().getPaint().setStrokeWidth(5); //if(focusedPlot.getType() == 0) { float[] dxy = {x, y, prevX, prevY}; //float[] dxy = {x - prevX, x - prevY}; Matrix inverse = new Matrix(); m.invert(inverse); inverse.mapPoints(dxy); focusedPlot.getShape().getBounds().offset((int) (- dxy[2] + dxy[0]), (int) (- dxy[3] + dxy[1])); //shape.setBounds((int) (focusedPlot.getShape().getBounds().left + dxy[0]),(int) (focusedPlot.getShape().getBounds().top + dxy[1]), (int) (focusedPlot.getShape().getBounds().right + dxy[0]), (int) (focusedPlot.getShape().getBounds().bottom + dxy[1])); //focusedPlot.setShape(shape); //} } break; } } else { if(event.getAction() == MotionEvent.ACTION_DOWN) { dragMode = false; downX = x; downY = y; focusedPlot = garden.plotAt(x, y, m); if (focusedPlot != null) { // set focused plot appearance focusedPlot.getShape().getPaint().setColor(0xFF7BB518); focusedPlot.getShape().getPaint().setStrokeWidth(5); } } else { float dx = x - prevX, dy = y - prevY; dragMatrix.postTranslate(dx / zoomScale, dy / zoomScale); bgDragMatrix.postTranslate(dx, dy); if (!dragMode) dragMode = Math.abs(downX - x) > 5 || Math.abs(downY - y) > 5; // show some leniency if (dragMode && focusedPlot != null) { // plot can no longer be clicked so reset appearance focusedPlot.getShape().getPaint().setColor(Color.BLACK); focusedPlot.getShape().getPaint().setStrokeWidth(3); } } // onClick for some reason doesn't execute on its own so manually do it if (event.getAction() == MotionEvent.ACTION_UP && !dragMode) { if (focusedPlot != null) { // reset clicked plot appearance focusedPlot.getShape().getPaint().setColor(Color.BLACK); focusedPlot.getShape().getPaint().setStrokeWidth(3); } performClick(); } } prevX = x; prevY = y; invalidate(); return true; } }
true
true
public boolean onTouch(View view, MotionEvent event) { context.handleZoom(); x = event.getX(); y = event.getY(); if (context.getDragPlot()) { switch(event.getAction()) { case(MotionEvent.ACTION_DOWN): focusedPlot = garden.plotAt(x, y, m); if (focusedPlot == context.newPlot) { // set focused plot appearance focusedPlot.getShape().getPaint().setColor(0xFF7BB518); focusedPlot.getShape().getPaint().setStrokeWidth(5); status = START_DRAGGING; } break; case(MotionEvent.ACTION_UP): status = STOP_DRAGGING; if(focusedPlot != null) { focusedPlot.getShape().getPaint().setColor(Color.BLACK); focusedPlot.getShape().getPaint().setStrokeWidth(3); } break; case(MotionEvent.ACTION_MOVE): if(status == START_DRAGGING && focusedPlot != null) { //focusedPlot.getShape().getPaint().setColor(0xFF7BB518); //focusedPlot.getShape().getPaint().setStrokeWidth(5); //if(focusedPlot.getType() == 0) { float[] dxy = {x, y, prevX, prevY}; //float[] dxy = {x - prevX, x - prevY}; Matrix inverse = new Matrix(); m.invert(inverse); inverse.mapPoints(dxy); focusedPlot.getShape().getBounds().offset((int) (- dxy[2] + dxy[0]), (int) (- dxy[3] + dxy[1])); //shape.setBounds((int) (focusedPlot.getShape().getBounds().left + dxy[0]),(int) (focusedPlot.getShape().getBounds().top + dxy[1]), (int) (focusedPlot.getShape().getBounds().right + dxy[0]), (int) (focusedPlot.getShape().getBounds().bottom + dxy[1])); //focusedPlot.setShape(shape); //} } break; } } else { if(event.getAction() == MotionEvent.ACTION_DOWN) { dragMode = false; downX = x; downY = y; focusedPlot = garden.plotAt(x, y, m); if (focusedPlot != null) { // set focused plot appearance focusedPlot.getShape().getPaint().setColor(0xFF7BB518); focusedPlot.getShape().getPaint().setStrokeWidth(5); } } else { float dx = x - prevX, dy = y - prevY; dragMatrix.postTranslate(dx / zoomScale, dy / zoomScale); bgDragMatrix.postTranslate(dx, dy); if (!dragMode) dragMode = Math.abs(downX - x) > 5 || Math.abs(downY - y) > 5; // show some leniency if (dragMode && focusedPlot != null) { // plot can no longer be clicked so reset appearance focusedPlot.getShape().getPaint().setColor(Color.BLACK); focusedPlot.getShape().getPaint().setStrokeWidth(3); } } // onClick for some reason doesn't execute on its own so manually do it if (event.getAction() == MotionEvent.ACTION_UP && !dragMode) { if (focusedPlot != null) { // reset clicked plot appearance focusedPlot.getShape().getPaint().setColor(Color.BLACK); focusedPlot.getShape().getPaint().setStrokeWidth(3); } performClick(); } } prevX = x; prevY = y; invalidate(); return true; }
public boolean onTouch(View view, MotionEvent event) { context.handleZoom(); x = event.getX(); y = event.getY(); if (context.getDragPlot()) { switch(event.getAction()) { case(MotionEvent.ACTION_DOWN): Matrix inv = new Matrix(); m.invert(inv); float[] xy = { x, y }; inv.mapPoints(xy); if (context.newPlot.contains(xy[0], xy[1])) { focusedPlot = context.newPlot; // set focused plot appearance focusedPlot.getShape().getPaint().setColor(0xFF7BB518); focusedPlot.getShape().getPaint().setStrokeWidth(5); status = START_DRAGGING; } break; case(MotionEvent.ACTION_UP): status = STOP_DRAGGING; if(focusedPlot != null) { focusedPlot.getShape().getPaint().setColor(Color.BLACK); focusedPlot.getShape().getPaint().setStrokeWidth(3); } break; case(MotionEvent.ACTION_MOVE): if(status == START_DRAGGING && focusedPlot != null) { //focusedPlot.getShape().getPaint().setColor(0xFF7BB518); //focusedPlot.getShape().getPaint().setStrokeWidth(5); //if(focusedPlot.getType() == 0) { float[] dxy = {x, y, prevX, prevY}; //float[] dxy = {x - prevX, x - prevY}; Matrix inverse = new Matrix(); m.invert(inverse); inverse.mapPoints(dxy); focusedPlot.getShape().getBounds().offset((int) (- dxy[2] + dxy[0]), (int) (- dxy[3] + dxy[1])); //shape.setBounds((int) (focusedPlot.getShape().getBounds().left + dxy[0]),(int) (focusedPlot.getShape().getBounds().top + dxy[1]), (int) (focusedPlot.getShape().getBounds().right + dxy[0]), (int) (focusedPlot.getShape().getBounds().bottom + dxy[1])); //focusedPlot.setShape(shape); //} } break; } } else { if(event.getAction() == MotionEvent.ACTION_DOWN) { dragMode = false; downX = x; downY = y; focusedPlot = garden.plotAt(x, y, m); if (focusedPlot != null) { // set focused plot appearance focusedPlot.getShape().getPaint().setColor(0xFF7BB518); focusedPlot.getShape().getPaint().setStrokeWidth(5); } } else { float dx = x - prevX, dy = y - prevY; dragMatrix.postTranslate(dx / zoomScale, dy / zoomScale); bgDragMatrix.postTranslate(dx, dy); if (!dragMode) dragMode = Math.abs(downX - x) > 5 || Math.abs(downY - y) > 5; // show some leniency if (dragMode && focusedPlot != null) { // plot can no longer be clicked so reset appearance focusedPlot.getShape().getPaint().setColor(Color.BLACK); focusedPlot.getShape().getPaint().setStrokeWidth(3); } } // onClick for some reason doesn't execute on its own so manually do it if (event.getAction() == MotionEvent.ACTION_UP && !dragMode) { if (focusedPlot != null) { // reset clicked plot appearance focusedPlot.getShape().getPaint().setColor(Color.BLACK); focusedPlot.getShape().getPaint().setStrokeWidth(3); } performClick(); } } prevX = x; prevY = y; invalidate(); return true; }
diff --git a/SWADroid/src/es/ugr/swad/swadroid/modules/downloads/DownloadNotification.java b/SWADroid/src/es/ugr/swad/swadroid/modules/downloads/DownloadNotification.java index 600c6261..aa44e221 100644 --- a/SWADroid/src/es/ugr/swad/swadroid/modules/downloads/DownloadNotification.java +++ b/SWADroid/src/es/ugr/swad/swadroid/modules/downloads/DownloadNotification.java @@ -1,196 +1,197 @@ /* * This file is part of SWADroid. * * Copyright (C) 2012 Helena Rodriguez Gijon <[email protected]> * * SWADroid 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. * * SWADroid 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 SWADroid. If not, see <http://www.gnu.org/licenses/>. */ package es.ugr.swad.swadroid.modules.downloads; import java.io.File; import java.util.List; import es.ugr.swad.swadroid.R; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.webkit.MimeTypeMap; /** *This class manages the notifications associated to downloading files. *It will create an ongoing notification while downloading and it will be updated to show the progress in percentage. *When the download is completed, it will create a static notification with the hability of opening the downloaded file. *When the download is failed, it will create a static notification with an informative message * @author Helena Rodriguez Gijon <[email protected]> * */ public class DownloadNotification { private Context mContext; private int NOTIFICATION_ID = 19982; private Notification mNotification; private NotificationManager mNotificationManager; private PendingIntent mContentIntent; private CharSequence mContentTitle; public DownloadNotification(Context context) { mContext = context; //get the notification manager mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); } /** * Creates an ongoing notification into the status bar * This notification will be updated while downloading with the percent downloaded * @param fileName name of file that is downloading. It is show on the notification. */ public void createNotification(String fileName) { mNotificationManager.cancel(NOTIFICATION_ID); //create the notification int icon = android.R.drawable.stat_sys_download; CharSequence tickerText =mContext.getString(R.string.app_name)+" " + mContext.getString(R.string.notificationDownloadTitle); //Initial text that appears in the status bar long when = System.currentTimeMillis(); mNotification = new Notification(icon, tickerText, when); //create the content which is shown in the notification pulldown // mContentTitle = "Your download is in progress"; mContentTitle = fileName; //Full title of the notification in the pull down CharSequence contentText = "0%" +" "+ mContext.getString(R.string.complete); //Text of the notification in the pull down //you have to set a PendingIntent on a notification to tell the system what you want it to do when the notification is selected //I don't want to use this here so I'm just creating a blank one Intent notificationIntent = new Intent(); mContentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0); //add the additional content and intent to the notification mNotification.setLatestEventInfo(mContext, mContentTitle, contentText, mContentIntent); //make this notification appear in the 'Ongoing events' section mNotification.flags = Notification.FLAG_ONGOING_EVENT; //show the notification mNotificationManager.notify(NOTIFICATION_ID, mNotification); } /** * Receives progress updates from the background task and updates the status bar notification appropriately * @param percentageComplete */ public void progressUpdate(int percentageComplete) { //build up the new status message CharSequence contentText = percentageComplete + "% "+ mContext.getString(R.string.complete); //publish it to the status bar mNotification.setLatestEventInfo(mContext, mContentTitle, contentText, mContentIntent); mNotificationManager.notify(NOTIFICATION_ID, mNotification); } /** * Called when the downloading task is complete. * It removes the ongoing notification and creates a new static notification. The new notification will open the downloaded file and erase itself when it is clicked * @param directoryPath directory where the downloaded file is stored * @param fileName name of the just downloaded file */ public void completedDownload(String directoryPath,String fileName) { mNotificationManager.cancel(NOTIFICATION_ID); //create the notification int icon = android.R.drawable.stat_sys_download_done; CharSequence tickerText =mContext.getString(R.string.app_name)+" " + mContext.getString(R.string.downloadCompletedTitle); //Initial text that appears in the status bar long when = System.currentTimeMillis(); mNotification = new Notification(icon, tickerText, when); //activity that will be launched when the notification is clicked. //this activity will open the downloaded file with the default app. Intent notificationIntent = openFileDefaultApp(directoryPath + File.separator+ fileName); - mContentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0); + if(notificationIntent != null) + mContentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0); //build up the new status message CharSequence contentText; if(notificationIntent != null){ contentText = mContext.getString(R.string.clickToOpenFile); mContentTitle = fileName; //Full title of the notification in the pull down }else{ contentText = mContext.getString(R.string.noApp); mContentTitle = directoryPath + File.separator+ fileName; } //publish it to the status bar mNotification.setLatestEventInfo(mContext, mContentTitle, contentText, mContentIntent); //add the additional content and intent to the notification mNotification.setLatestEventInfo(mContext, mContentTitle, contentText, mContentIntent); //Flag_auto_cancel allows to the notification to erases itself when is clicked. mNotification.flags = Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(NOTIFICATION_ID, mNotification); } /** * Called when the downloading task could not be completed * It removes the ongoing notification and creates a new static notification. The new notification will inform about download problem and erase itself when it is clicked */ public void eraseNotification(String fileName){ //remove the notification from the status bar mNotificationManager.cancel(NOTIFICATION_ID); //create the notification int icon = android.R.drawable.stat_sys_warning; CharSequence tickerText =mContext.getString(R.string.app_name)+" " + mContext.getString(R.string.downloadProblemTitle); //Initial text that appears in the status bar long when = System.currentTimeMillis(); mNotification = new Notification(icon, tickerText, when); //build up the new status message CharSequence contentText =mContext.getString(R.string.downloadProblemMsg); //publish it to the status bar mNotification.setLatestEventInfo(mContext, mContentTitle, contentText, mContentIntent); mNotification.flags = Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(NOTIFICATION_ID, mNotification); } /** * It is defined an Intent to open the file located in @a absolutePath with the default app associated with its extension * @return null It does not exist an app associated with the file type located in @a absolutePath * otherwise an intent that will launch the right app to open the file located in @a absolutePath * * */ private Intent openFileDefaultApp(String absolutePath){ File file = new File(absolutePath); Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); int lastDotIndex = absolutePath.lastIndexOf("."); String extension = absolutePath.substring(lastDotIndex+1); String MIME = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); intent.setDataAndType(Uri.fromFile(file), MIME); PackageManager packageManager = this.mContext.getPackageManager(); List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0); boolean isIntentSafe = activities.size() > 0; if(isIntentSafe) return intent; else return null; } }
true
true
public void completedDownload(String directoryPath,String fileName) { mNotificationManager.cancel(NOTIFICATION_ID); //create the notification int icon = android.R.drawable.stat_sys_download_done; CharSequence tickerText =mContext.getString(R.string.app_name)+" " + mContext.getString(R.string.downloadCompletedTitle); //Initial text that appears in the status bar long when = System.currentTimeMillis(); mNotification = new Notification(icon, tickerText, when); //activity that will be launched when the notification is clicked. //this activity will open the downloaded file with the default app. Intent notificationIntent = openFileDefaultApp(directoryPath + File.separator+ fileName); mContentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0); //build up the new status message CharSequence contentText; if(notificationIntent != null){ contentText = mContext.getString(R.string.clickToOpenFile); mContentTitle = fileName; //Full title of the notification in the pull down }else{ contentText = mContext.getString(R.string.noApp); mContentTitle = directoryPath + File.separator+ fileName; } //publish it to the status bar mNotification.setLatestEventInfo(mContext, mContentTitle, contentText, mContentIntent); //add the additional content and intent to the notification mNotification.setLatestEventInfo(mContext, mContentTitle, contentText, mContentIntent); //Flag_auto_cancel allows to the notification to erases itself when is clicked. mNotification.flags = Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(NOTIFICATION_ID, mNotification); }
public void completedDownload(String directoryPath,String fileName) { mNotificationManager.cancel(NOTIFICATION_ID); //create the notification int icon = android.R.drawable.stat_sys_download_done; CharSequence tickerText =mContext.getString(R.string.app_name)+" " + mContext.getString(R.string.downloadCompletedTitle); //Initial text that appears in the status bar long when = System.currentTimeMillis(); mNotification = new Notification(icon, tickerText, when); //activity that will be launched when the notification is clicked. //this activity will open the downloaded file with the default app. Intent notificationIntent = openFileDefaultApp(directoryPath + File.separator+ fileName); if(notificationIntent != null) mContentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0); //build up the new status message CharSequence contentText; if(notificationIntent != null){ contentText = mContext.getString(R.string.clickToOpenFile); mContentTitle = fileName; //Full title of the notification in the pull down }else{ contentText = mContext.getString(R.string.noApp); mContentTitle = directoryPath + File.separator+ fileName; } //publish it to the status bar mNotification.setLatestEventInfo(mContext, mContentTitle, contentText, mContentIntent); //add the additional content and intent to the notification mNotification.setLatestEventInfo(mContext, mContentTitle, contentText, mContentIntent); //Flag_auto_cancel allows to the notification to erases itself when is clicked. mNotification.flags = Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(NOTIFICATION_ID, mNotification); }
diff --git a/OpERP/src/main/java/devopsdistilled/operp/client/stock/panes/ListWarehousePane.java b/OpERP/src/main/java/devopsdistilled/operp/client/stock/panes/ListWarehousePane.java index 75a61be7..872f53d1 100644 --- a/OpERP/src/main/java/devopsdistilled/operp/client/stock/panes/ListWarehousePane.java +++ b/OpERP/src/main/java/devopsdistilled/operp/client/stock/panes/ListWarehousePane.java @@ -1,77 +1,77 @@ package devopsdistilled.operp.client.stock.panes; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.List; import javax.inject.Inject; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import net.miginfocom.swing.MigLayout; import devopsdistilled.operp.client.abstracts.SubTaskPane; import devopsdistilled.operp.client.abstracts.libs.BeanTableModel; import devopsdistilled.operp.client.stock.models.observers.WarehouseModelObserver; import devopsdistilled.operp.client.stock.panes.details.WarehouseDetailsPane; import devopsdistilled.operp.client.stock.panes.models.observers.ListWarehousePaneModelObserver; import devopsdistilled.operp.server.data.entity.stock.Warehouse; public class ListWarehousePane extends SubTaskPane implements ListWarehousePaneModelObserver, WarehouseModelObserver { @Inject private WarehouseDetailsPane warehouseDetailsPane; private final JPanel pane; private final JTable table; BeanTableModel<Warehouse> tableModel; public ListWarehousePane() { pane = new JPanel(); - pane.setLayout(new MigLayout("debug,fill")); + pane.setLayout(new MigLayout("fill")); table = new JTable(tableModel); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2 && table.getSelectedRow() != -1) { Warehouse warehouse = tableModel.getRow(table .getSelectedRow()); warehouseDetailsPane.show(warehouse, getPane()); } } }); final JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); pane.add(scrollPane, "grow"); } @Override public JComponent getPane() { return pane; } @Override public void updateWarehouses(List<Warehouse> warehouses) { tableModel = null; tableModel = new BeanTableModel<>(Warehouse.class, warehouses); for (int i = 0; i < table.getColumnCount(); i++) { tableModel.setColumnEditable(i, false); } tableModel.setModelEditable(false); table.setModel(tableModel); } }
true
true
public ListWarehousePane() { pane = new JPanel(); pane.setLayout(new MigLayout("debug,fill")); table = new JTable(tableModel); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2 && table.getSelectedRow() != -1) { Warehouse warehouse = tableModel.getRow(table .getSelectedRow()); warehouseDetailsPane.show(warehouse, getPane()); } } }); final JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); pane.add(scrollPane, "grow"); }
public ListWarehousePane() { pane = new JPanel(); pane.setLayout(new MigLayout("fill")); table = new JTable(tableModel); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2 && table.getSelectedRow() != -1) { Warehouse warehouse = tableModel.getRow(table .getSelectedRow()); warehouseDetailsPane.show(warehouse, getPane()); } } }); final JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); pane.add(scrollPane, "grow"); }
diff --git a/src/com/android/camera/VideoModule.java b/src/com/android/camera/VideoModule.java index 59ec3a145..6e55cd977 100644 --- a/src/com/android/camera/VideoModule.java +++ b/src/com/android/camera/VideoModule.java @@ -1,2612 +1,2612 @@ /* * Copyright (C) 2012 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.camera; import android.annotation.TargetApi; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences.Editor; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.SurfaceTexture; import android.hardware.Camera.CameraInfo; import android.hardware.Camera.Parameters; import android.hardware.Camera.PictureCallback; import android.hardware.Camera.Size; import android.location.Location; import android.media.CamcorderProfile; import android.media.CameraProfile; import android.media.MediaRecorder; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.ParcelFileDescriptor; import android.os.SystemClock; import android.provider.MediaStore; import android.provider.MediaStore.MediaColumns; import android.provider.MediaStore.Video; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.OrientationEventListener; import android.view.View; import android.view.WindowManager; import android.widget.Toast; import com.android.camera.ui.PopupManager; import com.android.camera.ui.RotateTextToast; import com.android.gallery3d.R; import com.android.gallery3d.common.ApiHelper; import com.android.gallery3d.exif.ExifInterface; import com.android.gallery3d.util.AccessibilityUtils; import com.android.gallery3d.util.UsageStatistics; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List; public class VideoModule implements CameraModule, VideoController, FocusOverlayManager.Listener, CameraPreference.OnPreferenceChangedListener, ShutterButton.OnShutterButtonListener, MediaRecorder.OnErrorListener, MediaRecorder.OnInfoListener, EffectsRecorder.EffectsListener { private static final String TAG = "CAM_VideoModule"; // We number the request code from 1000 to avoid collision with Gallery. private static final int REQUEST_EFFECT_BACKDROPPER = 1000; private static final int CHECK_DISPLAY_ROTATION = 3; private static final int CLEAR_SCREEN_DELAY = 4; private static final int UPDATE_RECORD_TIME = 5; private static final int ENABLE_SHUTTER_BUTTON = 6; private static final int SHOW_TAP_TO_SNAPSHOT_TOAST = 7; private static final int SWITCH_CAMERA = 8; private static final int SWITCH_CAMERA_START_ANIMATION = 9; private static final int HIDE_SURFACE_VIEW = 10; private static final int CAPTURE_ANIMATION_DONE = 11; private static final int START_PREVIEW_DONE = 12; private static final int SCREEN_DELAY = 2 * 60 * 1000; private static final long SHUTTER_BUTTON_TIMEOUT = 500L; // 500ms /** * An unpublished intent flag requesting to start recording straight away * and return as soon as recording is stopped. * TODO: consider publishing by moving into MediaStore. */ private static final String EXTRA_QUICK_CAPTURE = "android.intent.extra.quickCapture"; private static final int MIN_THUMB_SIZE = 64; // module fields private CameraActivity mActivity; private boolean mPaused; private int mCameraId; private Parameters mParameters; private boolean mFocusAreaSupported; private boolean mMeteringAreaSupported; private Boolean mCameraOpened = false; private boolean mSnapshotInProgress = false; private static final String EFFECT_BG_FROM_GALLERY = "gallery"; private final CameraErrorCallback mErrorCallback = new CameraErrorCallback(); private ComboPreferences mPreferences; private PreferenceGroup mPreferenceGroup; private CameraScreenNail.OnFrameDrawnListener mFrameDrawnListener; private boolean mIsVideoCaptureIntent; private boolean mQuickCapture; private boolean mIsInReviewMode = false; private MediaRecorder mMediaRecorder; private EffectsRecorder mEffectsRecorder; private boolean mEffectsDisplayResult; private int mEffectType = EffectsRecorder.EFFECT_NONE; private Object mEffectParameter = null; private String mEffectUriFromGallery = null; private String mPrefVideoEffectDefault; private boolean mResetEffect = true; private boolean mSwitchingCamera; private boolean mMediaRecorderRecording = false; private boolean mMediaRecorderPausing = false; private long mRecordingStartTime; private long mRecordingTotalTime; private boolean mRecordingTimeCountsDown = false; private long mOnResumeTime; // The video file that the hardware camera is about to record into // (or is recording into.) private String mVideoFilename; private ParcelFileDescriptor mVideoFileDescriptor; // The video file that has already been recorded, and that is being // examined by the user. private String mCurrentVideoFilename; private Uri mCurrentVideoUri; private ContentValues mCurrentVideoValues; private CamcorderProfile mProfile; // The video duration limit. 0 menas no limit. private int mMaxVideoDurationInMs; // Time Lapse parameters. private boolean mCaptureTimeLapse = false; // Default 0. If it is larger than 0, the camcorder is in time lapse mode. private int mTimeBetweenTimeLapseFrameCaptureMs = 0; boolean mPreviewing = false; // True if preview is started. // The display rotation in degrees. This is only valid when mPreviewing is // true. private int mDisplayRotation; private int mCameraDisplayOrientation; private int mDesiredPreviewWidth; private int mDesiredPreviewHeight; private ContentResolver mContentResolver; private LocationManager mLocationManager; private final AutoFocusCallback mAutoFocusCallback = new AutoFocusCallback(); private int mPendingSwitchCameraId; // This handles everything about focus. private FocusOverlayManager mFocusManager; private final Handler mHandler = new MainHandler(); private VideoUI mUI; // The degrees of the device rotated clockwise from its natural orientation. private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN; private int mZoomValue; // The current zoom value. private boolean mRestoreFlash; // This is used to check if we need to restore the flash // status when going back from gallery. private int mVideoWidth; private int mVideoHeight; private boolean mEnableHFR = false; private StartPreviewThread mStartPreviewThread; private final MediaSaveService.OnMediaSavedListener mOnVideoSavedListener = new MediaSaveService.OnMediaSavedListener() { @Override public void onMediaSaved(Uri uri) { if (uri != null) { mActivity.addSecureAlbumItemIfNeeded(true, uri); mActivity.sendBroadcast( new Intent(Util.ACTION_NEW_VIDEO, uri)); Util.broadcastNewPicture(mActivity, uri); } } }; private final MediaSaveService.OnMediaSavedListener mOnPhotoSavedListener = new MediaSaveService.OnMediaSavedListener() { @Override public void onMediaSaved(Uri uri) { if (uri != null) { Util.broadcastNewPicture(mActivity, uri); } } }; protected class CameraOpenThread extends Thread { @Override public void run() { openCamera(); if (mFocusManager == null) initializeFocusManager(); } } private class StartPreviewThread extends Thread { @Override public void run() { try { startPreview(); }catch (Exception e) { } } } private void openCamera() { try { synchronized(mCameraOpened) { if (!mCameraOpened) { mActivity.mCameraDevice = Util.openCamera(mActivity, mCameraId); mCameraOpened = true; } } mParameters = mActivity.mCameraDevice.getParameters(); mFocusAreaSupported = Util.isFocusAreaSupported(mParameters); mMeteringAreaSupported = Util.isMeteringAreaSupported(mParameters); } catch (CameraHardwareException e) { mActivity.mOpenCameraFail = true; } catch (CameraDisabledException e) { mActivity.mCameraDisabled = true; } } public void onScreenSizeChanged(int width, int height, int previewWidth, int previewHeight) { if (mFocusManager != null) mFocusManager.setPreviewSize(width, height); } // This Handler is used to post message back onto the main thread of the // application private class MainHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case ENABLE_SHUTTER_BUTTON: mUI.enableShutter(true); break; case CLEAR_SCREEN_DELAY: { mActivity.getWindow().clearFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); break; } case UPDATE_RECORD_TIME: { updateRecordingTime(); break; } case CHECK_DISPLAY_ROTATION: { // Restart the preview if display rotation has changed. // Sometimes this happens when the device is held upside // down and camera app is opened. Rotation animation will // take some time and the rotation value we have got may be // wrong. Framework does not have a callback for this now. if ((Util.getDisplayRotation(mActivity) != mDisplayRotation) && !mMediaRecorderRecording && !mSwitchingCamera) { startPreview(); } if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) { mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100); } break; } case SHOW_TAP_TO_SNAPSHOT_TOAST: { showTapToSnapshotToast(); break; } case SWITCH_CAMERA: { switchCamera(); break; } case SWITCH_CAMERA_START_ANIMATION: { ((CameraScreenNail) mActivity.mCameraScreenNail).animateSwitchCamera(); // Enable all camera controls. mSwitchingCamera = false; break; } case HIDE_SURFACE_VIEW: { mUI.hideSurfaceView(); break; } case CAPTURE_ANIMATION_DONE: { mUI.enablePreviewThumb(false); break; } case START_PREVIEW_DONE: { mStartPreviewThread = null; break; } default: Log.v(TAG, "Unhandled message: " + msg.what); break; } } } private BroadcastReceiver mReceiver = null; private class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_EJECT)) { stopVideoRecording(); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) { Toast.makeText(mActivity, mActivity.getResources().getString(R.string.wait), Toast.LENGTH_LONG).show(); } } } private String createName(long dateTaken) { Date date = new Date(dateTaken); SimpleDateFormat dateFormat = new SimpleDateFormat( mActivity.getString(R.string.video_file_name_format)); return dateFormat.format(date); } private int getPreferredCameraId(ComboPreferences preferences) { int intentCameraId = Util.getCameraFacingIntentExtras(mActivity); if (intentCameraId != -1) { // Testing purpose. Launch a specific camera through the intent // extras. return intentCameraId; } else { return CameraSettings.readPreferredCameraId(preferences); } } private void initializeSurfaceView() { if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) { // API level < 16 mFrameDrawnListener = new CameraScreenNail.OnFrameDrawnListener() { @Override public void onFrameDrawn(CameraScreenNail c) { mHandler.sendEmptyMessage(HIDE_SURFACE_VIEW); } }; mUI.getSurfaceHolder().addCallback(mUI); } } @Override public void init(CameraActivity activity, View root, boolean reuseScreenNail) { mActivity = activity; mUI = new VideoUI(activity, this, root); mPreferences = new ComboPreferences(mActivity); CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal()); mCameraId = getPreferredCameraId(mPreferences); mPreferences.setLocalId(mActivity, mCameraId); CameraSettings.upgradeLocalPreferences(mPreferences.getLocal()); mActivity.setStoragePath(mPreferences); mActivity.mNumberOfCameras = CameraHolder.instance().getNumberOfCameras(); mPrefVideoEffectDefault = mActivity.getString(R.string.pref_video_effect_default); resetEffect(); /* * To reduce startup time, we start the preview in another thread. * We make sure the preview is started at the end of onCreate. */ CameraOpenThread cameraOpenThread = new CameraOpenThread(); cameraOpenThread.start(); mContentResolver = mActivity.getContentResolver(); // Surface texture is from camera screen nail and startPreview needs it. // This must be done before startPreview. mIsVideoCaptureIntent = isVideoCaptureIntent(); if (reuseScreenNail) { mActivity.reuseCameraScreenNail(!mIsVideoCaptureIntent); } else { mActivity.createCameraScreenNail(!mIsVideoCaptureIntent); } initializeSurfaceView(); // Make sure camera device is opened. try { cameraOpenThread.join(); if (mActivity.mOpenCameraFail) { Util.showErrorAndFinish(mActivity, R.string.cannot_connect_camera); return; } else if (mActivity.mCameraDisabled) { Util.showErrorAndFinish(mActivity, R.string.camera_disabled); return; } } catch (InterruptedException ex) { // ignore } CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail; if (screenNail.getSurfaceTexture() == null) { screenNail.acquireSurfaceTexture(); } readVideoPreferences(); mUI.setPrefChangedListener(this); mStartPreviewThread = new StartPreviewThread(); mStartPreviewThread.start(); mQuickCapture = mActivity.getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false); mLocationManager = new LocationManager(mActivity, null); mUI.setOrientationIndicator(0, false); setDisplayOrientation(); mUI.showTimeLapseUI(mCaptureTimeLapse); initializeVideoSnapshot(); resizeForPreviewAspectRatio(); initializeVideoControl(); mPendingSwitchCameraId = -1; mUI.updateOnScreenIndicators(mParameters, mPreferences); // Disable the shutter button if effects are ON since it might take // a little more time for the effects preview to be ready. We do not // want to allow recording before that happens. The shutter button // will be enabled when we get the message from effectsrecorder that // the preview is running. This becomes critical when the camera is // swapped. if (effectsActive()) { mUI.enableShutter(false); } } @Override public void autoFocus() { Log.e(TAG, "start autoFocus."); mActivity.mCameraDevice.autoFocus(mAutoFocusCallback); } @Override public void cancelAutoFocus() { mActivity.mCameraDevice.cancelAutoFocus(); } @Override public boolean capture() { return true; } @Override public void startFaceDetection() { } @Override public void stopFaceDetection() { } @Override public void setFocusParameters() { if (mFocusAreaSupported) mParameters.setFocusAreas(mFocusManager.getFocusAreas()); if (mMeteringAreaSupported) mParameters.setMeteringAreas(mFocusManager.getMeteringAreas()); if (mFocusAreaSupported || mMeteringAreaSupported) mActivity.mCameraDevice.setParameters(mParameters); } // SingleTapListener // Preview area is touched. Take a picture. @Override public void onSingleTapUp(View view, int x, int y) { if (!mParameters.isVideoSnapshotSupported()) { // Do not trigger touch focus if popup window is opened. if (mUI.removeTopLevelPopup()) return; // Check if metering area or focus area is supported. if (mFocusAreaSupported || mMeteringAreaSupported) { mFocusManager.onSingleTapUp(x, y); } } //If recording pause, ignore livesnapshot if (mMediaRecorderPausing) return; if (mMediaRecorderRecording && effectsActive()) { new RotateTextToast(mActivity, R.string.disable_video_snapshot_hint, mOrientation).show(); return; } MediaSaveService s = mActivity.getMediaSaveService(); if (mPaused || mSnapshotInProgress || effectsActive() || s == null || s.isQueueFull() || !Util.isVideoSnapshotSupported(mParameters)) { return; } if (!mMediaRecorderRecording) { // check for dismissing popup mUI.dismissPopup(true); return; } // Set rotation and gps data. int rotation = Util.getJpegRotation(mCameraId, mOrientation); mParameters.setRotation(rotation); Location loc = mLocationManager.getCurrentLocation(); Util.setGpsParameters(mParameters, loc); mActivity.mCameraDevice.setParameters(mParameters); Log.v(TAG, "Video snapshot start"); mActivity.mCameraDevice.takePicture(null, null, null, new JpegPictureCallback(loc)); showVideoSnapshotUI(true); mSnapshotInProgress = true; UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA, UsageStatistics.ACTION_CAPTURE_DONE, "VideoSnapshot"); } @Override public void onStop() {} private void loadCameraPreferences() { CameraSettings settings = new CameraSettings(mActivity, mParameters, mCameraId, CameraHolder.instance().getCameraInfo()); // Remove the video quality preference setting when the quality is given in the intent. mPreferenceGroup = filterPreferenceScreenByIntent( settings.getPreferenceGroup(R.xml.video_preferences)); } private void initializeVideoControl() { loadCameraPreferences(); mUI.initializePopup(mPreferenceGroup); if (effectsActive()) { mUI.overrideSettings( CameraSettings.KEY_VIDEO_QUALITY, Integer.toString(getLowVideoQuality())); } } @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB) private static int getLowVideoQuality() { if (ApiHelper.HAS_FINE_RESOLUTION_QUALITY_LEVELS) { return CamcorderProfile.QUALITY_480P; } else { return CamcorderProfile.QUALITY_LOW; } } @Override public void onOrientationChanged(int orientation) { // We keep the last known orientation. So if the user first orient // the camera then point the camera to floor or sky, we still have // the correct orientation. if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) return; int newOrientation = Util.roundOrientation(orientation, mOrientation); if (mOrientation != newOrientation) { mOrientation = newOrientation; // The input of effects recorder is affected by // android.hardware.Camera.setDisplayOrientation. Its value only // compensates the camera orientation (no Display.getRotation). // So the orientation hint here should only consider sensor // orientation. if (effectsActive()) { mEffectsRecorder.setOrientationHint(mOrientation); } } // Show the toast after getting the first orientation changed. if (mHandler.hasMessages(SHOW_TAP_TO_SNAPSHOT_TOAST)) { mHandler.removeMessages(SHOW_TAP_TO_SNAPSHOT_TOAST); showTapToSnapshotToast(); } } private void startPlayVideoActivity() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(mCurrentVideoUri, convertOutputFormatToMimeType(mProfile.fileFormat)); try { mActivity.startActivity(intent); } catch (ActivityNotFoundException ex) { Log.e(TAG, "Couldn't view video " + mCurrentVideoUri, ex); } } @OnClickAttr public void onReviewPlayClicked(View v) { startPlayVideoActivity(); } @OnClickAttr public void onReviewDoneClicked(View v) { mIsInReviewMode = false; doReturnToCaller(true); } @OnClickAttr public void onReviewCancelClicked(View v) { mIsInReviewMode = false; stopVideoRecording(); doReturnToCaller(false); } @Override public boolean isInReviewMode() { return mIsInReviewMode; } private void onStopVideoRecording() { mEffectsDisplayResult = true; boolean recordFail = stopVideoRecording(); if (mIsVideoCaptureIntent) { if (!effectsActive()) { if (mQuickCapture) { doReturnToCaller(!recordFail); } else if (!recordFail) { showCaptureResult(); } } } else if (!recordFail){ // Start capture animation. if (!mPaused && ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) { // The capture animation is disabled on ICS because we use SurfaceView // for preview during recording. When the recording is done, we switch // back to use SurfaceTexture for preview and we need to stop then start // the preview. This will cause the preview flicker since the preview // will not be continuous for a short period of time. // Get orientation directly from display rotation to make sure it's up // to date. OnConfigurationChanged callback usually kicks in a bit later, if // device is rotated during recording. mDisplayRotation = Util.getDisplayRotation(mActivity); ((CameraScreenNail) mActivity.mCameraScreenNail).animateCapture(mDisplayRotation); mUI.enablePreviewThumb(true); // Make sure to disable the thumbnail preview after the // animation is done to disable the click target. mHandler.removeMessages(CAPTURE_ANIMATION_DONE); mHandler.sendEmptyMessageDelayed(CAPTURE_ANIMATION_DONE, CaptureAnimManager.getAnimationDuration()); } } } public void onProtectiveCurtainClick(View v) { // Consume clicks } @Override public void onShutterButtonClick() { if (mUI.collapseCameraControls() || mSwitchingCamera) return; boolean stop = mMediaRecorderRecording; if (stop) { onStopVideoRecording(); } else { startVideoRecording(); } mUI.enableShutter(false); // Keep the shutter button disabled when in video capture intent // mode and recording is stopped. It'll be re-enabled when // re-take button is clicked. if (!(mIsVideoCaptureIntent && stop)) { mHandler.sendEmptyMessageDelayed( ENABLE_SHUTTER_BUTTON, SHUTTER_BUTTON_TIMEOUT); } } @Override public void onShutterButtonFocus(boolean pressed) { mUI.setShutterPressed(pressed); } private final class AutoFocusCallback implements android.hardware.Camera.AutoFocusCallback { @Override public void onAutoFocus( boolean focused, android.hardware.Camera camera) { Log.e(TAG, "AutoFocusCallback, mPaused=" + mPaused); if (mPaused) return; //setCameraState(IDLE); mFocusManager.onAutoFocus(focused, false); } } private void readVideoPreferences() { // The preference stores values from ListPreference and is thus string type for all values. // We need to convert it to int manually. String defaultQuality = CameraSettings.getDefaultVideoQuality(mCameraId, mActivity.getResources().getString(R.string.pref_video_quality_default)); String videoQuality = mPreferences.getString(CameraSettings.KEY_VIDEO_QUALITY, defaultQuality); int quality = Integer.valueOf(videoQuality); // Enable HFR mode for WVGA mEnableHFR = quality == CamcorderProfile.QUALITY_WVGA; // Set video quality. Intent intent = mActivity.getIntent(); if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) { int extraVideoQuality = intent.getIntExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0); if (extraVideoQuality > 0) { quality = CamcorderProfile.QUALITY_HIGH; } else { // 0 is mms. quality = CamcorderProfile.QUALITY_LOW; } } // Set video duration limit. The limit is read from the preference, // unless it is specified in the intent. if (intent.hasExtra(MediaStore.EXTRA_DURATION_LIMIT)) { int seconds = intent.getIntExtra(MediaStore.EXTRA_DURATION_LIMIT, 0); mMaxVideoDurationInMs = 1000 * seconds; } else { mMaxVideoDurationInMs = CameraSettings.getMaxVideoDuration(mActivity); } // Set effect mEffectType = CameraSettings.readEffectType(mPreferences); if (mEffectType != EffectsRecorder.EFFECT_NONE) { mEffectParameter = CameraSettings.readEffectParameter(mPreferences); // Set quality to be no higher than 480p. CamcorderProfile profile = CamcorderProfile.get(mCameraId, quality); if (profile.videoFrameHeight > 480) { quality = getLowVideoQuality(); } } else { mEffectParameter = null; } // Read time lapse recording interval. if (ApiHelper.HAS_TIME_LAPSE_RECORDING) { String frameIntervalStr = mPreferences.getString( CameraSettings.KEY_VIDEO_TIME_LAPSE_FRAME_INTERVAL, mActivity.getString(R.string.pref_video_time_lapse_frame_interval_default)); mTimeBetweenTimeLapseFrameCaptureMs = Integer.parseInt(frameIntervalStr); mCaptureTimeLapse = (mTimeBetweenTimeLapseFrameCaptureMs != 0); } // TODO: This should be checked instead directly +1000. if (mCaptureTimeLapse) quality += 1000; mProfile = CamcorderProfile.get(mCameraId, quality); getDesiredPreviewSize(); } private void writeDefaultEffectToPrefs() { ComboPreferences.Editor editor = mPreferences.edit(); editor.putString(CameraSettings.KEY_VIDEO_EFFECT, mActivity.getString(R.string.pref_video_effect_default)); editor.apply(); } private boolean cantUsePreviewSizeDueToEffects() { if (!effectsActive()) { return false; } return !mActivity.getResources().getBoolean(R.bool.usePreferredPreviewSizeForEffects); } @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB) private void getDesiredPreviewSize() { mParameters = mActivity.mCameraDevice.getParameters(); if (ApiHelper.HAS_GET_SUPPORTED_VIDEO_SIZE) { if (mParameters.getSupportedVideoSizes() == null || cantUsePreviewSizeDueToEffects() || mActivity.getResources().getBoolean(R.bool.useVideoSizeForPreview)) { mDesiredPreviewWidth = mProfile.videoFrameWidth; mDesiredPreviewHeight = mProfile.videoFrameHeight; } else { // Driver supports separates outputs for preview and video. List<Size> sizes = mParameters.getSupportedPreviewSizes(); Size preferred = mParameters.getPreferredPreviewSizeForVideo(); if (mActivity.getResources().getBoolean(R.bool.ignorePreferredPreviewSizeForVideo) || preferred == null) { preferred = sizes.get(0); } int product = preferred.width * preferred.height; Iterator<Size> it = sizes.iterator(); // Remove the preview sizes that are not preferred. while (it.hasNext()) { Size size = it.next(); if (size.width * size.height > product) { it.remove(); } } Size optimalSize = Util.getOptimalPreviewSize(mActivity, sizes, (double) mProfile.videoFrameWidth / mProfile.videoFrameHeight); mDesiredPreviewWidth = optimalSize.width; mDesiredPreviewHeight = optimalSize.height; } } else { mDesiredPreviewWidth = mProfile.videoFrameWidth; mDesiredPreviewHeight = mProfile.videoFrameHeight; } Log.v(TAG, "mDesiredPreviewWidth=" + mDesiredPreviewWidth + ". mDesiredPreviewHeight=" + mDesiredPreviewHeight); } void setPreviewFrameLayoutCameraOrientation(){ CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId]; //if camera mount angle is 0 or 180, we want to resize preview if(info.orientation % 180 == 0){ mUI.mPreviewFrameLayout.setRenderer(mUI.mPieRenderer); mUI.mPreviewFrameLayout.cameraOrientationPreviewResize(true); } else{ mUI.mPreviewFrameLayout.cameraOrientationPreviewResize(false); } } private void resizeForPreviewAspectRatio() { setPreviewFrameLayoutCameraOrientation(); mUI.setAspectRatio( (double) mProfile.videoFrameWidth / mProfile.videoFrameHeight); } @Override public void installIntentFilter() { // install an intent filter to receive SD card related events. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_EJECT); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); intentFilter.addDataScheme("file"); mReceiver = new MyBroadcastReceiver(); mActivity.registerReceiver(mReceiver, intentFilter); } @Override public void onResumeBeforeSuper() { mPaused = false; } @Override public void onResumeAfterSuper() { if (mActivity.mOpenCameraFail || mActivity.mCameraDisabled) return; mZoomValue = 0; showVideoSnapshotUI(false); mUI.enableShutter(false); if (!mPreviewing && mStartPreviewThread == null) { resetEffect(); openCamera(); if (mActivity.mOpenCameraFail) { Util.showErrorAndFinish(mActivity, R.string.cannot_connect_camera); return; } else if (mActivity.mCameraDisabled) { Util.showErrorAndFinish(mActivity, R.string.camera_disabled); return; } readVideoPreferences(); resizeForPreviewAspectRatio(); CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail; screenNail.cancelAcquire(); if (screenNail.getSurfaceTexture() == null) { screenNail.acquireSurfaceTexture(); } mStartPreviewThread = new StartPreviewThread(); mStartPreviewThread.start(); } else { // preview already started mUI.enableShutter(true); } // Initializing it here after the preview is started. mUI.initializeZoom(mParameters); keepScreenOnAwhile(); // Initialize location service. boolean recordLocation = RecordLocationPreference.get(mPreferences, mContentResolver); mLocationManager.recordLocation(recordLocation); if (mPreviewing) { mOnResumeTime = SystemClock.uptimeMillis(); mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100); } // Dismiss open menu if exists. PopupManager.getInstance(mActivity).notifyShowPopup(null); UsageStatistics.onContentViewChanged( UsageStatistics.COMPONENT_CAMERA, "VideoModule"); } private void setDisplayOrientation() { mDisplayRotation = Util.getDisplayRotation(mActivity); if (ApiHelper.HAS_SURFACE_TEXTURE) { // The display rotation is handled by gallery. mCameraDisplayOrientation = Util.getDisplayOrientation(0, mCameraId); } else { // We need to consider display rotation ourselves. mCameraDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId); } if (mFocusManager != null) { int mDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId); mFocusManager.setDisplayOrientation(mDisplayOrientation); } // GLRoot also uses the DisplayRotation, and needs to be told to layout to update mActivity.getGLRoot().requestLayoutContentPane(); } @Override public int onZoomChanged(int index) { // Not useful to change zoom value when the activity is paused. if (mPaused) return index; mZoomValue = index; if (mParameters == null || mActivity.mCameraDevice == null) return index; // Set zoom parameters asynchronously mParameters.setZoom(mZoomValue); mActivity.mCameraDevice.setParameters(mParameters); Parameters p = mActivity.mCameraDevice.getParameters(); if (p != null) return p.getZoom(); return index; } private void startPreview() { Log.v(TAG, "startPreview"); mActivity.mCameraDevice.setErrorCallback(mErrorCallback); if (mPreviewing == true) { stopPreview(); if (effectsActive() && mEffectsRecorder != null) { mEffectsRecorder.release(); mEffectsRecorder = null; } } setDisplayOrientation(); mActivity.mCameraDevice.setDisplayOrientation(mCameraDisplayOrientation); setCameraParameters(); try { if (!effectsActive()) { mFocusManager.setAeAwbLock(false); // Unlock AE and AWB. if (ApiHelper.HAS_SURFACE_TEXTURE) { SurfaceTexture texture = mActivity.getScreenNailTextureForPreviewSize( mCameraId, mCameraDisplayOrientation, mParameters); if (texture == null) { return; // The texture has been destroyed (pause, etc) } mActivity.mCameraDevice.setPreviewTextureAsync(texture); } else { mActivity.mCameraDevice.setPreviewDisplayAsync(mUI.getSurfaceHolder()); } mActivity.mCameraDevice.startPreviewAsync(); mPreviewing = true; onPreviewStarted(); } else { initializeEffectsPreview(); mEffectsRecorder.startPreview(); mPreviewing = true; onPreviewStarted(); } } catch (Throwable ex) { closeCamera(); throw new RuntimeException("startPreview failed", ex); } finally { mActivity.runOnUiThread(new Runnable() { @Override public void run() { if (mActivity.mOpenCameraFail) { Util.showErrorAndFinish(mActivity, R.string.cannot_connect_camera); } else if (mActivity.mCameraDisabled) { Util.showErrorAndFinish(mActivity, R.string.camera_disabled); } } }); } mFocusManager.onPreviewStarted(); } private void onPreviewStarted() { mHandler.sendEmptyMessage(ENABLE_SHUTTER_BUTTON); mHandler.sendEmptyMessage(START_PREVIEW_DONE); } @Override public void stopPreview() { mActivity.mCameraDevice.stopPreview(); mPreviewing = false; if (mFocusManager != null) mFocusManager.onPreviewStopped(); } // Closing the effects out. Will shut down the effects graph. private void closeEffects() { Log.v(TAG, "Closing effects"); mEffectType = EffectsRecorder.EFFECT_NONE; if (mEffectsRecorder == null) { Log.d(TAG, "Effects are already closed. Nothing to do"); return; } // This call can handle the case where the camera is already released // after the recording has been stopped. mEffectsRecorder.release(); mEffectsRecorder = null; } // By default, we want to close the effects as well with the camera. private void closeCamera() { CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail; screenNail.cancelAcquire(); try { if (mStartPreviewThread != null) { mStartPreviewThread.interrupt(); mStartPreviewThread.join(); mStartPreviewThread = null; } } catch (InterruptedException e) { } closeCamera(true); } // In certain cases, when the effects are active, we may want to shutdown // only the camera related parts, and handle closing the effects in the // effectsUpdate callback. // For example, in onPause, we want to make the camera available to // outside world immediately, however, want to wait till the effects // callback to shut down the effects. In such a case, we just disconnect // the effects from the camera by calling disconnectCamera. That way // the effects can handle that when shutting down. // // @param closeEffectsAlso - indicates whether we want to close the // effects also along with the camera. private void closeCamera(boolean closeEffectsAlso) { Log.v(TAG, "closeCamera"); if (mActivity.mCameraDevice == null) { Log.d(TAG, "already stopped."); return; } if (mEffectsRecorder != null) { // Disconnect the camera from effects so that camera is ready to // be released to the outside world. mEffectsRecorder.disconnectCamera(); } if (closeEffectsAlso) closeEffects(); mActivity.mCameraDevice.setZoomChangeListener(null); mActivity.mCameraDevice.setErrorCallback(null); synchronized(mCameraOpened) { if (mCameraOpened) { CameraHolder.instance().release(); } mCameraOpened = false; } mActivity.mCameraDevice = null; mPreviewing = false; mSnapshotInProgress = false; mFocusManager.onCameraReleased(); } private void releasePreviewResources() { if (ApiHelper.HAS_SURFACE_TEXTURE) { CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail; screenNail.releaseSurfaceTexture(); if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) { mHandler.removeMessages(HIDE_SURFACE_VIEW); mUI.hideSurfaceView(); } } } @Override public void onPauseBeforeSuper() { mPaused = true; if (mMediaRecorderRecording) { // Camera will be released in onStopVideoRecording. onStopVideoRecording(); } else { closeCamera(); if (!effectsActive()) releaseMediaRecorder(); } if (effectsActive()) { // If the effects are active, make sure we tell the graph that the // surfacetexture is not valid anymore. Disconnect the graph from // the display. This should be done before releasing the surface // texture. mEffectsRecorder.disconnectDisplay(); } else { // Close the file descriptor and clear the video namer only if the // effects are not active. If effects are active, we need to wait // till we get the callback from the Effects that the graph is done // recording. That also needs a change in the stopVideoRecording() // call to not call closeCamera if the effects are active, because // that will close down the effects are well, thus making this if // condition invalid. closeVideoFileDescriptor(); } releasePreviewResources(); if (mReceiver != null) { mActivity.unregisterReceiver(mReceiver); mReceiver = null; } resetScreenOn(); mUI.onPause(); if (mLocationManager != null) mLocationManager.recordLocation(false); mHandler.removeMessages(CHECK_DISPLAY_ROTATION); mHandler.removeMessages(SWITCH_CAMERA); mHandler.removeMessages(SWITCH_CAMERA_START_ANIMATION); mPendingSwitchCameraId = -1; mSwitchingCamera = false; // Call onPause after stopping video recording. So the camera can be // released as soon as possible. } @Override public void onPauseAfterSuper() { if (mFocusManager != null) mFocusManager.removeMessages(); } /** * The focus manager is the first UI related element to get initialized, * and it requires the RenderOverlay, so initialize it here */ private void initializeFocusManager() { // Create FocusManager object. startPreview needs it. // if mFocusManager not null, reuse it // otherwise create a new instance if (mFocusManager != null) { mFocusManager.removeMessages(); } else { CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId]; boolean mirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT); String[] defaultFocusModes = mActivity.getResources().getStringArray( R.array.pref_camera_focusmode_default_array); mFocusManager = new FocusOverlayManager(mPreferences, defaultFocusModes, mParameters, this, mirror, mActivity.getMainLooper(), mUI); } } @Override public void onUserInteraction() { if (!mMediaRecorderRecording && !mActivity.isFinishing()) { keepScreenOnAwhile(); } } @Override public boolean onBackPressed() { if (mPaused) return true; if (mMediaRecorderRecording) { onStopVideoRecording(); return true; } else if (mUI.hidePieRenderer()) { return true; } else { return mUI.removeTopLevelPopup(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Do not handle any key if the activity is paused. if (mPaused) { return true; } switch (keyCode) { case KeyEvent.KEYCODE_CAMERA: if (event.getRepeatCount() == 0) { mUI.clickShutter(); return true; } break; case KeyEvent.KEYCODE_DPAD_CENTER: if (event.getRepeatCount() == 0) { mUI.clickShutter(); return true; } break; case KeyEvent.KEYCODE_MENU: if (mMediaRecorderRecording) return true; break; } return false; } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_CAMERA: mUI.pressShutter(false); return true; } return false; } @Override public boolean isVideoCaptureIntent() { String action = mActivity.getIntent().getAction(); return (MediaStore.ACTION_VIDEO_CAPTURE.equals(action)); } private void doReturnToCaller(boolean valid) { Intent resultIntent = new Intent(); int resultCode; if (valid) { resultCode = Activity.RESULT_OK; resultIntent.setData(mCurrentVideoUri); } else { resultCode = Activity.RESULT_CANCELED; } mActivity.setResultEx(resultCode, resultIntent); mActivity.finish(); } private void cleanupEmptyFile() { if (mVideoFilename != null) { File f = new File(mVideoFilename); if (f.length() == 0 && f.delete()) { Log.v(TAG, "Empty video file deleted: " + mVideoFilename); mVideoFilename = null; } } } private void setupMediaRecorderPreviewDisplay() { mFocusManager.resetTouchFocus(); // Nothing to do here if using SurfaceTexture. if (!ApiHelper.HAS_SURFACE_TEXTURE) { mMediaRecorder.setPreviewDisplay(mUI.getSurfaceHolder().getSurface()); } else if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) { // We stop the preview here before unlocking the device because we // need to change the SurfaceTexture to SurfaceView for preview. stopPreview(); mActivity.mCameraDevice.setPreviewDisplayAsync(mUI.getSurfaceHolder()); // The orientation for SurfaceTexture is different from that for // SurfaceView. For SurfaceTexture we don't need to consider the // display rotation. Just consider the sensor's orientation and we // will set the orientation correctly when showing the texture. // Gallery will handle the orientation for the preview. For // SurfaceView we will have to take everything into account so the // display rotation is considered. mActivity.mCameraDevice.setDisplayOrientation( Util.getDisplayOrientation(mDisplayRotation, mCameraId)); mActivity.mCameraDevice.startPreviewAsync(); mPreviewing = true; mMediaRecorder.setPreviewDisplay(mUI.getSurfaceHolder().getSurface()); } } // Prepares media recorder. private void initializeRecorder() { Log.v(TAG, "initializeRecorder"); // If the mCameraDevice is null, then this activity is going to finish if (mActivity.mCameraDevice == null) return; if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING && ApiHelper.HAS_SURFACE_TEXTURE) { // Set the SurfaceView to visible so the surface gets created. // surfaceCreated() is called immediately when the visibility is // changed to visible. Thus, mSurfaceViewReady should become true // right after calling setVisibility(). mUI.showSurfaceView(); if (!mUI.isSurfaceViewReady()) return; } Intent intent = mActivity.getIntent(); Bundle myExtras = intent.getExtras(); mVideoWidth = mProfile.videoFrameWidth; mVideoHeight = mProfile.videoFrameHeight; long requestedSizeLimit = 0; closeVideoFileDescriptor(); if (mIsVideoCaptureIntent && myExtras != null) { Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); if (saveUri != null) { try { mVideoFileDescriptor = mContentResolver.openFileDescriptor(saveUri, "rw"); mCurrentVideoUri = saveUri; } catch (java.io.FileNotFoundException ex) { // invalid uri Log.e(TAG, ex.toString()); } } requestedSizeLimit = myExtras.getLong(MediaStore.EXTRA_SIZE_LIMIT); } mMediaRecorder = new MediaRecorder(); setupMediaRecorderPreviewDisplay(); // Unlock the camera object before passing it to media recorder. mActivity.mCameraDevice.unlock(); mActivity.mCameraDevice.waitDone(); mMediaRecorder.setCamera(mActivity.mCameraDevice.getCamera()); if (!mCaptureTimeLapse) { mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); } mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mMediaRecorder.setProfile(mProfile); mMediaRecorder.setMaxDuration(mMaxVideoDurationInMs); if (mCaptureTimeLapse) { double fps = 1000 / (double) mTimeBetweenTimeLapseFrameCaptureMs; setCaptureRate(mMediaRecorder, fps); } setRecordLocation(); // Set output file. // Try Uri in the intent first. If it doesn't exist, use our own // instead. if (mVideoFileDescriptor != null) { mMediaRecorder.setOutputFile(mVideoFileDescriptor.getFileDescriptor()); } else { generateVideoFilename(mProfile.fileFormat); mMediaRecorder.setOutputFile(mVideoFilename); } // Set maximum file size. long maxFileSize = mActivity.getStorageSpace() - Storage.LOW_STORAGE_THRESHOLD; if (requestedSizeLimit > 0 && requestedSizeLimit < maxFileSize) { maxFileSize = requestedSizeLimit; } try { mMediaRecorder.setMaxFileSize(maxFileSize); } catch (RuntimeException exception) { // We are going to ignore failure of setMaxFileSize here, as // a) The composer selected may simply not support it, or // b) The underlying media framework may not handle 64-bit range // on the size restriction. } // See android.hardware.Camera.Parameters.setRotation for // documentation. // Note that mOrientation here is the device orientation, which is the opposite of // what activity.getWindowManager().getDefaultDisplay().getRotation() would return, // which is the orientation the graphics need to rotate in order to render correctly. int rotation = 0; if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) { CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId]; if (info.facing == CameraInfo.CAMERA_FACING_FRONT) { rotation = (info.orientation - mOrientation + 360) % 360; } else { // back-facing camera rotation = (info.orientation + mOrientation) % 360; } } mMediaRecorder.setOrientationHint(rotation); try { mMediaRecorder.prepare(); } catch (IOException e) { Log.e(TAG, "prepare failed for " + mVideoFilename, e); releaseMediaRecorder(); throw new RuntimeException(e); } mMediaRecorder.setOnErrorListener(this); mMediaRecorder.setOnInfoListener(this); } @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB) private static void setCaptureRate(MediaRecorder recorder, double fps) { recorder.setCaptureRate(fps); } @TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH) private void setRecordLocation() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { Location loc = mLocationManager.getCurrentLocation(); if (loc != null) { mMediaRecorder.setLocation((float) loc.getLatitude(), (float) loc.getLongitude()); } } } private void initializeEffectsPreview() { Log.v(TAG, "initializeEffectsPreview"); // If the mCameraDevice is null, then this activity is going to finish if (mActivity.mCameraDevice == null) return; boolean inLandscape = (mActivity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE); CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId]; mEffectsDisplayResult = false; mEffectsRecorder = new EffectsRecorder(mActivity); // TODO: Confirm none of the following need to go to initializeEffectsRecording() // and none of these change even when the preview is not refreshed. mEffectsRecorder.setCameraDisplayOrientation(mCameraDisplayOrientation); mEffectsRecorder.setCamera(mActivity.mCameraDevice); mEffectsRecorder.setCameraFacing(info.facing); mEffectsRecorder.setProfile(mProfile); mEffectsRecorder.setEffectsListener(this); mEffectsRecorder.setOnInfoListener(this); mEffectsRecorder.setOnErrorListener(this); // The input of effects recorder is affected by // android.hardware.Camera.setDisplayOrientation. Its value only // compensates the camera orientation (no Display.getRotation). So the // orientation hint here should only consider sensor orientation. int orientation = 0; if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) { orientation = mOrientation; } mEffectsRecorder.setOrientationHint(orientation); CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail; mEffectsRecorder.setPreviewSurfaceTexture(screenNail.getSurfaceTexture(), screenNail.getWidth(), screenNail.getHeight()); if (mEffectType == EffectsRecorder.EFFECT_BACKDROPPER && ((String) mEffectParameter).equals(EFFECT_BG_FROM_GALLERY)) { mEffectsRecorder.setEffect(mEffectType, mEffectUriFromGallery); } else { mEffectsRecorder.setEffect(mEffectType, mEffectParameter); } } private void initializeEffectsRecording() { Log.v(TAG, "initializeEffectsRecording"); Intent intent = mActivity.getIntent(); Bundle myExtras = intent.getExtras(); long requestedSizeLimit = 0; closeVideoFileDescriptor(); if (mIsVideoCaptureIntent && myExtras != null) { Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); if (saveUri != null) { try { mVideoFileDescriptor = mContentResolver.openFileDescriptor(saveUri, "rw"); mCurrentVideoUri = saveUri; } catch (java.io.FileNotFoundException ex) { // invalid uri Log.e(TAG, ex.toString()); } } requestedSizeLimit = myExtras.getLong(MediaStore.EXTRA_SIZE_LIMIT); } mEffectsRecorder.setProfile(mProfile); // important to set the capture rate to zero if not timelapsed, since the // effectsrecorder object does not get created again for each recording // session if (mCaptureTimeLapse) { mEffectsRecorder.setCaptureRate((1000 / (double) mTimeBetweenTimeLapseFrameCaptureMs)); } else { mEffectsRecorder.setCaptureRate(0); } // Set output file if (mVideoFileDescriptor != null) { mEffectsRecorder.setOutputFile(mVideoFileDescriptor.getFileDescriptor()); } else { generateVideoFilename(mProfile.fileFormat); mEffectsRecorder.setOutputFile(mVideoFilename); } // Set maximum file size. long maxFileSize = mActivity.getStorageSpace() - Storage.LOW_STORAGE_THRESHOLD; if (requestedSizeLimit > 0 && requestedSizeLimit < maxFileSize) { maxFileSize = requestedSizeLimit; } mEffectsRecorder.setMaxFileSize(maxFileSize); mEffectsRecorder.setMaxDuration(mMaxVideoDurationInMs); } private void releaseMediaRecorder() { Log.v(TAG, "Releasing media recorder."); if (mMediaRecorder != null) { cleanupEmptyFile(); mMediaRecorder.reset(); mMediaRecorder.release(); mMediaRecorder = null; } mVideoFilename = null; } private void releaseEffectsRecorder() { Log.v(TAG, "Releasing effects recorder."); if (mEffectsRecorder != null) { cleanupEmptyFile(); mEffectsRecorder.release(); mEffectsRecorder = null; } mEffectType = EffectsRecorder.EFFECT_NONE; mVideoFilename = null; } private void generateVideoFilename(int outputFileFormat) { long dateTaken = System.currentTimeMillis(); String title = createName(dateTaken); // Used when emailing. String filename = title + convertOutputFormatToFileExt(outputFileFormat); String mime = convertOutputFormatToMimeType(outputFileFormat); String path = Storage.getInstance().generateDirectory() + '/' + filename; String tmpPath = path + ".tmp"; mCurrentVideoValues = new ContentValues(9); mCurrentVideoValues.put(Video.Media.TITLE, title); mCurrentVideoValues.put(Video.Media.DISPLAY_NAME, filename); mCurrentVideoValues.put(Video.Media.DATE_TAKEN, dateTaken); mCurrentVideoValues.put(MediaColumns.DATE_MODIFIED, dateTaken / 1000); mCurrentVideoValues.put(Video.Media.MIME_TYPE, mime); mCurrentVideoValues.put(Video.Media.DATA, path); mCurrentVideoValues.put(Video.Media.RESOLUTION, Integer.toString(mProfile.videoFrameWidth) + "x" + Integer.toString(mProfile.videoFrameHeight)); Location loc = mLocationManager.getCurrentLocation(); if (loc != null) { mCurrentVideoValues.put(Video.Media.LATITUDE, loc.getLatitude()); mCurrentVideoValues.put(Video.Media.LONGITUDE, loc.getLongitude()); } mVideoFilename = tmpPath; Log.v(TAG, "New video filename: " + mVideoFilename); } private void saveVideo() { if (mVideoFileDescriptor == null) { long duration = SystemClock.uptimeMillis() - mRecordingStartTime + mRecordingTotalTime; if (duration > 0) { if (mCaptureTimeLapse) { duration = getTimeLapseVideoLength(duration); } } else { Log.w(TAG, "Video duration <= 0 : " + duration); } mActivity.getMediaSaveService().addVideo(mCurrentVideoFilename, duration, mCurrentVideoValues, mOnVideoSavedListener, mContentResolver); } mCurrentVideoValues = null; } private void deleteVideoFile(String fileName) { Log.v(TAG, "Deleting video " + fileName); File f = new File(fileName); if (!f.delete()) { Log.v(TAG, "Could not delete " + fileName); } } private PreferenceGroup filterPreferenceScreenByIntent( PreferenceGroup screen) { Intent intent = mActivity.getIntent(); if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) { CameraSettings.removePreferenceFromScreen(screen, CameraSettings.KEY_VIDEO_QUALITY); } if (intent.hasExtra(MediaStore.EXTRA_DURATION_LIMIT)) { CameraSettings.removePreferenceFromScreen(screen, CameraSettings.KEY_VIDEO_QUALITY); } return screen; } // from MediaRecorder.OnErrorListener @Override public void onError(MediaRecorder mr, int what, int extra) { Log.e(TAG, "MediaRecorder error. what=" + what + ". extra=" + extra); stopVideoRecording(); if (what == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) { // We may have run out of space on the sdcard. mActivity.updateStorageSpaceAndHint(); } } // from MediaRecorder.OnInfoListener @Override public void onInfo(MediaRecorder mr, int what, int extra) { if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) { if (mMediaRecorderRecording) onStopVideoRecording(); } else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) { if (mMediaRecorderRecording) onStopVideoRecording(); // Show the toast. Toast.makeText(mActivity, R.string.video_reach_size_limit, Toast.LENGTH_LONG).show(); } } /* * Make sure we're not recording music playing in the background, ask the * MediaPlaybackService to pause playback. */ private void pauseAudioPlayback() { // Shamelessly copied from MediaPlaybackService.java, which // should be public, but isn't. Intent i = new Intent("com.android.music.musicservicecommand"); i.putExtra("command", "pause"); mActivity.sendBroadcast(i); } // For testing. public boolean isRecording() { return mMediaRecorderRecording; } private void startVideoRecording() { Log.v(TAG, "startVideoRecording"); mActivity.updateStorageSpaceAndHint(); if (mActivity.getStorageSpace() <= Storage.LOW_STORAGE_THRESHOLD) { Log.v(TAG, "Storage issue, ignore the start request"); return; } if (!mActivity.mCameraDevice.waitDone()) return; mCurrentVideoUri = null; if (effectsActive()) { initializeEffectsRecording(); if (mEffectsRecorder == null) { Log.e(TAG, "Fail to initialize effect recorder"); return; } } else { initializeRecorder(); if (mMediaRecorder == null) { Log.e(TAG, "Fail to initialize media recorder"); return; } } pauseAudioPlayback(); if (effectsActive()) { try { mEffectsRecorder.startRecording(); } catch (RuntimeException e) { Log.e(TAG, "Could not start effects recorder. ", e); releaseEffectsRecorder(); return; } } else { try { mMediaRecorder.start(); // Recording is now started } catch (RuntimeException e) { Log.e(TAG, "Could not start media recorder. ", e); releaseMediaRecorder(); // If start fails, frameworks will not lock the camera for us. mActivity.mCameraDevice.lock(); return; } } mUI.enablePreviewThumb(false); mActivity.setSwipingEnabled(false); // Make sure the video recording has started before announcing // this in accessibility. AccessibilityUtils.makeAnnouncement(mActivity.getShutterButton(), mActivity.getString(R.string.video_recording_started)); // The parameters might have been altered by MediaRecorder already. // We need to force mCameraDevice to refresh before getting it. mActivity.mCameraDevice.refreshParameters(); // The parameters may have been changed by MediaRecorder upon starting // recording. We need to alter the parameters if we support camcorder // zoom. To reduce latency when setting the parameters during zoom, we // update mParameters here once. if (ApiHelper.HAS_ZOOM_WHEN_RECORDING) { mParameters = mActivity.mCameraDevice.getParameters(); } mUI.enableCameraControls(false); mMediaRecorderRecording = true; mMediaRecorderPausing = false; mUI.resetPauseButton(); if (!Util.systemRotationLocked(mActivity)) { mActivity.getOrientationManager().lockOrientation(); } mRecordingTotalTime = 0L; mRecordingStartTime = SystemClock.uptimeMillis(); mUI.showRecordingUI(true, mParameters.isZoomSupported()); updateRecordingTime(); keepScreenOn(); UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA, UsageStatistics.ACTION_CAPTURE_START, "Video"); } private void showCaptureResult() { mIsInReviewMode = true; Bitmap bitmap = null; if (mVideoFileDescriptor != null) { bitmap = Thumbnail.createVideoThumbnailBitmap(mVideoFileDescriptor.getFileDescriptor(), mDesiredPreviewWidth); } else if (mCurrentVideoFilename != null) { bitmap = Thumbnail.createVideoThumbnailBitmap(mCurrentVideoFilename, mDesiredPreviewWidth); } if (bitmap != null) { // MetadataRetriever already rotates the thumbnail. We should rotate // it to match the UI orientation (and mirror if it is front-facing camera). CameraInfo[] info = CameraHolder.instance().getCameraInfo(); boolean mirror = (info[mCameraId].facing == CameraInfo.CAMERA_FACING_FRONT); bitmap = Util.rotateAndMirror(bitmap, 0, mirror); mUI.showReviewImage(bitmap); } mUI.showReviewControls(); mUI.enableCameraControls(false); mUI.showTimeLapseUI(false); } private void hideAlert() { mUI.enableCameraControls(true); mUI.hideReviewUI(); if (mCaptureTimeLapse) { mUI.showTimeLapseUI(true); } } private void pauseVideoRecording() { Log.v(TAG, "pauseVideoRecording"); mMediaRecorderPausing = true; mRecordingTotalTime += SystemClock.uptimeMillis() - mRecordingStartTime; mMediaRecorder.pause(); } private void resumeVideoRecording() { Log.v(TAG, "resumeVideoRecording"); mMediaRecorderPausing = false; mRecordingStartTime = SystemClock.uptimeMillis(); updateRecordingTime(); mMediaRecorder.start(); } private boolean stopVideoRecording() { Log.v(TAG, "stopVideoRecording"); mActivity.setSwipingEnabled(true); mActivity.showSwitcher(); boolean fail = false; if (mMediaRecorderRecording) { boolean shouldAddToMediaStoreNow = false; try { if (effectsActive()) { // This is asynchronous, so we can't add to media store now because thumbnail // may not be ready. In such case saveVideo() is called later // through a callback from the MediaEncoderFilter to EffectsRecorder, // and then to the VideoModule. mEffectsRecorder.stopRecording(); } else { mMediaRecorder.setOnErrorListener(null); mMediaRecorder.setOnInfoListener(null); mMediaRecorder.stop(); shouldAddToMediaStoreNow = true; } mCurrentVideoFilename = mVideoFilename; Log.v(TAG, "stopVideoRecording: Setting current video filename: " + mCurrentVideoFilename); AccessibilityUtils.makeAnnouncement(mActivity.getShutterButton(), mActivity.getString(R.string.video_recording_stopped)); } catch (RuntimeException e) { Log.e(TAG, "stop fail", e); if (mVideoFilename != null) deleteVideoFile(mVideoFilename); fail = true; } mMediaRecorderRecording = false; if (!Util.systemRotationLocked(mActivity)) { mActivity.getOrientationManager().unlockOrientation(); } // If the activity is paused, this means activity is interrupted // during recording. Release the camera as soon as possible because // face unlock or other applications may need to use the camera. // However, if the effects are active, then we can only release the // camera and cannot release the effects recorder since that will // stop the graph. It is possible to separate out the Camera release // part and the effects release part. However, the effects recorder // does hold on to the camera, hence, it needs to be "disconnected" // from the camera in the closeCamera call. if (mPaused) { // Closing only the camera part if effects active. Effects will // be closed in the callback from effects. boolean closeEffects = !effectsActive(); closeCamera(closeEffects); } mUI.showRecordingUI(false, mParameters.isZoomSupported()); if (!mIsVideoCaptureIntent) { mUI.enableCameraControls(true); } // The orientation was fixed during video recording. Now make it // reflect the device orientation as video recording is stopped. mUI.setOrientationIndicator(0, true); keepScreenOnAwhile(); if (shouldAddToMediaStoreNow) { saveVideo(); } } // always release media recorder if no effects running if (!effectsActive()) { releaseMediaRecorder(); if (!mPaused) { mActivity.mCameraDevice.lock(); mActivity.mCameraDevice.waitDone(); if ((ApiHelper.HAS_SURFACE_TEXTURE && !ApiHelper.HAS_SURFACE_TEXTURE_RECORDING)) { stopPreview(); // Switch back to use SurfaceTexture for preview. ((CameraScreenNail) mActivity.mCameraScreenNail).setOneTimeOnFrameDrawnListener( mFrameDrawnListener); startPreview(); } } } // Update the parameters here because the parameters might have been altered // by MediaRecorder. if (!mPaused) mParameters = mActivity.mCameraDevice.getParameters(); UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA, fail ? UsageStatistics.ACTION_CAPTURE_FAIL : UsageStatistics.ACTION_CAPTURE_DONE, "Video", SystemClock.uptimeMillis() - mRecordingStartTime + mRecordingTotalTime); return fail; } private void resetScreenOn() { mHandler.removeMessages(CLEAR_SCREEN_DELAY); mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } private void keepScreenOnAwhile() { mHandler.removeMessages(CLEAR_SCREEN_DELAY); mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); } private void keepScreenOn() { mHandler.removeMessages(CLEAR_SCREEN_DELAY); mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } private static String millisecondToTimeString(long milliSeconds, boolean displayCentiSeconds) { long seconds = milliSeconds / 1000; // round down to compute seconds long minutes = seconds / 60; long hours = minutes / 60; long remainderMinutes = minutes - (hours * 60); long remainderSeconds = seconds - (minutes * 60); StringBuilder timeStringBuilder = new StringBuilder(); // Hours if (hours > 0) { if (hours < 10) { timeStringBuilder.append('0'); } timeStringBuilder.append(hours); timeStringBuilder.append(':'); } // Minutes if (remainderMinutes < 10) { timeStringBuilder.append('0'); } timeStringBuilder.append(remainderMinutes); timeStringBuilder.append(':'); // Seconds if (remainderSeconds < 10) { timeStringBuilder.append('0'); } timeStringBuilder.append(remainderSeconds); // Centi seconds if (displayCentiSeconds) { timeStringBuilder.append('.'); long remainderCentiSeconds = (milliSeconds - seconds * 1000) / 10; if (remainderCentiSeconds < 10) { timeStringBuilder.append('0'); } timeStringBuilder.append(remainderCentiSeconds); } return timeStringBuilder.toString(); } private long getTimeLapseVideoLength(long deltaMs) { // For better approximation calculate fractional number of frames captured. // This will update the video time at a higher resolution. double numberOfFrames = (double) deltaMs / mTimeBetweenTimeLapseFrameCaptureMs; return (long) (numberOfFrames / mProfile.videoFrameRate * 1000); } private void updateRecordingTime() { if (!mMediaRecorderRecording) { return; } if (mMediaRecorderPausing) { return; } long now = SystemClock.uptimeMillis(); long delta = now - mRecordingStartTime + mRecordingTotalTime; // Starting a minute before reaching the max duration // limit, we'll countdown the remaining time instead. boolean countdownRemainingTime = (mMaxVideoDurationInMs != 0 && delta >= mMaxVideoDurationInMs - 60000); long deltaAdjusted = delta; if (countdownRemainingTime) { deltaAdjusted = Math.max(0, mMaxVideoDurationInMs - deltaAdjusted) + 999; } String text; long targetNextUpdateDelay; if (!mCaptureTimeLapse) { text = millisecondToTimeString(deltaAdjusted, false); targetNextUpdateDelay = 1000; } else { // The length of time lapse video is different from the length // of the actual wall clock time elapsed. Display the video length // only in format hh:mm:ss.dd, where dd are the centi seconds. text = millisecondToTimeString(getTimeLapseVideoLength(delta), true); targetNextUpdateDelay = mTimeBetweenTimeLapseFrameCaptureMs; } mUI.setRecordingTime(text); if (mRecordingTimeCountsDown != countdownRemainingTime) { // Avoid setting the color on every update, do it only // when it needs changing. mRecordingTimeCountsDown = countdownRemainingTime; int color = mActivity.getResources().getColor(countdownRemainingTime ? R.color.recording_time_remaining_text : R.color.recording_time_elapsed_text); mUI.setRecordingTimeTextColor(color); } long actualNextUpdateDelay = targetNextUpdateDelay - (delta % targetNextUpdateDelay); mHandler.sendEmptyMessageDelayed( UPDATE_RECORD_TIME, actualNextUpdateDelay); } private static boolean isSupported(String value, List<String> supported) { return supported == null ? false : supported.indexOf(value) >= 0; } @SuppressWarnings("deprecation") private void setCameraParameters() { mParameters.setPreviewSize(mDesiredPreviewWidth, mDesiredPreviewHeight); mParameters.setPreviewFrameRate(mProfile.videoFrameRate); // Set video size before recording starts CameraSettings.setEarlyVideoSize(mParameters, mProfile); // Set video mode CameraSettings.setVideoMode(mParameters, true); // Reduce purple noise CameraSettings.setReducePurple(mParameters, true); // Set flash mode. String flashMode; if (mActivity.mShowCameraAppView) { flashMode = mPreferences.getString( CameraSettings.KEY_VIDEOCAMERA_FLASH_MODE, mActivity.getString(R.string.pref_camera_video_flashmode_default)); } else { flashMode = Parameters.FLASH_MODE_OFF; } List<String> supportedFlash = mParameters.getSupportedFlashModes(); if (isSupported(flashMode, supportedFlash)) { mParameters.setFlashMode(flashMode); } else { flashMode = mParameters.getFlashMode(); if (flashMode == null) { flashMode = mActivity.getString( R.string.pref_camera_flashmode_no_flash); } } // Set white balance parameter. String whiteBalance = mPreferences.getString( CameraSettings.KEY_WHITE_BALANCE, mActivity.getString(R.string.pref_camera_whitebalance_default)); if (isSupported(whiteBalance, mParameters.getSupportedWhiteBalance())) { mParameters.setWhiteBalance(whiteBalance); } else { whiteBalance = mParameters.getWhiteBalance(); if (whiteBalance == null) { whiteBalance = Parameters.WHITE_BALANCE_AUTO; } } // Set zoom. if (mParameters.isZoomSupported()) { mParameters.setZoom(mZoomValue); } // Set continuous autofocus. List<String> supportedFocus = mParameters.getSupportedFocusModes(); if (isSupported(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO, supportedFocus)) { mParameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO); } mParameters.set(Util.RECORDING_HINT, Util.TRUE); // Enable video stabilization. Convenience methods not available in API // level <= 14 String vstabSupported = mParameters.get("video-stabilization-supported"); if ("true".equals(vstabSupported)) { mParameters.set("video-stabilization", "true"); } // Set picture size. // The logic here is different from the logic in still-mode camera. // There we determine the preview size based on the picture size, but // here we determine the picture size based on the preview size. if (!mActivity.getResources().getBoolean(R.bool.useVideoSnapshotWorkaround)) { List<Size> supported = mParameters.getSupportedPictureSizes(); Size optimalSize = Util.getOptimalVideoSnapshotPictureSize(supported, (double) mDesiredPreviewWidth / mDesiredPreviewHeight); Size original = mParameters.getPictureSize(); if (!original.equals(optimalSize)) { mParameters.setPictureSize(optimalSize.width, optimalSize.height); } Log.v(TAG, "Video snapshot size is " + optimalSize.width + "x" + optimalSize.height); } else { // At least one device will get bus overflows if we set this too high mParameters.setPictureSize(mProfile.videoFrameWidth, mProfile.videoFrameHeight); } // Set JPEG quality. int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId, CameraProfile.QUALITY_HIGH); mParameters.setJpegQuality(jpegQuality); // Enable HFR mode for WVGA List<String> hfrModes = mParameters.getSupportedVideoHighFrameRateModes(); - if (hfrModes.size() > 0) { + if (hfrModes != null) { mParameters.setVideoHighFrameRate(mEnableHFR ? hfrModes.get(hfrModes.size() - 1) : "off"); } // Set Video HDR. if (mActivity.getResources().getBoolean(R.bool.enableVideoHDR)) { String videoHDR = mPreferences.getString( CameraSettings.KEY_VIDEO_HDR, mActivity.getString(R.string.pref_camera_video_hdr_default)); Log.v(TAG, "Video HDR Setting =" + videoHDR); if (isSupported(videoHDR, mParameters.getSupportedVideoHDRModes())) { mParameters.setVideoHDRMode(videoHDR); } else { mParameters.setVideoHDRMode("off"); } } Util.dumpParameters(mParameters); mActivity.mCameraDevice.setParameters(mParameters); // Keep preview size up to date. mParameters = mActivity.mCameraDevice.getParameters(); updateCameraScreenNailSize(mDesiredPreviewWidth, mDesiredPreviewHeight); CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail; int width = screenNail.getWidth(); int height = screenNail.getHeight(); mFocusManager.setPreviewSize(width, height); } private void updateCameraScreenNailSize(int width, int height) { if (!ApiHelper.HAS_SURFACE_TEXTURE) return; if (mCameraDisplayOrientation % 180 != 0) { int tmp = width; width = height; height = tmp; } CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail; int oldWidth = screenNail.getTextureWidth(); int oldHeight = screenNail.getTextureHeight(); if (oldWidth != width || oldHeight != height) { screenNail.setSize(width, height); screenNail.enableAspectRatioClamping(); mActivity.notifyScreenNailChanged(); } if (mStartPreviewThread == null && screenNail.getSurfaceTexture() == null) { screenNail.acquireSurfaceTexture(); } mFocusManager.setPreviewSize(width, height); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_EFFECT_BACKDROPPER: if (resultCode == Activity.RESULT_OK) { // onActivityResult() runs before onResume(), so this parameter will be // seen by startPreview from onResume() mEffectUriFromGallery = data.getData().toString(); Log.v(TAG, "Received URI from gallery: " + mEffectUriFromGallery); mResetEffect = false; } else { mEffectUriFromGallery = null; Log.w(TAG, "No URI from gallery"); mResetEffect = true; } break; } } @Override public void onEffectsUpdate(int effectId, int effectMsg) { Log.v(TAG, "onEffectsUpdate. Effect Message = " + effectMsg); if (effectMsg == EffectsRecorder.EFFECT_MSG_EFFECTS_STOPPED) { // Effects have shut down. Hide learning message if any, // and restart regular preview. checkQualityAndStartPreview(); } else if (effectMsg == EffectsRecorder.EFFECT_MSG_RECORDING_DONE) { // This follows the codepath from onStopVideoRecording. if (mEffectsDisplayResult) { saveVideo(); if (mIsVideoCaptureIntent) { if (mQuickCapture) { doReturnToCaller(true); } else { showCaptureResult(); } } } mEffectsDisplayResult = false; // In onPause, these were not called if the effects were active. We // had to wait till the effects recording is complete to do this. if (mPaused) { closeVideoFileDescriptor(); } } else if (effectMsg == EffectsRecorder.EFFECT_MSG_PREVIEW_RUNNING) { // Enable the shutter button once the preview is complete. mUI.enableShutter(true); } // In onPause, this was not called if the effects were active. We had to // wait till the effects completed to do this. if (mPaused) { Log.v(TAG, "OnEffectsUpdate: closing effects if activity paused"); closeEffects(); } } public void onCancelBgTraining(View v) { // Write default effect out to shared prefs writeDefaultEffectToPrefs(); // Tell VideoCamer to re-init based on new shared pref values. onSharedPreferenceChanged(); } @Override public synchronized void onEffectsError(Exception exception, String fileName) { // TODO: Eventually we may want to show the user an error dialog, and then restart the // camera and encoder gracefully. For now, we just delete the file and bail out. if (fileName != null && new File(fileName).exists()) { deleteVideoFile(fileName); } try { if (Class.forName("android.filterpacks.videosink.MediaRecorderStopException") .isInstance(exception)) { Log.w(TAG, "Problem recoding video file. Removing incomplete file."); return; } } catch (ClassNotFoundException ex) { Log.w(TAG, ex); } throw new RuntimeException("Error during recording!", exception); } @Override public void onConfigurationChanged(Configuration newConfig) { Log.v(TAG, "onConfigurationChanged"); setDisplayOrientation(); resizeForPreviewAspectRatio(); } @Override public void onOverriddenPreferencesClicked() { } @Override // TODO: Delete this after old camera code is removed public void onRestorePreferencesClicked() { } private boolean effectsActive() { return (mEffectType != EffectsRecorder.EFFECT_NONE); } @Override public void onSharedPreferenceChanged() { // ignore the events after "onPause()" or preview has not started yet if (mPaused) return; synchronized (mPreferences) { // If mCameraDevice is not ready then we can set the parameter in // startPreview(). if (mActivity.mCameraDevice == null) return; boolean recordLocation = RecordLocationPreference.get( mPreferences, mContentResolver); mLocationManager.recordLocation(recordLocation); // Check if the current effects selection has changed if (updateEffectSelection()) return; if (mActivity.setStoragePath(mPreferences)) { mActivity.updateStorageSpaceAndHint(); mActivity.reuseCameraScreenNail(!mIsVideoCaptureIntent); } readVideoPreferences(); mUI.showTimeLapseUI(mCaptureTimeLapse); // We need to restart the preview if preview size is changed. Size size = mParameters.getPreviewSize(); if (size.width != mDesiredPreviewWidth || size.height != mDesiredPreviewHeight || mProfile.videoFrameWidth != mVideoWidth || mProfile.videoFrameHeight != mVideoHeight) { if (!effectsActive()) { stopPreview(); } else { mEffectsRecorder.release(); mEffectsRecorder = null; } resizeForPreviewAspectRatio(); startPreview(); // Parameters will be set in startPreview(). } else { setCameraParameters(); } mUI.updateOnScreenIndicators(mParameters, mPreferences); } } protected void setCameraId(int cameraId) { ListPreference pref = mPreferenceGroup.findPreference(CameraSettings.KEY_CAMERA_ID); pref.setValue("" + cameraId); } private void switchCamera() { if (mPaused) return; Log.d(TAG, "Start to switch camera."); mCameraId = mPendingSwitchCameraId; mPendingSwitchCameraId = -1; setCameraId(mCameraId); closeCamera(); mUI.collapseCameraControls(); if (mFocusManager != null) mFocusManager.removeMessages(); // Restart the camera and initialize the UI. From onCreate. mPreferences.setLocalId(mActivity, mCameraId); CameraSettings.upgradeLocalPreferences(mPreferences.getLocal()); openCamera(); readVideoPreferences(); startPreview(); initializeVideoSnapshot(); resizeForPreviewAspectRatio(); initializeVideoControl(); CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId]; boolean mirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT); mParameters = mActivity.mCameraDevice.getParameters(); mFocusManager.setMirror(mirror); mFocusManager.setParameters(mParameters); mFocusAreaSupported = Util.isFocusAreaSupported(mParameters); mMeteringAreaSupported = Util.isMeteringAreaSupported(mParameters); // From onResume mUI.initializeZoom(mParameters); mUI.setOrientationIndicator(0, false); if (ApiHelper.HAS_SURFACE_TEXTURE) { // Start switch camera animation. Post a message because // onFrameAvailable from the old camera may already exist. mHandler.sendEmptyMessage(SWITCH_CAMERA_START_ANIMATION); } mUI.updateOnScreenIndicators(mParameters, mPreferences); } // Preview texture has been copied. Now camera can be released and the // animation can be started. @Override public void onPreviewTextureCopied() { mHandler.sendEmptyMessage(SWITCH_CAMERA); } @Override public void onCaptureTextureCopied() { } private boolean updateEffectSelection() { int previousEffectType = mEffectType; Object previousEffectParameter = mEffectParameter; mEffectType = CameraSettings.readEffectType(mPreferences); mEffectParameter = CameraSettings.readEffectParameter(mPreferences); if (mEffectType == previousEffectType) { if (mEffectType == EffectsRecorder.EFFECT_NONE) return false; if (mEffectParameter.equals(previousEffectParameter)) return false; } Log.v(TAG, "New effect selection: " + mPreferences.getString( CameraSettings.KEY_VIDEO_EFFECT, "none")); if (mEffectType == EffectsRecorder.EFFECT_NONE) { // Stop effects and return to normal preview mEffectsRecorder.stopPreview(); mPreviewing = false; return true; } if (mEffectType == EffectsRecorder.EFFECT_BACKDROPPER && ((String) mEffectParameter).equals(EFFECT_BG_FROM_GALLERY)) { // Request video from gallery to use for background Intent i = new Intent(Intent.ACTION_PICK); i.setDataAndType(Video.Media.EXTERNAL_CONTENT_URI, "video/*"); i.putExtra(Intent.EXTRA_LOCAL_ONLY, true); mActivity.startActivityForResult(i, REQUEST_EFFECT_BACKDROPPER); return true; } if (previousEffectType == EffectsRecorder.EFFECT_NONE) { // Stop regular preview and start effects. stopPreview(); checkQualityAndStartPreview(); } else { // Switch currently running effect mEffectsRecorder.setEffect(mEffectType, mEffectParameter); } return true; } // Verifies that the current preview view size is correct before starting // preview. If not, resets the surface texture and resizes the view. private void checkQualityAndStartPreview() { readVideoPreferences(); mUI.showTimeLapseUI(mCaptureTimeLapse); Size size = mParameters.getPreviewSize(); if (size.width != mDesiredPreviewWidth || size.height != mDesiredPreviewHeight) { resizeForPreviewAspectRatio(); } // Start up preview again startPreview(); } @Override public boolean dispatchTouchEvent(MotionEvent m) { if (mSwitchingCamera) return true; return mUI.dispatchTouchEvent(m); } private void initializeVideoSnapshot() { if (mParameters == null) return; if (Util.isVideoSnapshotSupported(mParameters) && !mIsVideoCaptureIntent) { mActivity.setSingleTapUpListener(mUI.getPreview()); // Show the tap to focus toast if this is the first start. if (mPreferences.getBoolean( CameraSettings.KEY_VIDEO_FIRST_USE_HINT_SHOWN, true)) { // Delay the toast for one second to wait for orientation. mHandler.sendEmptyMessageDelayed(SHOW_TAP_TO_SNAPSHOT_TOAST, 1000); } } else { mActivity.setSingleTapUpListener(null); } } void showVideoSnapshotUI(boolean enabled) { if (mParameters == null) return; if (Util.isVideoSnapshotSupported(mParameters) && !mIsVideoCaptureIntent) { if (ApiHelper.HAS_SURFACE_TEXTURE && enabled) { ((CameraScreenNail) mActivity.mCameraScreenNail).animateCapture(mDisplayRotation); } else { mUI.showPreviewBorder(enabled); } mUI.enableShutter(!enabled); } } @Override public void updateCameraAppView() { if (!mPreviewing || mParameters.getFlashMode() == null) return; // When going to and back from gallery, we need to turn off/on the flash. if (!mActivity.mShowCameraAppView) { if (mParameters.getFlashMode().equals(Parameters.FLASH_MODE_OFF)) { mRestoreFlash = false; return; } mRestoreFlash = true; setCameraParameters(); } else if (mRestoreFlash) { mRestoreFlash = false; setCameraParameters(); } } @Override public void onFullScreenChanged(boolean full) { mUI.onFullScreenChanged(full); if (ApiHelper.HAS_SURFACE_TEXTURE) { if (mActivity.mCameraScreenNail != null) { ((CameraScreenNail) mActivity.mCameraScreenNail).setFullScreen(full); } return; } } private final class JpegPictureCallback implements PictureCallback { Location mLocation; public JpegPictureCallback(Location loc) { mLocation = loc; } @Override public void onPictureTaken(byte [] jpegData, android.hardware.Camera camera) { Log.v(TAG, "onPictureTaken"); mSnapshotInProgress = false; showVideoSnapshotUI(false); storeImage(jpegData, mLocation); } } private void storeImage(final byte[] data, Location loc) { mParameters = mActivity.mCameraDevice.getParameters(); long dateTaken = System.currentTimeMillis(); String title = Util.createJpegName(dateTaken); ExifInterface exif = Exif.getExif(data); int orientation = Exif.getOrientation(exif); Size s = mParameters.getPictureSize(); mActivity.getMediaSaveService().addImage( data, title, dateTaken, loc, s.width, s.height, orientation, exif, mOnPhotoSavedListener, mContentResolver); } private boolean resetEffect() { if (mResetEffect) { String value = mPreferences.getString(CameraSettings.KEY_VIDEO_EFFECT, mPrefVideoEffectDefault); if (!mPrefVideoEffectDefault.equals(value)) { writeDefaultEffectToPrefs(); return true; } } mResetEffect = true; return false; } private String convertOutputFormatToMimeType(int outputFileFormat) { if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) { return "video/mp4"; } return "video/3gpp"; } private String convertOutputFormatToFileExt(int outputFileFormat) { if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) { return ".mp4"; } return ".3gp"; } private void closeVideoFileDescriptor() { if (mVideoFileDescriptor != null) { try { mVideoFileDescriptor.close(); } catch (IOException e) { Log.e(TAG, "Fail to close fd", e); } mVideoFileDescriptor = null; } } private void showTapToSnapshotToast() { new RotateTextToast(mActivity, R.string.video_snapshot_hint, 0) .show(); // Clear the preference. Editor editor = mPreferences.edit(); editor.putBoolean(CameraSettings.KEY_VIDEO_FIRST_USE_HINT_SHOWN, false); editor.apply(); } @Override public boolean updateStorageHintOnResume() { return true; } // required by OnPreferenceChangedListener @Override public void onCameraPickerClicked(int cameraId) { if (mPaused || mPendingSwitchCameraId != -1) return; mPendingSwitchCameraId = cameraId; if (ApiHelper.HAS_SURFACE_TEXTURE) { Log.d(TAG, "Start to copy texture."); // We need to keep a preview frame for the animation before // releasing the camera. This will trigger onPreviewTextureCopied. ((CameraScreenNail) mActivity.mCameraScreenNail).copyTexture(); } else { switchCamera(); } } @Override public void onCameraPickerSuperClicked() { if (mPaused || mPendingSwitchCameraId != -1) return; // Disable all camera controls. mSwitchingCamera = true; } @Override public boolean needsSwitcher() { return !mIsVideoCaptureIntent; } @Override public boolean needsPieMenu() { return true; } @Override public void onShowSwitcherPopup() { mUI.onShowSwitcherPopup(); } @Override public void onMediaSaveServiceConnected(MediaSaveService s) { // do nothing. } @Override public void onButtonPause() { pauseVideoRecording(); } @Override public void onButtonContinue() { resumeVideoRecording(); } }
true
true
private void setCameraParameters() { mParameters.setPreviewSize(mDesiredPreviewWidth, mDesiredPreviewHeight); mParameters.setPreviewFrameRate(mProfile.videoFrameRate); // Set video size before recording starts CameraSettings.setEarlyVideoSize(mParameters, mProfile); // Set video mode CameraSettings.setVideoMode(mParameters, true); // Reduce purple noise CameraSettings.setReducePurple(mParameters, true); // Set flash mode. String flashMode; if (mActivity.mShowCameraAppView) { flashMode = mPreferences.getString( CameraSettings.KEY_VIDEOCAMERA_FLASH_MODE, mActivity.getString(R.string.pref_camera_video_flashmode_default)); } else { flashMode = Parameters.FLASH_MODE_OFF; } List<String> supportedFlash = mParameters.getSupportedFlashModes(); if (isSupported(flashMode, supportedFlash)) { mParameters.setFlashMode(flashMode); } else { flashMode = mParameters.getFlashMode(); if (flashMode == null) { flashMode = mActivity.getString( R.string.pref_camera_flashmode_no_flash); } } // Set white balance parameter. String whiteBalance = mPreferences.getString( CameraSettings.KEY_WHITE_BALANCE, mActivity.getString(R.string.pref_camera_whitebalance_default)); if (isSupported(whiteBalance, mParameters.getSupportedWhiteBalance())) { mParameters.setWhiteBalance(whiteBalance); } else { whiteBalance = mParameters.getWhiteBalance(); if (whiteBalance == null) { whiteBalance = Parameters.WHITE_BALANCE_AUTO; } } // Set zoom. if (mParameters.isZoomSupported()) { mParameters.setZoom(mZoomValue); } // Set continuous autofocus. List<String> supportedFocus = mParameters.getSupportedFocusModes(); if (isSupported(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO, supportedFocus)) { mParameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO); } mParameters.set(Util.RECORDING_HINT, Util.TRUE); // Enable video stabilization. Convenience methods not available in API // level <= 14 String vstabSupported = mParameters.get("video-stabilization-supported"); if ("true".equals(vstabSupported)) { mParameters.set("video-stabilization", "true"); } // Set picture size. // The logic here is different from the logic in still-mode camera. // There we determine the preview size based on the picture size, but // here we determine the picture size based on the preview size. if (!mActivity.getResources().getBoolean(R.bool.useVideoSnapshotWorkaround)) { List<Size> supported = mParameters.getSupportedPictureSizes(); Size optimalSize = Util.getOptimalVideoSnapshotPictureSize(supported, (double) mDesiredPreviewWidth / mDesiredPreviewHeight); Size original = mParameters.getPictureSize(); if (!original.equals(optimalSize)) { mParameters.setPictureSize(optimalSize.width, optimalSize.height); } Log.v(TAG, "Video snapshot size is " + optimalSize.width + "x" + optimalSize.height); } else { // At least one device will get bus overflows if we set this too high mParameters.setPictureSize(mProfile.videoFrameWidth, mProfile.videoFrameHeight); } // Set JPEG quality. int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId, CameraProfile.QUALITY_HIGH); mParameters.setJpegQuality(jpegQuality); // Enable HFR mode for WVGA List<String> hfrModes = mParameters.getSupportedVideoHighFrameRateModes(); if (hfrModes.size() > 0) { mParameters.setVideoHighFrameRate(mEnableHFR ? hfrModes.get(hfrModes.size() - 1) : "off"); } // Set Video HDR. if (mActivity.getResources().getBoolean(R.bool.enableVideoHDR)) { String videoHDR = mPreferences.getString( CameraSettings.KEY_VIDEO_HDR, mActivity.getString(R.string.pref_camera_video_hdr_default)); Log.v(TAG, "Video HDR Setting =" + videoHDR); if (isSupported(videoHDR, mParameters.getSupportedVideoHDRModes())) { mParameters.setVideoHDRMode(videoHDR); } else { mParameters.setVideoHDRMode("off"); } } Util.dumpParameters(mParameters); mActivity.mCameraDevice.setParameters(mParameters); // Keep preview size up to date. mParameters = mActivity.mCameraDevice.getParameters(); updateCameraScreenNailSize(mDesiredPreviewWidth, mDesiredPreviewHeight); CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail; int width = screenNail.getWidth(); int height = screenNail.getHeight(); mFocusManager.setPreviewSize(width, height); }
private void setCameraParameters() { mParameters.setPreviewSize(mDesiredPreviewWidth, mDesiredPreviewHeight); mParameters.setPreviewFrameRate(mProfile.videoFrameRate); // Set video size before recording starts CameraSettings.setEarlyVideoSize(mParameters, mProfile); // Set video mode CameraSettings.setVideoMode(mParameters, true); // Reduce purple noise CameraSettings.setReducePurple(mParameters, true); // Set flash mode. String flashMode; if (mActivity.mShowCameraAppView) { flashMode = mPreferences.getString( CameraSettings.KEY_VIDEOCAMERA_FLASH_MODE, mActivity.getString(R.string.pref_camera_video_flashmode_default)); } else { flashMode = Parameters.FLASH_MODE_OFF; } List<String> supportedFlash = mParameters.getSupportedFlashModes(); if (isSupported(flashMode, supportedFlash)) { mParameters.setFlashMode(flashMode); } else { flashMode = mParameters.getFlashMode(); if (flashMode == null) { flashMode = mActivity.getString( R.string.pref_camera_flashmode_no_flash); } } // Set white balance parameter. String whiteBalance = mPreferences.getString( CameraSettings.KEY_WHITE_BALANCE, mActivity.getString(R.string.pref_camera_whitebalance_default)); if (isSupported(whiteBalance, mParameters.getSupportedWhiteBalance())) { mParameters.setWhiteBalance(whiteBalance); } else { whiteBalance = mParameters.getWhiteBalance(); if (whiteBalance == null) { whiteBalance = Parameters.WHITE_BALANCE_AUTO; } } // Set zoom. if (mParameters.isZoomSupported()) { mParameters.setZoom(mZoomValue); } // Set continuous autofocus. List<String> supportedFocus = mParameters.getSupportedFocusModes(); if (isSupported(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO, supportedFocus)) { mParameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO); } mParameters.set(Util.RECORDING_HINT, Util.TRUE); // Enable video stabilization. Convenience methods not available in API // level <= 14 String vstabSupported = mParameters.get("video-stabilization-supported"); if ("true".equals(vstabSupported)) { mParameters.set("video-stabilization", "true"); } // Set picture size. // The logic here is different from the logic in still-mode camera. // There we determine the preview size based on the picture size, but // here we determine the picture size based on the preview size. if (!mActivity.getResources().getBoolean(R.bool.useVideoSnapshotWorkaround)) { List<Size> supported = mParameters.getSupportedPictureSizes(); Size optimalSize = Util.getOptimalVideoSnapshotPictureSize(supported, (double) mDesiredPreviewWidth / mDesiredPreviewHeight); Size original = mParameters.getPictureSize(); if (!original.equals(optimalSize)) { mParameters.setPictureSize(optimalSize.width, optimalSize.height); } Log.v(TAG, "Video snapshot size is " + optimalSize.width + "x" + optimalSize.height); } else { // At least one device will get bus overflows if we set this too high mParameters.setPictureSize(mProfile.videoFrameWidth, mProfile.videoFrameHeight); } // Set JPEG quality. int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId, CameraProfile.QUALITY_HIGH); mParameters.setJpegQuality(jpegQuality); // Enable HFR mode for WVGA List<String> hfrModes = mParameters.getSupportedVideoHighFrameRateModes(); if (hfrModes != null) { mParameters.setVideoHighFrameRate(mEnableHFR ? hfrModes.get(hfrModes.size() - 1) : "off"); } // Set Video HDR. if (mActivity.getResources().getBoolean(R.bool.enableVideoHDR)) { String videoHDR = mPreferences.getString( CameraSettings.KEY_VIDEO_HDR, mActivity.getString(R.string.pref_camera_video_hdr_default)); Log.v(TAG, "Video HDR Setting =" + videoHDR); if (isSupported(videoHDR, mParameters.getSupportedVideoHDRModes())) { mParameters.setVideoHDRMode(videoHDR); } else { mParameters.setVideoHDRMode("off"); } } Util.dumpParameters(mParameters); mActivity.mCameraDevice.setParameters(mParameters); // Keep preview size up to date. mParameters = mActivity.mCameraDevice.getParameters(); updateCameraScreenNailSize(mDesiredPreviewWidth, mDesiredPreviewHeight); CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail; int width = screenNail.getWidth(); int height = screenNail.getHeight(); mFocusManager.setPreviewSize(width, height); }
diff --git a/org.emftext.sdk.codegen/src/org/emftext/sdk/codegen/generators/ui/BackgroundParsingStrategyGenerator.java b/org.emftext.sdk.codegen/src/org/emftext/sdk/codegen/generators/ui/BackgroundParsingStrategyGenerator.java index db5f17815..45adbdaab 100644 --- a/org.emftext.sdk.codegen/src/org/emftext/sdk/codegen/generators/ui/BackgroundParsingStrategyGenerator.java +++ b/org.emftext.sdk.codegen/src/org/emftext/sdk/codegen/generators/ui/BackgroundParsingStrategyGenerator.java @@ -1,115 +1,121 @@ package org.emftext.sdk.codegen.generators.ui; import static org.emftext.sdk.codegen.generators.IClassNameConstants.BYTE_ARRAY_INPUT_STREAM; import static org.emftext.sdk.codegen.generators.IClassNameConstants.DOCUMENT_EVENT; import static org.emftext.sdk.codegen.generators.IClassNameConstants.IO_EXCEPTION; import static org.emftext.sdk.codegen.generators.IClassNameConstants.I_PROGRESS_MONITOR; import static org.emftext.sdk.codegen.generators.IClassNameConstants.JOB; import static org.emftext.sdk.codegen.generators.IClassNameConstants.STATUS; import static org.emftext.sdk.codegen.generators.IClassNameConstants.I_STATUS; import java.io.PrintWriter; import org.emftext.sdk.codegen.EArtifact; import org.emftext.sdk.codegen.GenerationContext; import org.emftext.sdk.codegen.IGenerator; import org.emftext.sdk.codegen.generators.BaseGenerator; public class BackgroundParsingStrategyGenerator extends BaseGenerator { private String editorClassName; public BackgroundParsingStrategyGenerator() { super(); } private BackgroundParsingStrategyGenerator(GenerationContext context) { super(context, EArtifact.BACKGROUND_PARSING_STRATEGY); editorClassName = context.getQualifiedClassName(EArtifact.EDITOR); } public boolean generate(PrintWriter out) { org.emftext.sdk.codegen.composites.StringComposite sc = new org.emftext.sdk.codegen.composites.JavaComposite(); sc.add("package " + getResourcePackageName() + ";"); sc.addLineBreak(); sc.add("// A background parsing strategy that starts parsing after a amount of"); sc.add("// time after the last key stroke. If keys are pressed within the delay"); sc.add("// interval, the delay is reset. If keys are pressed during background"); sc.add("// parsing the parse thread is stopped and a new parse task is scheduled."); sc.add("public class " + getResourceClassName() + " {"); sc.addLineBreak(); addFields(sc); addParseMethod(sc); addCancelMethod(sc); sc.add("}"); out.print(sc.toString()); return true; } private void addCancelMethod( org.emftext.sdk.codegen.composites.StringComposite sc) { sc.add("protected void canceling() {"); sc.add("resource.cancelReload();"); sc.add("}"); sc.add("};"); sc.add("job.schedule(DELAY);"); sc.add("}"); sc.add("}"); } private void addParseMethod( org.emftext.sdk.codegen.composites.StringComposite sc) { sc.add("// Schedules a task for background parsing that will be started after"); sc.add("// a delay."); sc.add("public void parse(" + DOCUMENT_EVENT + " event, final " + getClassNameHelper().getI_TEXT_RESOURCE() + " resource, final " + editorClassName + " editor) {"); + sc.add("if (resource == null) {"); + sc.add("return;"); + sc.add("}"); sc.add("final String contents = event.getDocument().get();"); + sc.add("if (contents == null) {"); + sc.add("return;"); + sc.add("}"); sc.addLineBreak(); sc.add("// this synchronization is needed to avoid the creation"); sc.add("// of multiple tasks. without the synchronization this"); sc.add("// could easily happen, when this method is accessed by"); sc.add("// multiple threads. the creation of multiple task would"); sc.add("// imply the multiple background parsing threads for one"); sc.add("// editor are created, which is not desired."); sc.add("synchronized (lock) {"); sc.add("// cancel old task"); sc.add("if (job != null) {"); sc.add("// stop current parser (if there is one)"); sc.add("job.cancel();"); sc.add("try {"); sc.add("job.join();"); sc.add("} catch (InterruptedException e) {}"); sc.add("}"); sc.addLineBreak(); sc.add("// schedule new task"); sc.add("job = new " + JOB + "(\"parsing document\") {"); sc.addLineBreak(); sc.add("protected " + I_STATUS + " run(" + I_PROGRESS_MONITOR + " monitor) {"); sc.add("try {"); sc.add("resource.reload(new " + BYTE_ARRAY_INPUT_STREAM + "(contents.getBytes()), null);"); sc.add("} catch (" + IO_EXCEPTION + " e) {"); sc.add("e.printStackTrace();"); sc.add("}"); sc.add("editor.notifyBackgroundParsingFinished();"); sc.add("return " + STATUS + ".OK_STATUS;"); sc.add("}"); sc.addLineBreak(); } private void addFields(org.emftext.sdk.codegen.composites.StringComposite sc) { sc.add("private static long DELAY = 500;"); sc.addLineBreak(); sc.add("// this timer is used to schedule a parsing task and execute"); sc.add("// it after a given delay"); sc.add("private Object lock = new Object();"); sc.add("// the background parsing task (may be null)"); sc.add("private " + JOB + " job;"); sc.addLineBreak(); } public IGenerator newInstance(GenerationContext context) { return new BackgroundParsingStrategyGenerator(context); } }
false
true
private void addParseMethod( org.emftext.sdk.codegen.composites.StringComposite sc) { sc.add("// Schedules a task for background parsing that will be started after"); sc.add("// a delay."); sc.add("public void parse(" + DOCUMENT_EVENT + " event, final " + getClassNameHelper().getI_TEXT_RESOURCE() + " resource, final " + editorClassName + " editor) {"); sc.add("final String contents = event.getDocument().get();"); sc.addLineBreak(); sc.add("// this synchronization is needed to avoid the creation"); sc.add("// of multiple tasks. without the synchronization this"); sc.add("// could easily happen, when this method is accessed by"); sc.add("// multiple threads. the creation of multiple task would"); sc.add("// imply the multiple background parsing threads for one"); sc.add("// editor are created, which is not desired."); sc.add("synchronized (lock) {"); sc.add("// cancel old task"); sc.add("if (job != null) {"); sc.add("// stop current parser (if there is one)"); sc.add("job.cancel();"); sc.add("try {"); sc.add("job.join();"); sc.add("} catch (InterruptedException e) {}"); sc.add("}"); sc.addLineBreak(); sc.add("// schedule new task"); sc.add("job = new " + JOB + "(\"parsing document\") {"); sc.addLineBreak(); sc.add("protected " + I_STATUS + " run(" + I_PROGRESS_MONITOR + " monitor) {"); sc.add("try {"); sc.add("resource.reload(new " + BYTE_ARRAY_INPUT_STREAM + "(contents.getBytes()), null);"); sc.add("} catch (" + IO_EXCEPTION + " e) {"); sc.add("e.printStackTrace();"); sc.add("}"); sc.add("editor.notifyBackgroundParsingFinished();"); sc.add("return " + STATUS + ".OK_STATUS;"); sc.add("}"); sc.addLineBreak(); }
private void addParseMethod( org.emftext.sdk.codegen.composites.StringComposite sc) { sc.add("// Schedules a task for background parsing that will be started after"); sc.add("// a delay."); sc.add("public void parse(" + DOCUMENT_EVENT + " event, final " + getClassNameHelper().getI_TEXT_RESOURCE() + " resource, final " + editorClassName + " editor) {"); sc.add("if (resource == null) {"); sc.add("return;"); sc.add("}"); sc.add("final String contents = event.getDocument().get();"); sc.add("if (contents == null) {"); sc.add("return;"); sc.add("}"); sc.addLineBreak(); sc.add("// this synchronization is needed to avoid the creation"); sc.add("// of multiple tasks. without the synchronization this"); sc.add("// could easily happen, when this method is accessed by"); sc.add("// multiple threads. the creation of multiple task would"); sc.add("// imply the multiple background parsing threads for one"); sc.add("// editor are created, which is not desired."); sc.add("synchronized (lock) {"); sc.add("// cancel old task"); sc.add("if (job != null) {"); sc.add("// stop current parser (if there is one)"); sc.add("job.cancel();"); sc.add("try {"); sc.add("job.join();"); sc.add("} catch (InterruptedException e) {}"); sc.add("}"); sc.addLineBreak(); sc.add("// schedule new task"); sc.add("job = new " + JOB + "(\"parsing document\") {"); sc.addLineBreak(); sc.add("protected " + I_STATUS + " run(" + I_PROGRESS_MONITOR + " monitor) {"); sc.add("try {"); sc.add("resource.reload(new " + BYTE_ARRAY_INPUT_STREAM + "(contents.getBytes()), null);"); sc.add("} catch (" + IO_EXCEPTION + " e) {"); sc.add("e.printStackTrace();"); sc.add("}"); sc.add("editor.notifyBackgroundParsingFinished();"); sc.add("return " + STATUS + ".OK_STATUS;"); sc.add("}"); sc.addLineBreak(); }
diff --git a/src/haven/Equipory.java b/src/haven/Equipory.java index 29caadd..9951c85 100644 --- a/src/haven/Equipory.java +++ b/src/haven/Equipory.java @@ -1,127 +1,127 @@ package haven; import java.util.*; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.Reader; public class Equipory extends Window implements DTarget { List<Inventory> epoints; List<Item> equed; static final Tex bg = Resource.loadtex("gfx/hud/equip/bg"); int avagob = -1; static Coord ecoords[] = { new Coord(0, 0), new Coord(244, 0), new Coord(0, 31), new Coord(244, 31), new Coord(0, 62), new Coord(244, 62), new Coord(0, 93), new Coord(244, 93), new Coord(0, 124), new Coord(244, 124), new Coord(0, 155), new Coord(244, 155), new Coord(0, 186), new Coord(244, 186), new Coord(0, 217), new Coord(244, 217), }; static { Widget.addtype("epry", new WidgetFactory() { public Widget create(Coord c, Widget parent, Object[] args) { return(new Equipory(c, parent)); } }); } public Equipory(Coord c, Widget parent) { super(c, new Coord(0, 0), parent, "Equipment"); epoints = new ArrayList<Inventory>(); equed = new ArrayList<Item>(ecoords.length); //new Img(new Coord(32, 0), bg, this); for(int i = 0; i < ecoords.length; i++) { epoints.add(new Inventory(ecoords[i], new Coord(1, 1), this)); equed.add(null); } pack(); } public void uimsg(String msg, Object... args) { if(msg == "set") { synchronized(ui) { int i = 0, o = 0; while(i < equed.size()) { if(equed.get(i) != null) equed.get(i).unlink(); int res = (Integer)args[o++]; if(res >= 0) { Item ni = new Item(Coord.z, res, epoints.get(i), null); equed.set(i++, ni); - if(args[o] instanceof String) + if((o < args.length) && (args[o] instanceof String)) ni.tooltip = (String)args[o++]; } else { equed.set(i++, null); } } } } else if(msg == "setres") { int i = (Integer)args[0]; Indir<Resource> res = ui.sess.getres((Integer)args[1]); equed.get(i).chres(res); } else if(msg == "settt") { int i = (Integer)args[0]; String tt = (String)args[1]; equed.get(i).tooltip = tt; } else if(msg == "ava") { avagob = (Integer)args[0]; } } public void wdgmsg(Widget sender, String msg, Object... args) { int ep; if((ep = epoints.indexOf(sender)) != -1) { if(msg == "drop") { wdgmsg("drop", ep); return; } } if((ep = equed.indexOf(sender)) != -1) { if(msg == "take") wdgmsg("take", ep, args[0]); else if(msg == "itemact") wdgmsg("itemact", ep); else if(msg == "transfer") wdgmsg("transfer", ep, args[0]); else if(msg == "iact") wdgmsg("iact", ep, args[0]); return; } super.wdgmsg(sender, msg, args); } public boolean drop(Coord cc, Coord ul) { wdgmsg("drop", -1); return(true); } public boolean iteminteract(Coord cc, Coord ul) { return(false); } public void cdraw(GOut g) { Coord avac = new Coord(32, 0); g.image(bg, avac); if(avagob != -1) { Gob gob = ui.sess.glob.oc.getgob(avagob); if(gob != null) { Avatar ava = gob.getattr(Avatar.class); if(ava != null) g.image(ava.rend.tex(), avac); } } } }
true
true
public void uimsg(String msg, Object... args) { if(msg == "set") { synchronized(ui) { int i = 0, o = 0; while(i < equed.size()) { if(equed.get(i) != null) equed.get(i).unlink(); int res = (Integer)args[o++]; if(res >= 0) { Item ni = new Item(Coord.z, res, epoints.get(i), null); equed.set(i++, ni); if(args[o] instanceof String) ni.tooltip = (String)args[o++]; } else { equed.set(i++, null); } } } } else if(msg == "setres") { int i = (Integer)args[0]; Indir<Resource> res = ui.sess.getres((Integer)args[1]); equed.get(i).chres(res); } else if(msg == "settt") { int i = (Integer)args[0]; String tt = (String)args[1]; equed.get(i).tooltip = tt; } else if(msg == "ava") { avagob = (Integer)args[0]; } }
public void uimsg(String msg, Object... args) { if(msg == "set") { synchronized(ui) { int i = 0, o = 0; while(i < equed.size()) { if(equed.get(i) != null) equed.get(i).unlink(); int res = (Integer)args[o++]; if(res >= 0) { Item ni = new Item(Coord.z, res, epoints.get(i), null); equed.set(i++, ni); if((o < args.length) && (args[o] instanceof String)) ni.tooltip = (String)args[o++]; } else { equed.set(i++, null); } } } } else if(msg == "setres") { int i = (Integer)args[0]; Indir<Resource> res = ui.sess.getres((Integer)args[1]); equed.get(i).chres(res); } else if(msg == "settt") { int i = (Integer)args[0]; String tt = (String)args[1]; equed.get(i).tooltip = tt; } else if(msg == "ava") { avagob = (Integer)args[0]; } }
diff --git a/src/com/btmura/android/reddit/app/ThingTableMenuController.java b/src/com/btmura/android/reddit/app/ThingTableMenuController.java index a6eb3a69..47875055 100644 --- a/src/com/btmura/android/reddit/app/ThingTableMenuController.java +++ b/src/com/btmura/android/reddit/app/ThingTableMenuController.java @@ -1,112 +1,114 @@ /* * Copyright (C) 2013 Brian Muramatsu * * 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.btmura.android.reddit.app; import android.content.Context; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.text.TextUtils; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.btmura.android.reddit.R; import com.btmura.android.reddit.accounts.AccountUtils; import com.btmura.android.reddit.database.Subreddits; class ThingTableMenuController implements MenuController { private final Context context; private final FragmentManager fragmentManager; private final String accountName; private final String subreddit; private final String query; private final ThingBundleHolder thingBundleHolder; ThingTableMenuController(Context context, FragmentManager fragmentManager, String accountName, String subreddit, String query, ThingBundleHolder thingBundleHolder) { this.context = context; this.fragmentManager = fragmentManager; this.accountName = accountName; this.subreddit = subreddit; this.query = query; this.thingBundleHolder = thingBundleHolder; } @Override public void restoreInstanceState(Bundle savedInstanceState) { // No state to restore } @Override public void saveInstanceState(Bundle outState) { // No state to save } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.thing_list_menu, menu); } @Override public void onPrepareOptionsMenu(Menu menu) { boolean isQuery = !TextUtils.isEmpty(query); boolean hasAccount = AccountUtils.isAccount(accountName); boolean hasSubreddit = subreddit != null; boolean hasThing = thingBundleHolder != null && thingBundleHolder.getThingBundle() != null; boolean hasSidebar = Subreddits.hasSidebar(subreddit); - boolean showNewPost = !isQuery && hasAccount && hasSubreddit && !hasThing; - boolean showAddSubreddit = !isQuery && hasSubreddit && !hasThing; - boolean showSubreddit = !isQuery && hasSubreddit && !hasThing && hasSidebar; + boolean showRefresh = !isQuery && hasSubreddit && !hasThing; + boolean showAddSubreddit = showRefresh; + boolean showNewPost = showRefresh && hasAccount; + boolean showSubreddit = showRefresh && hasSidebar; menu.findItem(R.id.menu_new_post).setVisible(showNewPost); + menu.findItem(R.id.menu_refresh).setVisible(showAddSubreddit); menu.findItem(R.id.menu_add_subreddit).setVisible(showAddSubreddit); MenuItem subredditItem = menu.findItem(R.id.menu_subreddit); subredditItem.setVisible(showSubreddit); if (showSubreddit) { subredditItem.setTitle(MenuHelper.getSubredditTitle(context, subreddit)); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_add_subreddit: handleAddSubreddit(); return true; case R.id.menu_subreddit: handleSubreddit(); return true; } return false; } private void handleAddSubreddit() { MenuHelper.showAddSubredditDialog(fragmentManager, subreddit); } private void handleSubreddit() { MenuHelper.startSidebarActivity(context, subreddit); } }
false
true
public void onPrepareOptionsMenu(Menu menu) { boolean isQuery = !TextUtils.isEmpty(query); boolean hasAccount = AccountUtils.isAccount(accountName); boolean hasSubreddit = subreddit != null; boolean hasThing = thingBundleHolder != null && thingBundleHolder.getThingBundle() != null; boolean hasSidebar = Subreddits.hasSidebar(subreddit); boolean showNewPost = !isQuery && hasAccount && hasSubreddit && !hasThing; boolean showAddSubreddit = !isQuery && hasSubreddit && !hasThing; boolean showSubreddit = !isQuery && hasSubreddit && !hasThing && hasSidebar; menu.findItem(R.id.menu_new_post).setVisible(showNewPost); menu.findItem(R.id.menu_add_subreddit).setVisible(showAddSubreddit); MenuItem subredditItem = menu.findItem(R.id.menu_subreddit); subredditItem.setVisible(showSubreddit); if (showSubreddit) { subredditItem.setTitle(MenuHelper.getSubredditTitle(context, subreddit)); } }
public void onPrepareOptionsMenu(Menu menu) { boolean isQuery = !TextUtils.isEmpty(query); boolean hasAccount = AccountUtils.isAccount(accountName); boolean hasSubreddit = subreddit != null; boolean hasThing = thingBundleHolder != null && thingBundleHolder.getThingBundle() != null; boolean hasSidebar = Subreddits.hasSidebar(subreddit); boolean showRefresh = !isQuery && hasSubreddit && !hasThing; boolean showAddSubreddit = showRefresh; boolean showNewPost = showRefresh && hasAccount; boolean showSubreddit = showRefresh && hasSidebar; menu.findItem(R.id.menu_new_post).setVisible(showNewPost); menu.findItem(R.id.menu_refresh).setVisible(showAddSubreddit); menu.findItem(R.id.menu_add_subreddit).setVisible(showAddSubreddit); MenuItem subredditItem = menu.findItem(R.id.menu_subreddit); subredditItem.setVisible(showSubreddit); if (showSubreddit) { subredditItem.setTitle(MenuHelper.getSubredditTitle(context, subreddit)); } }
diff --git a/ide/eclipse/appfactory/org.wso2.developerstudio.appfactory.core/src/org/wso2/developerstudio/appfactory/core/client/HttpsJaggeryClient.java b/ide/eclipse/appfactory/org.wso2.developerstudio.appfactory.core/src/org/wso2/developerstudio/appfactory/core/client/HttpsJaggeryClient.java index 9b952f731..8b7e1bde9 100644 --- a/ide/eclipse/appfactory/org.wso2.developerstudio.appfactory.core/src/org/wso2/developerstudio/appfactory/core/client/HttpsJaggeryClient.java +++ b/ide/eclipse/appfactory/org.wso2.developerstudio.appfactory.core/src/org/wso2/developerstudio/appfactory/core/client/HttpsJaggeryClient.java @@ -1,156 +1,159 @@ /* Copyright (c) WSO2 Inc. (http://www.wso2.org) 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. */ package org.wso2.developerstudio.appfactory.core.client; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.wso2.developerstudio.appfactory.core.Activator; import org.wso2.developerstudio.appfactory.core.authentication.Authenticator; import org.wso2.developerstudio.appfactory.core.model.ErrorType; import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog; import org.wso2.developerstudio.eclipse.logging.core.Logger; public class HttpsJaggeryClient { private static IDeveloperStudioLog log=Logger.getLog(Activator.PLUGIN_ID); private static HttpClient client; public static String httpPostLogin(String urlStr, Map<String,String> params){ client = new DefaultHttpClient(); client = HttpsJaggeryClient.wrapClient(client,urlStr); return httpPost(urlStr,params); } public static String httpPost(String urlStr, Map<String,String> params){ + if(client ==null){ + httpPostLogin(urlStr,params); + } HttpPost post = new HttpPost(urlStr); String respond = ""; HttpResponse response=null; try{ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); Set<String> keySet = params.keySet(); for (String key : keySet) { nameValuePairs.add(new BasicNameValuePair(key, params.get(key))); } post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); response = client.execute(post); if(200==response.getStatusLine().getStatusCode()){ HttpEntity entityGetAppsOfUser = response.getEntity(); BufferedReader rd = new BufferedReader(new InputStreamReader(entityGetAppsOfUser.getContent())); StringBuilder sb = new StringBuilder(); String line =""; while ((line = rd.readLine()) != null) { sb.append(line); } respond = sb.toString(); if("false".equals(respond)){ Authenticator.getInstance().setErrorcode(ErrorType.INVALID); } EntityUtils.consume(entityGetAppsOfUser); if (entityGetAppsOfUser != null) { entityGetAppsOfUser.getContent().close(); } }else{ Authenticator.getInstance().setErrorcode(ErrorType.FAILD); Authenticator.getInstance().setErrormsg(response.getStatusLine().getReasonPhrase()); log.error("("+response.getStatusLine().getStatusCode()+")"+ ":"+response.getStatusLine().getReasonPhrase()); return "false"; } }catch(Exception e){ Authenticator.getInstance().setErrorcode(ErrorType.ERROR); log.error("Connection failure",e); return "false"; } finally{ client.getConnectionManager().closeExpiredConnections(); } return respond; } @SuppressWarnings("deprecation") public static HttpClient wrapClient(HttpClient base,String urlStr) { try { SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[]{tm}, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = new ThreadSafeClientConnManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); URL url = new URL(urlStr); int port = url.getPort(); if(port==-1){ port=443; } String protocol = url.getProtocol(); if("https".equals(protocol)){ if(port==-1){ port=443; } }else if("http".equals(protocol)){ if(port==-1){ port=80; } } sr.register(new Scheme(protocol, ssf, port)); return new DefaultHttpClient(ccm, base.getParams()); } catch (Throwable ex) { ex.printStackTrace(); log.error("Trust Manager Error", ex); return null; } } }
true
true
public static String httpPost(String urlStr, Map<String,String> params){ HttpPost post = new HttpPost(urlStr); String respond = ""; HttpResponse response=null; try{ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); Set<String> keySet = params.keySet(); for (String key : keySet) { nameValuePairs.add(new BasicNameValuePair(key, params.get(key))); } post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); response = client.execute(post); if(200==response.getStatusLine().getStatusCode()){ HttpEntity entityGetAppsOfUser = response.getEntity(); BufferedReader rd = new BufferedReader(new InputStreamReader(entityGetAppsOfUser.getContent())); StringBuilder sb = new StringBuilder(); String line =""; while ((line = rd.readLine()) != null) { sb.append(line); } respond = sb.toString(); if("false".equals(respond)){ Authenticator.getInstance().setErrorcode(ErrorType.INVALID); } EntityUtils.consume(entityGetAppsOfUser); if (entityGetAppsOfUser != null) { entityGetAppsOfUser.getContent().close(); } }else{ Authenticator.getInstance().setErrorcode(ErrorType.FAILD); Authenticator.getInstance().setErrormsg(response.getStatusLine().getReasonPhrase()); log.error("("+response.getStatusLine().getStatusCode()+")"+ ":"+response.getStatusLine().getReasonPhrase()); return "false"; } }catch(Exception e){ Authenticator.getInstance().setErrorcode(ErrorType.ERROR); log.error("Connection failure",e); return "false"; } finally{ client.getConnectionManager().closeExpiredConnections(); } return respond; }
public static String httpPost(String urlStr, Map<String,String> params){ if(client ==null){ httpPostLogin(urlStr,params); } HttpPost post = new HttpPost(urlStr); String respond = ""; HttpResponse response=null; try{ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); Set<String> keySet = params.keySet(); for (String key : keySet) { nameValuePairs.add(new BasicNameValuePair(key, params.get(key))); } post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); response = client.execute(post); if(200==response.getStatusLine().getStatusCode()){ HttpEntity entityGetAppsOfUser = response.getEntity(); BufferedReader rd = new BufferedReader(new InputStreamReader(entityGetAppsOfUser.getContent())); StringBuilder sb = new StringBuilder(); String line =""; while ((line = rd.readLine()) != null) { sb.append(line); } respond = sb.toString(); if("false".equals(respond)){ Authenticator.getInstance().setErrorcode(ErrorType.INVALID); } EntityUtils.consume(entityGetAppsOfUser); if (entityGetAppsOfUser != null) { entityGetAppsOfUser.getContent().close(); } }else{ Authenticator.getInstance().setErrorcode(ErrorType.FAILD); Authenticator.getInstance().setErrormsg(response.getStatusLine().getReasonPhrase()); log.error("("+response.getStatusLine().getStatusCode()+")"+ ":"+response.getStatusLine().getReasonPhrase()); return "false"; } }catch(Exception e){ Authenticator.getInstance().setErrorcode(ErrorType.ERROR); log.error("Connection failure",e); return "false"; } finally{ client.getConnectionManager().closeExpiredConnections(); } return respond; }
diff --git a/src/com/klaxnek/justifyx/Justifyx.java b/src/com/klaxnek/justifyx/Justifyx.java index 4be4e0b..750d6b5 100644 --- a/src/com/klaxnek/justifyx/Justifyx.java +++ b/src/com/klaxnek/justifyx/Justifyx.java @@ -1,485 +1,489 @@ /* This file is part of justifyx. justifyx 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. justifyx 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 Foobar. If not, see <http://www.gnu.org/licenses/>. */ package com.klaxnek.justifyx; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Method; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.FileImageOutputStream; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import static org.kohsuke.args4j.ExampleMode.REQUIRED; import de.felixbruns.jotify.JotifyConnection; import de.felixbruns.jotify.exceptions.AuthenticationException; import de.felixbruns.jotify.exceptions.ConnectionException; import de.felixbruns.jotify.media.Album; import de.felixbruns.jotify.media.Link; import de.felixbruns.jotify.media.Playlist; import de.felixbruns.jotify.media.Result; import de.felixbruns.jotify.media.Track; import de.felixbruns.jotify.media.User; import de.felixbruns.jotify.media.Link.InvalidSpotifyURIException; import de.felixbruns.jotify.player.SpotifyInputStream; import adamb.vorbis.CommentField; import adamb.vorbis.VorbisCommentHeader; import adamb.vorbis.VorbisIO; public class Justifyx extends JotifyConnection{ private static Pattern REGEX = Pattern.compile(":(.*?):"); private static String ALBUM_FORMAT = ":artist.name: - :name:"; private static String PLAYLIST_FORMAT = ":author: - :name:"; private static Integer discindex = 1; private static Integer oldtracknumber = 1; private static String country; @Option(name="-user", metaVar = "<spotify_user>", usage="Spotify Premium username (required)", required=true) private static String user; @Option(name="-password", metaVar = "<spotify_password>", usage="Spotify user password (required)", required=true) private static String password; @Option(name="-cover", metaVar = "<spotifyURI> or <spotifyHTTPLink>", usage="Downloads track/album cover") private static String coverURI; @Option(name="-download", metaVar ="<spotifyURI> or <spotifyHTTPLink>", usage="Downloads track/list/album") private static String downloadURI; @Option(name="-number", metaVar ="<song_number>", usage="Downloads starting on the specified track number. Requires -download") private static int songnumber; @Option(name="-codec", metaVar ="<format>", usage="Specify codec and bitrate of the download. Options:\n ogg_96: Ogg Vorbis @ 96kbps\n ogg_160: Ogg Vorbis @ 160kbps\n ogg_320: Ogg Vorbis @ 320kbps") private static String formataudio = "ogg_320"; @Option(name="-toplist", metaVar ="<type>", usage="Downloads toplist tracks/albums/artists.\n track: tracks toplist") private static String toplist_type = "track"; @Option(name="-toplist-region", metaVar ="<region>", usage="Specify region of toplist to download.\nNot specified: default region of the user.\n region (2 letters): a specified region.\n ALL: all regions toplist") private static String toplist_region; @Option(name="-oggcover", metaVar ="<method>", usage="Method to embed cover in ogg file. Options:\n new: new method (METADATA_BLOCK_PICTURE)\n old: old method (default, COVERART and COVERARTMIME)\n none: not embed cover in ogg") private static String oggcover = "old"; @Option(name="-timeout", metaVar ="<seconds>", usage="Number of seconds before throwing a timeout (default: 20 seconds)") private static long TIMEOUT = 20; @Option(name="-chunksize", metaVar ="<bytes>", usage="Fixed chunk size (default: 4096 bytes)") private static int chunksize = 4096; @Option(name="-substreamsize", metaVar ="<bytes>", usage="Fixed substream size (default: 30seconds of 320kbps audio data (320 * 1024 * 30 / 8) = 1228800 bytes)") private static int substreamsize = 320 * 1024 * 30 / 8; @Option(name="-clean",usage="Write clean ogg without tags") private static boolean clean = false; // receives other command line parameters than options @Argument private List<String> arguments = new ArrayList<String>(); public static void main(String args[]) throws IOException, InterruptedException { new Justifyx().doMain(args); Justifyx justifyx = new Justifyx(); try { try { justifyx.login(user, password); } catch(ConnectionException ce) { throw new JustifyxException("[ERROR] Error connecting the server"); } catch(AuthenticationException ae) { throw new JustifyxException("[ERROR] User or password is not valid"); } User spotifyuser = justifyx.user(); country = spotifyuser.getCountry(); System.out.println(spotifyuser); System.out.println(); if (!spotifyuser.isPremium()) throw new JustifyxException("[ERROR] You must be a 'premium' user"); if(toplist_region==null) toplist_region=country; try{ Link uri = null; if(downloadURI!=null) uri = Link.create(downloadURI); else if(coverURI!=null) uri = Link.create(coverURI); // Toplist command if(downloadURI==null && coverURI==null) { Result result = justifyx.toplist(toplist_type, toplist_region.equals("ALL") ? null : toplist_region, null); Date now = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String directorio = sdf.format(now) + " toplist-" + toplist_type + "-" + toplist_region; Integer indextoplist = 1; System.out.println("Toplist: " + toplist_type + " | Region: " + toplist_region + " | Tracks: " + result.getTotalTracks()); System.out.println(); if(toplist_type.equals("track")) { for(Track track : result.getTracks()) { justifyx.downloadTrack(justifyx, justifyx.browse(track), directorio, formataudio, "playlist", indextoplist); indextoplist++; } } } // Download command else if(downloadURI!=null) { // Download track command if (uri.isTrackLink()){ Track track = justifyx.browseTrack(uri.getId()); if (track == null) throw new JustifyxException("[ERROR] Track not found"); justifyx.downloadTrack(justifyx, track, null, formataudio, "track", 0); } // Download playlist command else if (uri.isPlaylistLink()){ Playlist playlist = justifyx.playlist(uri.getId()); if (playlist == null) throw new JustifyxException("[ERROR] Playlist not found"); System.out.println("Playlist: " + playlist.getName() + " | Author: " + playlist.getAuthor() + " | Tracks: " + playlist.getTracks().size()); System.out.println(); String directorio = replaceByReference(playlist, PLAYLIST_FORMAT); DecimalFormat f = new DecimalFormat("00"); Integer indexplaylist = 1; for(Track track : playlist.getTracks()) { System.out.print("[" + f.format((indexplaylist - 1) * 100 / playlist.getTracks().size()) + "%] "); justifyx.downloadTrack(justifyx, justifyx.browse(track), directorio, formataudio, "playlist", indexplaylist); indexplaylist++; } indexplaylist = 0; System.out.println("[100%] Playlist downloaded"); } // Download album command else if(uri.isAlbumLink()){ Album album = justifyx.browseAlbum(uri.getId()); if (album == null) throw new JustifyxException("[ERROR] Album not found"); System.out.println("Album: " + album.getName() + " | Artist: " + album.getArtist().getName() + " | Tracks: " + album.getTracks().size() +" | Discs: " + album.getDiscs().size()); System.out.println(); String directorio = replaceByReference(album, ALBUM_FORMAT); int ntrack=0; for(Track track : album.getTracks()){ ntrack++; if (songnumber == 0 || track.getTrackNumber() >= songnumber) justifyx.downloadTrack(justifyx, track, directorio, formataudio, "album", ntrack); } justifyx.downloadCover(justifyx.image(album.getCover()), directorio); } else throw new JustifyxException("[ERROR] Track, album or playlist not specified"); } // Cover command else if(coverURI!=null){ if(uri.isTrackLink()){ Track track = justifyx.browseTrack(uri.getId()); if (track == null) throw new JustifyxException("[ERROR] Track not found"); System.out.println("Track: " + track.getTitle() + " | Album: " + track.getAlbum().getName() + " | Artist: " + track.getArtist().getName()); System.out.println(); justifyx.downloadCover(justifyx.image(track.getCover()), "."); } if(uri.isAlbumLink()){ Album album = justifyx.browseAlbum(uri.getId()); if (album == null) throw new JustifyxException("[ERROR] Album not found"); System.out.println("Album: " + album.getName() + " | Artist: " + album.getArtist().getName()); System.out.println(); String directorio = replaceByReference(album, ALBUM_FORMAT); justifyx.downloadCover(justifyx.image(album.getCover()), directorio); } } }catch (InvalidSpotifyURIException urie){ throw new JustifyxException("[ERROR] Spotify URI is not valid"); } }catch (JustifyxException je){ System.err.println(je.getMessage()); je.printStackTrace(); }catch (TimeoutException te){ System.err.println(te.getMessage()); te.printStackTrace(); }finally{ try{ justifyx.close(); }catch (ConnectionException ce){ System.err.println("[ERROR] Problem disconnecting"); } } } public void doMain(String[] args) { CmdLineParser parser = new CmdLineParser(this); parser.setUsageWidth(120); try { parser.parseArgument(args); } catch( CmdLineException e ) { // if there's a problem in the command line, // you'll get this exception. this will report // an error message. System.err.println("java -jar justifyx.jar [options...]"); // print the list of available options parser.printUsage(System.err); System.err.println(); System.err.println("[ERROR] " + e.getMessage()); System.err.println(); // print option sample. This is useful some time System.err.println("Example: java -jar justifyx.jar"+ parser.printExample(REQUIRED) + " -download <spotifyURI>"); System.exit(-1); } } public Justifyx(){ super(TIMEOUT, TimeUnit.SECONDS); } private void downloadCover(Image image, String parent) throws TimeoutException, IOException { Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg"); ImageWriter writer = (ImageWriter)iter.next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality(1); java.io.File coverfile = new java.io.File(sanearNombre(parent), "folder.jpg"); coverfile.getParentFile().mkdirs(); FileImageOutputStream output = new FileImageOutputStream(coverfile); writer.setOutput(output); IIOImage iimage = new IIOImage((BufferedImage) image, null, null); writer.write(null, iimage, iwp); writer.dispose(); System.out.println("[100%] Cover ... ok"); } private void downloadTrack(Justifyx justifyx, Track track, String parent, String bitrate, String option, Integer index) throws JustifyxException, TimeoutException{ // Downloading an album, if the new track number is lower than the previous downloaded song, it means we are in a new disc if(option.equals("album")) { if(track.getTrackNumber() < oldtracknumber) { discindex++; oldtracknumber = 1; } else oldtracknumber = track.getTrackNumber(); } try{ String filename=""; DecimalFormat f = new DecimalFormat( "00" ); // Filename: sets the numbering of the track if it is an album / playlist if(option.equals("album")) { // Numbering of filename when downloads an album. numbering = "[number_of_disc] + number_of_track" : e.g. "101" filename = (track.getAlbum().getDiscs().size() > 1 ? discindex : "") + (track.getTrackNumber() < 10 ? "0" : "") + track.getTrackNumber() + " "; } else if (option.equals("playlist")) { // Numbering of filename when downloads a playlist. numbering = "index" : e.g. "01" filename = (index < 10 ? "0" : "") + index.toString() + " "; } // Filename: sets the final name to "numbering Album_Artist - Track_Title.ogg" filename = filename + track.getAlbum().getArtist().getName() + " - " + track.getTitle() + ".ogg"; java.io.File file = new java.io.File(sanearNombre(parent), sanearNombre(filename)); // Prints filename and with a progress percentage if downloading an album if(option.equals("track") || option.equals("playlist")) System.out.print(sanearNombre(filename)); else if (option.equals("album")) System.out.print("[" + f.format((index - 1) * 100 / track.getAlbum().getTracks().size()) + "%] " + sanearNombre(filename)); System.out.print(" "); // Create directory if(parent != null && !file.getParentFile().exists()) file.getParentFile().mkdirs(); // Check restrictions and parse alternative files checking their restrictions boolean allowed = true; Integer nalternative = 0; Integer talternative = 0; - if(track.getRestrictions().get(0).getForbidden() != null) - if(track.getRestrictions().get(0).getForbidden().contains(country) == true) - allowed = false; + for(int i=0; i<track.getRestrictions().size(); i++) { + if(track.getRestrictions().get(i).getForbidden() != null) + if(track.getRestrictions().get(i).getForbidden().contains(country) == true) + allowed = false; - if(track.getRestrictions().get(0).getAllowed() != null) - if (track.getRestrictions().get(0).getAllowed().contains(country) == false) - allowed = false; + if(track.getRestrictions().get(i).getAllowed() != null) + if (track.getRestrictions().get(i).getAllowed().contains(country) == false) + allowed = false; + else + allowed = true; + } if (!allowed) { for(Track pista : track.getAlternatives()) { nalternative++; if(pista.getRestrictions().get(0).getForbidden() != null) if(pista.getRestrictions().get(0).getForbidden().contains(country)) allowed = false; else { allowed = true; talternative++; } if(pista.getRestrictions().get(0).getAllowed() != null) if (pista.getRestrictions().get(0).getAllowed().contains(country)) { allowed = true; talternative = nalternative; } } } if(track.getFiles().size()==0) { System.out.println("-- ko!"); return; } if (allowed && nalternative == 0) download(track, file, bitrate); else if (allowed && nalternative > 0 ) download(track.getAlternatives().get(talternative-1), file, bitrate); else { System.out.println("-- ko!"); return; } if (!clean) try { VorbisCommentHeader comments = new VorbisCommentHeader(); // Embeds cover in .ogg for tracks and playlists (not albums) if((option.equals("track") || option.equals("playlist")) && (!oggcover.equals("none"))) { byte[] imagedata = null; try{ BufferedImage image = (BufferedImage) this.image(track.getCover()); ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageIO.write(image, ImageFormats.getFormatForMimeType(ImageFormats.MIME_TYPE_JPG), new DataOutputStream(output)); imagedata = output.toByteArray(); }catch(Exception e) { e.printStackTrace(); } if (imagedata != null){ char[] testdata = Base64Coder.encode(imagedata); String base64image = new String(testdata); //doc: embedded artwork vorbis standards: http://wiki.xiph.org/VorbisComment#Cover_art if(oggcover.equals("old")){ comments.fields.add(new CommentField("COVERART",base64image)); comments.fields.add(new CommentField("COVERARTMIME",ImageFormats.MIME_TYPE_JPG)); } else if(oggcover.equals("new")){ comments.fields.add(new CommentField("METADATA_BLOCK_PICTURE",base64image)); } } } comments.fields.add(new CommentField("ARTIST", track.getArtist().getName())); comments.fields.add(new CommentField("ALBUM ARTIST", track.getAlbum().getArtist().getName())); comments.fields.add(new CommentField("ALBUM", track.getAlbum().getName())); comments.fields.add(new CommentField("TITLE", track.getTitle())); comments.fields.add(new CommentField("DATE", String.valueOf(track.getYear()))); // Sets track_number to real track number except in playlists if(option.equals("playlist")) comments.fields.add(new CommentField("TRACKNUMBER", index.toString())); else comments.fields.add(new CommentField("TRACKNUMBER", String.valueOf(track.getTrackNumber()))); // Sets disc_number and total_discs only when downloading an album if (option.equals("album")) { comments.fields.add(new CommentField("DISCNUMBER", discindex.toString())); comments.fields.add(new CommentField("TOTALDISCS", String.valueOf(track.getAlbum().getDiscs().size()))); } VorbisIO.writeComments(file, comments); } catch (IOException e) { e.printStackTrace(); } System.out.println(" ok"); }catch(FileNotFoundException fnfe){ fnfe.printStackTrace(); }catch(IOException ioe){ ioe.printStackTrace(); } } private void download(Track track, java.io.File file, String bitrate) throws TimeoutException, IOException{ if (track.getFiles().size() == 0) return; FileOutputStream fos = new FileOutputStream(file); SpotifyInputStream sis = new SpotifyInputStream(protocol, track, bitrate, chunksize, substreamsize); System.out.print("."); int counter = 0; byte[] buf = new byte[8192]; sis.read(buf, 0, 167); // Skip Spotify OGG Header while (true) { counter++; int length = sis.read(buf); if (length < 0) break; fos.write(buf, 0, length); if(counter==256) { counter = 0; System.out.print("."); } } sis.close(); fos.close(); } public static boolean isWindows(){ String os = System.getProperty("os.name").toLowerCase(); return (os.indexOf( "win" ) >= 0); } public static String sanearNombre(String nombre){ if(nombre==null) return null; if(isWindows()) nombre = nombre.replaceAll("\\\\", "/"); else nombre = nombre.replaceAll("/", "\\\\"); nombre = nombre.replaceAll("[\\\\/:*?\"<>|\\$]", "_"); return nombre; } public static String capitalize(String s) { return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase(); } public static String replaceByReference(Object inicial, String formato) throws JustifyxException{ StringBuffer resultString = new StringBuffer(); try { Matcher regexMatcher = REGEX.matcher(formato); while (regexMatcher.find()) { String referencias = regexMatcher.group(); referencias = referencias.substring(1, referencias.length() - 1); String[] metodos = referencias.split("\\."); Object objeto = inicial; for (String metodo : metodos){ Class<?> clase = objeto.getClass(); Method method = clase.getMethod("get" + capitalize(metodo), new Class<?>[0]); objeto = method.invoke(objeto, new Object[0]); } regexMatcher.appendReplacement(resultString, sanearNombre((String)objeto)); } regexMatcher.appendTail(resultString); } catch (Exception e){ throw new JustifyxException(e); } return resultString.toString(); } }
false
true
private void downloadTrack(Justifyx justifyx, Track track, String parent, String bitrate, String option, Integer index) throws JustifyxException, TimeoutException{ // Downloading an album, if the new track number is lower than the previous downloaded song, it means we are in a new disc if(option.equals("album")) { if(track.getTrackNumber() < oldtracknumber) { discindex++; oldtracknumber = 1; } else oldtracknumber = track.getTrackNumber(); } try{ String filename=""; DecimalFormat f = new DecimalFormat( "00" ); // Filename: sets the numbering of the track if it is an album / playlist if(option.equals("album")) { // Numbering of filename when downloads an album. numbering = "[number_of_disc] + number_of_track" : e.g. "101" filename = (track.getAlbum().getDiscs().size() > 1 ? discindex : "") + (track.getTrackNumber() < 10 ? "0" : "") + track.getTrackNumber() + " "; } else if (option.equals("playlist")) { // Numbering of filename when downloads a playlist. numbering = "index" : e.g. "01" filename = (index < 10 ? "0" : "") + index.toString() + " "; } // Filename: sets the final name to "numbering Album_Artist - Track_Title.ogg" filename = filename + track.getAlbum().getArtist().getName() + " - " + track.getTitle() + ".ogg"; java.io.File file = new java.io.File(sanearNombre(parent), sanearNombre(filename)); // Prints filename and with a progress percentage if downloading an album if(option.equals("track") || option.equals("playlist")) System.out.print(sanearNombre(filename)); else if (option.equals("album")) System.out.print("[" + f.format((index - 1) * 100 / track.getAlbum().getTracks().size()) + "%] " + sanearNombre(filename)); System.out.print(" "); // Create directory if(parent != null && !file.getParentFile().exists()) file.getParentFile().mkdirs(); // Check restrictions and parse alternative files checking their restrictions boolean allowed = true; Integer nalternative = 0; Integer talternative = 0; if(track.getRestrictions().get(0).getForbidden() != null) if(track.getRestrictions().get(0).getForbidden().contains(country) == true) allowed = false; if(track.getRestrictions().get(0).getAllowed() != null) if (track.getRestrictions().get(0).getAllowed().contains(country) == false) allowed = false; if (!allowed) { for(Track pista : track.getAlternatives()) { nalternative++; if(pista.getRestrictions().get(0).getForbidden() != null) if(pista.getRestrictions().get(0).getForbidden().contains(country)) allowed = false; else { allowed = true; talternative++; } if(pista.getRestrictions().get(0).getAllowed() != null) if (pista.getRestrictions().get(0).getAllowed().contains(country)) { allowed = true; talternative = nalternative; } } } if(track.getFiles().size()==0) { System.out.println("-- ko!"); return; } if (allowed && nalternative == 0) download(track, file, bitrate); else if (allowed && nalternative > 0 ) download(track.getAlternatives().get(talternative-1), file, bitrate); else { System.out.println("-- ko!"); return; } if (!clean) try { VorbisCommentHeader comments = new VorbisCommentHeader(); // Embeds cover in .ogg for tracks and playlists (not albums) if((option.equals("track") || option.equals("playlist")) && (!oggcover.equals("none"))) { byte[] imagedata = null; try{ BufferedImage image = (BufferedImage) this.image(track.getCover()); ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageIO.write(image, ImageFormats.getFormatForMimeType(ImageFormats.MIME_TYPE_JPG), new DataOutputStream(output)); imagedata = output.toByteArray(); }catch(Exception e) { e.printStackTrace(); } if (imagedata != null){ char[] testdata = Base64Coder.encode(imagedata); String base64image = new String(testdata); //doc: embedded artwork vorbis standards: http://wiki.xiph.org/VorbisComment#Cover_art if(oggcover.equals("old")){ comments.fields.add(new CommentField("COVERART",base64image)); comments.fields.add(new CommentField("COVERARTMIME",ImageFormats.MIME_TYPE_JPG)); } else if(oggcover.equals("new")){ comments.fields.add(new CommentField("METADATA_BLOCK_PICTURE",base64image)); } } } comments.fields.add(new CommentField("ARTIST", track.getArtist().getName())); comments.fields.add(new CommentField("ALBUM ARTIST", track.getAlbum().getArtist().getName())); comments.fields.add(new CommentField("ALBUM", track.getAlbum().getName())); comments.fields.add(new CommentField("TITLE", track.getTitle())); comments.fields.add(new CommentField("DATE", String.valueOf(track.getYear()))); // Sets track_number to real track number except in playlists if(option.equals("playlist")) comments.fields.add(new CommentField("TRACKNUMBER", index.toString())); else comments.fields.add(new CommentField("TRACKNUMBER", String.valueOf(track.getTrackNumber()))); // Sets disc_number and total_discs only when downloading an album if (option.equals("album")) { comments.fields.add(new CommentField("DISCNUMBER", discindex.toString())); comments.fields.add(new CommentField("TOTALDISCS", String.valueOf(track.getAlbum().getDiscs().size()))); } VorbisIO.writeComments(file, comments); } catch (IOException e) { e.printStackTrace(); } System.out.println(" ok"); }catch(FileNotFoundException fnfe){ fnfe.printStackTrace(); }catch(IOException ioe){ ioe.printStackTrace(); } }
private void downloadTrack(Justifyx justifyx, Track track, String parent, String bitrate, String option, Integer index) throws JustifyxException, TimeoutException{ // Downloading an album, if the new track number is lower than the previous downloaded song, it means we are in a new disc if(option.equals("album")) { if(track.getTrackNumber() < oldtracknumber) { discindex++; oldtracknumber = 1; } else oldtracknumber = track.getTrackNumber(); } try{ String filename=""; DecimalFormat f = new DecimalFormat( "00" ); // Filename: sets the numbering of the track if it is an album / playlist if(option.equals("album")) { // Numbering of filename when downloads an album. numbering = "[number_of_disc] + number_of_track" : e.g. "101" filename = (track.getAlbum().getDiscs().size() > 1 ? discindex : "") + (track.getTrackNumber() < 10 ? "0" : "") + track.getTrackNumber() + " "; } else if (option.equals("playlist")) { // Numbering of filename when downloads a playlist. numbering = "index" : e.g. "01" filename = (index < 10 ? "0" : "") + index.toString() + " "; } // Filename: sets the final name to "numbering Album_Artist - Track_Title.ogg" filename = filename + track.getAlbum().getArtist().getName() + " - " + track.getTitle() + ".ogg"; java.io.File file = new java.io.File(sanearNombre(parent), sanearNombre(filename)); // Prints filename and with a progress percentage if downloading an album if(option.equals("track") || option.equals("playlist")) System.out.print(sanearNombre(filename)); else if (option.equals("album")) System.out.print("[" + f.format((index - 1) * 100 / track.getAlbum().getTracks().size()) + "%] " + sanearNombre(filename)); System.out.print(" "); // Create directory if(parent != null && !file.getParentFile().exists()) file.getParentFile().mkdirs(); // Check restrictions and parse alternative files checking their restrictions boolean allowed = true; Integer nalternative = 0; Integer talternative = 0; for(int i=0; i<track.getRestrictions().size(); i++) { if(track.getRestrictions().get(i).getForbidden() != null) if(track.getRestrictions().get(i).getForbidden().contains(country) == true) allowed = false; if(track.getRestrictions().get(i).getAllowed() != null) if (track.getRestrictions().get(i).getAllowed().contains(country) == false) allowed = false; else allowed = true; } if (!allowed) { for(Track pista : track.getAlternatives()) { nalternative++; if(pista.getRestrictions().get(0).getForbidden() != null) if(pista.getRestrictions().get(0).getForbidden().contains(country)) allowed = false; else { allowed = true; talternative++; } if(pista.getRestrictions().get(0).getAllowed() != null) if (pista.getRestrictions().get(0).getAllowed().contains(country)) { allowed = true; talternative = nalternative; } } } if(track.getFiles().size()==0) { System.out.println("-- ko!"); return; } if (allowed && nalternative == 0) download(track, file, bitrate); else if (allowed && nalternative > 0 ) download(track.getAlternatives().get(talternative-1), file, bitrate); else { System.out.println("-- ko!"); return; } if (!clean) try { VorbisCommentHeader comments = new VorbisCommentHeader(); // Embeds cover in .ogg for tracks and playlists (not albums) if((option.equals("track") || option.equals("playlist")) && (!oggcover.equals("none"))) { byte[] imagedata = null; try{ BufferedImage image = (BufferedImage) this.image(track.getCover()); ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageIO.write(image, ImageFormats.getFormatForMimeType(ImageFormats.MIME_TYPE_JPG), new DataOutputStream(output)); imagedata = output.toByteArray(); }catch(Exception e) { e.printStackTrace(); } if (imagedata != null){ char[] testdata = Base64Coder.encode(imagedata); String base64image = new String(testdata); //doc: embedded artwork vorbis standards: http://wiki.xiph.org/VorbisComment#Cover_art if(oggcover.equals("old")){ comments.fields.add(new CommentField("COVERART",base64image)); comments.fields.add(new CommentField("COVERARTMIME",ImageFormats.MIME_TYPE_JPG)); } else if(oggcover.equals("new")){ comments.fields.add(new CommentField("METADATA_BLOCK_PICTURE",base64image)); } } } comments.fields.add(new CommentField("ARTIST", track.getArtist().getName())); comments.fields.add(new CommentField("ALBUM ARTIST", track.getAlbum().getArtist().getName())); comments.fields.add(new CommentField("ALBUM", track.getAlbum().getName())); comments.fields.add(new CommentField("TITLE", track.getTitle())); comments.fields.add(new CommentField("DATE", String.valueOf(track.getYear()))); // Sets track_number to real track number except in playlists if(option.equals("playlist")) comments.fields.add(new CommentField("TRACKNUMBER", index.toString())); else comments.fields.add(new CommentField("TRACKNUMBER", String.valueOf(track.getTrackNumber()))); // Sets disc_number and total_discs only when downloading an album if (option.equals("album")) { comments.fields.add(new CommentField("DISCNUMBER", discindex.toString())); comments.fields.add(new CommentField("TOTALDISCS", String.valueOf(track.getAlbum().getDiscs().size()))); } VorbisIO.writeComments(file, comments); } catch (IOException e) { e.printStackTrace(); } System.out.println(" ok"); }catch(FileNotFoundException fnfe){ fnfe.printStackTrace(); }catch(IOException ioe){ ioe.printStackTrace(); } }
diff --git a/Tendu/src/it/chalmers/tendu/screens/LobbyScreen.java b/Tendu/src/it/chalmers/tendu/screens/LobbyScreen.java index f036669..5bd9fcd 100644 --- a/Tendu/src/it/chalmers/tendu/screens/LobbyScreen.java +++ b/Tendu/src/it/chalmers/tendu/screens/LobbyScreen.java @@ -1,147 +1,147 @@ package it.chalmers.tendu.screens; import it.chalmers.tendu.Tendu; import it.chalmers.tendu.controllers.InputController; import it.chalmers.tendu.controllers.LobbyController; import it.chalmers.tendu.defaults.Constants; import it.chalmers.tendu.defaults.PlayerColors; import it.chalmers.tendu.defaults.TextLabels; import it.chalmers.tendu.gamemodel.LobbyModel; import it.chalmers.tendu.gamemodel.Player; import it.chalmers.tendu.gamemodel.SimpleTimer; import it.chalmers.tendu.tbd.C; import it.chalmers.tendu.tbd.EventBus; import it.chalmers.tendu.tbd.EventMessage; import java.util.Map; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.math.Vector2; public class LobbyScreen implements Screen { private LobbyController lobbyController; private Tendu tendu; private TextWidget statusText; private TextWidget readyText; private TextWidget playerText; private TextWidget waitingText; private BitmapFont font; private int playersConnected; private final int maximumPlayers; private TextWidget testStuff; private boolean ready; public LobbyScreen(Tendu tendu, boolean isHost) { maximumPlayers = 4; this.tendu = tendu; LobbyModel model = new LobbyModel(maximumPlayers); lobbyController = new LobbyController(model); font = new BitmapFont(Gdx.files.internal("fonts/menuFont.fnt"), Gdx.files.internal("fonts/menuFont.png"), false); readyText = new TextWidget(TextLabels.READY, new Vector2(640, 150), Constants.MENU_FONT_COLOR); waitingText = new TextWidget(TextLabels.WAITING_FOR_PLAYERS, new Vector2(65, 150), Constants.MENU_FONT_COLOR); playerText = new TextWidget("This will never be shown on screen", new Vector2(65, 450), Constants.MENU_FONT_COLOR); ready = false; if (isHost) initHost(); else initClient(); testStuff = new TextWidget("test stuff", new Vector2(870, 120), Constants.MENU_FONT_COLOR); } private void initHost() { Player.getInstance().setHost(true); tendu.getNetworkHandler().hostSession(); String myMac = Player.getInstance().getMac(); lobbyController.getModel().addPlayer(myMac); statusText = new TextWidget(TextLabels.WAITING_FOR_CONNECTIONS, new Vector2(40, 620), Constants.MENU_FONT_COLOR); } private void initClient() { tendu.getNetworkHandler().joinGame(); statusText = new TextWidget(TextLabels.SEARCHING_FOR_SESSION, new Vector2( 40, 620), Constants.MENU_FONT_COLOR); } public void tick(InputController input) { playersConnected = getModel().getLobbyMembers().entrySet().size(); if (!Player.getInstance().isHost() && playersConnected > 0) { statusText.setText(TextLabels.CONNECTED_TO_SESSION); } else if (Player.getInstance().isHost() && playersConnected == maximumPlayers) { statusText.setText("Maximum players connected"); } if (input.isTouchedDown()) { if (readyText.collided(input.getCoordinates())) { Gdx.input.vibrate(25); readyText.setColor(Constants.MENU_FONT_COLOR_PRESSED); } } else if (input.isTouchedUp()) { if (readyText.collided(input.getCoordinates())) { ready = true; // Received by host and client in LobbyController. EventBus.INSTANCE.broadcast(new EventMessage(C.Tag.TO_SELF, C.Msg.PLAYER_READY, Player.getInstance().getMac())); } if (testStuff.collided(input.getCoordinates())) { // Received by host and client in LobbyController. - EventBus.INSTANCE.broadcast(new EventMessage(C.Tag.CLIENT_REQUESTED, + EventBus.INSTANCE.broadcast(new EventMessage(C.Tag.REQUEST_AS_CLIENT, C.Msg.TEST, new SimpleTimer())); } readyText.setColor(Constants.MENU_FONT_COLOR); } } @Override public void render() { statusText.draw(tendu.spriteBatch, font); testStuff.draw(tendu.spriteBatch, font); playerText.setY(580); for (Map.Entry<String, Integer> p : getModel().getLobbyMembers() .entrySet()) { if(p.getKey().equals(Player.getInstance().getMac())) { playerText.setText(TextLabels.ME + " - " + TextLabels.PLAYER + ": " + (p.getValue()+1)); } else { playerText.setText(TextLabels.PLAYER + ": " + (p.getValue()+1) + " Mac = " + p.getKey()); } playerText.addToY(-65); playerText.setColor(PlayerColors.getPlayerColor(p.getValue())); playerText.draw(tendu.spriteBatch, font); } if (playersConnected > 0 && !ready) { readyText.drawAtCenterPoint(tendu.spriteBatch, font); } else if(playersConnected > 0 && ready) { waitingText.draw(tendu.spriteBatch, font); } } private LobbyModel getModel() { return lobbyController.getModel(); } @Override public void removed() { font.dispose(); lobbyController.unregister(); } }
true
true
public void tick(InputController input) { playersConnected = getModel().getLobbyMembers().entrySet().size(); if (!Player.getInstance().isHost() && playersConnected > 0) { statusText.setText(TextLabels.CONNECTED_TO_SESSION); } else if (Player.getInstance().isHost() && playersConnected == maximumPlayers) { statusText.setText("Maximum players connected"); } if (input.isTouchedDown()) { if (readyText.collided(input.getCoordinates())) { Gdx.input.vibrate(25); readyText.setColor(Constants.MENU_FONT_COLOR_PRESSED); } } else if (input.isTouchedUp()) { if (readyText.collided(input.getCoordinates())) { ready = true; // Received by host and client in LobbyController. EventBus.INSTANCE.broadcast(new EventMessage(C.Tag.TO_SELF, C.Msg.PLAYER_READY, Player.getInstance().getMac())); } if (testStuff.collided(input.getCoordinates())) { // Received by host and client in LobbyController. EventBus.INSTANCE.broadcast(new EventMessage(C.Tag.CLIENT_REQUESTED, C.Msg.TEST, new SimpleTimer())); } readyText.setColor(Constants.MENU_FONT_COLOR); } }
public void tick(InputController input) { playersConnected = getModel().getLobbyMembers().entrySet().size(); if (!Player.getInstance().isHost() && playersConnected > 0) { statusText.setText(TextLabels.CONNECTED_TO_SESSION); } else if (Player.getInstance().isHost() && playersConnected == maximumPlayers) { statusText.setText("Maximum players connected"); } if (input.isTouchedDown()) { if (readyText.collided(input.getCoordinates())) { Gdx.input.vibrate(25); readyText.setColor(Constants.MENU_FONT_COLOR_PRESSED); } } else if (input.isTouchedUp()) { if (readyText.collided(input.getCoordinates())) { ready = true; // Received by host and client in LobbyController. EventBus.INSTANCE.broadcast(new EventMessage(C.Tag.TO_SELF, C.Msg.PLAYER_READY, Player.getInstance().getMac())); } if (testStuff.collided(input.getCoordinates())) { // Received by host and client in LobbyController. EventBus.INSTANCE.broadcast(new EventMessage(C.Tag.REQUEST_AS_CLIENT, C.Msg.TEST, new SimpleTimer())); } readyText.setColor(Constants.MENU_FONT_COLOR); } }
diff --git a/src/org/servalproject/batphone/BatPhone.java b/src/org/servalproject/batphone/BatPhone.java index 792ea7f9..cdc1fb4d 100644 --- a/src/org/servalproject/batphone/BatPhone.java +++ b/src/org/servalproject/batphone/BatPhone.java @@ -1,158 +1,160 @@ package org.servalproject.batphone; import org.servalproject.ServalBatPhoneApplication; import org.servalproject.ServalBatPhoneApplication.State; import org.servalproject.rhizome.Rhizome; import org.servalproject.system.WifiAdhocControl; import org.servalproject.system.WifiApControl; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.Uri; import android.net.wifi.WifiManager; import android.os.SystemClock; import android.util.Log; public class BatPhone extends BroadcastReceiver { static BatPhone instance = null; public static final String ACTION_MODE_ALARM = "org.servalproject.MODE_ALARM"; public BatPhone() { instance = this; } public static BatPhone getEngine() { // TODO Auto-generated method stub if (instance == null) instance = new BatPhone(); return instance; } public static void call(String phoneNumber) { // make call by cellular/normal means // we need to ignore this number when it is dialed in the next 3 seconds dial_time = SystemClock.elapsedRealtime(); dialed_number = phoneNumber; String url = "tel:" + phoneNumber; Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); ServalBatPhoneApplication.context.startActivity(intent); } static String dialed_number = null; static long dial_time = 0; public static String getDialedNumber() { return dialed_number; } private void onOutgoingCall(Intent intent) { ServalBatPhoneApplication app = ServalBatPhoneApplication.context; if (app.getState() != State.On) return; String number = getResultData(); // Set result data to null if we are claiming the call, else set // the result data to the number so that someone else can take // it. // Let the system complete the call if we have said we aren't // interested in it. if (dialed_number != null && dialed_number.equals(number) && (SystemClock.elapsedRealtime() - dial_time) < 3000) { return; } // Don't try to complete the call while we are // giving the user the choice of how to handle it. setResultData(null); // Send call to director to select how to handle it. Intent myIntent = new Intent(app, CallDirector.class); // Create call as a standalone activity stack myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); myIntent.putExtra("phone_number", number); // Uncomment below if we want to allow multiple mesh calls in // progress // myIndent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); app.startActivity(myIntent); } @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); ServalBatPhoneApplication app = ServalBatPhoneApplication.context; try { // Log.d("BatPhoneReceiver", "Got an intent: " + intent.toString()); if (action.equals(Intent.ACTION_NEW_OUTGOING_CALL)) { onOutgoingCall(intent); } else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) { // placeholder to ensure ServalBatPhoneApplication is created on // boot // WifiControl will restart adhoc if required // ServalBatPhoneApplication will re-enable services if required } else if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) { app.nm.onFlightModeChanged(intent); } else if (action.equals(Intent.ACTION_MEDIA_EJECT) || action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) { Rhizome.setRhizomeEnabled(false); } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { Rhizome.setRhizomeEnabled(); } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) { app.nm.control.onWifiStateChanged(intent); app.nm.getScanResults(); } else if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { app.nm.getScanResults(); } else if (action .equals(WifiApControl.WIFI_AP_STATE_CHANGED_ACTION)) { app.nm.control.onApStateChanged(intent); app.nm.updateApState(); + if (app.controlService != null) + app.controlService.onNetworkStateChanged(); } else if (action .equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) { app.nm.control.onSupplicantStateChanged(intent); app.nm.getScanResults(); } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { app.nm.onWifiNetworkStateChanged(intent); if (app.controlService != null) app.controlService.onNetworkStateChanged(); } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { // TODO? } else if (action .equals(WifiAdhocControl.ADHOC_STATE_CHANGED_ACTION)) { app.nm.onAdhocStateChanged(); if (app.controlService != null) app.controlService.onNetworkStateChanged(); } else if (action.equals(ACTION_MODE_ALARM)) { app.nm.control.onAlarm(); } else { Log.v("BatPhone", "Unexpected intent: " + intent.getAction()); } } catch (Exception e) { Log.e("BatPhone", e.toString(), e); } } }
true
true
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); ServalBatPhoneApplication app = ServalBatPhoneApplication.context; try { // Log.d("BatPhoneReceiver", "Got an intent: " + intent.toString()); if (action.equals(Intent.ACTION_NEW_OUTGOING_CALL)) { onOutgoingCall(intent); } else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) { // placeholder to ensure ServalBatPhoneApplication is created on // boot // WifiControl will restart adhoc if required // ServalBatPhoneApplication will re-enable services if required } else if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) { app.nm.onFlightModeChanged(intent); } else if (action.equals(Intent.ACTION_MEDIA_EJECT) || action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) { Rhizome.setRhizomeEnabled(false); } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { Rhizome.setRhizomeEnabled(); } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) { app.nm.control.onWifiStateChanged(intent); app.nm.getScanResults(); } else if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { app.nm.getScanResults(); } else if (action .equals(WifiApControl.WIFI_AP_STATE_CHANGED_ACTION)) { app.nm.control.onApStateChanged(intent); app.nm.updateApState(); } else if (action .equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) { app.nm.control.onSupplicantStateChanged(intent); app.nm.getScanResults(); } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { app.nm.onWifiNetworkStateChanged(intent); if (app.controlService != null) app.controlService.onNetworkStateChanged(); } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { // TODO? } else if (action .equals(WifiAdhocControl.ADHOC_STATE_CHANGED_ACTION)) { app.nm.onAdhocStateChanged(); if (app.controlService != null) app.controlService.onNetworkStateChanged(); } else if (action.equals(ACTION_MODE_ALARM)) { app.nm.control.onAlarm(); } else { Log.v("BatPhone", "Unexpected intent: " + intent.getAction()); } } catch (Exception e) { Log.e("BatPhone", e.toString(), e); } }
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); ServalBatPhoneApplication app = ServalBatPhoneApplication.context; try { // Log.d("BatPhoneReceiver", "Got an intent: " + intent.toString()); if (action.equals(Intent.ACTION_NEW_OUTGOING_CALL)) { onOutgoingCall(intent); } else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) { // placeholder to ensure ServalBatPhoneApplication is created on // boot // WifiControl will restart adhoc if required // ServalBatPhoneApplication will re-enable services if required } else if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) { app.nm.onFlightModeChanged(intent); } else if (action.equals(Intent.ACTION_MEDIA_EJECT) || action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) { Rhizome.setRhizomeEnabled(false); } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { Rhizome.setRhizomeEnabled(); } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) { app.nm.control.onWifiStateChanged(intent); app.nm.getScanResults(); } else if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { app.nm.getScanResults(); } else if (action .equals(WifiApControl.WIFI_AP_STATE_CHANGED_ACTION)) { app.nm.control.onApStateChanged(intent); app.nm.updateApState(); if (app.controlService != null) app.controlService.onNetworkStateChanged(); } else if (action .equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) { app.nm.control.onSupplicantStateChanged(intent); app.nm.getScanResults(); } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { app.nm.onWifiNetworkStateChanged(intent); if (app.controlService != null) app.controlService.onNetworkStateChanged(); } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { // TODO? } else if (action .equals(WifiAdhocControl.ADHOC_STATE_CHANGED_ACTION)) { app.nm.onAdhocStateChanged(); if (app.controlService != null) app.controlService.onNetworkStateChanged(); } else if (action.equals(ACTION_MODE_ALARM)) { app.nm.control.onAlarm(); } else { Log.v("BatPhone", "Unexpected intent: " + intent.getAction()); } } catch (Exception e) { Log.e("BatPhone", e.toString(), e); } }
diff --git a/WFPMapping/device/survey/src/com/gallatinsystems/survey/device/view/adapter/FileTransmissionArrayAdapter.java b/WFPMapping/device/survey/src/com/gallatinsystems/survey/device/view/adapter/FileTransmissionArrayAdapter.java index 93b32ffd7..7afe65c85 100644 --- a/WFPMapping/device/survey/src/com/gallatinsystems/survey/device/view/adapter/FileTransmissionArrayAdapter.java +++ b/WFPMapping/device/survey/src/com/gallatinsystems/survey/device/view/adapter/FileTransmissionArrayAdapter.java @@ -1,74 +1,74 @@ package com.gallatinsystems.survey.device.view.adapter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.gallatinsystems.survey.device.R; import com.gallatinsystems.survey.device.domain.FileTransmission; import com.gallatinsystems.survey.device.util.ConstantUtil; /** * Adapter that converts FileTransmission objects for display in a list view. * * @author Christopher Fagiani * */ public class FileTransmissionArrayAdapter extends ArrayAdapter<FileTransmission> { private DateFormat dateFormat; private int layoutId; public FileTransmissionArrayAdapter(Context context, int resourceId, List<FileTransmission> objects) { super(context, resourceId, objects); layoutId = resourceId; dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); } private void bindView(View view, FileTransmission trans) { ImageView imageView = (ImageView) view.findViewById(R.id.statusicon); if (ConstantUtil.IN_PROGRESS_STATUS.equals(trans.getStatus())) { imageView.setImageResource(R.drawable.blueuparrow); } else if (ConstantUtil.QUEUED_STATUS.equals(trans.getStatus())) { imageView.setImageResource(R.drawable.yellowcircle); } else if (ConstantUtil.COMPLETE_STATUS.equals(trans.getStatus())) { imageView.setImageResource(R.drawable.greencircle); } else if (ConstantUtil.FAILED_STATUS.equals(trans.getStatus())) { imageView.setImageResource(R.drawable.redcircle); } TextView statusLabel = (TextView) view.findViewById(R.id.statustext); statusLabel.setText(trans.getStatus()); TextView startDate = (TextView) view.findViewById(R.id.startdate); if (trans.getStartDate() != null) { startDate.setText(dateFormat.format(trans.getStartDate())); } TextView endDate = (TextView) view.findViewById(R.id.enddate); - if (trans.getStartDate() != null) { + if (trans.getEndDate() != null) { endDate.setText(dateFormat.format(trans.getEndDate())); } TextView fileName = (TextView) view.findViewById(R.id.filename); fileName.setText(trans.getFileName()); } public View getView(int position, View convertView, ViewGroup parent) { Context ctx = getContext(); LayoutInflater inflater = (LayoutInflater) ctx .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(layoutId, null); bindView(view, getItem(position)); return view; } }
true
true
private void bindView(View view, FileTransmission trans) { ImageView imageView = (ImageView) view.findViewById(R.id.statusicon); if (ConstantUtil.IN_PROGRESS_STATUS.equals(trans.getStatus())) { imageView.setImageResource(R.drawable.blueuparrow); } else if (ConstantUtil.QUEUED_STATUS.equals(trans.getStatus())) { imageView.setImageResource(R.drawable.yellowcircle); } else if (ConstantUtil.COMPLETE_STATUS.equals(trans.getStatus())) { imageView.setImageResource(R.drawable.greencircle); } else if (ConstantUtil.FAILED_STATUS.equals(trans.getStatus())) { imageView.setImageResource(R.drawable.redcircle); } TextView statusLabel = (TextView) view.findViewById(R.id.statustext); statusLabel.setText(trans.getStatus()); TextView startDate = (TextView) view.findViewById(R.id.startdate); if (trans.getStartDate() != null) { startDate.setText(dateFormat.format(trans.getStartDate())); } TextView endDate = (TextView) view.findViewById(R.id.enddate); if (trans.getStartDate() != null) { endDate.setText(dateFormat.format(trans.getEndDate())); } TextView fileName = (TextView) view.findViewById(R.id.filename); fileName.setText(trans.getFileName()); }
private void bindView(View view, FileTransmission trans) { ImageView imageView = (ImageView) view.findViewById(R.id.statusicon); if (ConstantUtil.IN_PROGRESS_STATUS.equals(trans.getStatus())) { imageView.setImageResource(R.drawable.blueuparrow); } else if (ConstantUtil.QUEUED_STATUS.equals(trans.getStatus())) { imageView.setImageResource(R.drawable.yellowcircle); } else if (ConstantUtil.COMPLETE_STATUS.equals(trans.getStatus())) { imageView.setImageResource(R.drawable.greencircle); } else if (ConstantUtil.FAILED_STATUS.equals(trans.getStatus())) { imageView.setImageResource(R.drawable.redcircle); } TextView statusLabel = (TextView) view.findViewById(R.id.statustext); statusLabel.setText(trans.getStatus()); TextView startDate = (TextView) view.findViewById(R.id.startdate); if (trans.getStartDate() != null) { startDate.setText(dateFormat.format(trans.getStartDate())); } TextView endDate = (TextView) view.findViewById(R.id.enddate); if (trans.getEndDate() != null) { endDate.setText(dateFormat.format(trans.getEndDate())); } TextView fileName = (TextView) view.findViewById(R.id.filename); fileName.setText(trans.getFileName()); }
diff --git a/invoice/src/test/java/com/ning/billing/invoice/dao/TestInvoiceDaoForItemAdjustment.java b/invoice/src/test/java/com/ning/billing/invoice/dao/TestInvoiceDaoForItemAdjustment.java index 1fac6f713..5fc759db6 100644 --- a/invoice/src/test/java/com/ning/billing/invoice/dao/TestInvoiceDaoForItemAdjustment.java +++ b/invoice/src/test/java/com/ning/billing/invoice/dao/TestInvoiceDaoForItemAdjustment.java @@ -1,147 +1,147 @@ /* * Copyright 2010-2012 Ning, Inc. * * Ning 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 com.ning.billing.invoice.dao; import java.math.BigDecimal; import java.util.List; import java.util.UUID; import org.joda.time.LocalDate; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.Test; import com.ning.billing.ErrorCode; import com.ning.billing.catalog.api.Currency; import com.ning.billing.invoice.api.Invoice; import com.ning.billing.invoice.api.InvoiceApiException; import com.ning.billing.invoice.api.InvoiceItem; import com.ning.billing.invoice.api.InvoiceItemType; import com.ning.billing.invoice.model.DefaultInvoice; import com.ning.billing.invoice.model.RecurringInvoiceItem; import com.ning.billing.util.callcontext.CallContext; public class TestInvoiceDaoForItemAdjustment extends InvoiceDaoTestBase { private static final BigDecimal INVOICE_ITEM_AMOUNT = new BigDecimal("21.00"); @Test(groups = "slow") public void testAddInvoiceItemAdjustmentForNonExistingInvoiceItemId() throws Exception { final UUID accountId = UUID.randomUUID(); final UUID invoiceId = UUID.randomUUID(); final UUID invoiceItemId = UUID.randomUUID(); final LocalDate effectiveDate = new LocalDate(); final CallContext context = Mockito.mock(CallContext.class); try { invoiceDao.insertInvoiceItemAdjustment(accountId, invoiceId, invoiceItemId, effectiveDate, null, null, context); Assert.fail("Should not have been able to adjust a non existing invoice item"); } catch (Exception e) { Assert.assertEquals(((InvoiceApiException) e.getCause()).getCode(), ErrorCode.INVOICE_ITEM_NOT_FOUND.getCode()); } } @Test(groups = "slow") public void testAddInvoiceItemAdjustmentForWrongInvoice() throws Exception { final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), clock.getUTCToday(), clock.getUTCToday(), Currency.USD); final InvoiceItem invoiceItem = new RecurringInvoiceItem(invoice.getId(), invoice.getAccountId(), UUID.randomUUID(), UUID.randomUUID(), "test plan", "test phase", new LocalDate(2010, 1, 1), new LocalDate(2010, 4, 1), INVOICE_ITEM_AMOUNT, new BigDecimal("7.00"), Currency.USD); invoice.addInvoiceItem(invoiceItem); invoiceDao.create(invoice, 1, true, context); try { invoiceDao.insertInvoiceItemAdjustment(invoice.getAccountId(), UUID.randomUUID(), invoiceItem.getId(), new LocalDate(2010, 1, 1), null, null, context); Assert.fail("Should not have been able to adjust an item on a non existing invoice"); } catch (Exception e) { Assert.assertEquals(((InvoiceApiException) e.getCause()).getCode(), ErrorCode.INVOICE_INVALID_FOR_INVOICE_ITEM_ADJUSTMENT.getCode()); } } @Test(groups = "slow") public void testAddInvoiceItemAdjustmentForFullAmount() throws Exception { final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), clock.getUTCToday(), clock.getUTCToday(), Currency.USD); final InvoiceItem invoiceItem = new RecurringInvoiceItem(invoice.getId(), invoice.getAccountId(), UUID.randomUUID(), UUID.randomUUID(), "test plan", "test phase", new LocalDate(2010, 1, 1), new LocalDate(2010, 4, 1), INVOICE_ITEM_AMOUNT, new BigDecimal("7.00"), Currency.USD); invoice.addInvoiceItem(invoiceItem); invoiceDao.create(invoice, 1, true, context); final InvoiceItem adjustedInvoiceItem = createAndCheckAdjustment(invoice, invoiceItem, null); Assert.assertEquals(adjustedInvoiceItem.getAmount().compareTo(invoiceItem.getAmount().negate()), 0); } @Test(groups = "slow") public void testAddInvoiceItemAdjustmentForPartialAmount() throws Exception { final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), clock.getUTCToday(), clock.getUTCToday(), Currency.USD); final InvoiceItem invoiceItem = new RecurringInvoiceItem(invoice.getId(), invoice.getAccountId(), UUID.randomUUID(), UUID.randomUUID(), "test plan", "test phase", new LocalDate(2010, 1, 1), new LocalDate(2010, 4, 1), INVOICE_ITEM_AMOUNT, new BigDecimal("7.00"), Currency.USD); invoice.addInvoiceItem(invoiceItem); invoiceDao.create(invoice, 1, true, context); final InvoiceItem adjustedInvoiceItem = createAndCheckAdjustment(invoice, invoiceItem, BigDecimal.TEN); Assert.assertEquals(adjustedInvoiceItem.getAmount().compareTo(BigDecimal.TEN.negate()), 0); } private InvoiceItem createAndCheckAdjustment(final Invoice invoice, final InvoiceItem invoiceItem, final BigDecimal amount) throws InvoiceApiException { final LocalDate effectiveDate = new LocalDate(2010, 1, 1); final InvoiceItem adjustedInvoiceItem = invoiceDao.insertInvoiceItemAdjustment(invoice.getAccountId(), invoice.getId(), invoiceItem.getId(), effectiveDate, amount, null, context); Assert.assertEquals(adjustedInvoiceItem.getAccountId(), invoiceItem.getAccountId()); Assert.assertNull(adjustedInvoiceItem.getBundleId()); Assert.assertEquals(adjustedInvoiceItem.getCurrency(), invoiceItem.getCurrency()); - Assert.assertEquals(adjustedInvoiceItem.getDescription(), "item-adj"); + Assert.assertEquals(adjustedInvoiceItem.getDescription(), "Invoice item adjustment"); Assert.assertEquals(adjustedInvoiceItem.getEndDate(), effectiveDate); Assert.assertEquals(adjustedInvoiceItem.getInvoiceId(), invoiceItem.getInvoiceId()); Assert.assertEquals(adjustedInvoiceItem.getInvoiceItemType(), InvoiceItemType.ITEM_ADJ); Assert.assertEquals(adjustedInvoiceItem.getLinkedItemId(), invoiceItem.getId()); Assert.assertNull(adjustedInvoiceItem.getPhaseName()); Assert.assertNull(adjustedInvoiceItem.getPlanName()); Assert.assertNull(adjustedInvoiceItem.getRate()); Assert.assertEquals(adjustedInvoiceItem.getStartDate(), effectiveDate); Assert.assertNull(adjustedInvoiceItem.getSubscriptionId()); // Retrieve the item by id final InvoiceItem retrievedInvoiceItem = invoiceItemSqlDao.getById(adjustedInvoiceItem.getId().toString()); Assert.assertEquals(retrievedInvoiceItem, adjustedInvoiceItem); // Retrieve the item by invoice id final Invoice retrievedInvoice = invoiceDao.getById(adjustedInvoiceItem.getInvoiceId()); final List<InvoiceItem> invoiceItems = retrievedInvoice.getInvoiceItems(); Assert.assertEquals(invoiceItems.size(), 2); final InvoiceItem retrievedByInvoiceInvoiceItem; if (invoiceItems.get(0).getId().equals(adjustedInvoiceItem.getId())) { retrievedByInvoiceInvoiceItem = invoiceItems.get(0); } else { retrievedByInvoiceInvoiceItem = invoiceItems.get(1); } Assert.assertEquals(retrievedByInvoiceInvoiceItem, adjustedInvoiceItem); // Verify the invoice balance if (amount == null) { Assert.assertEquals(retrievedInvoice.getBalance().compareTo(BigDecimal.ZERO), 0); } else { Assert.assertEquals(retrievedInvoice.getBalance().compareTo(INVOICE_ITEM_AMOUNT.add(amount.negate())), 0); } return adjustedInvoiceItem; } }
true
true
private InvoiceItem createAndCheckAdjustment(final Invoice invoice, final InvoiceItem invoiceItem, final BigDecimal amount) throws InvoiceApiException { final LocalDate effectiveDate = new LocalDate(2010, 1, 1); final InvoiceItem adjustedInvoiceItem = invoiceDao.insertInvoiceItemAdjustment(invoice.getAccountId(), invoice.getId(), invoiceItem.getId(), effectiveDate, amount, null, context); Assert.assertEquals(adjustedInvoiceItem.getAccountId(), invoiceItem.getAccountId()); Assert.assertNull(adjustedInvoiceItem.getBundleId()); Assert.assertEquals(adjustedInvoiceItem.getCurrency(), invoiceItem.getCurrency()); Assert.assertEquals(adjustedInvoiceItem.getDescription(), "item-adj"); Assert.assertEquals(adjustedInvoiceItem.getEndDate(), effectiveDate); Assert.assertEquals(adjustedInvoiceItem.getInvoiceId(), invoiceItem.getInvoiceId()); Assert.assertEquals(adjustedInvoiceItem.getInvoiceItemType(), InvoiceItemType.ITEM_ADJ); Assert.assertEquals(adjustedInvoiceItem.getLinkedItemId(), invoiceItem.getId()); Assert.assertNull(adjustedInvoiceItem.getPhaseName()); Assert.assertNull(adjustedInvoiceItem.getPlanName()); Assert.assertNull(adjustedInvoiceItem.getRate()); Assert.assertEquals(adjustedInvoiceItem.getStartDate(), effectiveDate); Assert.assertNull(adjustedInvoiceItem.getSubscriptionId()); // Retrieve the item by id final InvoiceItem retrievedInvoiceItem = invoiceItemSqlDao.getById(adjustedInvoiceItem.getId().toString()); Assert.assertEquals(retrievedInvoiceItem, adjustedInvoiceItem); // Retrieve the item by invoice id final Invoice retrievedInvoice = invoiceDao.getById(adjustedInvoiceItem.getInvoiceId()); final List<InvoiceItem> invoiceItems = retrievedInvoice.getInvoiceItems(); Assert.assertEquals(invoiceItems.size(), 2); final InvoiceItem retrievedByInvoiceInvoiceItem; if (invoiceItems.get(0).getId().equals(adjustedInvoiceItem.getId())) { retrievedByInvoiceInvoiceItem = invoiceItems.get(0); } else { retrievedByInvoiceInvoiceItem = invoiceItems.get(1); } Assert.assertEquals(retrievedByInvoiceInvoiceItem, adjustedInvoiceItem); // Verify the invoice balance if (amount == null) { Assert.assertEquals(retrievedInvoice.getBalance().compareTo(BigDecimal.ZERO), 0); } else { Assert.assertEquals(retrievedInvoice.getBalance().compareTo(INVOICE_ITEM_AMOUNT.add(amount.negate())), 0); } return adjustedInvoiceItem; }
private InvoiceItem createAndCheckAdjustment(final Invoice invoice, final InvoiceItem invoiceItem, final BigDecimal amount) throws InvoiceApiException { final LocalDate effectiveDate = new LocalDate(2010, 1, 1); final InvoiceItem adjustedInvoiceItem = invoiceDao.insertInvoiceItemAdjustment(invoice.getAccountId(), invoice.getId(), invoiceItem.getId(), effectiveDate, amount, null, context); Assert.assertEquals(adjustedInvoiceItem.getAccountId(), invoiceItem.getAccountId()); Assert.assertNull(adjustedInvoiceItem.getBundleId()); Assert.assertEquals(adjustedInvoiceItem.getCurrency(), invoiceItem.getCurrency()); Assert.assertEquals(adjustedInvoiceItem.getDescription(), "Invoice item adjustment"); Assert.assertEquals(adjustedInvoiceItem.getEndDate(), effectiveDate); Assert.assertEquals(adjustedInvoiceItem.getInvoiceId(), invoiceItem.getInvoiceId()); Assert.assertEquals(adjustedInvoiceItem.getInvoiceItemType(), InvoiceItemType.ITEM_ADJ); Assert.assertEquals(adjustedInvoiceItem.getLinkedItemId(), invoiceItem.getId()); Assert.assertNull(adjustedInvoiceItem.getPhaseName()); Assert.assertNull(adjustedInvoiceItem.getPlanName()); Assert.assertNull(adjustedInvoiceItem.getRate()); Assert.assertEquals(adjustedInvoiceItem.getStartDate(), effectiveDate); Assert.assertNull(adjustedInvoiceItem.getSubscriptionId()); // Retrieve the item by id final InvoiceItem retrievedInvoiceItem = invoiceItemSqlDao.getById(adjustedInvoiceItem.getId().toString()); Assert.assertEquals(retrievedInvoiceItem, adjustedInvoiceItem); // Retrieve the item by invoice id final Invoice retrievedInvoice = invoiceDao.getById(adjustedInvoiceItem.getInvoiceId()); final List<InvoiceItem> invoiceItems = retrievedInvoice.getInvoiceItems(); Assert.assertEquals(invoiceItems.size(), 2); final InvoiceItem retrievedByInvoiceInvoiceItem; if (invoiceItems.get(0).getId().equals(adjustedInvoiceItem.getId())) { retrievedByInvoiceInvoiceItem = invoiceItems.get(0); } else { retrievedByInvoiceInvoiceItem = invoiceItems.get(1); } Assert.assertEquals(retrievedByInvoiceInvoiceItem, adjustedInvoiceItem); // Verify the invoice balance if (amount == null) { Assert.assertEquals(retrievedInvoice.getBalance().compareTo(BigDecimal.ZERO), 0); } else { Assert.assertEquals(retrievedInvoice.getBalance().compareTo(INVOICE_ITEM_AMOUNT.add(amount.negate())), 0); } return adjustedInvoiceItem; }
diff --git a/src/com/itmill/toolkit/demo/featurebrowser/ComboBoxExample.java b/src/com/itmill/toolkit/demo/featurebrowser/ComboBoxExample.java index df8fa688d..810b5728f 100644 --- a/src/com/itmill/toolkit/demo/featurebrowser/ComboBoxExample.java +++ b/src/com/itmill/toolkit/demo/featurebrowser/ComboBoxExample.java @@ -1,69 +1,70 @@ /* @ITMillApache2LicenseForJavaFiles@ */ package com.itmill.toolkit.demo.featurebrowser; import java.util.Random; import com.itmill.toolkit.ui.ComboBox; import com.itmill.toolkit.ui.CustomComponent; import com.itmill.toolkit.ui.OrderedLayout; import com.itmill.toolkit.ui.AbstractSelect.Filtering; /** * */ public class ComboBoxExample extends CustomComponent { private static final String[] firstnames = new String[] { "John", "Mary", "Joe", "Sarah", "Jeff", "Jane", "Peter", "Marc", "Robert", "Paula", "Lenny", "Kenny", "Nathan", "Nicole", "Laura", "Jos", "Josie", "Linus" }; private static final String[] lastnames = new String[] { "Torvalds", "Smith", "Adams", "Black", "Wilson", "Richards", "Thompson", "McGoff", "Halas", "Jones", "Beck", "Sheridan", "Picard", "Hill", "Fielding", "Einstein" }; public ComboBoxExample() { final OrderedLayout main = new OrderedLayout(); main.setMargin(true); setCompositionRoot(main); // starts-with filter final ComboBox s1 = new ComboBox("Select with starts-with filter"); s1.setFilteringMode(Filtering.FILTERINGMODE_STARTSWITH); s1.setColumns(20); Random r = new Random(5); for (int i = 0; i < 105; i++) { s1 .addItem(firstnames[(int) (r.nextDouble() * (firstnames.length - 1))] + " " + lastnames[(int) (r.nextDouble() * (lastnames.length - 1))]); } s1.setImmediate(true); main.addComponent(s1); // contains filter final ComboBox s2 = new ComboBox("Select with contains filter"); s2.setFilteringMode(Filtering.FILTERINGMODE_CONTAINS); s2.setColumns(20); for (int i = 0; i < 500; i++) { s2 .addItem(firstnames[(int) (r.nextDouble() * (firstnames.length - 1))] + " " + lastnames[(int) (r.nextDouble() * (lastnames.length - 1))]); } s2.setImmediate(true); main.addComponent(s2); // initially empty final ComboBox s3 = new ComboBox("Initially empty; enter your own"); s3.setColumns(20); s3.setImmediate(true); + s3.setNewItemsAllowed(true); main.addComponent(s3); } }
true
true
public ComboBoxExample() { final OrderedLayout main = new OrderedLayout(); main.setMargin(true); setCompositionRoot(main); // starts-with filter final ComboBox s1 = new ComboBox("Select with starts-with filter"); s1.setFilteringMode(Filtering.FILTERINGMODE_STARTSWITH); s1.setColumns(20); Random r = new Random(5); for (int i = 0; i < 105; i++) { s1 .addItem(firstnames[(int) (r.nextDouble() * (firstnames.length - 1))] + " " + lastnames[(int) (r.nextDouble() * (lastnames.length - 1))]); } s1.setImmediate(true); main.addComponent(s1); // contains filter final ComboBox s2 = new ComboBox("Select with contains filter"); s2.setFilteringMode(Filtering.FILTERINGMODE_CONTAINS); s2.setColumns(20); for (int i = 0; i < 500; i++) { s2 .addItem(firstnames[(int) (r.nextDouble() * (firstnames.length - 1))] + " " + lastnames[(int) (r.nextDouble() * (lastnames.length - 1))]); } s2.setImmediate(true); main.addComponent(s2); // initially empty final ComboBox s3 = new ComboBox("Initially empty; enter your own"); s3.setColumns(20); s3.setImmediate(true); main.addComponent(s3); }
public ComboBoxExample() { final OrderedLayout main = new OrderedLayout(); main.setMargin(true); setCompositionRoot(main); // starts-with filter final ComboBox s1 = new ComboBox("Select with starts-with filter"); s1.setFilteringMode(Filtering.FILTERINGMODE_STARTSWITH); s1.setColumns(20); Random r = new Random(5); for (int i = 0; i < 105; i++) { s1 .addItem(firstnames[(int) (r.nextDouble() * (firstnames.length - 1))] + " " + lastnames[(int) (r.nextDouble() * (lastnames.length - 1))]); } s1.setImmediate(true); main.addComponent(s1); // contains filter final ComboBox s2 = new ComboBox("Select with contains filter"); s2.setFilteringMode(Filtering.FILTERINGMODE_CONTAINS); s2.setColumns(20); for (int i = 0; i < 500; i++) { s2 .addItem(firstnames[(int) (r.nextDouble() * (firstnames.length - 1))] + " " + lastnames[(int) (r.nextDouble() * (lastnames.length - 1))]); } s2.setImmediate(true); main.addComponent(s2); // initially empty final ComboBox s3 = new ComboBox("Initially empty; enter your own"); s3.setColumns(20); s3.setImmediate(true); s3.setNewItemsAllowed(true); main.addComponent(s3); }
diff --git a/src/main/java/net/floodlightcontroller/hand/HANDRulesResource.java b/src/main/java/net/floodlightcontroller/hand/HANDRulesResource.java index b76ffe51..ef4dffeb 100644 --- a/src/main/java/net/floodlightcontroller/hand/HANDRulesResource.java +++ b/src/main/java/net/floodlightcontroller/hand/HANDRulesResource.java @@ -1,246 +1,246 @@ package net.floodlightcontroller.hand; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.JsonToken; import org.codehaus.jackson.map.MappingJsonFactory; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Post; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HANDRulesResource extends ServerResource { public static Logger logger = LoggerFactory.getLogger(HANDGangliaHostsResource.class); @Get("json") public Object handleRequest(){ IHANDService hand = (IHANDService)getContext().getAttributes(). get(IHANDService.class.getCanonicalName()); String status = null; if(hand.isHANDEnabled()){ return hand.getRules(); } else{ status = "Please enable Host Aware Networking Decisions"; return ("{\"status\" : \"" + status + "\"}"); } } /** * * @param ruleJson * @return */ @Post public String addRule(String ruleJson){ IHANDService hand = (IHANDService)getContext().getAttributes(). get(IHANDService.class.getCanonicalName()); HANDRule rule; String status = null; try{ rule = jsonToGangliaRule(ruleJson); } catch(IOException e){ logger.error("Error parsing rule to JSON: {}, Error: {}", ruleJson, e); e.printStackTrace(); return "{\"status\" : \"Error! Could not parse rule, see log for details.\"}"; } if(ruleExists(rule, hand.getRules())){ status = "Error!, This rule already exists!"; logger.error(status); } else{ if(hand.isHANDEnabled()){ /** * Add Code to handle checks * e.g * * is firewall rule, is the firewall enabled? * is a qos rule, is QoS enabled? * is the polling time good? make sense? * * *Host Assoc is check in json parse * *ActionType is checked in json parse * *Metrics are parsed in json parse * * * Then add the rule * * TODO !!!!!!************** */ } } return "{\"status\" : "+ status +"}"; } /** * * @param ruleJson * @return */ @Delete public String deleteRule(String ruleJson){ //TODO /** * * !!!!!!!!!!!!!!!!!!!! * * */ return null; } private static HANDRule jsonToGangliaRule(String ruleJson) throws IOException{ HANDRule rule = new HANDRule(); MappingJsonFactory jsonFactory = new MappingJsonFactory(); JsonParser parser; try{ parser = jsonFactory.createJsonParser(ruleJson); }catch(JsonParseException e){ throw new IOException (e); } JsonToken token = parser.getCurrentToken(); if(token != JsonToken.START_OBJECT){ parser.nextToken(); if(parser.getCurrentToken() != JsonToken.START_OBJECT){ logger.error("did not recieve json start token, current token is: {}" + parser.getCurrentToken()); } } //Start parsing while(parser.nextToken() != JsonToken.END_OBJECT){ if(parser.getCurrentToken() != JsonToken.FIELD_NAME){ throw new IOException("FIELD_NAME expected"); } try{ String name = parser.getCurrentName(); parser.nextToken(); //current text in parser String jsonText = parser.getText(); logger.info("JSON Parser text is: {}", jsonText); //DEBUG if(jsonText.equals("")){ //ignore empty string, return to loop continue; } else if(name == "rule_name"){ rule.name = jsonText; } else if(name == "priority"){ //TODO } else if(name == "polling_time"){ //TODO } else if(name == "active"){ //TODO } else if(name == "check_limit"){ //TODO } else if(name == "attached_to"){ //TODO given host X, get the ID from the list of //hosts known by HAND } else if(name == "metrics"){ - //�metrics�:{�<m1>�:"<threshold>�}....(list assumes �and� ) + //"metrics":{"<m1>":"<threshold>"}....(list assumes "and" ) //TODO store key value pars in a json string. //Call parseMetrics //Return HashMap<String, HANDThreshold> //e.g a {"load_one":"gt-5"} should result in a // rule that tracks Load of 1 Min that triggers when it is >5 Load/Procs //Also, make sure ganglia can see this metric //TODO checkGangliaMetrics(HashMap<String, HANDThreshold> metrics) } else if(name == "action_type"){ //TODO /** Can be one of the following from * net.floodlightcontroller.hand.HandRule.java * RPRT, //Report threshold is reported AFR, //Add Firewall Rule DFW, //Delete Firewall Rule LB, //LoadBalance (placeholder for now //TODO ) PSF, //Push Static Flow AQOS, //Add QoS Rule DQOS, //Delete QoS Rule KR, //Kill Route */ //TODO call boolean checkActionType from HandRule // change the string to ALL CAPS. } else if(name == "action_string"){ //TODO /** * This is an odd one, depending on the * ActionType, we will need different information from * the actionString. I.E a Adding a Firewall Rule needs * specific info rather than Pushing a Static Flow */ //TODO Call parseActionString(rule.action, rule.actionString) //parsing the action string first looks at the ActionType, //depending on the ActionType, the functions will determine //what information it needs to call to the correct //controller API and checl the action_string if has given the //correct information via key:value pairs. rule.actionString = jsonText; } }catch(JsonParseException e){ logger.debug("Error getting current FIELD_NAME {}", e); }catch(IOException e){ logger.debug("Error procession Json {}", e); } } //Return the HANDGangliaHost Object to the GangliaHostResource return rule; } /** * * @param rule * @param ruleList * @return */ public static boolean ruleExists(HANDRule rule, ArrayList<HANDRule> ruleList){ Iterator<HANDRule> ruleIter = ruleList.iterator(); while(ruleIter.hasNext()){ HANDRule r = ruleIter.next(); if(rule.isSameAs(r) || rule.name == r.name || rule.equals(r)){ return true; } } return false; } }
true
true
private static HANDRule jsonToGangliaRule(String ruleJson) throws IOException{ HANDRule rule = new HANDRule(); MappingJsonFactory jsonFactory = new MappingJsonFactory(); JsonParser parser; try{ parser = jsonFactory.createJsonParser(ruleJson); }catch(JsonParseException e){ throw new IOException (e); } JsonToken token = parser.getCurrentToken(); if(token != JsonToken.START_OBJECT){ parser.nextToken(); if(parser.getCurrentToken() != JsonToken.START_OBJECT){ logger.error("did not recieve json start token, current token is: {}" + parser.getCurrentToken()); } } //Start parsing while(parser.nextToken() != JsonToken.END_OBJECT){ if(parser.getCurrentToken() != JsonToken.FIELD_NAME){ throw new IOException("FIELD_NAME expected"); } try{ String name = parser.getCurrentName(); parser.nextToken(); //current text in parser String jsonText = parser.getText(); logger.info("JSON Parser text is: {}", jsonText); //DEBUG if(jsonText.equals("")){ //ignore empty string, return to loop continue; } else if(name == "rule_name"){ rule.name = jsonText; } else if(name == "priority"){ //TODO } else if(name == "polling_time"){ //TODO } else if(name == "active"){ //TODO } else if(name == "check_limit"){ //TODO } else if(name == "attached_to"){ //TODO given host X, get the ID from the list of //hosts known by HAND } else if(name == "metrics"){ //�metrics�:{�<m1>�:"<threshold>�}....(list assumes �and� ) //TODO store key value pars in a json string. //Call parseMetrics //Return HashMap<String, HANDThreshold> //e.g a {"load_one":"gt-5"} should result in a // rule that tracks Load of 1 Min that triggers when it is >5 Load/Procs //Also, make sure ganglia can see this metric //TODO checkGangliaMetrics(HashMap<String, HANDThreshold> metrics) } else if(name == "action_type"){ //TODO /** Can be one of the following from * net.floodlightcontroller.hand.HandRule.java * RPRT, //Report threshold is reported AFR, //Add Firewall Rule DFW, //Delete Firewall Rule LB, //LoadBalance (placeholder for now //TODO ) PSF, //Push Static Flow AQOS, //Add QoS Rule DQOS, //Delete QoS Rule KR, //Kill Route */ //TODO call boolean checkActionType from HandRule // change the string to ALL CAPS. } else if(name == "action_string"){ //TODO /** * This is an odd one, depending on the * ActionType, we will need different information from * the actionString. I.E a Adding a Firewall Rule needs * specific info rather than Pushing a Static Flow */ //TODO Call parseActionString(rule.action, rule.actionString) //parsing the action string first looks at the ActionType, //depending on the ActionType, the functions will determine //what information it needs to call to the correct //controller API and checl the action_string if has given the //correct information via key:value pairs. rule.actionString = jsonText; } }catch(JsonParseException e){ logger.debug("Error getting current FIELD_NAME {}", e); }catch(IOException e){ logger.debug("Error procession Json {}", e); } } //Return the HANDGangliaHost Object to the GangliaHostResource return rule; }
private static HANDRule jsonToGangliaRule(String ruleJson) throws IOException{ HANDRule rule = new HANDRule(); MappingJsonFactory jsonFactory = new MappingJsonFactory(); JsonParser parser; try{ parser = jsonFactory.createJsonParser(ruleJson); }catch(JsonParseException e){ throw new IOException (e); } JsonToken token = parser.getCurrentToken(); if(token != JsonToken.START_OBJECT){ parser.nextToken(); if(parser.getCurrentToken() != JsonToken.START_OBJECT){ logger.error("did not recieve json start token, current token is: {}" + parser.getCurrentToken()); } } //Start parsing while(parser.nextToken() != JsonToken.END_OBJECT){ if(parser.getCurrentToken() != JsonToken.FIELD_NAME){ throw new IOException("FIELD_NAME expected"); } try{ String name = parser.getCurrentName(); parser.nextToken(); //current text in parser String jsonText = parser.getText(); logger.info("JSON Parser text is: {}", jsonText); //DEBUG if(jsonText.equals("")){ //ignore empty string, return to loop continue; } else if(name == "rule_name"){ rule.name = jsonText; } else if(name == "priority"){ //TODO } else if(name == "polling_time"){ //TODO } else if(name == "active"){ //TODO } else if(name == "check_limit"){ //TODO } else if(name == "attached_to"){ //TODO given host X, get the ID from the list of //hosts known by HAND } else if(name == "metrics"){ //"metrics":{"<m1>":"<threshold>"}....(list assumes "and" ) //TODO store key value pars in a json string. //Call parseMetrics //Return HashMap<String, HANDThreshold> //e.g a {"load_one":"gt-5"} should result in a // rule that tracks Load of 1 Min that triggers when it is >5 Load/Procs //Also, make sure ganglia can see this metric //TODO checkGangliaMetrics(HashMap<String, HANDThreshold> metrics) } else if(name == "action_type"){ //TODO /** Can be one of the following from * net.floodlightcontroller.hand.HandRule.java * RPRT, //Report threshold is reported AFR, //Add Firewall Rule DFW, //Delete Firewall Rule LB, //LoadBalance (placeholder for now //TODO ) PSF, //Push Static Flow AQOS, //Add QoS Rule DQOS, //Delete QoS Rule KR, //Kill Route */ //TODO call boolean checkActionType from HandRule // change the string to ALL CAPS. } else if(name == "action_string"){ //TODO /** * This is an odd one, depending on the * ActionType, we will need different information from * the actionString. I.E a Adding a Firewall Rule needs * specific info rather than Pushing a Static Flow */ //TODO Call parseActionString(rule.action, rule.actionString) //parsing the action string first looks at the ActionType, //depending on the ActionType, the functions will determine //what information it needs to call to the correct //controller API and checl the action_string if has given the //correct information via key:value pairs. rule.actionString = jsonText; } }catch(JsonParseException e){ logger.debug("Error getting current FIELD_NAME {}", e); }catch(IOException e){ logger.debug("Error procession Json {}", e); } } //Return the HANDGangliaHost Object to the GangliaHostResource return rule; }
diff --git a/web/src/main/java/de/betterform/agent/web/resources/ResourceServlet.java b/web/src/main/java/de/betterform/agent/web/resources/ResourceServlet.java index 97d5bc95..0915fbe4 100644 --- a/web/src/main/java/de/betterform/agent/web/resources/ResourceServlet.java +++ b/web/src/main/java/de/betterform/agent/web/resources/ResourceServlet.java @@ -1,188 +1,188 @@ /* * Copyright 2009 Prime Technology. * * 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 de.betterform.agent.web.resources; import de.betterform.agent.web.resources.stream.DefaultResourceStreamer; import de.betterform.agent.web.resources.stream.ResourceStreamer; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * ResourceServlet is responsible for streaming resources like css, script, images and etc to the client. * Streaming is done via ResourceStreamers and resources are forced to be cached indefinitely using convenient response headers. */ public class ResourceServlet extends HttpServlet { private static final Logger logger = Logger.getLogger(ResourceServlet.class.getName()); private static Map<String, String> mimeTypes; private List<ResourceStreamer> resourceStreamers; public final static String RESOURCE_FOLDER = "/META-INF/resources"; public final static String RESOURCE_PATTERN = "bfResources"; @Override public void init(ServletConfig config) throws ServletException { super.init(config); initMimeTypes(); initResourceStreamers(); } private void initMimeTypes() { mimeTypes = new HashMap<String, String>(); mimeTypes.put("css", "text/css"); mimeTypes.put("js", "text/js"); mimeTypes.put("jpg", "image/jpeg"); mimeTypes.put("jpeg", "image/jpeg"); mimeTypes.put("png", "image/png"); mimeTypes.put("gif", "image/gif"); mimeTypes.put("gif", "image/gif"); mimeTypes.put("html", "text/html"); mimeTypes.put("swf", "application/x-shockwave-flash"); } private void initResourceStreamers() { resourceStreamers = new ArrayList<ResourceStreamer>(); resourceStreamers.add(new DefaultResourceStreamer()); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String requestUri = req.getRequestURI(); String resourcePath = RESOURCE_FOLDER + getResourcePath(requestUri); URL url = ResourceServlet.class.getResource(resourcePath); if (logger.isLoggable(Level.FINE)){ logger.log(Level.INFO,"Request URI: " + requestUri); logger.log(Level.INFO,"resourcePath: " + requestUri); logger.log(Level.INFO,"resource url: " + requestUri); } if (url == null) { - logger.log(Level.WARNING, "Resource \"{0}\" not found", resourcePath); boolean error = true; if(requestUri.endsWith(".js")){ //try optimized version first if (requestUri.contains("scripts/betterform/betterform-")) { if (ResourceServlet.class.getResource(resourcePath) == null) { resourcePath = resourcePath.replace("betterform-", "BfRequired"); if (ResourceServlet.class.getResource(resourcePath) != null) { error=false; } } } } if(error) { + logger.log(Level.WARNING, "Resource \"{0}\" not found", resourcePath); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "Streaming resource \"{0}\"", resourcePath); InputStream inputStream = null; try { inputStream = ResourceServlet.class.getResourceAsStream(resourcePath); String mimeType = getResourceContentType(resourcePath); if (mimeType == null) { logger.log(Level.WARNING, "MimeType for \"{0}\" not found. Sending not found", resourcePath); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } resp.setContentType(mimeType); resp.setStatus(HttpServletResponse.SC_OK); setCaching(req, resp); streamResource(req, resp, mimeType, inputStream); if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "Resource \"{0}\" streamed succesfully", resourcePath); } catch (Exception exception) { logger.log(Level.SEVERE, "Error in streaming resource \"{0}\". Exception is \"{1}\"", new Object[]{resourcePath, exception.getMessage()}); } finally { if (inputStream != null) { inputStream.close(); } resp.getOutputStream().flush(); resp.getOutputStream().close(); } } private void streamResource(HttpServletRequest req, HttpServletResponse resp, String mimeType, InputStream inputStream) throws IOException { for (ResourceStreamer streamer : resourceStreamers) { if (streamer.isAppropriateStreamer(mimeType)) streamer.stream(req, resp, inputStream); } } private void setCaching(HttpServletRequest request, HttpServletResponse response) { long now = System.currentTimeMillis(); long oneYear = 31363200000L; String query = request.getParameter("nocache"); if(query == null){ response.setHeader("Cache-Control", "Public"); response.setDateHeader("Expires", now + oneYear); }else{ response.setHeader("Cache-Control", "no-cache"); } } protected String getResourcePath(String requestURI) { int jsessionidIndex = requestURI.toLowerCase().indexOf(";jsessionid"); if (jsessionidIndex != -1) { requestURI = requestURI.substring(0, jsessionidIndex); } int patternIndex = requestURI.indexOf(RESOURCE_PATTERN); return requestURI.substring(patternIndex + RESOURCE_PATTERN.length(), requestURI.length()); } protected String getResourceContentType(String resourcePath) { String resourceFileExtension = getResourceFileExtension(resourcePath); return mimeTypes.get(resourceFileExtension); } protected String getResourceFileExtension(String resourcePath) { String parsed[] = resourcePath.split("\\."); return parsed[parsed.length - 1]; } }
false
true
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String requestUri = req.getRequestURI(); String resourcePath = RESOURCE_FOLDER + getResourcePath(requestUri); URL url = ResourceServlet.class.getResource(resourcePath); if (logger.isLoggable(Level.FINE)){ logger.log(Level.INFO,"Request URI: " + requestUri); logger.log(Level.INFO,"resourcePath: " + requestUri); logger.log(Level.INFO,"resource url: " + requestUri); } if (url == null) { logger.log(Level.WARNING, "Resource \"{0}\" not found", resourcePath); boolean error = true; if(requestUri.endsWith(".js")){ //try optimized version first if (requestUri.contains("scripts/betterform/betterform-")) { if (ResourceServlet.class.getResource(resourcePath) == null) { resourcePath = resourcePath.replace("betterform-", "BfRequired"); if (ResourceServlet.class.getResource(resourcePath) != null) { error=false; } } } } if(error) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "Streaming resource \"{0}\"", resourcePath); InputStream inputStream = null; try { inputStream = ResourceServlet.class.getResourceAsStream(resourcePath); String mimeType = getResourceContentType(resourcePath); if (mimeType == null) { logger.log(Level.WARNING, "MimeType for \"{0}\" not found. Sending not found", resourcePath); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } resp.setContentType(mimeType); resp.setStatus(HttpServletResponse.SC_OK); setCaching(req, resp); streamResource(req, resp, mimeType, inputStream); if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "Resource \"{0}\" streamed succesfully", resourcePath); } catch (Exception exception) { logger.log(Level.SEVERE, "Error in streaming resource \"{0}\". Exception is \"{1}\"", new Object[]{resourcePath, exception.getMessage()}); } finally { if (inputStream != null) { inputStream.close(); } resp.getOutputStream().flush(); resp.getOutputStream().close(); } }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String requestUri = req.getRequestURI(); String resourcePath = RESOURCE_FOLDER + getResourcePath(requestUri); URL url = ResourceServlet.class.getResource(resourcePath); if (logger.isLoggable(Level.FINE)){ logger.log(Level.INFO,"Request URI: " + requestUri); logger.log(Level.INFO,"resourcePath: " + requestUri); logger.log(Level.INFO,"resource url: " + requestUri); } if (url == null) { boolean error = true; if(requestUri.endsWith(".js")){ //try optimized version first if (requestUri.contains("scripts/betterform/betterform-")) { if (ResourceServlet.class.getResource(resourcePath) == null) { resourcePath = resourcePath.replace("betterform-", "BfRequired"); if (ResourceServlet.class.getResource(resourcePath) != null) { error=false; } } } } if(error) { logger.log(Level.WARNING, "Resource \"{0}\" not found", resourcePath); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "Streaming resource \"{0}\"", resourcePath); InputStream inputStream = null; try { inputStream = ResourceServlet.class.getResourceAsStream(resourcePath); String mimeType = getResourceContentType(resourcePath); if (mimeType == null) { logger.log(Level.WARNING, "MimeType for \"{0}\" not found. Sending not found", resourcePath); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } resp.setContentType(mimeType); resp.setStatus(HttpServletResponse.SC_OK); setCaching(req, resp); streamResource(req, resp, mimeType, inputStream); if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "Resource \"{0}\" streamed succesfully", resourcePath); } catch (Exception exception) { logger.log(Level.SEVERE, "Error in streaming resource \"{0}\". Exception is \"{1}\"", new Object[]{resourcePath, exception.getMessage()}); } finally { if (inputStream != null) { inputStream.close(); } resp.getOutputStream().flush(); resp.getOutputStream().close(); } }
diff --git a/test/unit/DisplayControllerTest.java b/test/unit/DisplayControllerTest.java index 47b3430..17f04b4 100644 --- a/test/unit/DisplayControllerTest.java +++ b/test/unit/DisplayControllerTest.java @@ -1,47 +1,47 @@ package unit; import static org.junit.Assert.*; import glare.ClassFactory; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; import resources.DatabaseManagerDummy; import dal.DatabaseHandler; import dal.DatabaseManager; import bll.DisplayController; import bll.PictureController; public class DisplayControllerTest { private DisplayController dc; private PictureController pc; private DatabaseHandler dbHandler; private DatabaseManagerDummy dbManagerDummy; @Before public void setUp() throws IOException{ dbHandler = new DatabaseHandler(); dbManagerDummy = new DatabaseManagerDummy(dbHandler); pc = new PictureController(dbManagerDummy); dc = new DisplayController(pc); - dc.getCurrentPicture(false); + dc.getCurrentPicture(); } @After public void tearDown(){ dc = null; } @Test public void test() { fail("Not yet implemented"); } }
true
true
public void setUp() throws IOException{ dbHandler = new DatabaseHandler(); dbManagerDummy = new DatabaseManagerDummy(dbHandler); pc = new PictureController(dbManagerDummy); dc = new DisplayController(pc); dc.getCurrentPicture(false); }
public void setUp() throws IOException{ dbHandler = new DatabaseHandler(); dbManagerDummy = new DatabaseManagerDummy(dbHandler); pc = new PictureController(dbManagerDummy); dc = new DisplayController(pc); dc.getCurrentPicture(); }
diff --git a/java/client/src/org/openqa/selenium/internal/seleniumemulation/ElementFinder.java b/java/client/src/org/openqa/selenium/internal/seleniumemulation/ElementFinder.java index 18be2c908..28c12886e 100644 --- a/java/client/src/org/openqa/selenium/internal/seleniumemulation/ElementFinder.java +++ b/java/client/src/org/openqa/selenium/internal/seleniumemulation/ElementFinder.java @@ -1,164 +1,163 @@ /* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.internal.seleniumemulation; import java.io.IOException; import java.net.URL; import java.util.Map; import java.util.logging.Logger; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Charsets; import com.google.common.collect.Maps; import com.google.common.io.Resources; import com.thoughtworks.selenium.SeleniumException; public class ElementFinder { private final static Logger log = Logger.getLogger(ElementFinder.class.getName()); private final String findElement; private final String sizzle; private final Map<String, String> additionalLocators = Maps.newHashMap(); @VisibleForTesting protected ElementFinder() { findElement = null; sizzle = null; } public ElementFinder(JavascriptLibrary library) { String rawScript = library.getSeleniumScript("findElement.js"); findElement = "return (" + rawScript + ")(arguments[0]);"; String linkTextLocator = "return (" + library.getSeleniumScript("linkLocator.js") + ").call(null, arguments[0], document)"; add("link", linkTextLocator); try { URL url = Resources.getResource(getClass().getPackage().getName().replace(".", "/") + "/sizzle.js"); sizzle = Resources.toString(url, Charsets.UTF_8) + "var results = []; " + "try { Sizzle(arguments[0], document, results);} " + "catch (ignored) {} " + "return results.length ? results[0] : null;"; add("sizzle", sizzle); } catch (IOException e) { throw new SeleniumException("Cannot read sizzle"); } } public WebElement findElement(WebDriver driver, String locator) { WebElement toReturn = null; String strategy = searchAdditionalStrategies(locator); if (strategy != null) { String actualLocator = locator.substring(locator.indexOf('=') + 1); // TODO(simon): Recurse into child documents try { toReturn = (WebElement) ((JavascriptExecutor) driver).executeScript(strategy, actualLocator); if (toReturn == null) { throw new SeleniumException("Element " + locator + " not found"); } return toReturn; } catch (WebDriverException e) { throw new SeleniumException("Element " + locator + " not found"); } } try { toReturn = findElementDirectlyIfNecessary(driver, locator); if (toReturn != null) { return toReturn; } return (WebElement) ((JavascriptExecutor) driver).executeScript(findElement, locator); } catch (WebDriverException e) { - e.printStackTrace(); throw new SeleniumException("Element " + locator + " not found", e); } } public void add(String strategyName, String implementation) { additionalLocators.put(strategyName, implementation); } private String searchAdditionalStrategies(String locator) { int index = locator.indexOf('='); if (index == -1) { return null; } String key = locator.substring(0, index); return additionalLocators.get(key); } private WebElement findElementDirectlyIfNecessary(WebDriver driver, String locator) { if (locator.startsWith("xpath=")) { return xpathWizardry(driver, locator.substring("xpath=".length())); } if (locator.startsWith("//")) { return xpathWizardry(driver, locator); } if (locator.startsWith("css=")) { String selector = locator.substring("css=".length()); try { return driver.findElement(By.cssSelector(selector)); } catch (WebDriverException e) { return fallbackToSizzle(driver, selector); } } if (locator.startsWith("link=")) { } return null; } private WebElement xpathWizardry(WebDriver driver, String xpath) { try { return driver.findElement(By.xpath(xpath)); } catch (WebDriverException ignored) {} // Because we have inconsitent return values if (xpath.endsWith("/")) { return driver.findElement(By.xpath(xpath.substring(0, xpath.length() - 1))); } throw new NoSuchElementException("Cannot find an element with the xpath: " + xpath); } private WebElement fallbackToSizzle(WebDriver driver, String locator) { WebElement toReturn = (WebElement) ((JavascriptExecutor) driver).executeScript(sizzle, locator); if (toReturn != null) { log.warning("You are using a Sizzle locator as a CSS Selector. " + "Please use the Sizzle library directly via the JavascriptExecutor or a plain CSS " + "selector. Your locator was: " + locator); return toReturn; } throw new NoSuchElementException("Cannot locate element even after falling back to Sizzle: " + locator); } }
true
true
public WebElement findElement(WebDriver driver, String locator) { WebElement toReturn = null; String strategy = searchAdditionalStrategies(locator); if (strategy != null) { String actualLocator = locator.substring(locator.indexOf('=') + 1); // TODO(simon): Recurse into child documents try { toReturn = (WebElement) ((JavascriptExecutor) driver).executeScript(strategy, actualLocator); if (toReturn == null) { throw new SeleniumException("Element " + locator + " not found"); } return toReturn; } catch (WebDriverException e) { throw new SeleniumException("Element " + locator + " not found"); } } try { toReturn = findElementDirectlyIfNecessary(driver, locator); if (toReturn != null) { return toReturn; } return (WebElement) ((JavascriptExecutor) driver).executeScript(findElement, locator); } catch (WebDriverException e) { e.printStackTrace(); throw new SeleniumException("Element " + locator + " not found", e); } }
public WebElement findElement(WebDriver driver, String locator) { WebElement toReturn = null; String strategy = searchAdditionalStrategies(locator); if (strategy != null) { String actualLocator = locator.substring(locator.indexOf('=') + 1); // TODO(simon): Recurse into child documents try { toReturn = (WebElement) ((JavascriptExecutor) driver).executeScript(strategy, actualLocator); if (toReturn == null) { throw new SeleniumException("Element " + locator + " not found"); } return toReturn; } catch (WebDriverException e) { throw new SeleniumException("Element " + locator + " not found"); } } try { toReturn = findElementDirectlyIfNecessary(driver, locator); if (toReturn != null) { return toReturn; } return (WebElement) ((JavascriptExecutor) driver).executeScript(findElement, locator); } catch (WebDriverException e) { throw new SeleniumException("Element " + locator + " not found", e); } }
diff --git a/AndroidApp/src/net/hackergarten/android/app/client/HackergartenClient.java b/AndroidApp/src/net/hackergarten/android/app/client/HackergartenClient.java index 81a2b43..fa023dc 100644 --- a/AndroidApp/src/net/hackergarten/android/app/client/HackergartenClient.java +++ b/AndroidApp/src/net/hackergarten/android/app/client/HackergartenClient.java @@ -1,196 +1,196 @@ package net.hackergarten.android.app.client; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import android.content.ContentValues; import android.content.Entity; import android.util.Log; import net.hackergarten.android.app.model.Event; import net.hackergarten.android.app.model.User; /** * Handles all the communication to the Hackergarten server. All method calls * start new threads for the Http communication. * * @author asocaciu * */ public class HackergartenClient { private static final String BASE_URL = "http://hackergarten-register.appspot.com"; // private static final String BASE_URL = "http://192.168.3.136:8888"; private static final String TAG = "HackergartenClient"; private interface ResponseProcessor<T> { T processResponse(HttpResponse response) throws IllegalStateException, IOException, JSONException; } private HttpClient httpClient; public HackergartenClient() { httpClient = new DefaultHttpClient(); } /** * Register a new User * * @param user * filled user object * @param callback */ public void registerUser(User user, AsyncCallback<Void> callback) { Log.d(TAG, "registerUser " + user); HttpPost post = new HttpPost(BASE_URL + "/user/"); post.setHeader("Content-Type", "text/plain");//GAE workaround HttpMapper.map(user, post); requestAsynchronously(callback, post, null); } /** * Initiate a new Hackergarten event * * @param event * @param callback */ public void addEvent(Event event, AsyncCallback<Void> callback) { Log.d(TAG, "addEvent " + event); HttpPost post = new HttpPost(BASE_URL + "/event/"); post.setHeader("Content-Type", "text/plain");//GAE workaround HttpMapper.map(event, post); requestAsynchronously(callback, post, null); } /** * List upcoming events based on current time * * @param callback */ public void listUpcomingEvents(AsyncCallback<List<Event>> callback) { HttpGet get = new HttpGet(BASE_URL + "/event/"); long utcTimeMillis = DateUtils.getUTCTimeMillis(); get.getParams().setParameter(HttpMapper.TIME, utcTimeMillis); Log.d(TAG, "listUpcomingEvents " + utcTimeMillis); requestAsynchronously(callback, get, new ResponseProcessor<List<Event>>() { public List<Event> processResponse(HttpResponse response) throws IllegalStateException, IOException, JSONException { return HttpMapper.mapToEventList(response); } }); } /** * Check in a specific user to a specific event * * @param userEmail * @param eventId * @param callback */ public void checkInUser(String userEmail, String eventId, AsyncCallback<Void> callback) { Log.d(TAG, "checkInUser " + userEmail + ", " + eventId); HttpPost post = new HttpPost(BASE_URL + "/checkin/"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair(HttpMapper.EVENT_ID, eventId)); nameValuePairs.add(new BasicNameValuePair(HttpMapper.EMAIL, userEmail)); post.setHeader("Content-Type", "text/plain");//GAE workaround try { post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } requestAsynchronously(callback, post, null); } /** * List the top x users ordered by number of checkins descending * * @param callback */ public void listHallOfFame(AsyncCallback<List<User>> callback) { Log.d(TAG, "listHallOfFame"); HttpGet get = new HttpGet(BASE_URL + "/user/"); requestAsynchronously(callback, get, new ResponseProcessor<List<User>>() { public List<User> processResponse(HttpResponse response) throws IllegalStateException, IOException, JSONException { return HttpMapper.mapToUserList(response); } }); } /** * Release all connections */ public void close() { Log.d(TAG, "close"); httpClient.getConnectionManager().shutdown(); } private <V> void requestAsynchronously(final AsyncCallback<V> callback, final HttpUriRequest request, final ResponseProcessor<V> responseProcessor) { Thread thread = new Thread() { public void run() { try { Log.d(TAG, "requesting asynchronously " + request.getURI()); HttpResponse response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); Log.d(TAG, "got response code " + statusCode); if (statusCode == 200) { V result = null; if (responseProcessor != null) { Log.d(TAG, "processing response"); result = responseProcessor .processResponse(response); } Log.d(TAG, "onSuccess"); callback.onSuccess(result); } else { Log.d(TAG, "onFailure"); - callback.onFailure(null); + callback.onFailure(new Throwable("Unexpected status code: " + statusCode)); } if (response.getEntity() != null) { response.getEntity().consumeContent(); } } catch (ClientProtocolException e) { callback.onFailure(e); } catch (IOException e) { callback.onFailure(e); } catch (IllegalStateException e) { callback.onFailure(e); } catch (JSONException e) { callback.onFailure(e); } } }; thread.start(); } }
true
true
private <V> void requestAsynchronously(final AsyncCallback<V> callback, final HttpUriRequest request, final ResponseProcessor<V> responseProcessor) { Thread thread = new Thread() { public void run() { try { Log.d(TAG, "requesting asynchronously " + request.getURI()); HttpResponse response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); Log.d(TAG, "got response code " + statusCode); if (statusCode == 200) { V result = null; if (responseProcessor != null) { Log.d(TAG, "processing response"); result = responseProcessor .processResponse(response); } Log.d(TAG, "onSuccess"); callback.onSuccess(result); } else { Log.d(TAG, "onFailure"); callback.onFailure(null); } if (response.getEntity() != null) { response.getEntity().consumeContent(); } } catch (ClientProtocolException e) { callback.onFailure(e); } catch (IOException e) { callback.onFailure(e); } catch (IllegalStateException e) { callback.onFailure(e); } catch (JSONException e) { callback.onFailure(e); } } }; thread.start(); }
private <V> void requestAsynchronously(final AsyncCallback<V> callback, final HttpUriRequest request, final ResponseProcessor<V> responseProcessor) { Thread thread = new Thread() { public void run() { try { Log.d(TAG, "requesting asynchronously " + request.getURI()); HttpResponse response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); Log.d(TAG, "got response code " + statusCode); if (statusCode == 200) { V result = null; if (responseProcessor != null) { Log.d(TAG, "processing response"); result = responseProcessor .processResponse(response); } Log.d(TAG, "onSuccess"); callback.onSuccess(result); } else { Log.d(TAG, "onFailure"); callback.onFailure(new Throwable("Unexpected status code: " + statusCode)); } if (response.getEntity() != null) { response.getEntity().consumeContent(); } } catch (ClientProtocolException e) { callback.onFailure(e); } catch (IOException e) { callback.onFailure(e); } catch (IllegalStateException e) { callback.onFailure(e); } catch (JSONException e) { callback.onFailure(e); } } }; thread.start(); }
diff --git a/src/nz/gen/wellington/penguin/about.java b/src/nz/gen/wellington/penguin/about.java index 899385d..cea6849 100644 --- a/src/nz/gen/wellington/penguin/about.java +++ b/src/nz/gen/wellington/penguin/about.java @@ -1,40 +1,40 @@ package nz.gen.wellington.penguin; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.webkit.WebView; public class about extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.about); StringBuilder text = new StringBuilder(); - text.append("<p>The <a href=\"http://blog.tepapa.govt.nz/2011/06/29/the-global-penguin-%E2%80%93-part-2-the-young-emperor-penguin-pushes-the-boundaries-and-is-taken-into-care/\">lost emperor penguin 'Happy Feet'</a> is currently making his way home after recovering at Wellington Zoo. "); + text.append("<p>The <a href=\"http://tinyurl.com/3osqgtl/\">lost emperor penguin 'Happy Feet'</a> is currently making his way home after recovering at Wellington Zoo. "); text.append("<p>Happy Feet is wearing a <a href=\"http://blog.tepapa.govt.nz/2011/08/29/happy-feet-gets-technological/\">Sirtrack KiwiSat 202 Satellite Transmitter</a> which will track his progress after he is released into the Southern Ocean. "); text.append("This tracking data is been published on the <a href=\"http://www.nzemperor.com/\">@NZEmperor</a> website.</p>"); text.append("<p>This application periodically polls the tracking feed, raising an Android notification when a new position fix is published.</p>"); text.append("<p>Application developed by Tony McCrae.</p>"); text.append("<p>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.</p>"); text.append("<p>Full source code is available on Github: <a href=\"https://github.com/tonytw1/penguin-tracker\">https://github.com/tonytw1/penguin-tracker</a></p>"); text.append("<p>Penguin image obtained from a Creative Commons licensed photograph by <a href=\"http://www.flickr.com/photos/elisfanclub/5955801117\">Eli Duke</a>."); WebView about = (WebView) findViewById(R.id.about); about.loadData(text.toString(), "text/html", "UTF-8"); } // TODO Credit: // sirtrack // @nzemperor // github link }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.about); StringBuilder text = new StringBuilder(); text.append("<p>The <a href=\"http://blog.tepapa.govt.nz/2011/06/29/the-global-penguin-%E2%80%93-part-2-the-young-emperor-penguin-pushes-the-boundaries-and-is-taken-into-care/\">lost emperor penguin 'Happy Feet'</a> is currently making his way home after recovering at Wellington Zoo. "); text.append("<p>Happy Feet is wearing a <a href=\"http://blog.tepapa.govt.nz/2011/08/29/happy-feet-gets-technological/\">Sirtrack KiwiSat 202 Satellite Transmitter</a> which will track his progress after he is released into the Southern Ocean. "); text.append("This tracking data is been published on the <a href=\"http://www.nzemperor.com/\">@NZEmperor</a> website.</p>"); text.append("<p>This application periodically polls the tracking feed, raising an Android notification when a new position fix is published.</p>"); text.append("<p>Application developed by Tony McCrae.</p>"); text.append("<p>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.</p>"); text.append("<p>Full source code is available on Github: <a href=\"https://github.com/tonytw1/penguin-tracker\">https://github.com/tonytw1/penguin-tracker</a></p>"); text.append("<p>Penguin image obtained from a Creative Commons licensed photograph by <a href=\"http://www.flickr.com/photos/elisfanclub/5955801117\">Eli Duke</a>."); WebView about = (WebView) findViewById(R.id.about); about.loadData(text.toString(), "text/html", "UTF-8"); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.about); StringBuilder text = new StringBuilder(); text.append("<p>The <a href=\"http://tinyurl.com/3osqgtl/\">lost emperor penguin 'Happy Feet'</a> is currently making his way home after recovering at Wellington Zoo. "); text.append("<p>Happy Feet is wearing a <a href=\"http://blog.tepapa.govt.nz/2011/08/29/happy-feet-gets-technological/\">Sirtrack KiwiSat 202 Satellite Transmitter</a> which will track his progress after he is released into the Southern Ocean. "); text.append("This tracking data is been published on the <a href=\"http://www.nzemperor.com/\">@NZEmperor</a> website.</p>"); text.append("<p>This application periodically polls the tracking feed, raising an Android notification when a new position fix is published.</p>"); text.append("<p>Application developed by Tony McCrae.</p>"); text.append("<p>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.</p>"); text.append("<p>Full source code is available on Github: <a href=\"https://github.com/tonytw1/penguin-tracker\">https://github.com/tonytw1/penguin-tracker</a></p>"); text.append("<p>Penguin image obtained from a Creative Commons licensed photograph by <a href=\"http://www.flickr.com/photos/elisfanclub/5955801117\">Eli Duke</a>."); WebView about = (WebView) findViewById(R.id.about); about.loadData(text.toString(), "text/html", "UTF-8"); }
diff --git a/src/powercrystals/minefactoryreloaded/block/BlockVineScaffold.java b/src/powercrystals/minefactoryreloaded/block/BlockVineScaffold.java index 867b8331..6b27107b 100644 --- a/src/powercrystals/minefactoryreloaded/block/BlockVineScaffold.java +++ b/src/powercrystals/minefactoryreloaded/block/BlockVineScaffold.java @@ -1,188 +1,196 @@ package powercrystals.minefactoryreloaded.block; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.Icon; import net.minecraft.world.ColorizerFoliage; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.ForgeDirection; import powercrystals.core.position.BlockPosition; import powercrystals.minefactoryreloaded.MineFactoryReloadedCore; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class BlockVineScaffold extends Block { private Icon _sideIcon; private Icon _topIcon; private static final ForgeDirection[] _attachDirections = new ForgeDirection[] { ForgeDirection.NORTH, ForgeDirection.SOUTH, ForgeDirection.EAST, ForgeDirection.WEST }; private static final int _attachDistance = 16; public BlockVineScaffold(int id) { super(id, Material.leaves); setUnlocalizedName("mfr.vinescaffold"); setStepSound(soundGrassFootstep); setHardness(0.1F); setBlockBounds(0F, 0.01F, 0F, 1F, 0.99F, 1F); } @Override public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity entity) { if(entity instanceof EntityPlayerMP) { ((EntityPlayerMP)entity).playerNetServerHandler.ticksForFloatKick = 0; entity.fallDistance = 0; } } @Override public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int x, int y, int z) { return AxisAlignedBB.getAABBPool().getAABB(x + 0.05, y, z + 0.05, x + 0.95, y + 1, z + 0.95); } @Override @SideOnly(Side.CLIENT) public void registerIcons(IconRegister ir) { _sideIcon = ir.registerIcon("powercrystals/minefactoryreloaded/" + getUnlocalizedName() + ".side"); _topIcon = ir.registerIcon("powercrystals/minefactoryreloaded/" + getUnlocalizedName() + ".top"); } @Override @SideOnly(Side.CLIENT) public Icon getIcon(int side, int meta) { return side < 2 ? _topIcon : _sideIcon; } @Override public boolean isOpaqueCube() { return false; } @Override public boolean renderAsNormalBlock() { return false; } @Override public int getRenderType() { return MineFactoryReloadedCore.renderIdVineScaffold; } @Override @SideOnly(Side.CLIENT) public boolean shouldSideBeRendered(IBlockAccess world, int x, int y, int z, int side) { return true; } @Override @SideOnly(Side.CLIENT) public int getRenderColor(int meta) { return ColorizerFoliage.getFoliageColorBasic(); } @Override @SideOnly(Side.CLIENT) public int colorMultiplier(IBlockAccess world, int x, int y, int z) { int r = 0; int g = 0; int b = 0; for(int zOffset = -1; zOffset <= 1; ++zOffset) { for(int xOffset = -1; xOffset <= 1; ++xOffset) { int biomeColor = world.getBiomeGenForCoords(x + xOffset, z + zOffset).getBiomeFoliageColor(); r += (biomeColor & 16711680) >> 16; g += (biomeColor & 65280) >> 8; b += biomeColor & 255; } } return (r / 9 & 255) << 16 | (g / 9 & 255) << 8 | b / 9 & 255; } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float xOffset, float yOffset, float zOffset) { if(!world.isRemote && player.inventory.mainInventory[player.inventory.currentItem] != null && player.inventory.mainInventory[player.inventory.currentItem].itemID == blockID) { - for(int i = y; i < 256; i++) + for(int i = y + 1, e = world.getActualHeight(); i < e; ++i) { + int blockId = world.getBlockId(x, i, z); if(world.isAirBlock(x, i, z)) { - world.setBlock(x, i, z, blockID, 0, 3); - player.inventory.mainInventory[player.inventory.currentItem].stackSize--; - if(player.inventory.mainInventory[player.inventory.currentItem].stackSize == 0) + if (world.setBlock(x, i, z, blockID, 0, 3)) { - player.inventory.mainInventory[player.inventory.currentItem] = null; + player.swingItem(); + player.inventory.mainInventory[player.inventory.currentItem].stackSize--; + if(player.inventory.mainInventory[player.inventory.currentItem].stackSize == 0) + { + player.inventory.mainInventory[player.inventory.currentItem] = null; + } } break; } + else if (blockId != blockID) + { + break; + } } return true; } return false; } @Override public boolean canPlaceBlockAt(World world, int x, int y, int z) { return canBlockStay(world, x, y, z); } @Override public boolean canBlockStay(World world, int x, int y, int z) { if(world.isBlockSolidOnSide(x, y - 1, z, ForgeDirection.UP)) { return true; } for(ForgeDirection d : _attachDirections) { BlockPosition bp = new BlockPosition(x, y, z, d); for(int i = 0; i < _attachDistance; i++) { bp.moveForwards(1); if(world.getBlockId(bp.x, bp.y, bp.z) == blockID && world.isBlockSolidOnSide(bp.x, bp.y - 1, bp.z, ForgeDirection.UP)) { return true; } } } return false; } @Override public void onNeighborBlockChange(World world, int x, int y, int z, int side) { if(!canBlockStay(world, x, y, z)) { dropBlockAsItem(world, x, y, z, world.getBlockMetadata(x, y, z), 0); world.setBlockToAir(x, y, z); } } @Override public boolean isBlockSolidOnSide(World world, int x, int y, int z, ForgeDirection side) { return (side == ForgeDirection.UP || side == ForgeDirection.DOWN) ? true : false; } }
false
true
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float xOffset, float yOffset, float zOffset) { if(!world.isRemote && player.inventory.mainInventory[player.inventory.currentItem] != null && player.inventory.mainInventory[player.inventory.currentItem].itemID == blockID) { for(int i = y; i < 256; i++) { if(world.isAirBlock(x, i, z)) { world.setBlock(x, i, z, blockID, 0, 3); player.inventory.mainInventory[player.inventory.currentItem].stackSize--; if(player.inventory.mainInventory[player.inventory.currentItem].stackSize == 0) { player.inventory.mainInventory[player.inventory.currentItem] = null; } break; } } return true; } return false; }
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float xOffset, float yOffset, float zOffset) { if(!world.isRemote && player.inventory.mainInventory[player.inventory.currentItem] != null && player.inventory.mainInventory[player.inventory.currentItem].itemID == blockID) { for(int i = y + 1, e = world.getActualHeight(); i < e; ++i) { int blockId = world.getBlockId(x, i, z); if(world.isAirBlock(x, i, z)) { if (world.setBlock(x, i, z, blockID, 0, 3)) { player.swingItem(); player.inventory.mainInventory[player.inventory.currentItem].stackSize--; if(player.inventory.mainInventory[player.inventory.currentItem].stackSize == 0) { player.inventory.mainInventory[player.inventory.currentItem] = null; } } break; } else if (blockId != blockID) { break; } } return true; } return false; }
diff --git a/src/se/otaino2/breakoutgame/BreakoutBoardView.java b/src/se/otaino2/breakoutgame/BreakoutBoardView.java index 72195f8..c6be8e9 100644 --- a/src/se/otaino2/breakoutgame/BreakoutBoardView.java +++ b/src/se/otaino2/breakoutgame/BreakoutBoardView.java @@ -1,276 +1,277 @@ package se.otaino2.breakoutgame; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import se.otaino2.breakoutgame.model.Background; import se.otaino2.breakoutgame.model.Block; import se.otaino2.breakoutgame.model.Dot; import se.otaino2.breakoutgame.model.Entity; import se.otaino2.breakoutgame.model.Paddle; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.View.OnTouchListener; public class BreakoutBoardView extends SurfaceView implements SurfaceHolder.Callback, OnTouchListener { private static final String TAG = "BreakoutBoardView"; // Render thread private BreakoutBoardThread thread; // Touch event position for the paddle private double lastKnownPaddlePosition; public BreakoutBoardView(Context context, AttributeSet attrs) { super(context, attrs); SurfaceHolder holder = getHolder(); holder.addCallback(this); // SurfaceView must have focus to get touch events setFocusable(true); setOnTouchListener(this); } @Override public void surfaceCreated(SurfaceHolder holder) { Log.d(TAG, "Surface created, starting new thread..."); thread = new BreakoutBoardThread(holder); thread.setRunning(true); thread.start(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.d(TAG, "Surface changed, resetting game..."); thread.setSurfaceSize(width, height); thread.reset(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { Log.d(TAG, "Surface destroyed, trying to shut down thread..."); boolean retry = true; thread.setRunning(false); while (retry) { try { thread.join(); retry = false; } catch (InterruptedException e) { // Do nothing } } Log.d(TAG, "Thread's dead, baby. Thread's dead."); } @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_MOVE: lastKnownPaddlePosition = event.getX(); } return true; } public BreakoutBoardThread getThread() { return thread; } class BreakoutBoardThread extends Thread { // Debug private static final String TAG = "BreakoutBoardThread"; // Game constants private static final int NBR_OF_BLOCKS = 6; private static final double DOT_SPEED = 400.0; private SurfaceHolder surfaceHolder; private boolean running; private int canvasWidth; private int canvasHeight; private Background background; private long lastTime; // Entities private List<Entity> gameEntities; private ArrayList<Block> blocks; private ArrayList<Block> destroyedBlocks; private Paddle paddle; private Dot dot; public BreakoutBoardThread(SurfaceHolder surfaceHolder) { this.surfaceHolder = surfaceHolder; } public void setRunning(boolean running) { this.running = running; } public void reset() { synchronized (surfaceHolder) { resetEntities(canvasWidth, canvasHeight); } } @Override public void run() { while (running) { Canvas c = null; try { c = surfaceHolder.lockCanvas(null); synchronized (surfaceHolder) { updatePhysics(); // NOTE: In newer versions of Android (4+), it seems SurfaceHolder.lockCanvas() may return null whenever // SurfaceHolder.Callback.surfaceDestroyed() has been invoked. In earlier versions, a canvas was always // returned until SurfaceHolder.Callback.surfaceDestroyed() was FINISHED. See bug report: // https://code.google.com/p/android/issues/detail?id=38658 if (c != null) { doDraw(c); } } } finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { surfaceHolder.unlockCanvasAndPost(c); } } } } public void setSurfaceSize(int width, int height) { synchronized (surfaceHolder) { canvasWidth = width; canvasHeight = height; reset(); } } private void resetEntities(int width, int height) { background = new Background(width, height); gameEntities = new ArrayList<Entity>(); blocks = new ArrayList<Block>(); destroyedBlocks = new ArrayList<Block>(); double blockWidth = width / (1.1 * NBR_OF_BLOCKS + 0.1); double blockHeight = 0.1 * blockWidth; for (int i = 0; i < NBR_OF_BLOCKS; i++) { double blockX = i * (blockWidth + blockHeight) + blockHeight; double blockY = 2 * blockHeight; Block b = new Block((int) blockX, (int) blockY, (int) blockWidth, (int) blockHeight); blocks.add(b); gameEntities.add(b); } double paddleWidth = blockWidth * 2; double paddleHeight = blockHeight * 2; double paddleX = (width - paddleWidth) / 2; double paddleY = height - paddleHeight; paddle = new Paddle((int) paddleX, (int) paddleY, (int) paddleWidth, (int) paddleHeight); // TODO: Thread should not meddle with properties of the view. Refactor... lastKnownPaddlePosition = paddle.getX(); gameEntities.add(paddle); double dotSide = blockHeight; double dotX = paddleX + (paddleWidth - dotSide) / 2; double dotY = paddleY - dotSide; double startAngle = Math.PI * Math.random() * -0.25; // Starting angle should be somewhat upwards Log.d(TAG, "seed:" + startAngle); double vx = DOT_SPEED * Math.sin(startAngle); double vy = DOT_SPEED * Math.cos(startAngle); Log.d(TAG, "vx:" + vx + ", vy:" + vy); dot = new Dot((int) dotX, (int) dotY, (int) dotSide, (int) dotSide, vx, vy); gameEntities.add(dot); } // Update game entities for next iteration private void updatePhysics() { long now = System.currentTimeMillis(); // Make sure we don't update physics unnecessary often if (lastTime > now) return; double elapsed = (now - lastTime) / 1000.0; // Update paddle position paddle.move(lastKnownPaddlePosition); // Update dot position double dx = dot.getVx() * elapsed; double dy = dot.getVy() * elapsed; dot.move(dx, dy, dot.getVx(), dot.getVy()); // Check if dot collides with paddle if (dot.isColliding(paddle)) { - dot.move(0, 0, dot.getVx(), -dot.getVy()); + // New direction depends on where the dot hits the paddle + dot.move(-dx, -dy, dot.getVx(), -dot.getVy()); } // Check if dot hits block Iterator<Block> iter = blocks.iterator(); while (iter.hasNext()) { Block b = iter.next(); if (dot.isColliding(b)) { iter.remove(); gameEntities.remove(b); destroyedBlocks.add(b); - dot.move(0, 0, dot.getVx(), -dot.getVy()); + dot.move(-dx, -dy, dot.getVx(), -dot.getVy()); } } // Check if dot hits walls if (dot.getX() < 0 || dot.getX() > canvasWidth) { - dot.move(0, 0, -dot.getVx(), dot.getVy()); + dot.move(-dx, -dy, -dot.getVx(), dot.getVy()); } if (dot.getY() < 0) { - dot.move(0, 0, dot.getVx(), -dot.getVy()); + dot.move(-dx, -dy, dot.getVx(), -dot.getVy()); } // Check if game over if (dot.getY() > canvasHeight) { reset(); } lastTime = now; } // Draws game entities on canvas. Must be run in private void doDraw(Canvas c) { renderBackground(c); renderEntities(c); } // Render the board background. private void renderBackground(Canvas c) { c.drawRect(background.getRect(), background.getPaint()); } private void renderEntities(Canvas c) { for (Entity e : gameEntities) { c.drawRect(e.getRect(), e.getPaint()); } Iterator<Block> iter = destroyedBlocks.iterator(); while (iter.hasNext()) { Block b = iter.next(); Paint p = b.getPaint(); p.setAlpha(p.getAlpha() - 5); c.drawRect(b.getRect(), p); if (p.getAlpha() == 0) { iter.remove(); } } } } }
false
true
private void updatePhysics() { long now = System.currentTimeMillis(); // Make sure we don't update physics unnecessary often if (lastTime > now) return; double elapsed = (now - lastTime) / 1000.0; // Update paddle position paddle.move(lastKnownPaddlePosition); // Update dot position double dx = dot.getVx() * elapsed; double dy = dot.getVy() * elapsed; dot.move(dx, dy, dot.getVx(), dot.getVy()); // Check if dot collides with paddle if (dot.isColliding(paddle)) { dot.move(0, 0, dot.getVx(), -dot.getVy()); } // Check if dot hits block Iterator<Block> iter = blocks.iterator(); while (iter.hasNext()) { Block b = iter.next(); if (dot.isColliding(b)) { iter.remove(); gameEntities.remove(b); destroyedBlocks.add(b); dot.move(0, 0, dot.getVx(), -dot.getVy()); } } // Check if dot hits walls if (dot.getX() < 0 || dot.getX() > canvasWidth) { dot.move(0, 0, -dot.getVx(), dot.getVy()); } if (dot.getY() < 0) { dot.move(0, 0, dot.getVx(), -dot.getVy()); } // Check if game over if (dot.getY() > canvasHeight) { reset(); } lastTime = now; }
private void updatePhysics() { long now = System.currentTimeMillis(); // Make sure we don't update physics unnecessary often if (lastTime > now) return; double elapsed = (now - lastTime) / 1000.0; // Update paddle position paddle.move(lastKnownPaddlePosition); // Update dot position double dx = dot.getVx() * elapsed; double dy = dot.getVy() * elapsed; dot.move(dx, dy, dot.getVx(), dot.getVy()); // Check if dot collides with paddle if (dot.isColliding(paddle)) { // New direction depends on where the dot hits the paddle dot.move(-dx, -dy, dot.getVx(), -dot.getVy()); } // Check if dot hits block Iterator<Block> iter = blocks.iterator(); while (iter.hasNext()) { Block b = iter.next(); if (dot.isColliding(b)) { iter.remove(); gameEntities.remove(b); destroyedBlocks.add(b); dot.move(-dx, -dy, dot.getVx(), -dot.getVy()); } } // Check if dot hits walls if (dot.getX() < 0 || dot.getX() > canvasWidth) { dot.move(-dx, -dy, -dot.getVx(), dot.getVy()); } if (dot.getY() < 0) { dot.move(-dx, -dy, dot.getVx(), -dot.getVy()); } // Check if game over if (dot.getY() > canvasHeight) { reset(); } lastTime = now; }
diff --git a/src/org/nutz/dao/pager/ResultSetLooping.java b/src/org/nutz/dao/pager/ResultSetLooping.java index f295139cc..b0c76eb30 100644 --- a/src/org/nutz/dao/pager/ResultSetLooping.java +++ b/src/org/nutz/dao/pager/ResultSetLooping.java @@ -1,111 +1,112 @@ package org.nutz.dao.pager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.LinkedList; import java.util.List; import org.nutz.dao.sql.SqlContext; /** * 遍历 RersultSet * * @author zozoh([email protected]) */ public abstract class ResultSetLooping { protected List<Object> list; private int index; public ResultSetLooping() { list = new LinkedList<Object>(); index = -1; } public void doLoop(ResultSet rs, SqlContext context) throws SQLException { Pager pager = context.getPager(); if (null == rs) return; /** * 如果没有设置 Pager 或者 rs 的类型是 ResultSet.TYPE_FORWARD_ONLY,那么<br> * 无法利用 游标的滚动 来计算结果集合大小。这比较高效,但是如果使用者希望得到页数量,<br> * 需要为 Pager 另行计算 总体的结果集大小。 * <p> * 一般的,为特殊数据建立的 Pager,生成的 ResultSet 类型应该是 TYPE_FORWARD_ONLY */ if (null == pager || ResultSet.TYPE_FORWARD_ONLY == rs.getType() || pager.getPageNumber() <= 0) { // 根据 Pager 设定 Fetch Size - if (null != pager && pager.getPageSize() > 0) - rs.setFetchSize(pager.getPageSize()); + // by wendal: 设置与否,影响不大的,而且旧版本的Oracle会出问题,故,注释掉了 + //if (null != pager && pager.getPageSize() > 0) + // rs.setFetchSize(pager.getPageSize()); // 循环调用 while (rs.next()) { createObject(++index, rs, context, -1); } } /** * 如果进行到了这个分支,则表示,整个查询的 Pager 是不区分数据库类型的。 <br> * 并且 ResultSet 的游标是可以来回滚动的。 * <p> * 所以我就会利用游标的滚动,为你计算整个结果集的大小。比较低效,在很小<br> * 数据量的时候 还是比较有用的 */ else if (rs.last()) { // 设置结果集合的 FetchSize if (pager.getPageSize() <= 0) rs.setFetchSize(Pager.DEFAULT_PAGE_SIZE); else if (pager.getPageSize() > Pager.MAX_FETCH_SIZE) rs.setFetchSize(Pager.MAX_FETCH_SIZE); else rs.setFetchSize(pager.getPageSize()); // 开始循环 int rowCount = rs.getRow(); LoopScope ls = LoopScope.eval(pager, rowCount); if (rs.absolute(ls.start + 1)) for (int i = ls.start; i < ls.max; i++) { createObject(++index, rs, context, rowCount); if (!rs.next()) break; } } } /** * @return 当前获取的 List */ public List<Object> getList() { return list; } /** * 获得最后一次回调被调用时的下标。 index 的值初始为 -1,每次调用回调前都会自增 * * @return 当前循环的下标,下标由 0 开始 */ public int getIndex() { return index; } /** * 子类需要实现的函数 * * @param index * 当前下标 * @param rs * 结果集 * @param context * Sql 上下文 * @param rowCount * 总记录数,如果是原生分页语句,则会为 -1 * @return 是否成功的创建了对象 */ protected abstract boolean createObject(int index, ResultSet rs, SqlContext context, int rowCount); }
true
true
public void doLoop(ResultSet rs, SqlContext context) throws SQLException { Pager pager = context.getPager(); if (null == rs) return; /** * 如果没有设置 Pager 或者 rs 的类型是 ResultSet.TYPE_FORWARD_ONLY,那么<br> * 无法利用 游标的滚动 来计算结果集合大小。这比较高效,但是如果使用者希望得到页数量,<br> * 需要为 Pager 另行计算 总体的结果集大小。 * <p> * 一般的,为特殊数据建立的 Pager,生成的 ResultSet 类型应该是 TYPE_FORWARD_ONLY */ if (null == pager || ResultSet.TYPE_FORWARD_ONLY == rs.getType() || pager.getPageNumber() <= 0) { // 根据 Pager 设定 Fetch Size if (null != pager && pager.getPageSize() > 0) rs.setFetchSize(pager.getPageSize()); // 循环调用 while (rs.next()) { createObject(++index, rs, context, -1); } } /** * 如果进行到了这个分支,则表示,整个查询的 Pager 是不区分数据库类型的。 <br> * 并且 ResultSet 的游标是可以来回滚动的。 * <p> * 所以我就会利用游标的滚动,为你计算整个结果集的大小。比较低效,在很小<br> * 数据量的时候 还是比较有用的 */ else if (rs.last()) { // 设置结果集合的 FetchSize if (pager.getPageSize() <= 0) rs.setFetchSize(Pager.DEFAULT_PAGE_SIZE); else if (pager.getPageSize() > Pager.MAX_FETCH_SIZE) rs.setFetchSize(Pager.MAX_FETCH_SIZE); else rs.setFetchSize(pager.getPageSize()); // 开始循环 int rowCount = rs.getRow(); LoopScope ls = LoopScope.eval(pager, rowCount); if (rs.absolute(ls.start + 1)) for (int i = ls.start; i < ls.max; i++) { createObject(++index, rs, context, rowCount); if (!rs.next()) break; } } }
public void doLoop(ResultSet rs, SqlContext context) throws SQLException { Pager pager = context.getPager(); if (null == rs) return; /** * 如果没有设置 Pager 或者 rs 的类型是 ResultSet.TYPE_FORWARD_ONLY,那么<br> * 无法利用 游标的滚动 来计算结果集合大小。这比较高效,但是如果使用者希望得到页数量,<br> * 需要为 Pager 另行计算 总体的结果集大小。 * <p> * 一般的,为特殊数据建立的 Pager,生成的 ResultSet 类型应该是 TYPE_FORWARD_ONLY */ if (null == pager || ResultSet.TYPE_FORWARD_ONLY == rs.getType() || pager.getPageNumber() <= 0) { // 根据 Pager 设定 Fetch Size // by wendal: 设置与否,影响不大的,而且旧版本的Oracle会出问题,故,注释掉了 //if (null != pager && pager.getPageSize() > 0) // rs.setFetchSize(pager.getPageSize()); // 循环调用 while (rs.next()) { createObject(++index, rs, context, -1); } } /** * 如果进行到了这个分支,则表示,整个查询的 Pager 是不区分数据库类型的。 <br> * 并且 ResultSet 的游标是可以来回滚动的。 * <p> * 所以我就会利用游标的滚动,为你计算整个结果集的大小。比较低效,在很小<br> * 数据量的时候 还是比较有用的 */ else if (rs.last()) { // 设置结果集合的 FetchSize if (pager.getPageSize() <= 0) rs.setFetchSize(Pager.DEFAULT_PAGE_SIZE); else if (pager.getPageSize() > Pager.MAX_FETCH_SIZE) rs.setFetchSize(Pager.MAX_FETCH_SIZE); else rs.setFetchSize(pager.getPageSize()); // 开始循环 int rowCount = rs.getRow(); LoopScope ls = LoopScope.eval(pager, rowCount); if (rs.absolute(ls.start + 1)) for (int i = ls.start; i < ls.max; i++) { createObject(++index, rs, context, rowCount); if (!rs.next()) break; } } }
diff --git a/TSPi/src/mode0.java b/TSPi/src/mode0.java index 2362470..9a368f8 100644 --- a/TSPi/src/mode0.java +++ b/TSPi/src/mode0.java @@ -1,154 +1,154 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Random; public class mode0 { public ArrayList<Character> generateSet(){ ArrayList<Character> newSet = new ArrayList<Character>(Arrays.asList( 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '+', '@', '#', '$', '%', '^', '&', '*', '|', '<', '>', '?' )); return newSet; } public ArrayList<String> randomChar(ArrayList<Character> availableChar){ ArrayList<String> result = new ArrayList<String>(); Random rand = new Random(); int randomNumber = rand.nextInt(availableChar.size()-1); result.add(Integer.toString(randomNumber)); char randomChar = availableChar.get(randomNumber); result.add(Character.toString(randomChar)); return result; } public ArrayList<ArrayList<Object>> generateFPO(int lengthX, int lengthY){ ArrayList<ArrayList<Object>> result = new ArrayList<ArrayList<Object>>(); ArrayList<Character> availableChar = this.generateSet(); ArrayList<Character> excludeParent = new ArrayList<Character>(); for(int i = 0; i<lengthY; i++){ ArrayList<Object> lineContainer = new ArrayList<Object>(); ArrayList<Character> childContainer = new ArrayList<Character>(); char parent = Character.UNASSIGNED; boolean generateParent = true; while(generateParent){ - parent = this.randomChar(availableChar); + parent = this.randomChar(availableChar).get(1).charAt(0); if(excludeParent.size()!=0){ boolean noSameParent = true; for(int j = 0; j<excludeParent.size(); j++){ if(excludeParent.get(j)==parent){ noSameParent = false; } } if(noSameParent){ generateParent = false; } }else{ generateParent = false; } } lineContainer.add(parent); for(int j = 0; j<lengthX; j++){ boolean generateChild = true; char child = Character.UNASSIGNED; while(generateChild){ - child = this.randomChar(availableChar); + child = this.randomChar(availableChar).get(1).charAt(0); if(parent!=child){ boolean noSameChild = true; for(int m = 0; m<childContainer.size();m++){ if(childContainer.get(m)==child){ noSameChild = false; } } if(noSameChild){ if (result.size()!=0){ int indexParent = 0; boolean childIsParent = false; for(int k = 0; k<result.size(); k++){ if(result.get(k).get(0).toString().charAt(0)==child){ childIsParent = true; indexParent = k; } } if(childIsParent){ ArrayList<Character> focusChild = (ArrayList<Character>) result.get(indexParent).get(1); boolean noChildParentDependent = true; for(int l = 0; l<focusChild.size(); l++){ if(focusChild.get(l)==parent){ noChildParentDependent = false; } } if(noChildParentDependent){ generateChild = false; } }else{ generateChild = false; } }else{ generateChild = false; } } } } childContainer.add(child); } lineContainer.add(childContainer); result.add(lineContainer); } return result; } public static void main(String[] args) { // TODO Auto-generated method stub } }
false
true
public ArrayList<ArrayList<Object>> generateFPO(int lengthX, int lengthY){ ArrayList<ArrayList<Object>> result = new ArrayList<ArrayList<Object>>(); ArrayList<Character> availableChar = this.generateSet(); ArrayList<Character> excludeParent = new ArrayList<Character>(); for(int i = 0; i<lengthY; i++){ ArrayList<Object> lineContainer = new ArrayList<Object>(); ArrayList<Character> childContainer = new ArrayList<Character>(); char parent = Character.UNASSIGNED; boolean generateParent = true; while(generateParent){ parent = this.randomChar(availableChar); if(excludeParent.size()!=0){ boolean noSameParent = true; for(int j = 0; j<excludeParent.size(); j++){ if(excludeParent.get(j)==parent){ noSameParent = false; } } if(noSameParent){ generateParent = false; } }else{ generateParent = false; } } lineContainer.add(parent); for(int j = 0; j<lengthX; j++){ boolean generateChild = true; char child = Character.UNASSIGNED; while(generateChild){ child = this.randomChar(availableChar); if(parent!=child){ boolean noSameChild = true; for(int m = 0; m<childContainer.size();m++){ if(childContainer.get(m)==child){ noSameChild = false; } } if(noSameChild){ if (result.size()!=0){ int indexParent = 0; boolean childIsParent = false; for(int k = 0; k<result.size(); k++){ if(result.get(k).get(0).toString().charAt(0)==child){ childIsParent = true; indexParent = k; } } if(childIsParent){ ArrayList<Character> focusChild = (ArrayList<Character>) result.get(indexParent).get(1); boolean noChildParentDependent = true; for(int l = 0; l<focusChild.size(); l++){ if(focusChild.get(l)==parent){ noChildParentDependent = false; } } if(noChildParentDependent){ generateChild = false; } }else{ generateChild = false; } }else{ generateChild = false; } } } } childContainer.add(child); } lineContainer.add(childContainer); result.add(lineContainer); } return result; }
public ArrayList<ArrayList<Object>> generateFPO(int lengthX, int lengthY){ ArrayList<ArrayList<Object>> result = new ArrayList<ArrayList<Object>>(); ArrayList<Character> availableChar = this.generateSet(); ArrayList<Character> excludeParent = new ArrayList<Character>(); for(int i = 0; i<lengthY; i++){ ArrayList<Object> lineContainer = new ArrayList<Object>(); ArrayList<Character> childContainer = new ArrayList<Character>(); char parent = Character.UNASSIGNED; boolean generateParent = true; while(generateParent){ parent = this.randomChar(availableChar).get(1).charAt(0); if(excludeParent.size()!=0){ boolean noSameParent = true; for(int j = 0; j<excludeParent.size(); j++){ if(excludeParent.get(j)==parent){ noSameParent = false; } } if(noSameParent){ generateParent = false; } }else{ generateParent = false; } } lineContainer.add(parent); for(int j = 0; j<lengthX; j++){ boolean generateChild = true; char child = Character.UNASSIGNED; while(generateChild){ child = this.randomChar(availableChar).get(1).charAt(0); if(parent!=child){ boolean noSameChild = true; for(int m = 0; m<childContainer.size();m++){ if(childContainer.get(m)==child){ noSameChild = false; } } if(noSameChild){ if (result.size()!=0){ int indexParent = 0; boolean childIsParent = false; for(int k = 0; k<result.size(); k++){ if(result.get(k).get(0).toString().charAt(0)==child){ childIsParent = true; indexParent = k; } } if(childIsParent){ ArrayList<Character> focusChild = (ArrayList<Character>) result.get(indexParent).get(1); boolean noChildParentDependent = true; for(int l = 0; l<focusChild.size(); l++){ if(focusChild.get(l)==parent){ noChildParentDependent = false; } } if(noChildParentDependent){ generateChild = false; } }else{ generateChild = false; } }else{ generateChild = false; } } } } childContainer.add(child); } lineContainer.add(childContainer); result.add(lineContainer); } return result; }
diff --git a/src/share/classes/com/sun/tools/javafx/code/FunctionType.java b/src/share/classes/com/sun/tools/javafx/code/FunctionType.java index 1b056221e..5cae10945 100644 --- a/src/share/classes/com/sun/tools/javafx/code/FunctionType.java +++ b/src/share/classes/com/sun/tools/javafx/code/FunctionType.java @@ -1,75 +1,75 @@ /* * Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.tools.javafx.code; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.util.*; import com.sun.tools.javac.code.Symbol.TypeSymbol; /** * * @author bothner */ public class FunctionType extends Type.ClassType { public MethodType mtype; public FunctionType(Type outer, List<Type> typarams, TypeSymbol tsym, MethodType mtype) { super(outer, typarams, tsym); this.mtype = mtype; } /** Copy constructor. */ public FunctionType(FunctionType orig) { this(orig.getEnclosingType(), orig.typarams_field, orig.tsym, orig.mtype); } public List<Type> getParameterTypes() { return mtype.getParameterTypes(); } public Type getReturnType() { return mtype.restype; } public MethodType asMethodType () { return mtype; } public String toString() { StringBuilder s = new StringBuilder(); s.append("function("); if (mtype == null) s.append("???"); else { List<Type> args = mtype.argtypes; for (List<Type> l = args; l.nonEmpty(); l = l.tail) { if (l != args) s.append(','); s.append(':'); s.append(l.head); } } s.append("):"); - s.append(mtype.restype); + s.append(mtype == null ? "???" : mtype.restype); return s.toString(); } }
true
true
public String toString() { StringBuilder s = new StringBuilder(); s.append("function("); if (mtype == null) s.append("???"); else { List<Type> args = mtype.argtypes; for (List<Type> l = args; l.nonEmpty(); l = l.tail) { if (l != args) s.append(','); s.append(':'); s.append(l.head); } } s.append("):"); s.append(mtype.restype); return s.toString(); }
public String toString() { StringBuilder s = new StringBuilder(); s.append("function("); if (mtype == null) s.append("???"); else { List<Type> args = mtype.argtypes; for (List<Type> l = args; l.nonEmpty(); l = l.tail) { if (l != args) s.append(','); s.append(':'); s.append(l.head); } } s.append("):"); s.append(mtype == null ? "???" : mtype.restype); return s.toString(); }
diff --git a/src/java/com/atlassian/plugin/loaders/classloading/Scanner.java b/src/java/com/atlassian/plugin/loaders/classloading/Scanner.java index f6bb1093..9c234c1a 100644 --- a/src/java/com/atlassian/plugin/loaders/classloading/Scanner.java +++ b/src/java/com/atlassian/plugin/loaders/classloading/Scanner.java @@ -1,177 +1,183 @@ package com.atlassian.plugin.loaders.classloading; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.File; import java.io.FileFilter; import java.net.MalformedURLException; import java.util.*; /** * Deployment Scanner * * @author <a href="[email protected]">Victor Salaman</a> * @version 1.0 */ public class Scanner implements FileFilter { private static Log log = LogFactory.getLog(Scanner.class); /** * Tracks the classloading */ File libDir; /** * Tracks classloading modifications. Keeps a value of last modified for the plugin dir. */ long lastModified; /** * Holds the plugin extension. */ String pluginExtension = ".jar"; /** * Holds the classloaders keyed by deployment units. */ Map deployedLoaders = new HashMap(); /** * Constructor for scanner. * * @param libDir */ public Scanner(File libDir) { this.libDir = libDir; } public boolean accept(File file) { return file.getName().endsWith(pluginExtension); } private void deploy(File file) throws MalformedURLException { if (isDeployed(file)) return; DeploymentUnit unit = new DeploymentUnit(file); JarClassLoader cl = new JarClassLoader(file, Thread.currentThread().getContextClassLoader()); deployedLoaders.put(unit, cl); /** Your deploy stuff here **/ } public DeploymentUnit locateDeploymentUnit(File file) { Collection dUnits = deployedLoaders.keySet(); for (Iterator iterator = dUnits.iterator(); iterator.hasNext();) { DeploymentUnit unit = (DeploymentUnit) iterator.next(); if (unit.path.getAbsolutePath().equals(file.getAbsolutePath())) { return unit; } } return null; } public boolean isDeployed(File file) { return locateDeploymentUnit(file) != null; } public void undeploy(File file) { DeploymentUnit unit = locateDeploymentUnit(file); if (unit != null) { JarClassLoader jcl = (JarClassLoader) deployedLoaders.remove(unit); jcl.close(); } } public boolean isModified() { return libDir.canRead() && (lastModified != libDir.lastModified()); } /** * Scans the plugin classloading and does the proper things. * Handles deployment and undeployment. */ public void scan() { // Checks to see if we have deleted one of the deployment units. Collection dUnits = deployedLoaders.keySet(); List toUndeploy = new ArrayList(); for (Iterator iterator = dUnits.iterator(); iterator.hasNext();) { DeploymentUnit unit = (DeploymentUnit) iterator.next(); if (!unit.path.exists() || !unit.path.canRead()) { toUndeploy.add(unit.getPath()); } } undeploy(toUndeploy); // Checks for new files. File file[] = libDir.listFiles(this); - for (int i = 0; i < file.length; i++) + if (file == null) { - try + log.error("listFiles returned null for directory " + libDir.getAbsolutePath()); + } + else + { + for (int i = 0; i < file.length; i++) { - if (isDeployed(file[i]) && isModified(file[i])) + try { - undeploy(file[i]); - deploy(file[i]); + if (isDeployed(file[i]) && isModified(file[i])) + { + undeploy(file[i]); + deploy(file[i]); + } + else if (!isDeployed(file[i])) + { + deploy(file[i]); + } } - else if (!isDeployed(file[i])) + catch (MalformedURLException e) { - deploy(file[i]); + log.error("Error deploying plugin " + file[i].getAbsolutePath(), e); } } - catch (MalformedURLException e) - { - // Change this to log somewhere - e.printStackTrace(); - } } } private boolean isModified(File file) { DeploymentUnit unit = locateDeploymentUnit(file); return file.lastModified() > unit.lastModified(); } private void undeploy(List toUndeploy) { for (Iterator iterator = toUndeploy.iterator(); iterator.hasNext();) { undeploy((File) iterator.next()); } } public Collection getDeploymentUnits() { return deployedLoaders.keySet(); } public ClassLoader getClassLoader(DeploymentUnit deploymentUnit) { return (ClassLoader) deployedLoaders.get(deploymentUnit); } public void undeployAll() { for (Iterator iterator = deployedLoaders.values().iterator(); iterator.hasNext();) { JarClassLoader jarClassLoader = (JarClassLoader) iterator.next(); jarClassLoader.close(); iterator.remove(); } } }
false
true
public void scan() { // Checks to see if we have deleted one of the deployment units. Collection dUnits = deployedLoaders.keySet(); List toUndeploy = new ArrayList(); for (Iterator iterator = dUnits.iterator(); iterator.hasNext();) { DeploymentUnit unit = (DeploymentUnit) iterator.next(); if (!unit.path.exists() || !unit.path.canRead()) { toUndeploy.add(unit.getPath()); } } undeploy(toUndeploy); // Checks for new files. File file[] = libDir.listFiles(this); for (int i = 0; i < file.length; i++) { try { if (isDeployed(file[i]) && isModified(file[i])) { undeploy(file[i]); deploy(file[i]); } else if (!isDeployed(file[i])) { deploy(file[i]); } } catch (MalformedURLException e) { // Change this to log somewhere e.printStackTrace(); } } }
public void scan() { // Checks to see if we have deleted one of the deployment units. Collection dUnits = deployedLoaders.keySet(); List toUndeploy = new ArrayList(); for (Iterator iterator = dUnits.iterator(); iterator.hasNext();) { DeploymentUnit unit = (DeploymentUnit) iterator.next(); if (!unit.path.exists() || !unit.path.canRead()) { toUndeploy.add(unit.getPath()); } } undeploy(toUndeploy); // Checks for new files. File file[] = libDir.listFiles(this); if (file == null) { log.error("listFiles returned null for directory " + libDir.getAbsolutePath()); } else { for (int i = 0; i < file.length; i++) { try { if (isDeployed(file[i]) && isModified(file[i])) { undeploy(file[i]); deploy(file[i]); } else if (!isDeployed(file[i])) { deploy(file[i]); } } catch (MalformedURLException e) { log.error("Error deploying plugin " + file[i].getAbsolutePath(), e); } } } }
diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/FieldComponentComposer.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/FieldComponentComposer.java index 4a365e71..8237b6f1 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/FieldComponentComposer.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/FieldComponentComposer.java @@ -1,305 +1,310 @@ package org.codehaus.plexus.component.composition; /* * The MIT License * * Copyright (c) 2004, The Codehaus * * 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. */ import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.ComponentRequirement; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.util.ReflectionUtils; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * @author <a href="mailto:[email protected]">Jason van Zyl</a> * @author <a href="[email protected]">Michal Maczka</a> * @version $Id$ */ public class FieldComponentComposer extends AbstractComponentComposer { public List assembleComponent( Object component, ComponentDescriptor componentDescriptor, PlexusContainer container ) throws CompositionException { List retValue = new LinkedList(); List requirements = componentDescriptor.getRequirements(); for ( Iterator i = requirements.iterator(); i.hasNext(); ) { ComponentRequirement requirement = (ComponentRequirement) i.next(); Field field = findMatchingField( component, componentDescriptor, requirement, container ); // we want to use private fields. if ( !field.isAccessible() ) { field.setAccessible( true ); } // We have a field to which we should assigning component(s). // Cardinality is determined by field.getType() method // It can be array, map, collection or "ordinary" field List descriptors = assignRequirementToField( component, field, container, requirement ); retValue.addAll( descriptors ); } return retValue; } private List assignRequirementToField( Object component, Field field, PlexusContainer container, ComponentRequirement requirement ) throws CompositionException { try { List retValue; String role = requirement.getRole(); if ( field.getType().isArray() ) { List dependencies = container.lookupList( role ); Object[] array = (Object[]) Array.newInstance( field.getType(), dependencies.size() ); retValue = container.getComponentDescriptorList( role ); field.set( component, dependencies.toArray( array ) ); } else if ( Map.class.isAssignableFrom( field.getType() ) ) { Map dependencies = container.lookupMap( role ); retValue = container.getComponentDescriptorList( role ); field.set( component, dependencies ); } else if ( List.class.isAssignableFrom( field.getType() ) ) { List dependencies = container.lookupList( role ); retValue = container.getComponentDescriptorList( role ); field.set( component, dependencies ); } else if ( Set.class.isAssignableFrom( field.getType() ) ) { Map dependencies = container.lookupMap( role ); retValue = container.getComponentDescriptorList( role ); field.set( component, dependencies.entrySet() ); } else //"ordinary" field { String key = requirement.getRequirementKey(); Object dependency = container.lookup( key ); ComponentDescriptor componentDescriptor = container.getComponentDescriptor( key ); retValue = new ArrayList( 1 ); retValue.add( componentDescriptor ); field.set( component, dependency ); } return retValue; } + catch ( IllegalArgumentException e ) + { + throw new CompositionException( "Composition failed for the field " + field.getName() + " " + + "in object of type " + component.getClass().getName(), e ); + } catch ( IllegalAccessException e ) { - throw new CompositionException( "Composition failed of field " + field.getName() + " " + + throw new CompositionException( "Composition failed for the field " + field.getName() + " " + "in object of type " + component.getClass().getName(), e ); } catch ( ComponentLookupException e ) { throw new CompositionException( "Composition failed of field " + field.getName() + " " + "in object of type " + component.getClass().getName() + " because the requirement " + requirement + " was missing", e ); } } protected Field findMatchingField( Object component, ComponentDescriptor componentDescriptor, ComponentRequirement requirement, PlexusContainer container ) throws CompositionException { String fieldName = requirement.getFieldName(); Field field = null; if ( fieldName != null ) { field = getFieldByName( component, fieldName, componentDescriptor ); } else { Class fieldClass = null; try { if ( container != null ) { fieldClass = container.getComponentRealm( requirement.getRole() ).loadClass( requirement.getRole() ); } else { fieldClass = Thread.currentThread().getContextClassLoader().loadClass( requirement.getRole() ); } } catch ( ClassNotFoundException e ) { StringBuffer msg = new StringBuffer( "Component Composition failed for component: " ); msg.append( componentDescriptor.getHumanReadableKey() ); msg.append( ": Requirement class: '" ); msg.append( requirement.getRole() ); msg.append( "' not found." ); throw new CompositionException( msg.toString(), e ); } field = getFieldByType( component, fieldClass, componentDescriptor ); } return field; } protected Field getFieldByName( Object component, String fieldName, ComponentDescriptor componentDescriptor ) throws CompositionException { Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses( fieldName, component.getClass() ); if ( field == null ) { StringBuffer msg = new StringBuffer( "Component Composition failed. No field of name: '" ); msg.append( fieldName ); msg.append( "' exists in component: " ); msg.append( componentDescriptor.getHumanReadableKey() ); throw new CompositionException( msg.toString() ); } return field; } protected Field getFieldByTypeIncludingSuperclasses( Class componentClass, Class type, ComponentDescriptor componentDescriptor ) throws CompositionException { List fields = getFieldsByTypeIncludingSuperclasses( componentClass, type, componentDescriptor ); if ( fields.size() == 0 ) { return null; } if ( fields.size() == 1 ) { return (Field) fields.get( 0 ); } throw new CompositionException( "There are several fields of type '" + type + "', " + "use 'field-name' to select the correct field." ); } protected List getFieldsByTypeIncludingSuperclasses( Class componentClass, Class type, ComponentDescriptor componentDescriptor ) throws CompositionException { Class arrayType = Array.newInstance( type, 0 ).getClass(); Field[] fields = componentClass.getDeclaredFields(); List foundFields = new ArrayList(); for ( int i = 0; i < fields.length; i++ ) { Class fieldType = fields[i].getType(); if ( fieldType.isAssignableFrom( type ) || fieldType.isAssignableFrom( arrayType ) ) { foundFields.add( fields[i] ); } } if ( componentClass.getSuperclass() != Object.class ) { List superFields = getFieldsByTypeIncludingSuperclasses( componentClass.getSuperclass(), type, componentDescriptor ); foundFields.addAll( superFields ); } return foundFields; } protected Field getFieldByType( Object component, Class type, ComponentDescriptor componentDescriptor ) throws CompositionException { Field field = getFieldByTypeIncludingSuperclasses( component.getClass(), type, componentDescriptor ); if ( field == null ) { StringBuffer msg = new StringBuffer( "Component composition failed. No field of type: '" ); msg.append( type ); msg.append( "' exists in class '" ); msg.append( component.getClass().getName() ); msg.append( "'." ); if ( componentDescriptor != null ) { msg.append( " Component: " ); msg.append( componentDescriptor.getHumanReadableKey() ); } throw new CompositionException( msg.toString() ); } return field; } }
false
true
private List assignRequirementToField( Object component, Field field, PlexusContainer container, ComponentRequirement requirement ) throws CompositionException { try { List retValue; String role = requirement.getRole(); if ( field.getType().isArray() ) { List dependencies = container.lookupList( role ); Object[] array = (Object[]) Array.newInstance( field.getType(), dependencies.size() ); retValue = container.getComponentDescriptorList( role ); field.set( component, dependencies.toArray( array ) ); } else if ( Map.class.isAssignableFrom( field.getType() ) ) { Map dependencies = container.lookupMap( role ); retValue = container.getComponentDescriptorList( role ); field.set( component, dependencies ); } else if ( List.class.isAssignableFrom( field.getType() ) ) { List dependencies = container.lookupList( role ); retValue = container.getComponentDescriptorList( role ); field.set( component, dependencies ); } else if ( Set.class.isAssignableFrom( field.getType() ) ) { Map dependencies = container.lookupMap( role ); retValue = container.getComponentDescriptorList( role ); field.set( component, dependencies.entrySet() ); } else //"ordinary" field { String key = requirement.getRequirementKey(); Object dependency = container.lookup( key ); ComponentDescriptor componentDescriptor = container.getComponentDescriptor( key ); retValue = new ArrayList( 1 ); retValue.add( componentDescriptor ); field.set( component, dependency ); } return retValue; } catch ( IllegalAccessException e ) { throw new CompositionException( "Composition failed of field " + field.getName() + " " + "in object of type " + component.getClass().getName(), e ); } catch ( ComponentLookupException e ) { throw new CompositionException( "Composition failed of field " + field.getName() + " " + "in object of type " + component.getClass().getName() + " because the requirement " + requirement + " was missing", e ); } }
private List assignRequirementToField( Object component, Field field, PlexusContainer container, ComponentRequirement requirement ) throws CompositionException { try { List retValue; String role = requirement.getRole(); if ( field.getType().isArray() ) { List dependencies = container.lookupList( role ); Object[] array = (Object[]) Array.newInstance( field.getType(), dependencies.size() ); retValue = container.getComponentDescriptorList( role ); field.set( component, dependencies.toArray( array ) ); } else if ( Map.class.isAssignableFrom( field.getType() ) ) { Map dependencies = container.lookupMap( role ); retValue = container.getComponentDescriptorList( role ); field.set( component, dependencies ); } else if ( List.class.isAssignableFrom( field.getType() ) ) { List dependencies = container.lookupList( role ); retValue = container.getComponentDescriptorList( role ); field.set( component, dependencies ); } else if ( Set.class.isAssignableFrom( field.getType() ) ) { Map dependencies = container.lookupMap( role ); retValue = container.getComponentDescriptorList( role ); field.set( component, dependencies.entrySet() ); } else //"ordinary" field { String key = requirement.getRequirementKey(); Object dependency = container.lookup( key ); ComponentDescriptor componentDescriptor = container.getComponentDescriptor( key ); retValue = new ArrayList( 1 ); retValue.add( componentDescriptor ); field.set( component, dependency ); } return retValue; } catch ( IllegalArgumentException e ) { throw new CompositionException( "Composition failed for the field " + field.getName() + " " + "in object of type " + component.getClass().getName(), e ); } catch ( IllegalAccessException e ) { throw new CompositionException( "Composition failed for the field " + field.getName() + " " + "in object of type " + component.getClass().getName(), e ); } catch ( ComponentLookupException e ) { throw new CompositionException( "Composition failed of field " + field.getName() + " " + "in object of type " + component.getClass().getName() + " because the requirement " + requirement + " was missing", e ); } }
diff --git a/sopremo/sopremo-query/src/main/java/eu/stratosphere/sopremo/query/PackageInfo.java b/sopremo/sopremo-query/src/main/java/eu/stratosphere/sopremo/query/PackageInfo.java index 06a30ae79..6a83925ab 100644 --- a/sopremo/sopremo-query/src/main/java/eu/stratosphere/sopremo/query/PackageInfo.java +++ b/sopremo/sopremo-query/src/main/java/eu/stratosphere/sopremo/query/PackageInfo.java @@ -1,262 +1,260 @@ /*********************************************************************************************************************** * * Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **********************************************************************************************************************/ package eu.stratosphere.sopremo.query; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.jar.JarEntry; import java.util.jar.JarFile; import eu.stratosphere.nephele.util.StringUtils; import eu.stratosphere.sopremo.AbstractSopremoType; import eu.stratosphere.sopremo.ISopremoType; import eu.stratosphere.sopremo.io.SopremoFormat; import eu.stratosphere.sopremo.operator.Internal; import eu.stratosphere.sopremo.operator.Operator; import eu.stratosphere.sopremo.packages.BuiltinProvider; import eu.stratosphere.sopremo.packages.ConstantRegistryCallback; import eu.stratosphere.sopremo.packages.DefaultConstantRegistry; import eu.stratosphere.sopremo.packages.DefaultFunctionRegistry; import eu.stratosphere.sopremo.packages.DefaultTypeRegistry; import eu.stratosphere.sopremo.packages.IConstantRegistry; import eu.stratosphere.sopremo.packages.IFunctionRegistry; import eu.stratosphere.sopremo.packages.ITypeRegistry; import eu.stratosphere.sopremo.type.IJsonNode; import eu.stratosphere.util.reflect.ReflectUtil; /** * @author Arvid Heise */ public class PackageInfo extends AbstractSopremoType implements ISopremoType, ParsingScope { private final transient PackageClassLoader classLoader; /** * Initializes PackageInfo. * * @param packageName * @param packagePath */ public PackageInfo(String packageName, ClassLoader classLoader, NameChooserProvider nameChooserProvider) { this.packageName = packageName; this.classLoader = new PackageClassLoader(classLoader); this.operatorRegistry = new DefaultConfObjectRegistry<Operator<?>>( nameChooserProvider.getOperatorNameChooser(), nameChooserProvider.getPropertyNameChooser()); this.fileFormatRegistry = new DefaultConfObjectRegistry<SopremoFormat>( nameChooserProvider.getFormatNameChooser(), nameChooserProvider.getPropertyNameChooser()); this.constantRegistry = new DefaultConstantRegistry(nameChooserProvider.getConstantNameChooser()); this.functionRegistry = new DefaultFunctionRegistry(nameChooserProvider.getFunctionNameChooser()); this.typeRegistry = new DefaultTypeRegistry(nameChooserProvider.getTypeNameChooser()); } /** * Initialiszes PackageInfo. * * @param packageName2 */ public PackageInfo(String packageName, NameChooserProvider nameChooserProvider) { this(packageName, new PackageClassLoader(ClassLoader.getSystemClassLoader()), nameChooserProvider); } private final IConfObjectRegistry<Operator<?>> operatorRegistry; private final IConfObjectRegistry<SopremoFormat> fileFormatRegistry; private final IConstantRegistry constantRegistry; private final IFunctionRegistry functionRegistry; private final ITypeRegistry typeRegistry; private String packageName; private File packagePath; public String getPackageName() { return this.packageName; } public File getPackagePath() { return this.packagePath; } public List<File> getRequiredJarPaths() { return this.classLoader.getFiles(); } /** * Returns the typeRegistry. * * @return the typeRegistry */ @Override public ITypeRegistry getTypeRegistry() { return this.typeRegistry; } /** * Returns the fileFormatRegistry. * * @return the fileFormatRegistry */ @Override public IConfObjectRegistry<SopremoFormat> getFileFormatRegistry() { return this.fileFormatRegistry; } @SuppressWarnings("unchecked") private void importClass(String className) { Class<?> clazz; try { clazz = this.classLoader.loadClass(className); if(clazz.getAnnotation(Internal.class) != null) return; if (Operator.class.isAssignableFrom(clazz) && (clazz.getModifiers() & Modifier.ABSTRACT) == 0) { clazz = Class.forName(className, true, this.classLoader); QueryUtil.LOG.trace("adding operator " + clazz); this.getOperatorRegistry().put((Class<? extends Operator<?>>) clazz); } else if (SopremoFormat.class.isAssignableFrom(clazz) && (clazz.getModifiers() & Modifier.ABSTRACT) == 0) { clazz = Class.forName(className, true, this.classLoader); QueryUtil.LOG.trace("adding operator " + clazz); this.getFileFormatRegistry().put((Class<? extends SopremoFormat>) clazz); } else if (BuiltinProvider.class.isAssignableFrom(clazz)) { clazz = Class.forName(className, true, this.classLoader); this.addFunctionsAndConstants(clazz); } else if (IJsonNode.class.isAssignableFrom(clazz)) this.getTypeRegistry().put((Class<? extends IJsonNode>) clazz); - } catch (ClassNotFoundException e) { + } catch (Exception e) { QueryUtil.LOG.warn("could not load operator " + className + ": " + StringUtils.stringifyException(e)); - } catch (NoClassDefFoundError e) { - QueryUtil.LOG.warn("could not load operator " + className + ": " + StringUtils.stringifyException(e)); - } + } } public void importFromProject() { Queue<File> directories = new LinkedList<File>(); directories.add(this.packagePath); while (!directories.isEmpty()) for (File file : directories.poll().listFiles()) if (file.isDirectory()) directories.add(file); else if (file.getName().endsWith(".class") && !file.getName().contains("$")) this.importFromFile(file, this.packagePath); } private void importFromFile(File file, File packagePath) { String classFileName = file.getAbsolutePath().substring(packagePath.getAbsolutePath().length() + 1); String className = classFileName.replaceAll(".class$", "").replaceAll("/|\\\\", ".").replaceAll("^\\.", ""); this.importClass(className); } private void addFunctionsAndConstants(Class<?> clazz) { this.getFunctionRegistry().put(clazz); if (ConstantRegistryCallback.class.isAssignableFrom(clazz)) ((ConstantRegistryCallback) ReflectUtil.newInstance(clazz)).registerConstants(this.getConstantRegistry()); } public void importFromJar(File jarFileLocation) throws IOException { final JarFile jarFile = new JarFile(jarFileLocation); try { this.classLoader.addJar(jarFileLocation); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); final String entryName = jarEntry.getName(); if (entryName.endsWith(".class") && !entryName.contains("$")) { String className = entryName.replaceAll(".class$", "").replaceAll("/|\\\\", ".").replaceAll("^\\.", ""); this.importClass(className); } } } finally { jarFile.close(); } } @Override public void appendAsString(Appendable appendable) throws IOException { appendable.append("Package ").append(this.packageName); appendable.append("\n "); this.operatorRegistry.appendAsString(appendable); appendable.append("\n "); this.functionRegistry.appendAsString(appendable); appendable.append("\n "); this.constantRegistry.appendAsString(appendable); appendable.append("\n "); this.fileFormatRegistry.appendAsString(appendable); } @Override public IConfObjectRegistry<Operator<?>> getOperatorRegistry() { return this.operatorRegistry; } @Override public IConstantRegistry getConstantRegistry() { return this.constantRegistry; } @Override public IFunctionRegistry getFunctionRegistry() { return this.functionRegistry; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return this.getPackageName(); } /** * @param packageName * @param packagePath */ public void importFrom(File packagePath, String packageName) throws IOException { this.packagePath = packagePath.getAbsoluteFile(); if (packagePath.getName().endsWith(".jar")) this.importFromJar(this.packagePath); // FIXME hack for testing in eclipse else { File jarFileInParentDirectory = getJarFileInParentDirectory(packagePath, packageName); if (jarFileInParentDirectory.exists()) { this.packagePath = jarFileInParentDirectory; this.importFromJar(jarFileInParentDirectory); } else throw new IllegalStateException("Cannot import non-jar " + packagePath); } } private File getJarFileInParentDirectory(File packagePath, final String packageName) { final File[] jarsInParentDir = packagePath.getParentFile().listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return new File(dir, name).isFile() && name.toLowerCase().endsWith(".jar") && name.contains(PackageManager.getJarFileNameForPackageName(packageName)); } }); return jarsInParentDir.length == 0 ? null : jarsInParentDir[0]; } }
false
true
private void importClass(String className) { Class<?> clazz; try { clazz = this.classLoader.loadClass(className); if(clazz.getAnnotation(Internal.class) != null) return; if (Operator.class.isAssignableFrom(clazz) && (clazz.getModifiers() & Modifier.ABSTRACT) == 0) { clazz = Class.forName(className, true, this.classLoader); QueryUtil.LOG.trace("adding operator " + clazz); this.getOperatorRegistry().put((Class<? extends Operator<?>>) clazz); } else if (SopremoFormat.class.isAssignableFrom(clazz) && (clazz.getModifiers() & Modifier.ABSTRACT) == 0) { clazz = Class.forName(className, true, this.classLoader); QueryUtil.LOG.trace("adding operator " + clazz); this.getFileFormatRegistry().put((Class<? extends SopremoFormat>) clazz); } else if (BuiltinProvider.class.isAssignableFrom(clazz)) { clazz = Class.forName(className, true, this.classLoader); this.addFunctionsAndConstants(clazz); } else if (IJsonNode.class.isAssignableFrom(clazz)) this.getTypeRegistry().put((Class<? extends IJsonNode>) clazz); } catch (ClassNotFoundException e) { QueryUtil.LOG.warn("could not load operator " + className + ": " + StringUtils.stringifyException(e)); } catch (NoClassDefFoundError e) { QueryUtil.LOG.warn("could not load operator " + className + ": " + StringUtils.stringifyException(e)); } }
private void importClass(String className) { Class<?> clazz; try { clazz = this.classLoader.loadClass(className); if(clazz.getAnnotation(Internal.class) != null) return; if (Operator.class.isAssignableFrom(clazz) && (clazz.getModifiers() & Modifier.ABSTRACT) == 0) { clazz = Class.forName(className, true, this.classLoader); QueryUtil.LOG.trace("adding operator " + clazz); this.getOperatorRegistry().put((Class<? extends Operator<?>>) clazz); } else if (SopremoFormat.class.isAssignableFrom(clazz) && (clazz.getModifiers() & Modifier.ABSTRACT) == 0) { clazz = Class.forName(className, true, this.classLoader); QueryUtil.LOG.trace("adding operator " + clazz); this.getFileFormatRegistry().put((Class<? extends SopremoFormat>) clazz); } else if (BuiltinProvider.class.isAssignableFrom(clazz)) { clazz = Class.forName(className, true, this.classLoader); this.addFunctionsAndConstants(clazz); } else if (IJsonNode.class.isAssignableFrom(clazz)) this.getTypeRegistry().put((Class<? extends IJsonNode>) clazz); } catch (Exception e) { QueryUtil.LOG.warn("could not load operator " + className + ": " + StringUtils.stringifyException(e)); } }
diff --git a/src/com/jidesoft/swing/CheckBoxListSelectionModel.java b/src/com/jidesoft/swing/CheckBoxListSelectionModel.java index 96e8b5fd..2f3ad80e 100644 --- a/src/com/jidesoft/swing/CheckBoxListSelectionModel.java +++ b/src/com/jidesoft/swing/CheckBoxListSelectionModel.java @@ -1,59 +1,65 @@ package com.jidesoft.swing; import javax.swing.*; public class CheckBoxListSelectionModel extends DefaultListSelectionModel { private ListModel _model; public CheckBoxListSelectionModel() { setSelectionMode(MULTIPLE_INTERVAL_SELECTION); } public CheckBoxListSelectionModel(ListModel model) { _model = model; setSelectionMode(MULTIPLE_INTERVAL_SELECTION); } public ListModel getModel() { return _model; } public void setModel(ListModel model) { int oldLength = 0; int newLength = 0; if (_model != null) { oldLength = _model.getSize(); } _model = model; if (_model != null) { newLength = _model.getSize(); } if (oldLength > newLength) { removeIndexInterval(newLength, oldLength); } } /** * Overrides so that inserting a row will not be selected automatically if the row after it is selected. * * @param index the index where the rows will be inserted. * @param length the number of the rows that will be inserted. * @param before it's before or after the index. */ @Override public void insertIndexInterval(int index, int length, boolean before) { if (before) { boolean old = isSelectedIndex(index); - if (old) { - removeSelectionInterval(index, index); + super.setValueIsAdjusting(true); + try { + if (old) { + removeSelectionInterval(index, index); + } + super.insertIndexInterval(index, length, before); + if (old) { + addSelectionInterval(index + length, index + length); + } } - super.insertIndexInterval(index, length, before); - if (old) { - addSelectionInterval(index + length, index + length); + finally { + super.setValueIsAdjusting(false); } } else { super.insertIndexInterval(index, length, before); } } }
false
true
public void insertIndexInterval(int index, int length, boolean before) { if (before) { boolean old = isSelectedIndex(index); if (old) { removeSelectionInterval(index, index); } super.insertIndexInterval(index, length, before); if (old) { addSelectionInterval(index + length, index + length); } } else { super.insertIndexInterval(index, length, before); } }
public void insertIndexInterval(int index, int length, boolean before) { if (before) { boolean old = isSelectedIndex(index); super.setValueIsAdjusting(true); try { if (old) { removeSelectionInterval(index, index); } super.insertIndexInterval(index, length, before); if (old) { addSelectionInterval(index + length, index + length); } } finally { super.setValueIsAdjusting(false); } } else { super.insertIndexInterval(index, length, before); } }
diff --git a/org.codemap/src/org/codemap/mapview/MenuAction.java b/org.codemap/src/org/codemap/mapview/MenuAction.java index 06776eaa..302b8538 100644 --- a/org.codemap/src/org/codemap/mapview/MenuAction.java +++ b/org.codemap/src/org/codemap/mapview/MenuAction.java @@ -1,29 +1,31 @@ package org.codemap.mapview; import org.codemap.CodemapCore; import org.codemap.MapPerProject; public abstract class MenuAction extends CodemapAction { public MenuAction(String text, int style) { super(text, style); } @Override public void configureAction(MapPerProject map) { setChecked(map.getPropertyOrDefault(getKey(), isDefaultChecked())); - run(); +// TODO: find a way to re-run the action-enabling on startup +// do *not* use run() as it causes the program to loop infinitely +// run(); } @Override public void run() { super.run(); CodemapCore.getPlugin().getActiveMap().setProperty(getKey(), isChecked()); } protected abstract String getKey(); protected abstract boolean isDefaultChecked(); }
true
true
public void configureAction(MapPerProject map) { setChecked(map.getPropertyOrDefault(getKey(), isDefaultChecked())); run(); }
public void configureAction(MapPerProject map) { setChecked(map.getPropertyOrDefault(getKey(), isDefaultChecked())); // TODO: find a way to re-run the action-enabling on startup // do *not* use run() as it causes the program to loop infinitely // run(); }
diff --git a/src/main/java/de/minestar/AdminStuff/commands/cmdGive.java b/src/main/java/de/minestar/AdminStuff/commands/cmdGive.java index 29147fa..97b9d7c 100644 --- a/src/main/java/de/minestar/AdminStuff/commands/cmdGive.java +++ b/src/main/java/de/minestar/AdminStuff/commands/cmdGive.java @@ -1,89 +1,89 @@ /* b * Copyright (C) 2011 MineStar.de * * This file is part of 'AdminStuff'. * * 'AdminStuff' 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, version 3 of the License. * * 'AdminStuff' 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 'AdminStuff'. If not, see <http://www.gnu.org/licenses/>. * * AUTHOR: GeMoschen * */ package de.minestar.AdminStuff.commands; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import de.minestar.AdminStuff.Core; import de.minestar.AdminStuff.data.ASItem; import de.minestar.minestarlibrary.commands.AbstractExtendedCommand; import de.minestar.minestarlibrary.utils.ConsoleUtils; import de.minestar.minestarlibrary.utils.PlayerUtils; public class cmdGive extends AbstractExtendedCommand { public cmdGive(String syntax, String arguments, String node) { super(Core.NAME, syntax, arguments, node); } @Override /** * Representing the command <br> * /give <ItemID or Name>[:SubID] <Amount> <br> * This gives the player a specified itemstack * * @param player * Called the command * @param split * split[0] is the targets name * split[1] is the item name * split[2] is the itemamount */ public void execute(String[] args, Player player) { Player target = PlayerUtils.getOnlinePlayer(args[0]); if (target == null) { PlayerUtils.sendError(player, pluginName, "Spieler '" + args[0] + "' nicht gefunden!"); return; } String ID = ASItem.getIDPart(args[1]); int amount = 1; if (args.length == 2) amount = 64; else if (args.length == 3) { try { amount = Integer.parseInt(args[2]); } catch (Exception e) { PlayerUtils.sendError(player, ID, args[2] + " ist keine Zahl! Itemanzahl auf Eins gesetzt!"); } if (amount < 1) { PlayerUtils.sendError(player, pluginName, args[2] + "ist kleiner als Eins! Itemanzahl auf Eins gesetzt!"); amount = 1; } } byte data = ASItem.getDataPart(args[1]); ItemStack item = ASItem.getItemStack(ID, amount); if (item == null) { - PlayerUtils.sendError(player, pluginName, "'" + args[0] + "' wurde nicht gefunden"); + PlayerUtils.sendError(player, pluginName, "'" + args[1] + "' wurde nicht gefunden"); return; } item.setDurability(data); target.getInventory().addItem(item); // when item has a sub id String itemName = item.getType().name() + (data == 0 ? "" : ":" + data); PlayerUtils.sendSuccess(player, pluginName, "Spieler '" + target.getName() + "' erhaelt " + amount + " mal " + itemName); PlayerUtils.sendInfo(target, "Du erhaelst " + amount + " mal " + itemName); ConsoleUtils.printInfo(pluginName, "GIVE: " + player.getName() + " TO " + target.getName() + " : " + amount + " x " + itemName); } }
true
true
public void execute(String[] args, Player player) { Player target = PlayerUtils.getOnlinePlayer(args[0]); if (target == null) { PlayerUtils.sendError(player, pluginName, "Spieler '" + args[0] + "' nicht gefunden!"); return; } String ID = ASItem.getIDPart(args[1]); int amount = 1; if (args.length == 2) amount = 64; else if (args.length == 3) { try { amount = Integer.parseInt(args[2]); } catch (Exception e) { PlayerUtils.sendError(player, ID, args[2] + " ist keine Zahl! Itemanzahl auf Eins gesetzt!"); } if (amount < 1) { PlayerUtils.sendError(player, pluginName, args[2] + "ist kleiner als Eins! Itemanzahl auf Eins gesetzt!"); amount = 1; } } byte data = ASItem.getDataPart(args[1]); ItemStack item = ASItem.getItemStack(ID, amount); if (item == null) { PlayerUtils.sendError(player, pluginName, "'" + args[0] + "' wurde nicht gefunden"); return; } item.setDurability(data); target.getInventory().addItem(item); // when item has a sub id String itemName = item.getType().name() + (data == 0 ? "" : ":" + data); PlayerUtils.sendSuccess(player, pluginName, "Spieler '" + target.getName() + "' erhaelt " + amount + " mal " + itemName); PlayerUtils.sendInfo(target, "Du erhaelst " + amount + " mal " + itemName); ConsoleUtils.printInfo(pluginName, "GIVE: " + player.getName() + " TO " + target.getName() + " : " + amount + " x " + itemName); }
public void execute(String[] args, Player player) { Player target = PlayerUtils.getOnlinePlayer(args[0]); if (target == null) { PlayerUtils.sendError(player, pluginName, "Spieler '" + args[0] + "' nicht gefunden!"); return; } String ID = ASItem.getIDPart(args[1]); int amount = 1; if (args.length == 2) amount = 64; else if (args.length == 3) { try { amount = Integer.parseInt(args[2]); } catch (Exception e) { PlayerUtils.sendError(player, ID, args[2] + " ist keine Zahl! Itemanzahl auf Eins gesetzt!"); } if (amount < 1) { PlayerUtils.sendError(player, pluginName, args[2] + "ist kleiner als Eins! Itemanzahl auf Eins gesetzt!"); amount = 1; } } byte data = ASItem.getDataPart(args[1]); ItemStack item = ASItem.getItemStack(ID, amount); if (item == null) { PlayerUtils.sendError(player, pluginName, "'" + args[1] + "' wurde nicht gefunden"); return; } item.setDurability(data); target.getInventory().addItem(item); // when item has a sub id String itemName = item.getType().name() + (data == 0 ? "" : ":" + data); PlayerUtils.sendSuccess(player, pluginName, "Spieler '" + target.getName() + "' erhaelt " + amount + " mal " + itemName); PlayerUtils.sendInfo(target, "Du erhaelst " + amount + " mal " + itemName); ConsoleUtils.printInfo(pluginName, "GIVE: " + player.getName() + " TO " + target.getName() + " : " + amount + " x " + itemName); }
diff --git a/ServerThread.java b/ServerThread.java index f14ee05..f83346f 100644 --- a/ServerThread.java +++ b/ServerThread.java @@ -1,21 +1,23 @@ import java.net.*; import java.io.*; public class ServerThread extends Thread { Socket s = null; public ServerThread(Socket socket) { super("ServerThread"); s = socket; } public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); while (s.isConnected() && !s.isClosed()) { - System.out.println(in.readLine()); + String line = in.readLine(); + if (line.equals("exit")) break; + System.out.println(line); } } catch (Exception e) { e.printStackTrace(); } System.out.println("Done!"); } }
true
true
public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); while (s.isConnected() && !s.isClosed()) { System.out.println(in.readLine()); } } catch (Exception e) { e.printStackTrace(); } System.out.println("Done!"); }
public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); while (s.isConnected() && !s.isClosed()) { String line = in.readLine(); if (line.equals("exit")) break; System.out.println(line); } } catch (Exception e) { e.printStackTrace(); } System.out.println("Done!"); }
diff --git a/rwiki-impl/impl/src/java/uk/ac/cam/caret/sakai/rwiki/component/macros/BlockMacro.java b/rwiki-impl/impl/src/java/uk/ac/cam/caret/sakai/rwiki/component/macros/BlockMacro.java index de557afb..81bd382f 100755 --- a/rwiki-impl/impl/src/java/uk/ac/cam/caret/sakai/rwiki/component/macros/BlockMacro.java +++ b/rwiki-impl/impl/src/java/uk/ac/cam/caret/sakai/rwiki/component/macros/BlockMacro.java @@ -1,152 +1,152 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * 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 uk.ac.cam.caret.sakai.rwiki.component.macros; import java.io.IOException; import java.io.Writer; import org.radeox.api.macro.MacroParameter; import org.radeox.macro.BaseMacro; import uk.ac.cam.caret.sakai.rwiki.component.Messages; public class BlockMacro extends BaseMacro { public String[] getParamDescription() { return new String[] { Messages.getString("BlockMacro.0"), //$NON-NLS-1$ Messages.getString("BlockMacro.01"), //$NON-NLS-1$ Messages.getString("BlockMacro.1"), //$NON-NLS-1$ Messages.getString("BlockMacro.2") }; //$NON-NLS-1$ } /* * (non-Javadoc) * * @see org.radeox.macro.Macro#getDescription() */ public String getDescription() { return Messages.getString("BlockMacro.3"); //$NON-NLS-1$ } public String getName() { return "block"; //$NON-NLS-1$ } /* * (non-Javadoc) * * @see org.radeox.macro.Macro#execute(java.io.Writer, * org.radeox.macro.parameter.MacroParameter) */ public void execute(Writer writer, MacroParameter params) throws IllegalArgumentException, IOException { String cssClass = params.get("class"); //$NON-NLS-1$ if (cssClass == null) { cssClass = params.get(0); if (cssClass == null) { // do nothing } else if (cssClass.startsWith("id=")) //$NON-NLS-1$ { cssClass = null; } else if (cssClass.startsWith("name=")) //$NON-NLS-1$ { cssClass = null; } } String id = params.get("id"); //$NON-NLS-1$ String anchorName = params.get("name"); //$NON-NLS-1$ String style = params.get("style"); //$NON-NLS-1$ writer.write("<div"); //$NON-NLS-1$ if (cssClass != null && !"".equals(cssClass)) //$NON-NLS-1$ { - cssClass = cssClass.replaceAll("[^A-Za-z0-9]", ""); + cssClass = cssClass.replaceAll("[^A-Za-z0-9-_]", ""); writer.write(" class='"); //$NON-NLS-1$ writer.write(cssClass); //$NON-NLS-1$ //$NON-NLS-2$ writer.write('\''); } if (style != null && !"".equals(style)) //$NON-NLS-1$ { // SAK-20449 disabling style output // writer.write(" style='"); //$NON-NLS-1$ // writer.write(style.replaceAll("'", "&apos;")); //$NON-NLS-1$ //$NON-NLS-2$ // writer.write('\''); } if (id != null && !"".equals(id)) //$NON-NLS-1$ { writer.write(" id='"); //$NON-NLS-1$ char[] nameChars = id.toCharArray(); int end = 0; for (int i = 0; i < nameChars.length; i++) { if (Character.isLetterOrDigit(nameChars[i])) { nameChars[end++] = nameChars[i]; } } if (end > 0) { writer.write(nameChars, 0, end); } writer.write('\''); } writer.write('>'); if (anchorName != null && !"".equals(anchorName)) //$NON-NLS-1$ { writer.write("<a name=\""); //$NON-NLS-1$ char[] nameChars = anchorName.toCharArray(); int end = 0; for (int i = 0; i < nameChars.length; i++) { if (Character.isLetterOrDigit(nameChars[i])) { nameChars[end++] = nameChars[i]; } } if (end > 0) { writer.write(nameChars, 0, end); } writer.write("' class='anchorpoint'>"); //$NON-NLS-1$ writer.write("<!-- --></a>"); //$NON-NLS-1$ } if (params.getContent() != null) { writer.write("<p class=\"paragraph\">"); //$NON-NLS-1$ writer.write(params.getContent()); writer.write("</p>"); //$NON-NLS-1$ } writer.write("</div>"); //$NON-NLS-1$ } }
true
true
public void execute(Writer writer, MacroParameter params) throws IllegalArgumentException, IOException { String cssClass = params.get("class"); //$NON-NLS-1$ if (cssClass == null) { cssClass = params.get(0); if (cssClass == null) { // do nothing } else if (cssClass.startsWith("id=")) //$NON-NLS-1$ { cssClass = null; } else if (cssClass.startsWith("name=")) //$NON-NLS-1$ { cssClass = null; } } String id = params.get("id"); //$NON-NLS-1$ String anchorName = params.get("name"); //$NON-NLS-1$ String style = params.get("style"); //$NON-NLS-1$ writer.write("<div"); //$NON-NLS-1$ if (cssClass != null && !"".equals(cssClass)) //$NON-NLS-1$ { cssClass = cssClass.replaceAll("[^A-Za-z0-9]", ""); writer.write(" class='"); //$NON-NLS-1$ writer.write(cssClass); //$NON-NLS-1$ //$NON-NLS-2$ writer.write('\''); } if (style != null && !"".equals(style)) //$NON-NLS-1$ { // SAK-20449 disabling style output // writer.write(" style='"); //$NON-NLS-1$ // writer.write(style.replaceAll("'", "&apos;")); //$NON-NLS-1$ //$NON-NLS-2$ // writer.write('\''); } if (id != null && !"".equals(id)) //$NON-NLS-1$ { writer.write(" id='"); //$NON-NLS-1$ char[] nameChars = id.toCharArray(); int end = 0; for (int i = 0; i < nameChars.length; i++) { if (Character.isLetterOrDigit(nameChars[i])) { nameChars[end++] = nameChars[i]; } } if (end > 0) { writer.write(nameChars, 0, end); } writer.write('\''); } writer.write('>'); if (anchorName != null && !"".equals(anchorName)) //$NON-NLS-1$ { writer.write("<a name=\""); //$NON-NLS-1$ char[] nameChars = anchorName.toCharArray(); int end = 0; for (int i = 0; i < nameChars.length; i++) { if (Character.isLetterOrDigit(nameChars[i])) { nameChars[end++] = nameChars[i]; } } if (end > 0) { writer.write(nameChars, 0, end); } writer.write("' class='anchorpoint'>"); //$NON-NLS-1$ writer.write("<!-- --></a>"); //$NON-NLS-1$ } if (params.getContent() != null) { writer.write("<p class=\"paragraph\">"); //$NON-NLS-1$ writer.write(params.getContent()); writer.write("</p>"); //$NON-NLS-1$ } writer.write("</div>"); //$NON-NLS-1$ }
public void execute(Writer writer, MacroParameter params) throws IllegalArgumentException, IOException { String cssClass = params.get("class"); //$NON-NLS-1$ if (cssClass == null) { cssClass = params.get(0); if (cssClass == null) { // do nothing } else if (cssClass.startsWith("id=")) //$NON-NLS-1$ { cssClass = null; } else if (cssClass.startsWith("name=")) //$NON-NLS-1$ { cssClass = null; } } String id = params.get("id"); //$NON-NLS-1$ String anchorName = params.get("name"); //$NON-NLS-1$ String style = params.get("style"); //$NON-NLS-1$ writer.write("<div"); //$NON-NLS-1$ if (cssClass != null && !"".equals(cssClass)) //$NON-NLS-1$ { cssClass = cssClass.replaceAll("[^A-Za-z0-9-_]", ""); writer.write(" class='"); //$NON-NLS-1$ writer.write(cssClass); //$NON-NLS-1$ //$NON-NLS-2$ writer.write('\''); } if (style != null && !"".equals(style)) //$NON-NLS-1$ { // SAK-20449 disabling style output // writer.write(" style='"); //$NON-NLS-1$ // writer.write(style.replaceAll("'", "&apos;")); //$NON-NLS-1$ //$NON-NLS-2$ // writer.write('\''); } if (id != null && !"".equals(id)) //$NON-NLS-1$ { writer.write(" id='"); //$NON-NLS-1$ char[] nameChars = id.toCharArray(); int end = 0; for (int i = 0; i < nameChars.length; i++) { if (Character.isLetterOrDigit(nameChars[i])) { nameChars[end++] = nameChars[i]; } } if (end > 0) { writer.write(nameChars, 0, end); } writer.write('\''); } writer.write('>'); if (anchorName != null && !"".equals(anchorName)) //$NON-NLS-1$ { writer.write("<a name=\""); //$NON-NLS-1$ char[] nameChars = anchorName.toCharArray(); int end = 0; for (int i = 0; i < nameChars.length; i++) { if (Character.isLetterOrDigit(nameChars[i])) { nameChars[end++] = nameChars[i]; } } if (end > 0) { writer.write(nameChars, 0, end); } writer.write("' class='anchorpoint'>"); //$NON-NLS-1$ writer.write("<!-- --></a>"); //$NON-NLS-1$ } if (params.getContent() != null) { writer.write("<p class=\"paragraph\">"); //$NON-NLS-1$ writer.write(params.getContent()); writer.write("</p>"); //$NON-NLS-1$ } writer.write("</div>"); //$NON-NLS-1$ }
diff --git a/src/com/android/bluetooth/btservice/AdapterProperties.java b/src/com/android/bluetooth/btservice/AdapterProperties.java index 73e795e..0c00ffd 100755 --- a/src/com/android/bluetooth/btservice/AdapterProperties.java +++ b/src/com/android/bluetooth/btservice/AdapterProperties.java @@ -1,559 +1,560 @@ /* * Copyright (C) 2012 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.bluetooth.btservice; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.content.Context; import android.content.Intent; import android.os.ParcelUuid; import android.os.UserHandle; import android.util.Log; import android.util.Pair; import com.android.bluetooth.Utils; import com.android.bluetooth.btservice.RemoteDevices.DeviceProperties; import java.util.HashMap; import java.util.ArrayList; class AdapterProperties { private static final boolean DBG = false; private static final String TAG = "BluetoothAdapterProperties"; private static final int BD_ADDR_LEN = 6; // 6 bytes private String mName; private byte[] mAddress; private int mBluetoothClass; private int mScanMode; private int mDiscoverableTimeout; private ParcelUuid[] mUuids; private ArrayList<BluetoothDevice> mBondedDevices = new ArrayList<BluetoothDevice>(); private int mProfilesConnecting, mProfilesConnected, mProfilesDisconnecting; private HashMap<Integer, Pair<Integer, Integer>> mProfileConnectionState; private int mConnectionState = BluetoothAdapter.STATE_DISCONNECTED; private int mState = BluetoothAdapter.STATE_OFF; private AdapterService mService; private boolean mDiscovering; private RemoteDevices mRemoteDevices; private BluetoothAdapter mAdapter; // Lock for all getters and setters. // If finer grained locking is needer, more locks // can be added here. private Object mObject = new Object(); public AdapterProperties(AdapterService service) { mService = service; mAdapter = BluetoothAdapter.getDefaultAdapter(); } public void init(RemoteDevices remoteDevices) { if (mProfileConnectionState ==null) { mProfileConnectionState = new HashMap<Integer, Pair<Integer, Integer>>(); } else { mProfileConnectionState.clear(); } mRemoteDevices = remoteDevices; } public void cleanup() { mRemoteDevices = null; if (mProfileConnectionState != null) { mProfileConnectionState.clear(); mProfileConnectionState = null; } mService = null; if (!mBondedDevices.isEmpty()) mBondedDevices.clear(); } public Object Clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } /** * @return the mName */ String getName() { synchronized (mObject) { return mName; } } /** * Set the local adapter property - name * @param name the name to set */ boolean setName(String name) { synchronized (mObject) { return mService.setAdapterPropertyNative( AbstractionLayer.BT_PROPERTY_BDNAME, name.getBytes()); } } /** * @return the mClass */ int getBluetoothClass() { synchronized (mObject) { return mBluetoothClass; } } /** * @return the mScanMode */ int getScanMode() { synchronized (mObject) { return mScanMode; } } /** * Set the local adapter property - scanMode * * @param scanMode the ScanMode to set */ boolean setScanMode(int scanMode) { synchronized (mObject) { return mService.setAdapterPropertyNative( AbstractionLayer.BT_PROPERTY_ADAPTER_SCAN_MODE, Utils.intToByteArray(scanMode)); } } /** * @return the mUuids */ ParcelUuid[] getUuids() { synchronized (mObject) { return mUuids; } } /** * Set local adapter UUIDs. * * @param uuids the uuids to be set. */ boolean setUuids(ParcelUuid[] uuids) { synchronized (mObject) { return mService.setAdapterPropertyNative( AbstractionLayer.BT_PROPERTY_UUIDS, Utils.uuidsToByteArray(uuids)); } } /** * @return the mAddress */ byte[] getAddress() { synchronized (mObject) { return mAddress; } } /** * @param mConnectionState the mConnectionState to set */ void setConnectionState(int mConnectionState) { synchronized (mObject) { this.mConnectionState = mConnectionState; } } /** * @return the mConnectionState */ int getConnectionState() { synchronized (mObject) { return mConnectionState; } } /** * @param mState the mState to set */ void setState(int mState) { synchronized (mObject) { debugLog("Setting state to " + mState); this.mState = mState; } } /** * @return the mState */ int getState() { synchronized (mObject) { debugLog("State = " + mState); return mState; } } /** * @return the mBondedDevices */ BluetoothDevice[] getBondedDevices() { BluetoothDevice[] bondedDeviceList = new BluetoothDevice[0]; synchronized (mObject) { if(mBondedDevices.isEmpty()) return (new BluetoothDevice[0]); try { bondedDeviceList = mBondedDevices.toArray(bondedDeviceList); debugLog("getBondedDevices: length="+bondedDeviceList.length); return bondedDeviceList; } catch(ArrayStoreException ee) { errorLog("Error retrieving bonded device array"); return (new BluetoothDevice[0]); } } } // This function shall be invoked from BondStateMachine whenever the bond // state changes. void onBondStateChanged(BluetoothDevice device, int state) { if(device == null) return; try { byte[] addrByte = Utils.getByteAddress(device); DeviceProperties prop = mRemoteDevices.getDeviceProperties(device); if (prop == null) prop = mRemoteDevices.addDeviceProperties(addrByte); prop.setBondState(state); if (state == BluetoothDevice.BOND_BONDED) { // add if not already in list if(!mBondedDevices.contains(device)) { debugLog("Adding bonded device:" + device); mBondedDevices.add(device); } } else if (state == BluetoothDevice.BOND_NONE) { // remove device from list if (mBondedDevices.remove(device)) debugLog("Removing bonded device:" + device); else debugLog("Failed to remove device: " + device); } } catch(Exception ee) { Log.e(TAG, "Exception in onBondStateChanged : ", ee); } } int getDiscoverableTimeout() { synchronized (mObject) { return mDiscoverableTimeout; } } boolean setDiscoverableTimeout(int timeout) { synchronized (mObject) { return mService.setAdapterPropertyNative( AbstractionLayer.BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT, Utils.intToByteArray(timeout)); } } int getProfileConnectionState(int profile) { synchronized (mObject) { Pair<Integer, Integer> p = mProfileConnectionState.get(profile); if (p != null) return p.first; return BluetoothProfile.STATE_DISCONNECTED; } } boolean isDiscovering() { synchronized (mObject) { return mDiscovering; } } void sendConnectionStateChange(BluetoothDevice device, int profile, int state, int prevState) { if (!validateProfileConnectionState(state) || !validateProfileConnectionState(prevState)) { // Previously, an invalid state was broadcast anyway, // with the invalid state converted to -1 in the intent. // Better to log an error and not send an intent with // invalid contents or set mAdapterConnectionState to -1. errorLog("Error in sendConnectionStateChange: " + "prevState " + prevState + " state " + state); return; } synchronized (mObject) { updateProfileConnectionState(profile, state, prevState); if (updateCountersAndCheckForConnectionStateChange(state, prevState)) { setConnectionState(state); Intent intent = new Intent(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED); intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device); intent.putExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, convertToAdapterState(state)); intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_CONNECTION_STATE, convertToAdapterState(prevState)); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); mService.sendBroadcastAsUser(intent, UserHandle.ALL, mService.BLUETOOTH_PERM); Log.d(TAG, "CONNECTION_STATE_CHANGE: " + device + ": " + prevState + " -> " + state); } } } private boolean validateProfileConnectionState(int state) { return (state == BluetoothProfile.STATE_DISCONNECTED || state == BluetoothProfile.STATE_CONNECTING || state == BluetoothProfile.STATE_CONNECTED || state == BluetoothProfile.STATE_DISCONNECTING); } private int convertToAdapterState(int state) { switch (state) { case BluetoothProfile.STATE_DISCONNECTED: return BluetoothAdapter.STATE_DISCONNECTED; case BluetoothProfile.STATE_DISCONNECTING: return BluetoothAdapter.STATE_DISCONNECTING; case BluetoothProfile.STATE_CONNECTED: return BluetoothAdapter.STATE_CONNECTED; case BluetoothProfile.STATE_CONNECTING: return BluetoothAdapter.STATE_CONNECTING; } Log.e(TAG, "Error in convertToAdapterState"); return -1; } private boolean updateCountersAndCheckForConnectionStateChange(int state, int prevState) { switch (prevState) { case BluetoothProfile.STATE_CONNECTING: mProfilesConnecting--; break; case BluetoothProfile.STATE_CONNECTED: mProfilesConnected--; break; case BluetoothProfile.STATE_DISCONNECTING: mProfilesDisconnecting--; break; } switch (state) { case BluetoothProfile.STATE_CONNECTING: mProfilesConnecting++; return (mProfilesConnected == 0 && mProfilesConnecting == 1); case BluetoothProfile.STATE_CONNECTED: mProfilesConnected++; return (mProfilesConnected == 1); case BluetoothProfile.STATE_DISCONNECTING: mProfilesDisconnecting++; return (mProfilesConnected == 0 && mProfilesDisconnecting == 1); case BluetoothProfile.STATE_DISCONNECTED: return (mProfilesConnected == 0 && mProfilesConnecting == 0); default: return true; } } private void updateProfileConnectionState(int profile, int newState, int oldState) { // mProfileConnectionState is a hashmap - // <Integer, Pair<Integer, Integer>> // The key is the profile, the value is a pair. first element // is the state and the second element is the number of devices // in that state. int numDev = 1; int newHashState = newState; boolean update = true; // The following conditions are considered in this function: // 1. If there is no record of profile and state - update // 2. If a new device's state is current hash state - increment // number of devices in the state. // 3. If a state change has happened to Connected or Connecting // (if current state is not connected), update. // 4. If numDevices is 1 and that device state is being updated, update // 5. If numDevices is > 1 and one of the devices is changing state, // decrement numDevices but maintain oldState if it is Connected or // Connecting Pair<Integer, Integer> stateNumDev = mProfileConnectionState.get(profile); if (stateNumDev != null) { int currHashState = stateNumDev.first; numDev = stateNumDev.second; if (newState == currHashState) { numDev ++; } else if (newState == BluetoothProfile.STATE_CONNECTED || (newState == BluetoothProfile.STATE_CONNECTING && currHashState != BluetoothProfile.STATE_CONNECTED)) { numDev = 1; } else if (numDev == 1 && oldState == currHashState) { update = true; } else if (numDev > 1 && oldState == currHashState) { numDev --; if (currHashState == BluetoothProfile.STATE_CONNECTED || currHashState == BluetoothProfile.STATE_CONNECTING) { newHashState = currHashState; } } else { update = false; } } if (update) { mProfileConnectionState.put(profile, new Pair<Integer, Integer>(newHashState, numDev)); } } void adapterPropertyChangedCallback(int[] types, byte[][] values) { Intent intent; int type; byte[] val; for (int i = 0; i < types.length; i++) { val = values[i]; type = types[i]; infoLog("adapterPropertyChangedCallback with type:" + type + " len:" + val.length); synchronized (mObject) { switch (type) { case AbstractionLayer.BT_PROPERTY_BDNAME: mName = new String(val); intent = new Intent(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED); intent.putExtra(BluetoothAdapter.EXTRA_LOCAL_NAME, mName); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); - mService.sendBroadcast(intent, mService.BLUETOOTH_PERM); + mService.sendBroadcastAsUser(intent, UserHandle.ALL, + mService.BLUETOOTH_PERM); debugLog("Name is: " + mName); break; case AbstractionLayer.BT_PROPERTY_BDADDR: mAddress = val; debugLog("Address is:" + Utils.getAddressStringFromByte(mAddress)); break; case AbstractionLayer.BT_PROPERTY_CLASS_OF_DEVICE: mBluetoothClass = Utils.byteArrayToInt(val, 0); debugLog("BT Class:" + mBluetoothClass); break; case AbstractionLayer.BT_PROPERTY_ADAPTER_SCAN_MODE: int mode = Utils.byteArrayToInt(val, 0); mScanMode = mService.convertScanModeFromHal(mode); intent = new Intent(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); intent.putExtra(BluetoothAdapter.EXTRA_SCAN_MODE, mScanMode); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); mService.sendBroadcast(intent, mService.BLUETOOTH_PERM); debugLog("Scan Mode:" + mScanMode); if (mBluetoothDisabling) { mBluetoothDisabling=false; mService.startBluetoothDisable(); } break; case AbstractionLayer.BT_PROPERTY_UUIDS: mUuids = Utils.byteArrayToUuid(val); break; case AbstractionLayer.BT_PROPERTY_ADAPTER_BONDED_DEVICES: int number = val.length/BD_ADDR_LEN; byte[] addrByte = new byte[BD_ADDR_LEN]; for (int j = 0; j < number; j++) { System.arraycopy(val, j * BD_ADDR_LEN, addrByte, 0, BD_ADDR_LEN); onBondStateChanged(mAdapter.getRemoteDevice( Utils.getAddressStringFromByte(addrByte)), BluetoothDevice.BOND_BONDED); } break; case AbstractionLayer.BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT: mDiscoverableTimeout = Utils.byteArrayToInt(val, 0); debugLog("Discoverable Timeout:" + mDiscoverableTimeout); break; default: errorLog("Property change not handled in Java land:" + type); } } } } void onBluetoothReady() { Log.d(TAG, "ScanMode = " + mScanMode ); Log.d(TAG, "State = " + getState() ); // When BT is being turned on, all adapter properties will be sent in 1 // callback. At this stage, set the scan mode. synchronized (mObject) { if (getState() == BluetoothAdapter.STATE_TURNING_ON && mScanMode == BluetoothAdapter.SCAN_MODE_NONE) { /* mDiscoverableTimeout is part of the adapterPropertyChangedCallback received before onBluetoothReady */ if (mDiscoverableTimeout != 0) setScanMode(AbstractionLayer.BT_SCAN_MODE_CONNECTABLE); else /* if timeout == never (0) at startup */ setScanMode(AbstractionLayer.BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); /* though not always required, this keeps NV up-to date on first-boot after flash */ setDiscoverableTimeout(mDiscoverableTimeout); } } } private boolean mBluetoothDisabling=false; void onBluetoothDisable() { // When BT disable is invoked, set the scan_mode to NONE // so no incoming connections are possible //Set flag to indicate we are disabling. When property change of scan mode done //continue with disable sequence debugLog("onBluetoothDisable()"); mBluetoothDisabling = true; if (getState() == BluetoothAdapter.STATE_TURNING_OFF) { setScanMode(AbstractionLayer.BT_SCAN_MODE_NONE); } } void discoveryStateChangeCallback(int state) { infoLog("Callback:discoveryStateChangeCallback with state:" + state); synchronized (mObject) { Intent intent; if (state == AbstractionLayer.BT_DISCOVERY_STOPPED) { mDiscovering = false; intent = new Intent(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); mService.sendBroadcast(intent, mService.BLUETOOTH_PERM); } else if (state == AbstractionLayer.BT_DISCOVERY_STARTED) { mDiscovering = true; intent = new Intent(BluetoothAdapter.ACTION_DISCOVERY_STARTED); mService.sendBroadcast(intent, mService.BLUETOOTH_PERM); } } } private void infoLog(String msg) { Log.i(TAG, msg); } private void debugLog(String msg) { if (DBG) Log.d(TAG, msg); } private void errorLog(String msg) { Log.e(TAG, msg); } }
true
true
void adapterPropertyChangedCallback(int[] types, byte[][] values) { Intent intent; int type; byte[] val; for (int i = 0; i < types.length; i++) { val = values[i]; type = types[i]; infoLog("adapterPropertyChangedCallback with type:" + type + " len:" + val.length); synchronized (mObject) { switch (type) { case AbstractionLayer.BT_PROPERTY_BDNAME: mName = new String(val); intent = new Intent(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED); intent.putExtra(BluetoothAdapter.EXTRA_LOCAL_NAME, mName); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); mService.sendBroadcast(intent, mService.BLUETOOTH_PERM); debugLog("Name is: " + mName); break; case AbstractionLayer.BT_PROPERTY_BDADDR: mAddress = val; debugLog("Address is:" + Utils.getAddressStringFromByte(mAddress)); break; case AbstractionLayer.BT_PROPERTY_CLASS_OF_DEVICE: mBluetoothClass = Utils.byteArrayToInt(val, 0); debugLog("BT Class:" + mBluetoothClass); break; case AbstractionLayer.BT_PROPERTY_ADAPTER_SCAN_MODE: int mode = Utils.byteArrayToInt(val, 0); mScanMode = mService.convertScanModeFromHal(mode); intent = new Intent(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); intent.putExtra(BluetoothAdapter.EXTRA_SCAN_MODE, mScanMode); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); mService.sendBroadcast(intent, mService.BLUETOOTH_PERM); debugLog("Scan Mode:" + mScanMode); if (mBluetoothDisabling) { mBluetoothDisabling=false; mService.startBluetoothDisable(); } break; case AbstractionLayer.BT_PROPERTY_UUIDS: mUuids = Utils.byteArrayToUuid(val); break; case AbstractionLayer.BT_PROPERTY_ADAPTER_BONDED_DEVICES: int number = val.length/BD_ADDR_LEN; byte[] addrByte = new byte[BD_ADDR_LEN]; for (int j = 0; j < number; j++) { System.arraycopy(val, j * BD_ADDR_LEN, addrByte, 0, BD_ADDR_LEN); onBondStateChanged(mAdapter.getRemoteDevice( Utils.getAddressStringFromByte(addrByte)), BluetoothDevice.BOND_BONDED); } break; case AbstractionLayer.BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT: mDiscoverableTimeout = Utils.byteArrayToInt(val, 0); debugLog("Discoverable Timeout:" + mDiscoverableTimeout); break; default: errorLog("Property change not handled in Java land:" + type); } } } }
void adapterPropertyChangedCallback(int[] types, byte[][] values) { Intent intent; int type; byte[] val; for (int i = 0; i < types.length; i++) { val = values[i]; type = types[i]; infoLog("adapterPropertyChangedCallback with type:" + type + " len:" + val.length); synchronized (mObject) { switch (type) { case AbstractionLayer.BT_PROPERTY_BDNAME: mName = new String(val); intent = new Intent(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED); intent.putExtra(BluetoothAdapter.EXTRA_LOCAL_NAME, mName); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); mService.sendBroadcastAsUser(intent, UserHandle.ALL, mService.BLUETOOTH_PERM); debugLog("Name is: " + mName); break; case AbstractionLayer.BT_PROPERTY_BDADDR: mAddress = val; debugLog("Address is:" + Utils.getAddressStringFromByte(mAddress)); break; case AbstractionLayer.BT_PROPERTY_CLASS_OF_DEVICE: mBluetoothClass = Utils.byteArrayToInt(val, 0); debugLog("BT Class:" + mBluetoothClass); break; case AbstractionLayer.BT_PROPERTY_ADAPTER_SCAN_MODE: int mode = Utils.byteArrayToInt(val, 0); mScanMode = mService.convertScanModeFromHal(mode); intent = new Intent(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); intent.putExtra(BluetoothAdapter.EXTRA_SCAN_MODE, mScanMode); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); mService.sendBroadcast(intent, mService.BLUETOOTH_PERM); debugLog("Scan Mode:" + mScanMode); if (mBluetoothDisabling) { mBluetoothDisabling=false; mService.startBluetoothDisable(); } break; case AbstractionLayer.BT_PROPERTY_UUIDS: mUuids = Utils.byteArrayToUuid(val); break; case AbstractionLayer.BT_PROPERTY_ADAPTER_BONDED_DEVICES: int number = val.length/BD_ADDR_LEN; byte[] addrByte = new byte[BD_ADDR_LEN]; for (int j = 0; j < number; j++) { System.arraycopy(val, j * BD_ADDR_LEN, addrByte, 0, BD_ADDR_LEN); onBondStateChanged(mAdapter.getRemoteDevice( Utils.getAddressStringFromByte(addrByte)), BluetoothDevice.BOND_BONDED); } break; case AbstractionLayer.BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT: mDiscoverableTimeout = Utils.byteArrayToInt(val, 0); debugLog("Discoverable Timeout:" + mDiscoverableTimeout); break; default: errorLog("Property change not handled in Java land:" + type); } } } }
diff --git a/src/gui/CalendarGui.java b/src/gui/CalendarGui.java index ea52ef2..7d69188 100644 --- a/src/gui/CalendarGui.java +++ b/src/gui/CalendarGui.java @@ -1,420 +1,421 @@ package gui; import static gui.GuiConstants.DEFAULT_END_HOUR; import static gui.GuiConstants.DEFAULT_START_HOUR; import static gui.GuiConstants.FRAME_HEIGHT; import static gui.GuiConstants.FRAME_WIDTH; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.Image; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.GroupLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import cal_master.Communicator; import cal_master.NameIDPair; import calendar.CalendarResponses; import calendar.Event; import calendar.Event.PaintMethod; import calendar.UserCal; import calendar.When2MeetEvent; public class CalendarGui { private Event _slotGroup = null; private int _startHour = DEFAULT_START_HOUR; private int _numHours = DEFAULT_END_HOUR - DEFAULT_START_HOUR; private JFrame _frame; private ReplyPanel _replyPanel; // private JPanel _hourOfDayLabels; // private ArrayList<Integer> _hoursOfDay = new ArrayList<Integer>(); private Communicator _communicator = new Communicator(); private UserCalPanel _userCalPanel; //private JButton _eventDispButton = new JButton("Toggle Event Display"); private PaintMethod _eventDispStyle = PaintMethod.Bars; private EventPanel _eventPanel = new EventPanel(_communicator, this); private UpdatesPanel _updatesPanel = new UpdatesPanel(); private FriendBar _friendBar = new FriendBar(this); ImageIcon _findTimeIcon = new ImageIcon("small_logo_button.png"); ImageIcon _findTimeIconInverted = new ImageIcon("small_logo_button_invert.png"); ImageIcon _toggleIcon = new ImageIcon("small_switch_button.png"); ImageIcon _toggleIconInverted = new ImageIcon("small_switch_button_invert.png"); ImageIcon _refreshIcon = new ImageIcon("small_refresh_button.png"); ImageIcon _refreshIconInverted = new ImageIcon("small_refresh_button_invert.png"); ImageIcon _submitIcon = new ImageIcon("small_submit_button.png"); ImageIcon _submitIconInverted = new ImageIcon("small_submit_button_invert"); ImageIcon _prevIcon = new ImageIcon("small_left_button.png"); ImageIcon _prevIconInverted = new ImageIcon("small_left_button_invert"); ImageIcon _nextIcon = new ImageIcon("small_right_button.png"); ImageIcon _nextIconInverted = new ImageIcon("small_right_button_invert"); private JButton _refreshButton = new JButton(_refreshIcon); private JButton _eventDispButton = new JButton(_toggleIcon); private JButton _timeFindButton = new JButton(_findTimeIcon); private JButton _submitButton = new JButton(_submitIcon); private JButton _nextButton = new JButton(_nextIcon); private JButton _prevButton = new JButton(_prevIcon); public static enum DaysOfWeek {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}; JLabel picLabel; public CalendarGui() throws URISyntaxException{ this.displayButton(_refreshButton); this.displayButton(_eventDispButton); this.displayButton(_timeFindButton); this.displayButton(_submitButton); this.displayButton(_prevButton); this.displayButton(_nextButton); _communicator.startUp(); _startHour = 9; _friendBar.setEvent(null); UserCal userCal = null; if(_communicator.hasUserCal()) userCal =_communicator.getUserCal(); _replyPanel = new ReplyPanel(userCal, null); ArrayList<NameIDPair> pairs = _communicator.getNameIDPairs(); for(NameIDPair pair : pairs) { _eventPanel.addEvent(new EventLabel(pair.getName(), pair.getID(), _communicator, this)); } _userCalPanel = new UserCalPanel(_communicator, this); _submitButton.addActionListener(new SubmitListener()); _submitButton.setFont(new Font(GuiConstants.FONT_NAME, _submitButton.getFont().getStyle(), _submitButton.getFont().getSize())); _submitButton.setToolTipText("Submit Response"); _submitButton.setPressedIcon(_submitIconInverted); _timeFindButton.addActionListener(new TimeFindListener()); _timeFindButton.setFont(new Font(GuiConstants.FONT_NAME, _timeFindButton.getFont().getStyle(), _timeFindButton.getFont().getSize())); _timeFindButton.setToolTipText("Find Best Times"); _timeFindButton.setPressedIcon(_findTimeIconInverted); _nextButton.addActionListener(new NextListener()); _nextButton.setFont(new Font(GuiConstants.FONT_NAME, _nextButton.getFont().getStyle(), _nextButton.getFont().getSize())); _nextButton.setPressedIcon(_nextIconInverted); _nextButton.setToolTipText("Next"); _prevButton.addActionListener(new PrevListener()); _prevButton.setFont(new Font(GuiConstants.FONT_NAME, _prevButton.getFont().getStyle(), _prevButton.getFont().getSize())); _prevButton.setFocusable(false); _prevButton.setPressedIcon(_prevIconInverted); _prevButton.setToolTipText("Previous"); _eventDispButton.addActionListener(new EventDispButtonListener()); _eventDispButton.setFocusable(false); _eventDispButton.setToolTipText("Toggle Display"); // _eventDispButton.setFont(new Font(GuiConstants.FONT_NAME, _eventDispButton.getFont().getStyle(), _eventDispButton.getFont().getSize())); _refreshButton.addActionListener(new RefreshListener()); _refreshButton.setFocusable(false); _refreshButton.setToolTipText("Refresh"); BufferedImage kairosLogo; try { kairosLogo = ImageIO.read(new File("KairosLogo.png")); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); kairosLogo = null; } picLabel = new JLabel(new ImageIcon(kairosLogo)); _numHours = 8; buildFrame(); } public void displayButton(JButton button) { button.setBorderPainted(false); button.setContentAreaFilled(false); button.setFocusPainted(false); button.setOpaque(false); } public Event getEvent(){ return _slotGroup; } public void setEvent(Event event){ _slotGroup= event; if(_slotGroup != null){ _slotGroup.init(); event.setPaintMethod(_eventDispStyle); } System.out.println("SLOT GROUP IN SET EVENT: " + _slotGroup); _replyPanel.setEvent(_slotGroup); System.out.println("Setting event for reply panel"); UserCal userCal = _communicator.getUserCal(); _replyPanel.setUserCal(userCal); _replyPanel.repaint(); if(_slotGroup != null){ _startHour = event.getStartTime().getHourOfDay(); _numHours = event.getNumHours(); } else{ _startHour = 9; _numHours = 8; } _updatesPanel.setEvent(_slotGroup); _friendBar.setEvent(_slotGroup); // updateHourLabels(); _eventPanel.refresh(); } public void setUserCal(UserCal userCal){ _replyPanel.setUserCal(userCal); } private class InnerWindowListener extends WindowAdapter { @Override public void windowClosing(WindowEvent e) { //System.out.println("Window closing triggered"); //_communicator.saveAll(); } } public void buildFrame(){ _frame = new JFrame("Kairos"); _frame.addWindowListener(new InnerWindowListener()); JPanel calPanel = new JPanel(); GroupLayout calLayout = new GroupLayout(calPanel); calPanel.setLayout(calLayout); // TODO change to false _frame.setResizable(true); calLayout.setHorizontalGroup( calLayout.createSequentialGroup() // .addComponent(_hourOfDayLabels, GroupLayout.PREFERRED_SIZE, _hourOfDayLabels.getPreferredSize().width, // GroupLayout.PREFERRED_SIZE) - .addComponent(_replyPanel, GroupLayout.PREFERRED_SIZE, (int) (FRAME_WIDTH*.75), + .addComponent(_replyPanel, GroupLayout.PREFERRED_SIZE, (int) (FRAME_WIDTH*.70), GroupLayout.PREFERRED_SIZE)); calLayout.setVerticalGroup( calLayout.createParallelGroup(GroupLayout.Alignment.TRAILING) - .addComponent(_replyPanel, GroupLayout.PREFERRED_SIZE, FRAME_HEIGHT - _replyPanel.getPreferredSize().height, + .addComponent(_replyPanel, GroupLayout.PREFERRED_SIZE, FRAME_HEIGHT - _replyPanel.getPreferredSize().height + 15, GroupLayout.PREFERRED_SIZE) // .addComponent(_hourOfDayLabels, GroupLayout.PREFERRED_SIZE, FRAME_HEIGHT - _replyPanel.getPreferredSize().height - _replyPanel.getWeekDayPanelHeight(), // GroupLayout.PREFERRED_SIZE) ); _frame.add(calPanel, BorderLayout.CENTER); JPanel submitPanel = new JPanel(); submitPanel.add(_submitButton); JPanel timeFindPanel = new JPanel(); timeFindPanel.add(_timeFindButton); JPanel prevPanel = new JPanel(); prevPanel.add(_prevButton); prevPanel.add(_nextButton); JPanel dispStylePanel = new JPanel(); dispStylePanel.add(_eventDispButton); JPanel refreshPanel = new JPanel(); refreshPanel.add(_refreshButton); JPanel buttonPanel = new JPanel(new GridLayout(1, 0)); buttonPanel.add(prevPanel); // buttonPanel.add(nextPanel); buttonPanel.add(dispStylePanel); buttonPanel.add(submitPanel); buttonPanel.add(timeFindPanel); buttonPanel.add(refreshPanel); // buttonPanel.add( picLabel ); //JPanel northPanel = new JPanel(new GridLayout(2,1)); //northPanel.add(buttonPanel); //northPanel.add(_friendBar); _frame.add(buttonPanel, BorderLayout.NORTH); JPanel westPanel = new JPanel(new GridLayout(0, 1)); westPanel.add(_friendBar); - _friendBar.mySetSize(new Dimension((int) ((FRAME_WIDTH*.25*.25)), 400)); + westPanel.setPreferredSize(new Dimension((int) ((FRAME_WIDTH*.25*.40)), 400)); + _friendBar.mySetSize(new Dimension((int) ((FRAME_WIDTH*.25*.40)), 400)); _frame.add(westPanel, BorderLayout.WEST); JPanel eastPanel = new JPanel(new GridLayout(0,1)); eastPanel.add(_userCalPanel); eastPanel.add(_eventPanel); eastPanel.add(_updatesPanel); eastPanel.setPreferredSize(new Dimension((int) ((FRAME_WIDTH*.25)*.60), 700)); _frame.add(eastPanel, BorderLayout.EAST); _frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //_frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); _frame.pack(); _frame.setVisible(true); } public void replyToEvent(){ if(_slotGroup != null && _replyPanel.getClicks() != null) _communicator.submitResponse(Integer.toString(((When2MeetEvent) _slotGroup).getID()), _replyPanel.getClicks()); } public void repaint(){ if(_frame != null){ _frame.invalidate(); _frame.validate(); _frame.repaint(); } } public void setBestTimes(int duration){ if(_slotGroup != null){ CalendarResponses bestTimes = _communicator.getBestTimes(String.valueOf(_slotGroup.getID()), duration); _replyPanel.setBestTimes(bestTimes); repaint(); } } private class SubmitListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if(_slotGroup != null){ int selection = JOptionPane.showConfirmDialog(null,"Are you sure you want to submit?", "", JOptionPane.YES_NO_OPTION); if(selection == JOptionPane.YES_OPTION) replyToEvent(); } } } private class NextListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if(_slotGroup != null) _replyPanel.nextWeek(); } } private class PrevListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if(_slotGroup != null) _replyPanel.prevWeek(); } } private class EventDispButtonListener implements ActionListener { public void actionPerformed(ActionEvent arg0) { if(_slotGroup != null) { if(_eventDispStyle == PaintMethod.Bars){ _eventDispStyle = PaintMethod.HeatMap; } else if(_eventDispStyle == PaintMethod.HeatMap) { _eventDispStyle = PaintMethod.Bars; } if(_eventDispButton.getIcon() == _toggleIcon) { _eventDispButton.setIcon(_toggleIconInverted); } else { _eventDispButton.setIcon(_toggleIcon); } CalendarGui.this.getEvent().setPaintMethod(_eventDispStyle); repaint(); } } } private class TimeFindListener implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { if(_slotGroup != null && !_slotGroup.getCalendars().isEmpty() && !(_slotGroup.getCalendars().size() ==1 && _slotGroup.userHasSubmitted())) new SliderPane(_numHours, CalendarGui.this); } } private class RefreshListener implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { URL url=null; try { url = new URL("http://www.google.com"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (Communicator.webConnected(url)) { _refreshButton.setIcon(_refreshIconInverted); _communicator.refresh(); // Retrieve this when2meet in case it has changed if(_slotGroup != null){ setEvent(_communicator.getEvent(""+_slotGroup.getID())); System.out.println("After setting event in GUI"); _slotGroup.printUpdates(); System.out.println("====="); } setUserCal(_communicator.getUserCal()); _userCalPanel.initLabels(); _refreshButton.setIcon(_refreshIcon); repaint(); } else { ImageIcon grey = new ImageIcon("small_logo_button.png"); JOptionPane.showMessageDialog(null, "You are not connected to the Internet.\nKairos cannot import current data.", "Connection Error", JOptionPane.ERROR_MESSAGE, grey); } } } }
false
true
public void buildFrame(){ _frame = new JFrame("Kairos"); _frame.addWindowListener(new InnerWindowListener()); JPanel calPanel = new JPanel(); GroupLayout calLayout = new GroupLayout(calPanel); calPanel.setLayout(calLayout); // TODO change to false _frame.setResizable(true); calLayout.setHorizontalGroup( calLayout.createSequentialGroup() // .addComponent(_hourOfDayLabels, GroupLayout.PREFERRED_SIZE, _hourOfDayLabels.getPreferredSize().width, // GroupLayout.PREFERRED_SIZE) .addComponent(_replyPanel, GroupLayout.PREFERRED_SIZE, (int) (FRAME_WIDTH*.75), GroupLayout.PREFERRED_SIZE)); calLayout.setVerticalGroup( calLayout.createParallelGroup(GroupLayout.Alignment.TRAILING) .addComponent(_replyPanel, GroupLayout.PREFERRED_SIZE, FRAME_HEIGHT - _replyPanel.getPreferredSize().height, GroupLayout.PREFERRED_SIZE) // .addComponent(_hourOfDayLabels, GroupLayout.PREFERRED_SIZE, FRAME_HEIGHT - _replyPanel.getPreferredSize().height - _replyPanel.getWeekDayPanelHeight(), // GroupLayout.PREFERRED_SIZE) ); _frame.add(calPanel, BorderLayout.CENTER); JPanel submitPanel = new JPanel(); submitPanel.add(_submitButton); JPanel timeFindPanel = new JPanel(); timeFindPanel.add(_timeFindButton); JPanel prevPanel = new JPanel(); prevPanel.add(_prevButton); prevPanel.add(_nextButton); JPanel dispStylePanel = new JPanel(); dispStylePanel.add(_eventDispButton); JPanel refreshPanel = new JPanel(); refreshPanel.add(_refreshButton); JPanel buttonPanel = new JPanel(new GridLayout(1, 0)); buttonPanel.add(prevPanel); // buttonPanel.add(nextPanel); buttonPanel.add(dispStylePanel); buttonPanel.add(submitPanel); buttonPanel.add(timeFindPanel); buttonPanel.add(refreshPanel); // buttonPanel.add( picLabel ); //JPanel northPanel = new JPanel(new GridLayout(2,1)); //northPanel.add(buttonPanel); //northPanel.add(_friendBar); _frame.add(buttonPanel, BorderLayout.NORTH); JPanel westPanel = new JPanel(new GridLayout(0, 1)); westPanel.add(_friendBar); _friendBar.mySetSize(new Dimension((int) ((FRAME_WIDTH*.25*.25)), 400)); _frame.add(westPanel, BorderLayout.WEST); JPanel eastPanel = new JPanel(new GridLayout(0,1)); eastPanel.add(_userCalPanel); eastPanel.add(_eventPanel); eastPanel.add(_updatesPanel); eastPanel.setPreferredSize(new Dimension((int) ((FRAME_WIDTH*.25)*.60), 700)); _frame.add(eastPanel, BorderLayout.EAST); _frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //_frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); _frame.pack(); _frame.setVisible(true); }
public void buildFrame(){ _frame = new JFrame("Kairos"); _frame.addWindowListener(new InnerWindowListener()); JPanel calPanel = new JPanel(); GroupLayout calLayout = new GroupLayout(calPanel); calPanel.setLayout(calLayout); // TODO change to false _frame.setResizable(true); calLayout.setHorizontalGroup( calLayout.createSequentialGroup() // .addComponent(_hourOfDayLabels, GroupLayout.PREFERRED_SIZE, _hourOfDayLabels.getPreferredSize().width, // GroupLayout.PREFERRED_SIZE) .addComponent(_replyPanel, GroupLayout.PREFERRED_SIZE, (int) (FRAME_WIDTH*.70), GroupLayout.PREFERRED_SIZE)); calLayout.setVerticalGroup( calLayout.createParallelGroup(GroupLayout.Alignment.TRAILING) .addComponent(_replyPanel, GroupLayout.PREFERRED_SIZE, FRAME_HEIGHT - _replyPanel.getPreferredSize().height + 15, GroupLayout.PREFERRED_SIZE) // .addComponent(_hourOfDayLabels, GroupLayout.PREFERRED_SIZE, FRAME_HEIGHT - _replyPanel.getPreferredSize().height - _replyPanel.getWeekDayPanelHeight(), // GroupLayout.PREFERRED_SIZE) ); _frame.add(calPanel, BorderLayout.CENTER); JPanel submitPanel = new JPanel(); submitPanel.add(_submitButton); JPanel timeFindPanel = new JPanel(); timeFindPanel.add(_timeFindButton); JPanel prevPanel = new JPanel(); prevPanel.add(_prevButton); prevPanel.add(_nextButton); JPanel dispStylePanel = new JPanel(); dispStylePanel.add(_eventDispButton); JPanel refreshPanel = new JPanel(); refreshPanel.add(_refreshButton); JPanel buttonPanel = new JPanel(new GridLayout(1, 0)); buttonPanel.add(prevPanel); // buttonPanel.add(nextPanel); buttonPanel.add(dispStylePanel); buttonPanel.add(submitPanel); buttonPanel.add(timeFindPanel); buttonPanel.add(refreshPanel); // buttonPanel.add( picLabel ); //JPanel northPanel = new JPanel(new GridLayout(2,1)); //northPanel.add(buttonPanel); //northPanel.add(_friendBar); _frame.add(buttonPanel, BorderLayout.NORTH); JPanel westPanel = new JPanel(new GridLayout(0, 1)); westPanel.add(_friendBar); westPanel.setPreferredSize(new Dimension((int) ((FRAME_WIDTH*.25*.40)), 400)); _friendBar.mySetSize(new Dimension((int) ((FRAME_WIDTH*.25*.40)), 400)); _frame.add(westPanel, BorderLayout.WEST); JPanel eastPanel = new JPanel(new GridLayout(0,1)); eastPanel.add(_userCalPanel); eastPanel.add(_eventPanel); eastPanel.add(_updatesPanel); eastPanel.setPreferredSize(new Dimension((int) ((FRAME_WIDTH*.25)*.60), 700)); _frame.add(eastPanel, BorderLayout.EAST); _frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //_frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); _frame.pack(); _frame.setVisible(true); }
diff --git a/msv/src/com/sun/msv/driver/textui/Driver.java b/msv/src/com/sun/msv/driver/textui/Driver.java index bdc2a249..d487a2bd 100644 --- a/msv/src/com/sun/msv/driver/textui/Driver.java +++ b/msv/src/com/sun/msv/driver/textui/Driver.java @@ -1,402 +1,403 @@ /* * @(#)$Id$ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.driver.textui; import javax.xml.parsers.*; import com.sun.msv.grammar.xmlschema.*; import com.sun.msv.grammar.trex.*; import com.sun.msv.grammar.relax.*; import com.sun.msv.grammar.*; import com.sun.msv.grammar.util.ExpressionPrinter; import com.sun.msv.reader.util.GrammarLoader; import com.sun.msv.relaxns.grammar.RELAXGrammar; import com.sun.msv.relaxns.verifier.SchemaProviderImpl; import com.sun.msv.verifier.*; import com.sun.msv.verifier.identity.IDConstraintChecker; import com.sun.msv.verifier.regexp.REDocumentDeclaration; import com.sun.msv.verifier.util.ErrorHandlerImpl; import com.sun.msv.util.Util; import com.sun.resolver.tools.CatalogResolver; import org.iso_relax.dispatcher.Dispatcher; import org.iso_relax.dispatcher.SchemaProvider; import org.iso_relax.dispatcher.impl.DispatcherImpl; import org.xml.sax.*; import java.util.*; /** * command line Verifier. * * @author <a href="mailto:[email protected]">Kohsuke KAWAGUCHI</a> */ public class Driver { static SAXParserFactory factory; public static void main( String[] args ) throws Exception { final Vector fileNames = new Vector(); String grammarName = null; boolean dump=false; boolean verbose = false; boolean warning = false; boolean standalone=false; boolean strict=false; EntityResolver entityResolver=null; if( args.length==0 ) { System.out.println( localize(MSG_USAGE) ); return; } for( int i=0; i<args.length; i++ ) { if( args[i].equalsIgnoreCase("-strict") ) strict = true; else if( args[i].equalsIgnoreCase("-standalone") ) standalone = true; else if( args[i].equalsIgnoreCase("-loose") ) standalone = true; // backward compatible name else if( args[i].equalsIgnoreCase("-dtd") ) ; // this option is ignored. else if( args[i].equalsIgnoreCase("-dump") ) dump = true; else if( args[i].equalsIgnoreCase("-debug") ) Debug.debug = true; else if( args[i].equalsIgnoreCase("-xerces") ) factory = (SAXParserFactory)Class.forName("org.apache.xerces.jaxp.SAXParserFactoryImpl").newInstance(); else if( args[i].equalsIgnoreCase("-crimson") ) factory = (SAXParserFactory)Class.forName("org.apache.crimson.jaxp.SAXParserFactoryImpl").newInstance(); else if( args[i].equalsIgnoreCase("-oraclev2") ) factory = (SAXParserFactory)Class.forName("oracle.xml.jaxp.JXSAXParserFactory").newInstance(); else if( args[i].equalsIgnoreCase("-verbose") ) verbose = true; else if( args[i].equalsIgnoreCase("-warning") ) warning = true; else if( args[i].equalsIgnoreCase("-locale") ) { String code = args[++i]; int idx = code.indexOf('-'); if(idx<0) idx = code.indexOf('_'); if(idx<0) Locale.setDefault( new Locale(code,"") ); else Locale.setDefault( new Locale( code.substring(0,idx), code.substring(idx+1) )); } else if( args[i].equalsIgnoreCase("-catalog") ) { // use Sun's "XML Entity and URI Resolvers" by Norman Walsh // to resolve external entities. // http://www.sun.com/xml/developers/resolver/ if(entityResolver!=null) entityResolver = new CatalogResolver(true); ((CatalogResolver)entityResolver).getCatalog().parseCatalog(args[++i]); } else if( args[i].equalsIgnoreCase("-version") ) { System.out.println("Multi Schema Validator Ver."+ java.util.ResourceBundle.getBundle("version").getString("version") ); return; } else { if( args[i].charAt(0)=='-' ) { System.err.println(localize(MSG_UNRECOGNIZED_OPTION,args[i])); return; } if( grammarName==null ) grammarName = args[i]; else { fileNames.add(args[i]); } } } if( factory==null ) factory = SAXParserFactory.newInstance(); if( verbose ) System.out.println( localize( MSG_PARSER, factory.getClass().getName()) ); factory.setNamespaceAware(true); factory.setValidating(false); if( !standalone && verbose ) System.out.println( localize( MSG_DTDVALIDATION ) ); if( standalone ) try { factory.setFeature("http://xml.org/sax/features/validation",false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false); } catch(Exception e) { // e.printStackTrace(); System.out.println( localize( MSG_FAILED_TO_IGNORE_EXTERNAL_DTD ) ); } else try { factory.setFeature("http://apache.org/xml/features/validation/dynamic",true); } catch( Exception e ) { ; } // parse schema //-------------------- final long stime = System.currentTimeMillis(); System.out.println( localize(MSG_START_PARSING_GRAMMAR) ); Grammar grammar=null; try { GrammarLoader loader = new GrammarLoader(); // set various parameters loader.setController( new DebugController(warning,false,entityResolver) ); loader.setSAXParserFactory(factory); loader.setStrictCheck(strict); grammar = loader.parse(grammarName); } catch(SAXParseException spe) { -// spe.getException().printStackTrace(); + if(Debug.debug) + spe.getException().printStackTrace(); ; // this error is already reported. } catch(SAXException se ) { if( se.getException()!=null ) throw se.getException(); throw se; } if( grammar==null ) { System.out.println( localize(ERR_LOAD_GRAMMAR) ); return; } long parsingTime = System.currentTimeMillis(); if( verbose ) System.out.println( localize( MSG_PARSING_TIME, new Long(parsingTime-stime) ) ); if(dump) { if( grammar instanceof RELAXModule ) dumpRELAXModule( (RELAXModule)grammar ); else if( grammar instanceof RELAXGrammar ) dumpRELAXGrammar( (RELAXGrammar)grammar ); else if( grammar instanceof TREXGrammar ) dumpTREX( (TREXGrammar)grammar ); else if( grammar instanceof XMLSchemaGrammar ) dumpXMLSchema( (XMLSchemaGrammar)grammar ); return; } // validate documents //-------------------- DocumentVerifier verifier; if( grammar instanceof RELAXGrammar ) // use divide&validate framework to validate document verifier = new RELAXNSVerifier( new SchemaProviderImpl((RELAXGrammar)grammar) ); else if( grammar instanceof XMLSchemaGrammar ) // use verifier+identity constraint checker. verifier = new XMLSchemaVerifier( (XMLSchemaGrammar)grammar ); else // validate normally by using Verifier. verifier = new SimpleVerifier( new REDocumentDeclaration(grammar) ); for( int i=0; i<fileNames.size(); i++ ) { final String instName = (String)fileNames.elementAt(i); System.out.println( localize( MSG_VALIDATING, instName) ); boolean result=false; try { XMLReader reader = factory.newSAXParser().getXMLReader(); if(entityResolver!=null) reader.setEntityResolver(entityResolver); reader.setErrorHandler( new ReportErrorHandler() ); result = verifier.verify( reader, Util.getInputSource(instName)); } catch( com.sun.msv.verifier.ValidationUnrecoverableException vv ) { System.out.println(localize(MSG_BAILOUT)); } catch( SAXParseException se ) { ; // error is already reported by ErrorHandler } catch( SAXException e ) { e.getException().printStackTrace(); } if(result) System.out.println(localize(MSG_VALID)); else System.out.println(localize(MSG_INVALID)); if( i!=fileNames.size()-1 ) System.out.println("--------------------------------------"); } if( verbose ) System.out.println( localize( MSG_VALIDATION_TIME, new Long(System.currentTimeMillis()-parsingTime) ) ); } public static void dumpTREX( TREXGrammar g ) throws Exception { System.out.println("*** start ***"); System.out.println(ExpressionPrinter.printFragment(g.start)); System.out.println("*** others ***"); System.out.print( ExpressionPrinter.fragmentInstance.printRefContainer( g.namedPatterns ) ); } public static void dumpXMLSchema( XMLSchemaGrammar g ) throws Exception { System.out.println("*** top level ***"); System.out.println(ExpressionPrinter.printFragment(g.topLevel)); Iterator itr = g.iterateSchemas(); while(itr.hasNext()) { XMLSchemaSchema s = (XMLSchemaSchema)itr.next(); dumpXMLSchema(s); } } public static void dumpXMLSchema( XMLSchemaSchema s ) throws Exception { System.out.println("\n $$$$$$[ " + s.targetNamespace + " ]$$$$$$"); System.out.println("*** elementDecls ***"); ReferenceExp[] es = s.elementDecls.getAll(); for( int i=0; i<es.length; i++ ) { ElementDeclExp exp = (ElementDeclExp)es[i]; System.out.println( exp.name + " : " + ExpressionPrinter.printContentModel(exp.body.contentModel) ); } System.out.println("*** complex types ***"); System.out.print( ExpressionPrinter.contentModelInstance.printRefContainer( s.complexTypes ) ); } public static void dumpRELAXModule( RELAXModule m ) throws Exception { System.out.println("*** top level ***"); System.out.println(ExpressionPrinter.printFragment(m.topLevel)); System.out.println("\n $$$$$$[ " + m.targetNamespace + " ]$$$$$$"); System.out.println("*** elementRule ***"); System.out.print( ExpressionPrinter.fragmentInstance.printRefContainer( m.elementRules ) ); System.out.println("*** hedgeRule ***"); System.out.print( ExpressionPrinter.fragmentInstance.printRefContainer( m.hedgeRules ) ); System.out.println("*** attPool ***"); System.out.print( ExpressionPrinter.fragmentInstance.printRefContainer( m.attPools ) ); System.out.println("*** tag ***"); System.out.print( ExpressionPrinter.fragmentInstance.printRefContainer( m.tags ) ); } public static void dumpRELAXGrammar( RELAXGrammar m ) throws Exception { System.out.println("operation is not implemented yet."); } /** acts as a function closure to validate a document. */ private interface DocumentVerifier { boolean verify( XMLReader p, InputSource instance ) throws Exception; } /** validates a document by using divide &amp; validate framework. */ private static class RELAXNSVerifier implements DocumentVerifier { private final SchemaProvider sp; RELAXNSVerifier( SchemaProvider sp ) { this.sp=sp; } public boolean verify( XMLReader p, InputSource instance ) throws Exception { Dispatcher dispatcher = new DispatcherImpl(sp); dispatcher.attachXMLReader(p); ReportErrorHandler errorHandler = new ReportErrorHandler(); dispatcher.setErrorHandler( errorHandler ); p.parse(instance); return !errorHandler.hadError; } } private static class SimpleVerifier implements DocumentVerifier { private final DocumentDeclaration docDecl; SimpleVerifier( DocumentDeclaration docDecl ) { this.docDecl = docDecl; } public boolean verify( XMLReader p, InputSource instance ) throws Exception { ReportErrorHandler reh = new ReportErrorHandler(); Verifier v = new Verifier( docDecl, reh ); p.setDTDHandler(v); p.setContentHandler(v); p.setErrorHandler(reh); p.parse( instance ); return v.isValid(); } } private static class XMLSchemaVerifier implements DocumentVerifier { private final XMLSchemaGrammar grammar; XMLSchemaVerifier( XMLSchemaGrammar grammar ) { this.grammar = grammar; } public boolean verify( XMLReader p, InputSource instance ) throws Exception { ReportErrorHandler reh = new ReportErrorHandler(); Verifier v = new IDConstraintChecker( grammar, reh ); p.setDTDHandler(v); p.setContentHandler(v); p.setErrorHandler(reh); p.parse( instance ); return v.isValid(); } } public static String localize( String propertyName, Object[] args ) { String format = java.util.ResourceBundle.getBundle( "com.sun.msv.driver.textui.Messages").getString(propertyName); return java.text.MessageFormat.format(format, args ); } public static String localize( String prop ) { return localize(prop,null); } public static String localize( String prop, Object arg1 ) { return localize(prop,new Object[]{arg1}); } public static String localize( String prop, Object arg1, Object arg2 ) { return localize(prop,new Object[]{arg1,arg2}); } public static final String MSG_DTDVALIDATION = "Driver.DTDValidation"; public static final String MSG_PARSER = "Driver.Parser"; public static final String MSG_USAGE = "Driver.Usage"; public static final String MSG_UNRECOGNIZED_OPTION ="Driver.UnrecognizedOption"; public static final String MSG_START_PARSING_GRAMMAR="Driver.StartParsingGrammar"; public static final String MSG_PARSING_TIME = "Driver.ParsingTime"; public static final String MSG_VALIDATING = "Driver.Validating"; public static final String MSG_VALIDATION_TIME = "Driver.ValidationTime"; public static final String MSG_VALID = "Driver.Valid"; public static final String MSG_INVALID = "Driver.Invalid"; public static final String ERR_LOAD_GRAMMAR = "Driver.ErrLoadGrammar"; public static final String MSG_BAILOUT = "Driver.BailOut"; public static final String MSG_FAILED_TO_IGNORE_EXTERNAL_DTD ="Driver.FailedToIgnoreExternalDTD"; public static final String MSG_WARNING_FOUND = "Driver.WarningFound"; }
true
true
public static void main( String[] args ) throws Exception { final Vector fileNames = new Vector(); String grammarName = null; boolean dump=false; boolean verbose = false; boolean warning = false; boolean standalone=false; boolean strict=false; EntityResolver entityResolver=null; if( args.length==0 ) { System.out.println( localize(MSG_USAGE) ); return; } for( int i=0; i<args.length; i++ ) { if( args[i].equalsIgnoreCase("-strict") ) strict = true; else if( args[i].equalsIgnoreCase("-standalone") ) standalone = true; else if( args[i].equalsIgnoreCase("-loose") ) standalone = true; // backward compatible name else if( args[i].equalsIgnoreCase("-dtd") ) ; // this option is ignored. else if( args[i].equalsIgnoreCase("-dump") ) dump = true; else if( args[i].equalsIgnoreCase("-debug") ) Debug.debug = true; else if( args[i].equalsIgnoreCase("-xerces") ) factory = (SAXParserFactory)Class.forName("org.apache.xerces.jaxp.SAXParserFactoryImpl").newInstance(); else if( args[i].equalsIgnoreCase("-crimson") ) factory = (SAXParserFactory)Class.forName("org.apache.crimson.jaxp.SAXParserFactoryImpl").newInstance(); else if( args[i].equalsIgnoreCase("-oraclev2") ) factory = (SAXParserFactory)Class.forName("oracle.xml.jaxp.JXSAXParserFactory").newInstance(); else if( args[i].equalsIgnoreCase("-verbose") ) verbose = true; else if( args[i].equalsIgnoreCase("-warning") ) warning = true; else if( args[i].equalsIgnoreCase("-locale") ) { String code = args[++i]; int idx = code.indexOf('-'); if(idx<0) idx = code.indexOf('_'); if(idx<0) Locale.setDefault( new Locale(code,"") ); else Locale.setDefault( new Locale( code.substring(0,idx), code.substring(idx+1) )); } else if( args[i].equalsIgnoreCase("-catalog") ) { // use Sun's "XML Entity and URI Resolvers" by Norman Walsh // to resolve external entities. // http://www.sun.com/xml/developers/resolver/ if(entityResolver!=null) entityResolver = new CatalogResolver(true); ((CatalogResolver)entityResolver).getCatalog().parseCatalog(args[++i]); } else if( args[i].equalsIgnoreCase("-version") ) { System.out.println("Multi Schema Validator Ver."+ java.util.ResourceBundle.getBundle("version").getString("version") ); return; } else { if( args[i].charAt(0)=='-' ) { System.err.println(localize(MSG_UNRECOGNIZED_OPTION,args[i])); return; } if( grammarName==null ) grammarName = args[i]; else { fileNames.add(args[i]); } } } if( factory==null ) factory = SAXParserFactory.newInstance(); if( verbose ) System.out.println( localize( MSG_PARSER, factory.getClass().getName()) ); factory.setNamespaceAware(true); factory.setValidating(false); if( !standalone && verbose ) System.out.println( localize( MSG_DTDVALIDATION ) ); if( standalone ) try { factory.setFeature("http://xml.org/sax/features/validation",false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false); } catch(Exception e) { // e.printStackTrace(); System.out.println( localize( MSG_FAILED_TO_IGNORE_EXTERNAL_DTD ) ); } else try { factory.setFeature("http://apache.org/xml/features/validation/dynamic",true); } catch( Exception e ) { ; } // parse schema //-------------------- final long stime = System.currentTimeMillis(); System.out.println( localize(MSG_START_PARSING_GRAMMAR) ); Grammar grammar=null; try { GrammarLoader loader = new GrammarLoader(); // set various parameters loader.setController( new DebugController(warning,false,entityResolver) ); loader.setSAXParserFactory(factory); loader.setStrictCheck(strict); grammar = loader.parse(grammarName); } catch(SAXParseException spe) { // spe.getException().printStackTrace(); ; // this error is already reported. } catch(SAXException se ) { if( se.getException()!=null ) throw se.getException(); throw se; } if( grammar==null ) { System.out.println( localize(ERR_LOAD_GRAMMAR) ); return; } long parsingTime = System.currentTimeMillis(); if( verbose ) System.out.println( localize( MSG_PARSING_TIME, new Long(parsingTime-stime) ) ); if(dump) { if( grammar instanceof RELAXModule ) dumpRELAXModule( (RELAXModule)grammar ); else if( grammar instanceof RELAXGrammar ) dumpRELAXGrammar( (RELAXGrammar)grammar ); else if( grammar instanceof TREXGrammar ) dumpTREX( (TREXGrammar)grammar ); else if( grammar instanceof XMLSchemaGrammar ) dumpXMLSchema( (XMLSchemaGrammar)grammar ); return; } // validate documents //-------------------- DocumentVerifier verifier; if( grammar instanceof RELAXGrammar ) // use divide&validate framework to validate document verifier = new RELAXNSVerifier( new SchemaProviderImpl((RELAXGrammar)grammar) ); else if( grammar instanceof XMLSchemaGrammar ) // use verifier+identity constraint checker. verifier = new XMLSchemaVerifier( (XMLSchemaGrammar)grammar ); else // validate normally by using Verifier. verifier = new SimpleVerifier( new REDocumentDeclaration(grammar) ); for( int i=0; i<fileNames.size(); i++ ) { final String instName = (String)fileNames.elementAt(i); System.out.println( localize( MSG_VALIDATING, instName) ); boolean result=false; try { XMLReader reader = factory.newSAXParser().getXMLReader(); if(entityResolver!=null) reader.setEntityResolver(entityResolver); reader.setErrorHandler( new ReportErrorHandler() ); result = verifier.verify( reader, Util.getInputSource(instName)); } catch( com.sun.msv.verifier.ValidationUnrecoverableException vv ) { System.out.println(localize(MSG_BAILOUT)); } catch( SAXParseException se ) { ; // error is already reported by ErrorHandler } catch( SAXException e ) { e.getException().printStackTrace(); } if(result) System.out.println(localize(MSG_VALID)); else System.out.println(localize(MSG_INVALID)); if( i!=fileNames.size()-1 ) System.out.println("--------------------------------------"); } if( verbose ) System.out.println( localize( MSG_VALIDATION_TIME, new Long(System.currentTimeMillis()-parsingTime) ) ); }
public static void main( String[] args ) throws Exception { final Vector fileNames = new Vector(); String grammarName = null; boolean dump=false; boolean verbose = false; boolean warning = false; boolean standalone=false; boolean strict=false; EntityResolver entityResolver=null; if( args.length==0 ) { System.out.println( localize(MSG_USAGE) ); return; } for( int i=0; i<args.length; i++ ) { if( args[i].equalsIgnoreCase("-strict") ) strict = true; else if( args[i].equalsIgnoreCase("-standalone") ) standalone = true; else if( args[i].equalsIgnoreCase("-loose") ) standalone = true; // backward compatible name else if( args[i].equalsIgnoreCase("-dtd") ) ; // this option is ignored. else if( args[i].equalsIgnoreCase("-dump") ) dump = true; else if( args[i].equalsIgnoreCase("-debug") ) Debug.debug = true; else if( args[i].equalsIgnoreCase("-xerces") ) factory = (SAXParserFactory)Class.forName("org.apache.xerces.jaxp.SAXParserFactoryImpl").newInstance(); else if( args[i].equalsIgnoreCase("-crimson") ) factory = (SAXParserFactory)Class.forName("org.apache.crimson.jaxp.SAXParserFactoryImpl").newInstance(); else if( args[i].equalsIgnoreCase("-oraclev2") ) factory = (SAXParserFactory)Class.forName("oracle.xml.jaxp.JXSAXParserFactory").newInstance(); else if( args[i].equalsIgnoreCase("-verbose") ) verbose = true; else if( args[i].equalsIgnoreCase("-warning") ) warning = true; else if( args[i].equalsIgnoreCase("-locale") ) { String code = args[++i]; int idx = code.indexOf('-'); if(idx<0) idx = code.indexOf('_'); if(idx<0) Locale.setDefault( new Locale(code,"") ); else Locale.setDefault( new Locale( code.substring(0,idx), code.substring(idx+1) )); } else if( args[i].equalsIgnoreCase("-catalog") ) { // use Sun's "XML Entity and URI Resolvers" by Norman Walsh // to resolve external entities. // http://www.sun.com/xml/developers/resolver/ if(entityResolver!=null) entityResolver = new CatalogResolver(true); ((CatalogResolver)entityResolver).getCatalog().parseCatalog(args[++i]); } else if( args[i].equalsIgnoreCase("-version") ) { System.out.println("Multi Schema Validator Ver."+ java.util.ResourceBundle.getBundle("version").getString("version") ); return; } else { if( args[i].charAt(0)=='-' ) { System.err.println(localize(MSG_UNRECOGNIZED_OPTION,args[i])); return; } if( grammarName==null ) grammarName = args[i]; else { fileNames.add(args[i]); } } } if( factory==null ) factory = SAXParserFactory.newInstance(); if( verbose ) System.out.println( localize( MSG_PARSER, factory.getClass().getName()) ); factory.setNamespaceAware(true); factory.setValidating(false); if( !standalone && verbose ) System.out.println( localize( MSG_DTDVALIDATION ) ); if( standalone ) try { factory.setFeature("http://xml.org/sax/features/validation",false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false); } catch(Exception e) { // e.printStackTrace(); System.out.println( localize( MSG_FAILED_TO_IGNORE_EXTERNAL_DTD ) ); } else try { factory.setFeature("http://apache.org/xml/features/validation/dynamic",true); } catch( Exception e ) { ; } // parse schema //-------------------- final long stime = System.currentTimeMillis(); System.out.println( localize(MSG_START_PARSING_GRAMMAR) ); Grammar grammar=null; try { GrammarLoader loader = new GrammarLoader(); // set various parameters loader.setController( new DebugController(warning,false,entityResolver) ); loader.setSAXParserFactory(factory); loader.setStrictCheck(strict); grammar = loader.parse(grammarName); } catch(SAXParseException spe) { if(Debug.debug) spe.getException().printStackTrace(); ; // this error is already reported. } catch(SAXException se ) { if( se.getException()!=null ) throw se.getException(); throw se; } if( grammar==null ) { System.out.println( localize(ERR_LOAD_GRAMMAR) ); return; } long parsingTime = System.currentTimeMillis(); if( verbose ) System.out.println( localize( MSG_PARSING_TIME, new Long(parsingTime-stime) ) ); if(dump) { if( grammar instanceof RELAXModule ) dumpRELAXModule( (RELAXModule)grammar ); else if( grammar instanceof RELAXGrammar ) dumpRELAXGrammar( (RELAXGrammar)grammar ); else if( grammar instanceof TREXGrammar ) dumpTREX( (TREXGrammar)grammar ); else if( grammar instanceof XMLSchemaGrammar ) dumpXMLSchema( (XMLSchemaGrammar)grammar ); return; } // validate documents //-------------------- DocumentVerifier verifier; if( grammar instanceof RELAXGrammar ) // use divide&validate framework to validate document verifier = new RELAXNSVerifier( new SchemaProviderImpl((RELAXGrammar)grammar) ); else if( grammar instanceof XMLSchemaGrammar ) // use verifier+identity constraint checker. verifier = new XMLSchemaVerifier( (XMLSchemaGrammar)grammar ); else // validate normally by using Verifier. verifier = new SimpleVerifier( new REDocumentDeclaration(grammar) ); for( int i=0; i<fileNames.size(); i++ ) { final String instName = (String)fileNames.elementAt(i); System.out.println( localize( MSG_VALIDATING, instName) ); boolean result=false; try { XMLReader reader = factory.newSAXParser().getXMLReader(); if(entityResolver!=null) reader.setEntityResolver(entityResolver); reader.setErrorHandler( new ReportErrorHandler() ); result = verifier.verify( reader, Util.getInputSource(instName)); } catch( com.sun.msv.verifier.ValidationUnrecoverableException vv ) { System.out.println(localize(MSG_BAILOUT)); } catch( SAXParseException se ) { ; // error is already reported by ErrorHandler } catch( SAXException e ) { e.getException().printStackTrace(); } if(result) System.out.println(localize(MSG_VALID)); else System.out.println(localize(MSG_INVALID)); if( i!=fileNames.size()-1 ) System.out.println("--------------------------------------"); } if( verbose ) System.out.println( localize( MSG_VALIDATION_TIME, new Long(System.currentTimeMillis()-parsingTime) ) ); }
diff --git a/ant-tasks/src/net/java/jsip/ant/tasks/VersionerTask.java b/ant-tasks/src/net/java/jsip/ant/tasks/VersionerTask.java index 28b5e854..c5704c9d 100644 --- a/ant-tasks/src/net/java/jsip/ant/tasks/VersionerTask.java +++ b/ant-tasks/src/net/java/jsip/ant/tasks/VersionerTask.java @@ -1,271 +1,271 @@ package net.java.jsip.ant.tasks; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Date; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.jdom.output.XMLOutputter; /** * * @author [email protected] * */ public class VersionerTask extends Task { protected File cvsVersionFile = null; protected int version = -1; protected File pomFile = null; protected File toVersion = null; protected boolean incrementCVSVersion = false; protected boolean parent = false; protected int mainVersionParts = 3; private boolean doPom = false; private boolean doToVersion = false; private String timeStampFileName = "TIMESTAMP"; private String antprops = "ant-version.properties"; public void setMainVersionParts(int mainVersionParts) { this.mainVersionParts = mainVersionParts; } public void setParent(boolean parent) { this.parent = parent; } public void setCvsVersionFile(File cvsVersionFile) { this.cvsVersionFile = cvsVersionFile; } public void setVersion(int version) { this.version = version; } public void setPomFile(File pomFile) { this.pomFile = pomFile; } public void setToVersion(File toVersion) { this.toVersion = toVersion; } public void setIncrementCVSVersion(boolean incrementCVSVersion) { this.incrementCVSVersion = incrementCVSVersion; } @Override public void execute() throws BuildException { if (this.cvsVersionFile == null && this.version < 0) { throw new BuildException( "Version file property file is not set and version property is not set - one of them must be used!!!"); } if (toVersion == null) { } else { doToVersion = true; } if(pomFile==null) {}else { doPom=true; } // Check cvsVersionFile if ( this.version < 0 && ( cvsVersionFile==null ||!cvsVersionFile.canRead())) { throw new BuildException("Cant read from " + cvsVersionFile + " - eiher set it or version property!!!"); } if (incrementCVSVersion && !cvsVersionFile.canWrite()) { throw new BuildException("Cant write to " + cvsVersionFile + "!!!"); } if ( doPom && (!pomFile.canRead() || !pomFile.canWrite())) { throw new BuildException("Cant read/write pom file " + cvsVersionFile + "!!!"); } if (doToVersion && !toVersion.canRead()) { throw new BuildException( "Cant read file that is going to be versioned " + cvsVersionFile + "!!!"); } super.execute(); int localVersion = -1; if (cvsVersionFile != null) { //ObjectInputStream ois = null; BufferedReader br=null; try { //ois = new ObjectInputStream(new FileInputStream(cvsVersionFile)); String versionValue=null; br=new BufferedReader(new FileReader(cvsVersionFile)); versionValue=br.readLine(); localVersion = Math.abs(Integer.valueOf(versionValue)); } catch (Exception e) { log("Failed to fetch version from file!!"); - throw new BuildException(e); + localVersion = this.version; } finally { if (br != null) try { br.close(); } catch (Exception e) { - throw new BuildException(e); + localVersion = this.version; } } if (incrementCVSVersion) { cvsVersionFile.delete(); try { cvsVersionFile.createNewFile(); //ObjectOutputStream oos = new ObjectOutputStream( // new FileOutputStream(cvsVersionFile)); //oos.writeUTF(""+localVersion + 1); BufferedWriter bw=new BufferedWriter(new FileWriter(cvsVersionFile)); bw.write(""+(localVersion + 1)); bw.flush(); bw.close(); File antPropertiesFile = new File( this.antprops); antPropertiesFile.createNewFile(); bw=new BufferedWriter(new FileWriter(antPropertiesFile)); bw.write("jain-sip-ri-jar=jain-sip-ri-1.2."+(localVersion + 1) + ".jar\n"); bw.write("jain-sip-sdp-jar=jain-sip-sdp-1.2."+(localVersion + 1) + ".jar\n"); bw.write("jain-sip-src-tar=jain-sip-src-1.2."+(localVersion + 1) + ".tar.gz\n"); bw.write("jain-sip-javadoc-tar=jain-sip-javadoc-1.2."+(localVersion + 1) + ".tar.gz\n"); bw.write("jain-sip-all-tar=jain-sip-1.2." +(localVersion + 1) + ".tar.gz\n"); bw.write("jain-sip-tck-jar=jain-sip-tck-1.2."+(localVersion + 1) + ".jar\n"); bw.write("sdp_jar=jain-sdp-1.0."+(localVersion + 1) + ".jar\n"); bw.write("sdp-src-jar=jain-sdp-src-1.0."+(localVersion + 1) + ".jar\n"); bw.write("jain-sip-src-jar=jain-sip-src-1.2." + +(localVersion + 1) + ".jar\n"); bw.write("jain-sip-sctp-jar=jain-sip-sctp-1.2."+(localVersion + 1) + ".jar\n"); bw.write("unit_test_jar=jain-sip-unit-test-1.2." + (localVersion+1) + ".jar\n"); bw.flush(); bw.close(); bw=new BufferedWriter(new FileWriter(this.timeStampFileName)); Date date = new Date ( System.currentTimeMillis()); bw.write(date.toString()); bw.close(); } catch (IOException e) { log("Failed to increment version in file. See stack trace:",e,0); e.printStackTrace(); } } } else { localVersion = this.version; } if(doPom) try { SAXBuilder saxb = new SAXBuilder(); Document doc = saxb.build(pomFile); Element root = doc.getRootElement(); // dont be supripsed - jdom and other work weird - // Element.getChild(Element.getName)==null even though child element // exists... if (parent) { for (Object o : root.getChildren()) { Element current = (Element) o; if (current.getName().equals("parent")) { doVersionChange(current, localVersion); } else { continue; } break; } } else { doVersionChange(root, localVersion); } XMLOutputter outputter = new XMLOutputter(); outputter.output(doc, new FileOutputStream(pomFile)); } catch (Exception e) { throw new BuildException(e); } try{ if(doToVersion) { String name=toVersion.toString(); name=name.substring(0, name.lastIndexOf("."))+localVersion+name.substring( name.lastIndexOf(".")); File outputFile=new File(name); toVersion.renameTo(outputFile); } }catch(Exception e) { log("Failed to rename file!!",e,0); } } private void doVersionChange(Element root, int ver) { log("Doing version injection - version parts:"+this.mainVersionParts); for (Object o : root.getChildren()) { Element current = (Element) o; if (current.getName().equals("version")) { String[] currentVersion = current.getText().split("\\."); log("Version from file:"+current.getText()); String nextV = ""; for (int i = 0; i < currentVersion.length && i < this.mainVersionParts; i++) { nextV = nextV + currentVersion[i] + "."; } nextV = nextV + ver; log("Resulting version:"+nextV); current.setText(nextV); } else { continue; } break; } } @Override public void init() throws BuildException { super.init(); } }
false
true
public void execute() throws BuildException { if (this.cvsVersionFile == null && this.version < 0) { throw new BuildException( "Version file property file is not set and version property is not set - one of them must be used!!!"); } if (toVersion == null) { } else { doToVersion = true; } if(pomFile==null) {}else { doPom=true; } // Check cvsVersionFile if ( this.version < 0 && ( cvsVersionFile==null ||!cvsVersionFile.canRead())) { throw new BuildException("Cant read from " + cvsVersionFile + " - eiher set it or version property!!!"); } if (incrementCVSVersion && !cvsVersionFile.canWrite()) { throw new BuildException("Cant write to " + cvsVersionFile + "!!!"); } if ( doPom && (!pomFile.canRead() || !pomFile.canWrite())) { throw new BuildException("Cant read/write pom file " + cvsVersionFile + "!!!"); } if (doToVersion && !toVersion.canRead()) { throw new BuildException( "Cant read file that is going to be versioned " + cvsVersionFile + "!!!"); } super.execute(); int localVersion = -1; if (cvsVersionFile != null) { //ObjectInputStream ois = null; BufferedReader br=null; try { //ois = new ObjectInputStream(new FileInputStream(cvsVersionFile)); String versionValue=null; br=new BufferedReader(new FileReader(cvsVersionFile)); versionValue=br.readLine(); localVersion = Math.abs(Integer.valueOf(versionValue)); } catch (Exception e) { log("Failed to fetch version from file!!"); throw new BuildException(e); } finally { if (br != null) try { br.close(); } catch (Exception e) { throw new BuildException(e); } } if (incrementCVSVersion) { cvsVersionFile.delete(); try { cvsVersionFile.createNewFile(); //ObjectOutputStream oos = new ObjectOutputStream( // new FileOutputStream(cvsVersionFile)); //oos.writeUTF(""+localVersion + 1); BufferedWriter bw=new BufferedWriter(new FileWriter(cvsVersionFile)); bw.write(""+(localVersion + 1)); bw.flush(); bw.close(); File antPropertiesFile = new File( this.antprops); antPropertiesFile.createNewFile(); bw=new BufferedWriter(new FileWriter(antPropertiesFile)); bw.write("jain-sip-ri-jar=jain-sip-ri-1.2."+(localVersion + 1) + ".jar\n"); bw.write("jain-sip-sdp-jar=jain-sip-sdp-1.2."+(localVersion + 1) + ".jar\n"); bw.write("jain-sip-src-tar=jain-sip-src-1.2."+(localVersion + 1) + ".tar.gz\n"); bw.write("jain-sip-javadoc-tar=jain-sip-javadoc-1.2."+(localVersion + 1) + ".tar.gz\n"); bw.write("jain-sip-all-tar=jain-sip-1.2." +(localVersion + 1) + ".tar.gz\n"); bw.write("jain-sip-tck-jar=jain-sip-tck-1.2."+(localVersion + 1) + ".jar\n"); bw.write("sdp_jar=jain-sdp-1.0."+(localVersion + 1) + ".jar\n"); bw.write("sdp-src-jar=jain-sdp-src-1.0."+(localVersion + 1) + ".jar\n"); bw.write("jain-sip-src-jar=jain-sip-src-1.2." + +(localVersion + 1) + ".jar\n"); bw.write("jain-sip-sctp-jar=jain-sip-sctp-1.2."+(localVersion + 1) + ".jar\n"); bw.write("unit_test_jar=jain-sip-unit-test-1.2." + (localVersion+1) + ".jar\n"); bw.flush(); bw.close(); bw=new BufferedWriter(new FileWriter(this.timeStampFileName)); Date date = new Date ( System.currentTimeMillis()); bw.write(date.toString()); bw.close(); } catch (IOException e) { log("Failed to increment version in file. See stack trace:",e,0); e.printStackTrace(); } } } else { localVersion = this.version; } if(doPom) try { SAXBuilder saxb = new SAXBuilder(); Document doc = saxb.build(pomFile); Element root = doc.getRootElement(); // dont be supripsed - jdom and other work weird - // Element.getChild(Element.getName)==null even though child element // exists... if (parent) { for (Object o : root.getChildren()) { Element current = (Element) o; if (current.getName().equals("parent")) { doVersionChange(current, localVersion); } else { continue; } break; } } else { doVersionChange(root, localVersion); } XMLOutputter outputter = new XMLOutputter(); outputter.output(doc, new FileOutputStream(pomFile)); } catch (Exception e) { throw new BuildException(e); } try{ if(doToVersion) { String name=toVersion.toString(); name=name.substring(0, name.lastIndexOf("."))+localVersion+name.substring( name.lastIndexOf(".")); File outputFile=new File(name); toVersion.renameTo(outputFile); } }catch(Exception e) { log("Failed to rename file!!",e,0); } }
public void execute() throws BuildException { if (this.cvsVersionFile == null && this.version < 0) { throw new BuildException( "Version file property file is not set and version property is not set - one of them must be used!!!"); } if (toVersion == null) { } else { doToVersion = true; } if(pomFile==null) {}else { doPom=true; } // Check cvsVersionFile if ( this.version < 0 && ( cvsVersionFile==null ||!cvsVersionFile.canRead())) { throw new BuildException("Cant read from " + cvsVersionFile + " - eiher set it or version property!!!"); } if (incrementCVSVersion && !cvsVersionFile.canWrite()) { throw new BuildException("Cant write to " + cvsVersionFile + "!!!"); } if ( doPom && (!pomFile.canRead() || !pomFile.canWrite())) { throw new BuildException("Cant read/write pom file " + cvsVersionFile + "!!!"); } if (doToVersion && !toVersion.canRead()) { throw new BuildException( "Cant read file that is going to be versioned " + cvsVersionFile + "!!!"); } super.execute(); int localVersion = -1; if (cvsVersionFile != null) { //ObjectInputStream ois = null; BufferedReader br=null; try { //ois = new ObjectInputStream(new FileInputStream(cvsVersionFile)); String versionValue=null; br=new BufferedReader(new FileReader(cvsVersionFile)); versionValue=br.readLine(); localVersion = Math.abs(Integer.valueOf(versionValue)); } catch (Exception e) { log("Failed to fetch version from file!!"); localVersion = this.version; } finally { if (br != null) try { br.close(); } catch (Exception e) { localVersion = this.version; } } if (incrementCVSVersion) { cvsVersionFile.delete(); try { cvsVersionFile.createNewFile(); //ObjectOutputStream oos = new ObjectOutputStream( // new FileOutputStream(cvsVersionFile)); //oos.writeUTF(""+localVersion + 1); BufferedWriter bw=new BufferedWriter(new FileWriter(cvsVersionFile)); bw.write(""+(localVersion + 1)); bw.flush(); bw.close(); File antPropertiesFile = new File( this.antprops); antPropertiesFile.createNewFile(); bw=new BufferedWriter(new FileWriter(antPropertiesFile)); bw.write("jain-sip-ri-jar=jain-sip-ri-1.2."+(localVersion + 1) + ".jar\n"); bw.write("jain-sip-sdp-jar=jain-sip-sdp-1.2."+(localVersion + 1) + ".jar\n"); bw.write("jain-sip-src-tar=jain-sip-src-1.2."+(localVersion + 1) + ".tar.gz\n"); bw.write("jain-sip-javadoc-tar=jain-sip-javadoc-1.2."+(localVersion + 1) + ".tar.gz\n"); bw.write("jain-sip-all-tar=jain-sip-1.2." +(localVersion + 1) + ".tar.gz\n"); bw.write("jain-sip-tck-jar=jain-sip-tck-1.2."+(localVersion + 1) + ".jar\n"); bw.write("sdp_jar=jain-sdp-1.0."+(localVersion + 1) + ".jar\n"); bw.write("sdp-src-jar=jain-sdp-src-1.0."+(localVersion + 1) + ".jar\n"); bw.write("jain-sip-src-jar=jain-sip-src-1.2." + +(localVersion + 1) + ".jar\n"); bw.write("jain-sip-sctp-jar=jain-sip-sctp-1.2."+(localVersion + 1) + ".jar\n"); bw.write("unit_test_jar=jain-sip-unit-test-1.2." + (localVersion+1) + ".jar\n"); bw.flush(); bw.close(); bw=new BufferedWriter(new FileWriter(this.timeStampFileName)); Date date = new Date ( System.currentTimeMillis()); bw.write(date.toString()); bw.close(); } catch (IOException e) { log("Failed to increment version in file. See stack trace:",e,0); e.printStackTrace(); } } } else { localVersion = this.version; } if(doPom) try { SAXBuilder saxb = new SAXBuilder(); Document doc = saxb.build(pomFile); Element root = doc.getRootElement(); // dont be supripsed - jdom and other work weird - // Element.getChild(Element.getName)==null even though child element // exists... if (parent) { for (Object o : root.getChildren()) { Element current = (Element) o; if (current.getName().equals("parent")) { doVersionChange(current, localVersion); } else { continue; } break; } } else { doVersionChange(root, localVersion); } XMLOutputter outputter = new XMLOutputter(); outputter.output(doc, new FileOutputStream(pomFile)); } catch (Exception e) { throw new BuildException(e); } try{ if(doToVersion) { String name=toVersion.toString(); name=name.substring(0, name.lastIndexOf("."))+localVersion+name.substring( name.lastIndexOf(".")); File outputFile=new File(name); toVersion.renameTo(outputFile); } }catch(Exception e) { log("Failed to rename file!!",e,0); } }
diff --git a/src/main/java/com/datascience/gal/dawidSkeneProcessors/DawidSkeneProcessorManager.java b/src/main/java/com/datascience/gal/dawidSkeneProcessors/DawidSkeneProcessorManager.java index cfaa3cf4..035c18f9 100644 --- a/src/main/java/com/datascience/gal/dawidSkeneProcessors/DawidSkeneProcessorManager.java +++ b/src/main/java/com/datascience/gal/dawidSkeneProcessors/DawidSkeneProcessorManager.java @@ -1,167 +1,169 @@ /******************************************************************************* * Copyright (c) 2012 Panagiotis G. Ipeirotis & Josh M. Attenberg * * 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 com.datascience.gal.dawidSkeneProcessors; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.log4j.Logger; public class DawidSkeneProcessorManager extends Thread { public DawidSkeneProcessorManager(int threadPoolSize,int sleepPeriod) { this.processorQueue = new HashMap<String,Queue<DawidSkeneProcessor>>(); this.executor = Executors.newFixedThreadPool(threadPoolSize); this.stopped = false; this.sleepPeriod = sleepPeriod; } @Override public void run() { logger.info("Starting DawidSkene processor manager."); while(!this.stopped) { this.executeProcessors(); try { this.sleep(this.sleepPeriod); } catch(InterruptedException e) { //THIS CAN BE EMPTY } } logger.info("DawidSkene processor manager stopped."); } /** * This function adds a new processor to manager * @param processor Processor that's going to be added to manager */ public void addProcessor(DawidSkeneProcessor processor) { synchronized(this.processorQueue) { if(processor.getState().equals(DawidSkeneProcessorState.CREATED)) { if(!this.processorQueue.containsKey(processor.getDawidSkeneId())) { this.processorQueue.put(processor.getDawidSkeneId(),new ConcurrentLinkedQueue<DawidSkeneProcessor>()); } this.processorQueue.get(processor.getDawidSkeneId()).add(processor); processor.setState(DawidSkeneProcessorState.IN_QUEUE); logger.info("Added new processor to queue"); this.interrupt(); } } } private void executeProcessors() { synchronized(this.processorQueue) { Collection<String> projects = this.processorQueue.keySet(); for (String project : projects) { Queue<DawidSkeneProcessor> queue = this.processorQueue.get(project); - if(queue.peek()!=null&&queue.peek().getState().equals(DawidSkeneProcessorState.FINISHED)) { - queue.poll(); + if(queue.peek()!=null&&!queue.peek().getState().equals(DawidSkeneProcessorState.RUNNING)) { + if(queue.peek().getState().equals(DawidSkeneProcessorState.FINISHED)) { + queue.poll(); + } if(queue.peek()!=null) { this.executor.execute(queue.peek()); queue.peek().setState(DawidSkeneProcessorState.RUNNING); } } } } } /** * Map that holds queues of processors for each project */ private Map<String,Queue<DawidSkeneProcessor>> processorQueue; /** * @return Map that holds queues of processors for each project */ public Map<String,Queue<DawidSkeneProcessor>> getProcessorQueue() { return processorQueue; } /** * @param processorQueue Map that holds queues of processors for each project */ public void setProcessorQueue(Map<String,Queue<DawidSkeneProcessor>> processorQueue) { this.processorQueue = processorQueue; } /** * Executor that executes processor threads */ private ExecutorService executor; /** * @return Executor that executes processor threads */ public ExecutorService getExecutor() { return executor; } /** * @param executor Executor that executes processor threads */ public void setExecutor(ExecutorService executor) { this.executor = executor; } /** * Set to true if manager is stopped */ private boolean stopped; /** * @return Set to true if manager is stopped */ public boolean isStopped() { return stopped; } /** * @param stopped Set to true if manager is stopped */ public void setStopped() { this.stopped = true; } /** * Time for wtih manager thread will be put to sleep between executions */ private int sleepPeriod; /** * @return Time for wtih manager thread will be put to sleep between executions */ public int getSleepPeriod() { return sleepPeriod; } /** * @param sleepPeriod Time for wtih manager thread will be put to sleep between executions */ public void setSleepPeriod(int sleepPeriod) { this.sleepPeriod = sleepPeriod; } private static Logger logger = Logger.getLogger(DawidSkeneProcessorManager.class); }
true
true
private void executeProcessors() { synchronized(this.processorQueue) { Collection<String> projects = this.processorQueue.keySet(); for (String project : projects) { Queue<DawidSkeneProcessor> queue = this.processorQueue.get(project); if(queue.peek()!=null&&queue.peek().getState().equals(DawidSkeneProcessorState.FINISHED)) { queue.poll(); if(queue.peek()!=null) { this.executor.execute(queue.peek()); queue.peek().setState(DawidSkeneProcessorState.RUNNING); } } } } }
private void executeProcessors() { synchronized(this.processorQueue) { Collection<String> projects = this.processorQueue.keySet(); for (String project : projects) { Queue<DawidSkeneProcessor> queue = this.processorQueue.get(project); if(queue.peek()!=null&&!queue.peek().getState().equals(DawidSkeneProcessorState.RUNNING)) { if(queue.peek().getState().equals(DawidSkeneProcessorState.FINISHED)) { queue.poll(); } if(queue.peek()!=null) { this.executor.execute(queue.peek()); queue.peek().setState(DawidSkeneProcessorState.RUNNING); } } } } }
diff --git a/src/com/android/mms/data/RecipientIdCache.java b/src/com/android/mms/data/RecipientIdCache.java index 4547a5d..f3ed4ab 100644 --- a/src/com/android/mms/data/RecipientIdCache.java +++ b/src/com/android/mms/data/RecipientIdCache.java @@ -1,170 +1,170 @@ package com.android.mms.data; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.content.Context; import android.content.ContentValues; import android.content.ContentUris; import android.database.Cursor; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import android.provider.Telephony; import com.google.android.mms.util.SqliteWrapper; import com.android.mms.LogTag; public class RecipientIdCache { private static final String TAG = "Mms/cache"; private static Uri sAllCanonical = Uri.parse("content://mms-sms/canonical-addresses"); private static Uri sSingleCanonicalAddressUri = Uri.parse("content://mms-sms/canonical-address"); private static RecipientIdCache sInstance; static RecipientIdCache getInstance() { return sInstance; } private final Map<Long, String> mCache; private final Context mContext; public static class Entry { public long id; public String number; public Entry(long id, String number) { this.id = id; this.number = number; } }; static void init(Context context) { sInstance = new RecipientIdCache(context); new Thread(new Runnable() { public void run() { fill(); } }).start(); } RecipientIdCache(Context context) { mCache = new HashMap<Long, String>(); mContext = context; } public static void fill() { Context context = sInstance.mContext; Cursor c = SqliteWrapper.query(context, context.getContentResolver(), sAllCanonical, null, null, null, null); try { synchronized (sInstance) { // Technically we don't have to clear this because the stupid // canonical_addresses table is never GC'ed. sInstance.mCache.clear(); while (c.moveToNext()) { // TODO: don't hardcode the column indices long id = c.getLong(0); String number = c.getString(1); sInstance.mCache.put(id, number); } } } finally { c.close(); } } public static List<Entry> getAddresses(String spaceSepIds) { synchronized (sInstance) { List<Entry> numbers = new ArrayList<Entry>(); String[] ids = spaceSepIds.split(" "); for (String id : ids) { long longId; try { longId = Long.parseLong(id); } catch (NumberFormatException ex) { // skip this id continue; } String number = sInstance.mCache.get(longId); if (number == null) { - Log.w(TAG, "Recipient ID " + id + " not in DB!"); + Log.w(TAG, "RecipientId " + longId + " not in cache!"); dump(); fill(); - number = sInstance.mCache.get(id); + number = sInstance.mCache.get(longId); } if (TextUtils.isEmpty(number)) { - Log.w(TAG, "Recipient ID " + id + " has empty number!"); + Log.w(TAG, "RecipientId " + longId + " has empty number!"); } else { numbers.add(new Entry(longId, number)); } } return numbers; } } public static void updateNumbers(long threadId, ContactList contacts) { long recipientId = 0; for (Contact contact : contacts) { if (contact.isNumberModified()) { contact.setIsNumberModified(false); } else { // if the contact's number wasn't modified, don't bother. continue; } recipientId = contact.getRecipientId(); if (recipientId == 0) { continue; } String number1 = contact.getNumber(); String number2 = sInstance.mCache.get(recipientId); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.d(TAG, "[RecipientIdCache] updateNumbers: comparing " + number1 + " with " + number2); } // if the numbers don't match, let's update the RecipientIdCache's number // with the new number in the contact. if (!number1.equalsIgnoreCase(number2)) { sInstance.mCache.put(recipientId, number1); sInstance.updateCanonicalAddressInDb(recipientId, number1); } } } private void updateCanonicalAddressInDb(long id, String number) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.d(TAG, "[RecipientIdCache] updateCanonicalAddressInDb: id=" + id + ", number=" + number); } ContentValues values = new ContentValues(); values.put(Telephony.CanonicalAddressesColumns.ADDRESS, number); StringBuilder buf = new StringBuilder(Telephony.CanonicalAddressesColumns._ID); buf.append('=').append(id); Uri uri = ContentUris.withAppendedId(sSingleCanonicalAddressUri, id); mContext.getContentResolver().update(uri, values, buf.toString(), null); } public static void dump() { synchronized (sInstance) { Log.d(TAG, "*** Recipient ID cache dump ***"); for (Long id : sInstance.mCache.keySet()) { Log.d(TAG, id + ": " + sInstance.mCache.get(id)); } } } }
false
true
public static List<Entry> getAddresses(String spaceSepIds) { synchronized (sInstance) { List<Entry> numbers = new ArrayList<Entry>(); String[] ids = spaceSepIds.split(" "); for (String id : ids) { long longId; try { longId = Long.parseLong(id); } catch (NumberFormatException ex) { // skip this id continue; } String number = sInstance.mCache.get(longId); if (number == null) { Log.w(TAG, "Recipient ID " + id + " not in DB!"); dump(); fill(); number = sInstance.mCache.get(id); } if (TextUtils.isEmpty(number)) { Log.w(TAG, "Recipient ID " + id + " has empty number!"); } else { numbers.add(new Entry(longId, number)); } } return numbers; } }
public static List<Entry> getAddresses(String spaceSepIds) { synchronized (sInstance) { List<Entry> numbers = new ArrayList<Entry>(); String[] ids = spaceSepIds.split(" "); for (String id : ids) { long longId; try { longId = Long.parseLong(id); } catch (NumberFormatException ex) { // skip this id continue; } String number = sInstance.mCache.get(longId); if (number == null) { Log.w(TAG, "RecipientId " + longId + " not in cache!"); dump(); fill(); number = sInstance.mCache.get(longId); } if (TextUtils.isEmpty(number)) { Log.w(TAG, "RecipientId " + longId + " has empty number!"); } else { numbers.add(new Entry(longId, number)); } } return numbers; } }
diff --git a/kdcloud-webservice/src/main/java/com/kdcloud/server/rest/application/MainApplication.java b/kdcloud-webservice/src/main/java/com/kdcloud/server/rest/application/MainApplication.java index dfb4040..b9cc59c 100644 --- a/kdcloud-webservice/src/main/java/com/kdcloud/server/rest/application/MainApplication.java +++ b/kdcloud-webservice/src/main/java/com/kdcloud/server/rest/application/MainApplication.java @@ -1,40 +1,40 @@ package com.kdcloud.server.rest.application; import java.util.logging.Level; import org.restlet.Application; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.data.ChallengeScheme; import org.restlet.resource.Directory; import org.restlet.routing.Router; import org.restlet.security.ChallengeAuthenticator; import com.kdcloud.lib.domain.ServerParameter; import com.kdcloud.server.rest.resource.QueueWorkerServerResource; import com.kdcloud.server.tasks.TaskQueue; public class MainApplication extends Application { @Override public Restlet createInboundRoot() { getLogger().setLevel(Level.FINEST); Context applicationContext = new GAEContext(getLogger()); Router router = new Router(getContext()); - router.attach("/xml", new Directory(getContext(), "war:///")); + router.attach("/XML", new Directory(getContext(), "war:///")); router.attach(TaskQueue.WORKER_URI + ServerParameter.TASK_ID, QueueWorkerServerResource.class); ChallengeAuthenticator guard = new ChallengeAuthenticator(null, ChallengeScheme.HTTP_BASIC, "testRealm"); guard.setVerifier(new OAuthVerifier(getLogger(), true)); guard.setNext(new KDApplication(applicationContext)); router.attachDefault(guard); return router; } }
true
true
public Restlet createInboundRoot() { getLogger().setLevel(Level.FINEST); Context applicationContext = new GAEContext(getLogger()); Router router = new Router(getContext()); router.attach("/xml", new Directory(getContext(), "war:///")); router.attach(TaskQueue.WORKER_URI + ServerParameter.TASK_ID, QueueWorkerServerResource.class); ChallengeAuthenticator guard = new ChallengeAuthenticator(null, ChallengeScheme.HTTP_BASIC, "testRealm"); guard.setVerifier(new OAuthVerifier(getLogger(), true)); guard.setNext(new KDApplication(applicationContext)); router.attachDefault(guard); return router; }
public Restlet createInboundRoot() { getLogger().setLevel(Level.FINEST); Context applicationContext = new GAEContext(getLogger()); Router router = new Router(getContext()); router.attach("/XML", new Directory(getContext(), "war:///")); router.attach(TaskQueue.WORKER_URI + ServerParameter.TASK_ID, QueueWorkerServerResource.class); ChallengeAuthenticator guard = new ChallengeAuthenticator(null, ChallengeScheme.HTTP_BASIC, "testRealm"); guard.setVerifier(new OAuthVerifier(getLogger(), true)); guard.setNext(new KDApplication(applicationContext)); router.attachDefault(guard); return router; }
diff --git a/src/prettify/lang/LangSql.java b/src/prettify/lang/LangSql.java index 83def8c..89bc582 100644 --- a/src/prettify/lang/LangSql.java +++ b/src/prettify/lang/LangSql.java @@ -1,72 +1,72 @@ // 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 prettify.lang; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import prettify.parser.Prettify; /** * This is similar to the lang-sql.js in JavaScript Prettify. * * All comments are adapted from the JavaScript Prettify. * * <p> * Registers a language handler for SQL. * * * To use, include prettify.js and this file in your HTML page. * Then put your code in an HTML tag like * <pre class="prettyprint lang-sql">(my SQL code)</pre> * * * http://savage.net.au/SQL/sql-99.bnf.html is the basis for the grammar, and * http://msdn.microsoft.com/en-us/library/aa238507(SQL.80).aspx and * http://meta.stackoverflow.com/q/92352/137403 as the bases for the keyword * list. * * @author [email protected] */ public class LangSql extends Lang { public LangSql() { List<List<Object>> _shortcutStylePatterns = new ArrayList<List<Object>>(); List<List<Object>> _fallthroughStylePatterns = new ArrayList<List<Object>>(); // Whitespace _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("^[\\t\\n\\r \\xA0]+"), null, "\t\n\r " + Character.toString((char) 0xA0)})); // A double or single quoted, possibly multi-line, string. _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_STRING, Pattern.compile("^(?:\"(?:[^\\\"\\\\]|\\\\.)*\"|'(?:[^\\'\\\\]|\\\\.)*')"), null, "\"'"})); // A comment is either a line comment that starts with two dashes, or // two dashes preceding a long bracketed block. _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_COMMENT, Pattern.compile("^(?:--[^\\r\\n]*|\\/\\*[\\s\\S]*?(?:\\*\\/|$))")})); - _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^(?:ADD|ALL|ALTER|AND|ANY|APPLY|AS|ASC|AUTHORIZATION|BACKUP|BEGIN|BETWEEN|BREAK|BROWSE|BULK|BY|CASCADE|CASE|CHECK|CHECKPOINT|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMN|COMMIT|COMPUTE|CONSTRAINT|CONTAINS|CONTAINSTABLE|CONTINUE|CONVERT|CREATE|CROSS|CURRENT|CURRENT_DATE|CURRENT_TIME|CURRENT_TIMESTAMP|CURRENT_USER|CURSOR|DATABASE|DBCC|DEALLOCATE|DECLARE|DEFAULT|DELETE|DENY|DESC|DISK|DISTINCT|DISTRIBUTED|DOUBLE|DROP|DUMMY|DUMP|ELSE|END|ERRLVL|ESCAPE|EXCEPT|EXEC|EXECUTE|EXISTS|EXIT|FETCH|FILE|FILLFACTOR|FOLLOWING|FOR|FOREIGN|FREETEXT|FREETEXTTABLE|FROM|FULL|FUNCTION|GOTO|GRANT|GROUP|HAVING|HOLDLOCK|IDENTITY|IDENTITYCOL|IDENTITY_INSERT|IF|IN|INDEX|INNER|INSERT|INTERSECT|INTO|IS|JOIN|KEY|KILL|LEFT|LIKE|LINENO|LOAD|MATCH|MERGE|NATIONAL|NOCHECK|NONCLUSTERED|NOT|NULL|NULLIF|OF|OFF|OFFSETS|ON|OPEN|OPENDATASOURCE|OPENQUERY|OPENROWSET|OPENXML|OPTION|OR|ORDER|OUTER|OVER|PERCENT|PLAN|PRECEDING|PRECISION|PRIMARY|PRINT|PROC|PROCEDURE|PUBLIC|RAISERROR|READ|READTEXT|RECONFIGURE|REFERENCES|REPLICATION|RESTORE|RESTRICT|RETURN|REVOKE|RIGHT|ROLLBACK|ROWCOUNT|ROWGUIDCOL|ROWS?|RULE|SAVE|SCHEMA|SELECT|SESSION_USER|SET|SETUSER|SHUTDOWN|SOME|STATISTICS|SYSTEM_USER|TABLE|TEXTSIZE|THEN|TO|TOP|TRAN|TRANSACTION|TRIGGER|TRUNCATE|TSEQUAL|UNBOUNDED|UNION|UNIQUE|UPDATE|UPDATETEXT|USE|USER|USING|VALUES|VARYING|VIEW|WAITFOR|WHEN|WHERE|WHILE|WITH|WRITETEXT)(?=[^\\w-]|$)", Pattern.CASE_INSENSITIVE), null})); + _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^(?:ADD|ALL|ALTER|AND|ANY|APPLY|AS|ASC|AUTHORIZATION|BACKUP|BEGIN|BETWEEN|BREAK|BROWSE|BULK|BY|CASCADE|CASE|CHECK|CHECKPOINT|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMN|COMMIT|COMPUTE|CONNECT|CONSTRAINT|CONTAINS|CONTAINSTABLE|CONTINUE|CONVERT|CREATE|CROSS|CURRENT|CURRENT_DATE|CURRENT_TIME|CURRENT_TIMESTAMP|CURRENT_USER|CURSOR|DATABASE|DBCC|DEALLOCATE|DECLARE|DEFAULT|DELETE|DENY|DESC|DISK|DISTINCT|DISTRIBUTED|DOUBLE|DROP|DUMMY|DUMP|ELSE|END|ERRLVL|ESCAPE|EXCEPT|EXEC|EXECUTE|EXISTS|EXIT|FETCH|FILE|FILLFACTOR|FOLLOWING|FOR|FOREIGN|FREETEXT|FREETEXTTABLE|FROM|FULL|FUNCTION|GOTO|GRANT|GROUP|HAVING|HOLDLOCK|IDENTITY|IDENTITYCOL|IDENTITY_INSERT|IF|IN|INDEX|INNER|INSERT|INTERSECT|INTO|IS|JOIN|KEY|KILL|LEFT|LIKE|LINENO|LOAD|MATCH|MERGE|NATIONAL|NOCHECK|NONCLUSTERED|NOT|NULL|NULLIF|OF|OFF|OFFSETS|ON|OPEN|OPENDATASOURCE|OPENQUERY|OPENROWSET|OPENXML|OPTION|OR|ORDER|OUTER|OVER|PERCENT|PLAN|PRECEDING|PRECISION|PRIMARY|PRINT|PROC|PROCEDURE|PUBLIC|RAISERROR|READ|READTEXT|RECONFIGURE|REFERENCES|REPLICATION|RESTORE|RESTRICT|RETURN|REVOKE|RIGHT|ROLLBACK|ROWCOUNT|ROWGUIDCOL|ROWS?|RULE|SAVE|SCHEMA|SELECT|SESSION_USER|SET|SETUSER|SHUTDOWN|SOME|STATISTICS|SYSTEM_USER|TABLE|TEXTSIZE|THEN|TO|TOP|TRAN|TRANSACTION|TRIGGER|TRUNCATE|TSEQUAL|UNBOUNDED|UNION|UNIQUE|UPDATE|UPDATETEXT|USE|USER|USING|VALUES|VARYING|VIEW|WAITFOR|WHEN|WHERE|WHILE|WITH|WRITETEXT)(?=[^\\w-]|$)", Pattern.CASE_INSENSITIVE), null})); // A number is a hex integer literal, a decimal real literal, or in // scientific notation. _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^[+-]?(?:0x[\\da-f]+|(?:(?:\\.\\d+|\\d+(?:\\.\\d*)?)(?:e[+\\-]?\\d+)?))", Pattern.CASE_INSENSITIVE)})); // An identifier _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("^[a-z_][\\w-]*", Pattern.CASE_INSENSITIVE)})); // A run of punctuation _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PUNCTUATION, Pattern.compile("^[^\\w\\t\\n\\r \\xA0\\\"\\'][^\\w\\t\\n\\r \\xA0+\\-\\\"\\']*")})); setShortcutStylePatterns(_shortcutStylePatterns); setFallthroughStylePatterns(_fallthroughStylePatterns); } public static List<String> getFileExtensions() { return Arrays.asList(new String[]{"sql"}); } }
true
true
public LangSql() { List<List<Object>> _shortcutStylePatterns = new ArrayList<List<Object>>(); List<List<Object>> _fallthroughStylePatterns = new ArrayList<List<Object>>(); // Whitespace _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("^[\\t\\n\\r \\xA0]+"), null, "\t\n\r " + Character.toString((char) 0xA0)})); // A double or single quoted, possibly multi-line, string. _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_STRING, Pattern.compile("^(?:\"(?:[^\\\"\\\\]|\\\\.)*\"|'(?:[^\\'\\\\]|\\\\.)*')"), null, "\"'"})); // A comment is either a line comment that starts with two dashes, or // two dashes preceding a long bracketed block. _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_COMMENT, Pattern.compile("^(?:--[^\\r\\n]*|\\/\\*[\\s\\S]*?(?:\\*\\/|$))")})); _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^(?:ADD|ALL|ALTER|AND|ANY|APPLY|AS|ASC|AUTHORIZATION|BACKUP|BEGIN|BETWEEN|BREAK|BROWSE|BULK|BY|CASCADE|CASE|CHECK|CHECKPOINT|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMN|COMMIT|COMPUTE|CONSTRAINT|CONTAINS|CONTAINSTABLE|CONTINUE|CONVERT|CREATE|CROSS|CURRENT|CURRENT_DATE|CURRENT_TIME|CURRENT_TIMESTAMP|CURRENT_USER|CURSOR|DATABASE|DBCC|DEALLOCATE|DECLARE|DEFAULT|DELETE|DENY|DESC|DISK|DISTINCT|DISTRIBUTED|DOUBLE|DROP|DUMMY|DUMP|ELSE|END|ERRLVL|ESCAPE|EXCEPT|EXEC|EXECUTE|EXISTS|EXIT|FETCH|FILE|FILLFACTOR|FOLLOWING|FOR|FOREIGN|FREETEXT|FREETEXTTABLE|FROM|FULL|FUNCTION|GOTO|GRANT|GROUP|HAVING|HOLDLOCK|IDENTITY|IDENTITYCOL|IDENTITY_INSERT|IF|IN|INDEX|INNER|INSERT|INTERSECT|INTO|IS|JOIN|KEY|KILL|LEFT|LIKE|LINENO|LOAD|MATCH|MERGE|NATIONAL|NOCHECK|NONCLUSTERED|NOT|NULL|NULLIF|OF|OFF|OFFSETS|ON|OPEN|OPENDATASOURCE|OPENQUERY|OPENROWSET|OPENXML|OPTION|OR|ORDER|OUTER|OVER|PERCENT|PLAN|PRECEDING|PRECISION|PRIMARY|PRINT|PROC|PROCEDURE|PUBLIC|RAISERROR|READ|READTEXT|RECONFIGURE|REFERENCES|REPLICATION|RESTORE|RESTRICT|RETURN|REVOKE|RIGHT|ROLLBACK|ROWCOUNT|ROWGUIDCOL|ROWS?|RULE|SAVE|SCHEMA|SELECT|SESSION_USER|SET|SETUSER|SHUTDOWN|SOME|STATISTICS|SYSTEM_USER|TABLE|TEXTSIZE|THEN|TO|TOP|TRAN|TRANSACTION|TRIGGER|TRUNCATE|TSEQUAL|UNBOUNDED|UNION|UNIQUE|UPDATE|UPDATETEXT|USE|USER|USING|VALUES|VARYING|VIEW|WAITFOR|WHEN|WHERE|WHILE|WITH|WRITETEXT)(?=[^\\w-]|$)", Pattern.CASE_INSENSITIVE), null})); // A number is a hex integer literal, a decimal real literal, or in // scientific notation. _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^[+-]?(?:0x[\\da-f]+|(?:(?:\\.\\d+|\\d+(?:\\.\\d*)?)(?:e[+\\-]?\\d+)?))", Pattern.CASE_INSENSITIVE)})); // An identifier _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("^[a-z_][\\w-]*", Pattern.CASE_INSENSITIVE)})); // A run of punctuation _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PUNCTUATION, Pattern.compile("^[^\\w\\t\\n\\r \\xA0\\\"\\'][^\\w\\t\\n\\r \\xA0+\\-\\\"\\']*")})); setShortcutStylePatterns(_shortcutStylePatterns); setFallthroughStylePatterns(_fallthroughStylePatterns); }
public LangSql() { List<List<Object>> _shortcutStylePatterns = new ArrayList<List<Object>>(); List<List<Object>> _fallthroughStylePatterns = new ArrayList<List<Object>>(); // Whitespace _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("^[\\t\\n\\r \\xA0]+"), null, "\t\n\r " + Character.toString((char) 0xA0)})); // A double or single quoted, possibly multi-line, string. _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_STRING, Pattern.compile("^(?:\"(?:[^\\\"\\\\]|\\\\.)*\"|'(?:[^\\'\\\\]|\\\\.)*')"), null, "\"'"})); // A comment is either a line comment that starts with two dashes, or // two dashes preceding a long bracketed block. _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_COMMENT, Pattern.compile("^(?:--[^\\r\\n]*|\\/\\*[\\s\\S]*?(?:\\*\\/|$))")})); _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^(?:ADD|ALL|ALTER|AND|ANY|APPLY|AS|ASC|AUTHORIZATION|BACKUP|BEGIN|BETWEEN|BREAK|BROWSE|BULK|BY|CASCADE|CASE|CHECK|CHECKPOINT|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMN|COMMIT|COMPUTE|CONNECT|CONSTRAINT|CONTAINS|CONTAINSTABLE|CONTINUE|CONVERT|CREATE|CROSS|CURRENT|CURRENT_DATE|CURRENT_TIME|CURRENT_TIMESTAMP|CURRENT_USER|CURSOR|DATABASE|DBCC|DEALLOCATE|DECLARE|DEFAULT|DELETE|DENY|DESC|DISK|DISTINCT|DISTRIBUTED|DOUBLE|DROP|DUMMY|DUMP|ELSE|END|ERRLVL|ESCAPE|EXCEPT|EXEC|EXECUTE|EXISTS|EXIT|FETCH|FILE|FILLFACTOR|FOLLOWING|FOR|FOREIGN|FREETEXT|FREETEXTTABLE|FROM|FULL|FUNCTION|GOTO|GRANT|GROUP|HAVING|HOLDLOCK|IDENTITY|IDENTITYCOL|IDENTITY_INSERT|IF|IN|INDEX|INNER|INSERT|INTERSECT|INTO|IS|JOIN|KEY|KILL|LEFT|LIKE|LINENO|LOAD|MATCH|MERGE|NATIONAL|NOCHECK|NONCLUSTERED|NOT|NULL|NULLIF|OF|OFF|OFFSETS|ON|OPEN|OPENDATASOURCE|OPENQUERY|OPENROWSET|OPENXML|OPTION|OR|ORDER|OUTER|OVER|PERCENT|PLAN|PRECEDING|PRECISION|PRIMARY|PRINT|PROC|PROCEDURE|PUBLIC|RAISERROR|READ|READTEXT|RECONFIGURE|REFERENCES|REPLICATION|RESTORE|RESTRICT|RETURN|REVOKE|RIGHT|ROLLBACK|ROWCOUNT|ROWGUIDCOL|ROWS?|RULE|SAVE|SCHEMA|SELECT|SESSION_USER|SET|SETUSER|SHUTDOWN|SOME|STATISTICS|SYSTEM_USER|TABLE|TEXTSIZE|THEN|TO|TOP|TRAN|TRANSACTION|TRIGGER|TRUNCATE|TSEQUAL|UNBOUNDED|UNION|UNIQUE|UPDATE|UPDATETEXT|USE|USER|USING|VALUES|VARYING|VIEW|WAITFOR|WHEN|WHERE|WHILE|WITH|WRITETEXT)(?=[^\\w-]|$)", Pattern.CASE_INSENSITIVE), null})); // A number is a hex integer literal, a decimal real literal, or in // scientific notation. _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^[+-]?(?:0x[\\da-f]+|(?:(?:\\.\\d+|\\d+(?:\\.\\d*)?)(?:e[+\\-]?\\d+)?))", Pattern.CASE_INSENSITIVE)})); // An identifier _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("^[a-z_][\\w-]*", Pattern.CASE_INSENSITIVE)})); // A run of punctuation _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PUNCTUATION, Pattern.compile("^[^\\w\\t\\n\\r \\xA0\\\"\\'][^\\w\\t\\n\\r \\xA0+\\-\\\"\\']*")})); setShortcutStylePatterns(_shortcutStylePatterns); setFallthroughStylePatterns(_fallthroughStylePatterns); }
diff --git a/GIL/src/gil/web/html/page/AboutPage.java b/GIL/src/gil/web/html/page/AboutPage.java index 559a340..8ecb14e 100644 --- a/GIL/src/gil/web/html/page/AboutPage.java +++ b/GIL/src/gil/web/html/page/AboutPage.java @@ -1,70 +1,70 @@ /* Copyright (C) 2010 LearningWell AB (www.learningwell.com), Kärnkraftsäkerhet och Utbildning AB (www.ksu.se) This file is part of GIL (Generic Integration Layer). GIL 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. GIL 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 GIL. If not, see <http://www.gnu.org/licenses/>. */ package gil.web.html.page; import gil.GIL; import gil.core.SoftwareInfo; import gil.web.html.Div; import gil.web.html.Heading; import gil.web.html.PlainText; import gil.web.html.Tag; /** * @author Göran Larsson @ LearningWell AB */ public class AboutPage extends MasterPage { public AboutPage() { GIL.VersionInfo info = GIL.instance().getVersionInfo(); Div div = new Div("about"); div.addContent(new Heading("About", Heading.H2)); - div.addContent(new Heading("Current CIR", Heading.H3)); + div.addContent(new Heading("Current GIL", Heading.H3)); addVersionInfo(div, info.gilInfo); div.addContent(new Heading("External System", Heading.H3)); addVersionInfoSection(info.externalSystemInfo, div); div.addContent(new Heading("Process Model", Heading.H3)); addVersionInfoSection(info.processModelInfo, div); this.setSectionContent("content", div); } private void addVersionInfoSection(SoftwareInfo[] info, Div div) { for (SoftwareInfo i : info) { addVersionInfo(div, i); if (i != info[info.length - 1]) { div.addContent(new Tag("hr")); } } } private void addVersionInfo(Div addTo, SoftwareInfo info) { Div div = new Div("aboutVersion"); div.addContent(new Heading("Name", Heading.H4)).addContent(new PlainText(info.getName())); div.addContent(new Heading("Version", Heading.H4)).addContent(new PlainText(info.getVersion())); div.addContent(new Heading("Company", Heading.H4)).addContent(new PlainText(info.getCompany())); div.addContent(new Heading("Description", Heading.H4)).addContent(new PlainText(info.getDescription())); addTo.addContent(div); } }
true
true
public AboutPage() { GIL.VersionInfo info = GIL.instance().getVersionInfo(); Div div = new Div("about"); div.addContent(new Heading("About", Heading.H2)); div.addContent(new Heading("Current CIR", Heading.H3)); addVersionInfo(div, info.gilInfo); div.addContent(new Heading("External System", Heading.H3)); addVersionInfoSection(info.externalSystemInfo, div); div.addContent(new Heading("Process Model", Heading.H3)); addVersionInfoSection(info.processModelInfo, div); this.setSectionContent("content", div); }
public AboutPage() { GIL.VersionInfo info = GIL.instance().getVersionInfo(); Div div = new Div("about"); div.addContent(new Heading("About", Heading.H2)); div.addContent(new Heading("Current GIL", Heading.H3)); addVersionInfo(div, info.gilInfo); div.addContent(new Heading("External System", Heading.H3)); addVersionInfoSection(info.externalSystemInfo, div); div.addContent(new Heading("Process Model", Heading.H3)); addVersionInfoSection(info.processModelInfo, div); this.setSectionContent("content", div); }
diff --git a/src/ua/com/vassiliev/androidfilebrowser/FileBrowserActivity.java b/src/ua/com/vassiliev/androidfilebrowser/FileBrowserActivity.java index 4082f0b..835de65 100644 --- a/src/ua/com/vassiliev/androidfilebrowser/FileBrowserActivity.java +++ b/src/ua/com/vassiliev/androidfilebrowser/FileBrowserActivity.java @@ -1,424 +1,432 @@ package ua.com.vassiliev.androidfilebrowser; //Heavily based on code from //https://github.com/mburman/Android-File-Explore // Version of Aug 13, 2011 //Also contributed: // Sugan Krishnan (https://github.com/rgksugan) - Jan 2013. // //Project type now is Android library: // http://developer.android.com/guide/developing/projects/projects-eclipse.html#ReferencingLibraryProject //General Java imports import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Collections; //Android imports import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Color; import android.os.Bundle; import android.os.Environment; import android.os.StatFs; import android.util.Log; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.*; import android.widget.*; //Import of resources file for file browser import ua.com.vassiliev.androidfilebrowser.R; public class FileBrowserActivity extends Activity { // Intent Action Constants public static final String INTENT_ACTION_SELECT_DIR = "ua.com.vassiliev.androidfilebrowser.SELECT_DIRECTORY_ACTION"; public static final String INTENT_ACTION_SELECT_FILE = "ua.com.vassiliev.androidfilebrowser.SELECT_FILE_ACTION"; // Intent parameters names constants public static final String startDirectoryParameter = "ua.com.vassiliev.androidfilebrowser.directoryPath"; public static final String returnDirectoryParameter = "ua.com.vassiliev.androidfilebrowser.directoryPathRet"; public static final String returnFileParameter = "ua.com.vassiliev.androidfilebrowser.filePathRet"; public static final String showCannotReadParameter = "ua.com.vassiliev.androidfilebrowser.showCannotRead"; public static final String filterExtension = "ua.com.vassiliev.androidfilebrowser.filterExtension"; // Stores names of traversed directories ArrayList<String> pathDirsList = new ArrayList<String>(); // Check if the first level of the directory structure is the one showing // private Boolean firstLvl = true; private static final String LOGTAG = "F_PATH"; private List<Item> fileList = new ArrayList<Item>(); private File path = null; private String chosenFile; // private static final int DIALOG_LOAD_FILE = 1000; ArrayAdapter<Item> adapter; private boolean showHiddenFilesAndDirs = true; private boolean directoryShownIsEmpty = false; private String filterFileExtension = null; // Action constants private static int currentAction = -1; private static final int SELECT_DIRECTORY = 1; private static final int SELECT_FILE = 2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // In case of // ua.com.vassiliev.androidfilebrowser.SELECT_DIRECTORY_ACTION // Expects com.mburman.fileexplore.directoryPath parameter to // point to the start folder. // If empty or null, will start from SDcard root. setContentView(R.layout.ua_com_vassiliev_filebrowser_layout); // Set action for this activity Intent thisInt = this.getIntent(); currentAction = SELECT_DIRECTORY;// This would be a default action in // case not set by intent if (thisInt.getAction().equalsIgnoreCase(INTENT_ACTION_SELECT_FILE)) { Log.d(LOGTAG, "SELECT ACTION - SELECT FILE"); currentAction = SELECT_FILE; } showHiddenFilesAndDirs = thisInt.getBooleanExtra( showCannotReadParameter, true); filterFileExtension = thisInt.getStringExtra(filterExtension); setInitialDirectory(); parseDirectoryPath(); loadFileList(); this.createFileListAdapter(); this.initializeButtons(); this.initializeFileListView(); updateCurrentDirectoryTextView(); Log.d(LOGTAG, path.getAbsolutePath()); } private void setInitialDirectory() { Intent thisInt = this.getIntent(); String requestedStartDir = thisInt .getStringExtra(startDirectoryParameter); if (requestedStartDir != null && requestedStartDir.length() > 0) {// if(requestedStartDir!=null File tempFile = new File(requestedStartDir); if (tempFile.isDirectory()) this.path = tempFile; }// if(requestedStartDir!=null if (this.path == null) {// No or invalid directory supplied in intent // parameter if (Environment.getExternalStorageDirectory().isDirectory() && Environment.getExternalStorageDirectory().canRead()) path = Environment.getExternalStorageDirectory(); else path = new File("/"); }// if(this.path==null) {//No or invalid directory supplied in intent // parameter }// private void setInitialDirectory() { private void parseDirectoryPath() { pathDirsList.clear(); String pathString = path.getAbsolutePath(); String[] parts = pathString.split("/"); int i = 0; while (i < parts.length) { pathDirsList.add(parts[i]); i++; } } private void initializeButtons() { Button upDirButton = (Button) this.findViewById(R.id.upDirectoryButton); upDirButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Log.d(LOGTAG, "onclick for upDirButton"); loadDirectoryUp(); loadFileList(); adapter.notifyDataSetChanged(); updateCurrentDirectoryTextView(); } });// upDirButton.setOnClickListener( Button selectFolderButton = (Button) this .findViewById(R.id.selectCurrentDirectoryButton); if (currentAction == SELECT_DIRECTORY) { selectFolderButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Log.d(LOGTAG, "onclick for selectFolderButton"); returnDirectoryFinishActivity(); } }); } else {// if(currentAction == this.SELECT_DIRECTORY) { selectFolderButton.setVisibility(View.GONE); }// } else {//if(currentAction == this.SELECT_DIRECTORY) { }// private void initializeButtons() { private void loadDirectoryUp() { // present directory removed from list String s = pathDirsList.remove(pathDirsList.size() - 1); // path modified to exclude present directory path = new File(path.toString().substring(0, path.toString().lastIndexOf(s))); fileList.clear(); } private void updateCurrentDirectoryTextView() { int i = 0; String curDirString = ""; while (i < pathDirsList.size()) { curDirString += pathDirsList.get(i) + "/"; i++; } if (pathDirsList.size() == 0) { ((Button) this.findViewById(R.id.upDirectoryButton)) .setEnabled(false); curDirString = "/"; } else ((Button) this.findViewById(R.id.upDirectoryButton)) .setEnabled(true); + long freeSpace = getFreeSpace(curDirString); + String formattedSpaceString = formatBytes(freeSpace); + if (freeSpace == 0) { + Log.d(LOGTAG, "NO FREE SPACE"); + File currentDir = new File(curDirString); + if(!currentDir.canWrite()) + formattedSpaceString = "NON Writable"; + } ((Button) this.findViewById(R.id.selectCurrentDirectoryButton)) - .setText("Select\n[" + formatBytes(getFreeSpace(curDirString)) + .setText("Select\n[" + formattedSpaceString + "]"); ((TextView) this.findViewById(R.id.currentDirectoryTextView)) .setText("Current directory: " + curDirString); }// END private void updateCurrentDirectoryTextView() { private void showToast(String message) { Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } private void initializeFileListView() { ListView lView = (ListView) this.findViewById(R.id.fileListView); lView.setBackgroundColor(Color.LTGRAY); LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); lParam.setMargins(15, 5, 15, 5); lView.setAdapter(this.adapter); lView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { chosenFile = fileList.get(position).file; File sel = new File(path + "/" + chosenFile); Log.d(LOGTAG, "Clicked:" + chosenFile); if (sel.isDirectory()) { if (sel.canRead()) { // Adds chosen directory to list pathDirsList.add(chosenFile); path = new File(sel + ""); Log.d(LOGTAG, "Just reloading the list"); loadFileList(); adapter.notifyDataSetChanged(); updateCurrentDirectoryTextView(); Log.d(LOGTAG, path.getAbsolutePath()); } else {// if(sel.canRead()) { showToast("Path does not exist or cannot be read"); }// } else {//if(sel.canRead()) { }// if (sel.isDirectory()) { // File picked or an empty directory message clicked else {// if (sel.isDirectory()) { Log.d(LOGTAG, "item clicked"); if (!directoryShownIsEmpty) { Log.d(LOGTAG, "File selected:" + chosenFile); returnFileFinishActivity(sel.getAbsolutePath()); } }// else {//if (sel.isDirectory()) { }// public void onClick(DialogInterface dialog, int which) { });// lView.setOnClickListener( }// private void initializeFileListView() { private void returnDirectoryFinishActivity() { Intent retIntent = new Intent(); retIntent.putExtra(returnDirectoryParameter, path.getAbsolutePath()); this.setResult(RESULT_OK, retIntent); this.finish(); }// END private void returnDirectoryFinishActivity() { private void returnFileFinishActivity(String filePath) { Intent retIntent = new Intent(); retIntent.putExtra(returnFileParameter, filePath); this.setResult(RESULT_OK, retIntent); this.finish(); }// END private void returnDirectoryFinishActivity() { private void loadFileList() { try { path.mkdirs(); } catch (SecurityException e) { Log.e(LOGTAG, "unable to write on the sd card "); } fileList.clear(); if (path.exists() && path.canRead()) { FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String filename) { File sel = new File(dir, filename); boolean showReadableFile = showHiddenFilesAndDirs || sel.canRead(); // Filters based on whether the file is hidden or not if (currentAction == SELECT_DIRECTORY) { return (sel.isDirectory() && showReadableFile); } if (currentAction == SELECT_FILE) { // If it is a file check the extension if provided if (sel.isFile() && filterFileExtension != null) { return (showReadableFile && sel.getName().endsWith( filterFileExtension)); } return (showReadableFile); } return true; }// public boolean accept(File dir, String filename) { };// FilenameFilter filter = new FilenameFilter() { String[] fList = path.list(filter); this.directoryShownIsEmpty = false; for (int i = 0; i < fList.length; i++) { // Convert into file path File sel = new File(path, fList[i]); Log.d(LOGTAG, "File:" + fList[i] + " readable:" + (Boolean.valueOf(sel.canRead())).toString()); int drawableID = R.drawable.file_icon; boolean canRead = sel.canRead(); // Set drawables if (sel.isDirectory()) { if (canRead) { drawableID = R.drawable.folder_icon; } else { drawableID = R.drawable.folder_icon_light; } } fileList.add(i, new Item(fList[i], drawableID, canRead)); }// for (int i = 0; i < fList.length; i++) { if (fileList.size() == 0) { // Log.d(LOGTAG, "This directory is empty"); this.directoryShownIsEmpty = true; fileList.add(0, new Item("Directory is empty", -1, true)); } else {// sort non empty list Collections.sort(fileList, new ItemFileNameComparator()); } } else { Log.e(LOGTAG, "path does not exist or cannot be read"); } // Log.d(TAG, "loadFileList finished"); }// private void loadFileList() { private void createFileListAdapter() { adapter = new ArrayAdapter<Item>(this, android.R.layout.select_dialog_item, android.R.id.text1, fileList) { @Override public View getView(int position, View convertView, ViewGroup parent) { // creates view View view = super.getView(position, convertView, parent); TextView textView = (TextView) view .findViewById(android.R.id.text1); // put the image on the text view int drawableID = 0; if (fileList.get(position).icon != -1) { // If icon == -1, then directory is empty drawableID = fileList.get(position).icon; } textView.setCompoundDrawablesWithIntrinsicBounds(drawableID, 0, 0, 0); textView.setEllipsize(null); // add margin between image and text (support various screen // densities) // int dp5 = (int) (5 * // getResources().getDisplayMetrics().density + 0.5f); int dp3 = (int) (3 * getResources().getDisplayMetrics().density + 0.5f); // TODO: change next line for empty directory, so text will be // centered textView.setCompoundDrawablePadding(dp3); textView.setBackgroundColor(Color.LTGRAY); return view; }// public View getView(int position, View convertView, ViewGroup };// adapter = new ArrayAdapter<Item>(this, }// private createFileListAdapter(){ private class Item { public String file; public int icon; public boolean canRead; public Item(String file, Integer icon, boolean canRead) { this.file = file; this.icon = icon; } @Override public String toString() { return file; } }// END private class Item { private class ItemFileNameComparator implements Comparator<Item> { public int compare(Item lhs, Item rhs) { return lhs.file.toLowerCase().compareTo(rhs.file.toLowerCase()); } } public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { Log.d(LOGTAG, "ORIENTATION_LANDSCAPE"); } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { Log.d(LOGTAG, "ORIENTATION_PORTRAIT"); } // Layout apparently changes itself, only have to provide good onMeasure // in custom components // TODO: check with keyboard // if(newConfig.keyboard == Configuration.KEYBOARDHIDDEN_YES) }// END public void onConfigurationChanged(Configuration newConfig) { public static long getFreeSpace(String path) { StatFs stat = new StatFs(path); long availSize = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize(); return availSize; }// END public static long getFreeSpace(String path) { public static String formatBytes(long bytes) { // TODO: add flag to which part is needed (e.g. GB, MB, KB or bytes) String retStr = ""; // One binary gigabyte equals 1,073,741,824 bytes. if (bytes > 1073741824) {// Add GB long gbs = bytes / 1073741824; retStr += (new Long(gbs)).toString() + "GB "; bytes = bytes - (gbs * 1073741824); } // One MB - 1048576 bytes if (bytes > 1048576) {// Add GB long mbs = bytes / 1048576; retStr += (new Long(mbs)).toString() + "MB "; bytes = bytes - (mbs * 1048576); } if (bytes > 1024) { long kbs = bytes / 1024; retStr += (new Long(kbs)).toString() + "KB"; bytes = bytes - (kbs * 1024); } else retStr += (new Long(bytes)).toString() + " bytes"; return retStr; }// public static String formatBytes(long bytes){ }// END public class FileBrowserActivity extends Activity {
false
true
private void setInitialDirectory() { Intent thisInt = this.getIntent(); String requestedStartDir = thisInt .getStringExtra(startDirectoryParameter); if (requestedStartDir != null && requestedStartDir.length() > 0) {// if(requestedStartDir!=null File tempFile = new File(requestedStartDir); if (tempFile.isDirectory()) this.path = tempFile; }// if(requestedStartDir!=null if (this.path == null) {// No or invalid directory supplied in intent // parameter if (Environment.getExternalStorageDirectory().isDirectory() && Environment.getExternalStorageDirectory().canRead()) path = Environment.getExternalStorageDirectory(); else path = new File("/"); }// if(this.path==null) {//No or invalid directory supplied in intent // parameter }// private void setInitialDirectory() { private void parseDirectoryPath() { pathDirsList.clear(); String pathString = path.getAbsolutePath(); String[] parts = pathString.split("/"); int i = 0; while (i < parts.length) { pathDirsList.add(parts[i]); i++; } } private void initializeButtons() { Button upDirButton = (Button) this.findViewById(R.id.upDirectoryButton); upDirButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Log.d(LOGTAG, "onclick for upDirButton"); loadDirectoryUp(); loadFileList(); adapter.notifyDataSetChanged(); updateCurrentDirectoryTextView(); } });// upDirButton.setOnClickListener( Button selectFolderButton = (Button) this .findViewById(R.id.selectCurrentDirectoryButton); if (currentAction == SELECT_DIRECTORY) { selectFolderButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Log.d(LOGTAG, "onclick for selectFolderButton"); returnDirectoryFinishActivity(); } }); } else {// if(currentAction == this.SELECT_DIRECTORY) { selectFolderButton.setVisibility(View.GONE); }// } else {//if(currentAction == this.SELECT_DIRECTORY) { }// private void initializeButtons() { private void loadDirectoryUp() { // present directory removed from list String s = pathDirsList.remove(pathDirsList.size() - 1); // path modified to exclude present directory path = new File(path.toString().substring(0, path.toString().lastIndexOf(s))); fileList.clear(); } private void updateCurrentDirectoryTextView() { int i = 0; String curDirString = ""; while (i < pathDirsList.size()) { curDirString += pathDirsList.get(i) + "/"; i++; } if (pathDirsList.size() == 0) { ((Button) this.findViewById(R.id.upDirectoryButton)) .setEnabled(false); curDirString = "/"; } else ((Button) this.findViewById(R.id.upDirectoryButton)) .setEnabled(true); ((Button) this.findViewById(R.id.selectCurrentDirectoryButton)) .setText("Select\n[" + formatBytes(getFreeSpace(curDirString)) + "]"); ((TextView) this.findViewById(R.id.currentDirectoryTextView)) .setText("Current directory: " + curDirString); }// END private void updateCurrentDirectoryTextView() { private void showToast(String message) { Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } private void initializeFileListView() { ListView lView = (ListView) this.findViewById(R.id.fileListView); lView.setBackgroundColor(Color.LTGRAY); LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); lParam.setMargins(15, 5, 15, 5); lView.setAdapter(this.adapter); lView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { chosenFile = fileList.get(position).file; File sel = new File(path + "/" + chosenFile); Log.d(LOGTAG, "Clicked:" + chosenFile); if (sel.isDirectory()) { if (sel.canRead()) { // Adds chosen directory to list pathDirsList.add(chosenFile); path = new File(sel + ""); Log.d(LOGTAG, "Just reloading the list"); loadFileList(); adapter.notifyDataSetChanged(); updateCurrentDirectoryTextView(); Log.d(LOGTAG, path.getAbsolutePath()); } else {// if(sel.canRead()) { showToast("Path does not exist or cannot be read"); }// } else {//if(sel.canRead()) { }// if (sel.isDirectory()) { // File picked or an empty directory message clicked else {// if (sel.isDirectory()) { Log.d(LOGTAG, "item clicked"); if (!directoryShownIsEmpty) { Log.d(LOGTAG, "File selected:" + chosenFile); returnFileFinishActivity(sel.getAbsolutePath()); } }// else {//if (sel.isDirectory()) { }// public void onClick(DialogInterface dialog, int which) { });// lView.setOnClickListener( }// private void initializeFileListView() { private void returnDirectoryFinishActivity() { Intent retIntent = new Intent(); retIntent.putExtra(returnDirectoryParameter, path.getAbsolutePath()); this.setResult(RESULT_OK, retIntent); this.finish(); }// END private void returnDirectoryFinishActivity() { private void returnFileFinishActivity(String filePath) { Intent retIntent = new Intent(); retIntent.putExtra(returnFileParameter, filePath); this.setResult(RESULT_OK, retIntent); this.finish(); }// END private void returnDirectoryFinishActivity() { private void loadFileList() { try { path.mkdirs(); } catch (SecurityException e) { Log.e(LOGTAG, "unable to write on the sd card "); } fileList.clear(); if (path.exists() && path.canRead()) { FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String filename) { File sel = new File(dir, filename); boolean showReadableFile = showHiddenFilesAndDirs || sel.canRead(); // Filters based on whether the file is hidden or not if (currentAction == SELECT_DIRECTORY) { return (sel.isDirectory() && showReadableFile); } if (currentAction == SELECT_FILE) { // If it is a file check the extension if provided if (sel.isFile() && filterFileExtension != null) { return (showReadableFile && sel.getName().endsWith( filterFileExtension)); } return (showReadableFile); } return true; }// public boolean accept(File dir, String filename) { };// FilenameFilter filter = new FilenameFilter() { String[] fList = path.list(filter); this.directoryShownIsEmpty = false; for (int i = 0; i < fList.length; i++) { // Convert into file path File sel = new File(path, fList[i]); Log.d(LOGTAG, "File:" + fList[i] + " readable:" + (Boolean.valueOf(sel.canRead())).toString()); int drawableID = R.drawable.file_icon; boolean canRead = sel.canRead(); // Set drawables if (sel.isDirectory()) { if (canRead) { drawableID = R.drawable.folder_icon; } else { drawableID = R.drawable.folder_icon_light; } } fileList.add(i, new Item(fList[i], drawableID, canRead)); }// for (int i = 0; i < fList.length; i++) { if (fileList.size() == 0) { // Log.d(LOGTAG, "This directory is empty"); this.directoryShownIsEmpty = true; fileList.add(0, new Item("Directory is empty", -1, true)); } else {// sort non empty list Collections.sort(fileList, new ItemFileNameComparator()); } } else { Log.e(LOGTAG, "path does not exist or cannot be read"); } // Log.d(TAG, "loadFileList finished"); }// private void loadFileList() { private void createFileListAdapter() { adapter = new ArrayAdapter<Item>(this, android.R.layout.select_dialog_item, android.R.id.text1, fileList) { @Override public View getView(int position, View convertView, ViewGroup parent) { // creates view View view = super.getView(position, convertView, parent); TextView textView = (TextView) view .findViewById(android.R.id.text1); // put the image on the text view int drawableID = 0; if (fileList.get(position).icon != -1) { // If icon == -1, then directory is empty drawableID = fileList.get(position).icon; } textView.setCompoundDrawablesWithIntrinsicBounds(drawableID, 0, 0, 0); textView.setEllipsize(null); // add margin between image and text (support various screen // densities) // int dp5 = (int) (5 * // getResources().getDisplayMetrics().density + 0.5f); int dp3 = (int) (3 * getResources().getDisplayMetrics().density + 0.5f); // TODO: change next line for empty directory, so text will be // centered textView.setCompoundDrawablePadding(dp3); textView.setBackgroundColor(Color.LTGRAY); return view; }// public View getView(int position, View convertView, ViewGroup };// adapter = new ArrayAdapter<Item>(this, }// private createFileListAdapter(){ private class Item { public String file; public int icon; public boolean canRead; public Item(String file, Integer icon, boolean canRead) { this.file = file; this.icon = icon; } @Override public String toString() { return file; } }// END private class Item { private class ItemFileNameComparator implements Comparator<Item> { public int compare(Item lhs, Item rhs) { return lhs.file.toLowerCase().compareTo(rhs.file.toLowerCase()); } } public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { Log.d(LOGTAG, "ORIENTATION_LANDSCAPE"); } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { Log.d(LOGTAG, "ORIENTATION_PORTRAIT"); } // Layout apparently changes itself, only have to provide good onMeasure // in custom components // TODO: check with keyboard // if(newConfig.keyboard == Configuration.KEYBOARDHIDDEN_YES) }// END public void onConfigurationChanged(Configuration newConfig) { public static long getFreeSpace(String path) { StatFs stat = new StatFs(path); long availSize = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize(); return availSize; }// END public static long getFreeSpace(String path) { public static String formatBytes(long bytes) { // TODO: add flag to which part is needed (e.g. GB, MB, KB or bytes) String retStr = ""; // One binary gigabyte equals 1,073,741,824 bytes. if (bytes > 1073741824) {// Add GB long gbs = bytes / 1073741824; retStr += (new Long(gbs)).toString() + "GB "; bytes = bytes - (gbs * 1073741824); } // One MB - 1048576 bytes if (bytes > 1048576) {// Add GB long mbs = bytes / 1048576; retStr += (new Long(mbs)).toString() + "MB "; bytes = bytes - (mbs * 1048576); } if (bytes > 1024) { long kbs = bytes / 1024; retStr += (new Long(kbs)).toString() + "KB"; bytes = bytes - (kbs * 1024); } else retStr += (new Long(bytes)).toString() + " bytes"; return retStr; }// public static String formatBytes(long bytes){ }// END public class FileBrowserActivity extends Activity {
private void setInitialDirectory() { Intent thisInt = this.getIntent(); String requestedStartDir = thisInt .getStringExtra(startDirectoryParameter); if (requestedStartDir != null && requestedStartDir.length() > 0) {// if(requestedStartDir!=null File tempFile = new File(requestedStartDir); if (tempFile.isDirectory()) this.path = tempFile; }// if(requestedStartDir!=null if (this.path == null) {// No or invalid directory supplied in intent // parameter if (Environment.getExternalStorageDirectory().isDirectory() && Environment.getExternalStorageDirectory().canRead()) path = Environment.getExternalStorageDirectory(); else path = new File("/"); }// if(this.path==null) {//No or invalid directory supplied in intent // parameter }// private void setInitialDirectory() { private void parseDirectoryPath() { pathDirsList.clear(); String pathString = path.getAbsolutePath(); String[] parts = pathString.split("/"); int i = 0; while (i < parts.length) { pathDirsList.add(parts[i]); i++; } } private void initializeButtons() { Button upDirButton = (Button) this.findViewById(R.id.upDirectoryButton); upDirButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Log.d(LOGTAG, "onclick for upDirButton"); loadDirectoryUp(); loadFileList(); adapter.notifyDataSetChanged(); updateCurrentDirectoryTextView(); } });// upDirButton.setOnClickListener( Button selectFolderButton = (Button) this .findViewById(R.id.selectCurrentDirectoryButton); if (currentAction == SELECT_DIRECTORY) { selectFolderButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Log.d(LOGTAG, "onclick for selectFolderButton"); returnDirectoryFinishActivity(); } }); } else {// if(currentAction == this.SELECT_DIRECTORY) { selectFolderButton.setVisibility(View.GONE); }// } else {//if(currentAction == this.SELECT_DIRECTORY) { }// private void initializeButtons() { private void loadDirectoryUp() { // present directory removed from list String s = pathDirsList.remove(pathDirsList.size() - 1); // path modified to exclude present directory path = new File(path.toString().substring(0, path.toString().lastIndexOf(s))); fileList.clear(); } private void updateCurrentDirectoryTextView() { int i = 0; String curDirString = ""; while (i < pathDirsList.size()) { curDirString += pathDirsList.get(i) + "/"; i++; } if (pathDirsList.size() == 0) { ((Button) this.findViewById(R.id.upDirectoryButton)) .setEnabled(false); curDirString = "/"; } else ((Button) this.findViewById(R.id.upDirectoryButton)) .setEnabled(true); long freeSpace = getFreeSpace(curDirString); String formattedSpaceString = formatBytes(freeSpace); if (freeSpace == 0) { Log.d(LOGTAG, "NO FREE SPACE"); File currentDir = new File(curDirString); if(!currentDir.canWrite()) formattedSpaceString = "NON Writable"; } ((Button) this.findViewById(R.id.selectCurrentDirectoryButton)) .setText("Select\n[" + formattedSpaceString + "]"); ((TextView) this.findViewById(R.id.currentDirectoryTextView)) .setText("Current directory: " + curDirString); }// END private void updateCurrentDirectoryTextView() { private void showToast(String message) { Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } private void initializeFileListView() { ListView lView = (ListView) this.findViewById(R.id.fileListView); lView.setBackgroundColor(Color.LTGRAY); LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); lParam.setMargins(15, 5, 15, 5); lView.setAdapter(this.adapter); lView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { chosenFile = fileList.get(position).file; File sel = new File(path + "/" + chosenFile); Log.d(LOGTAG, "Clicked:" + chosenFile); if (sel.isDirectory()) { if (sel.canRead()) { // Adds chosen directory to list pathDirsList.add(chosenFile); path = new File(sel + ""); Log.d(LOGTAG, "Just reloading the list"); loadFileList(); adapter.notifyDataSetChanged(); updateCurrentDirectoryTextView(); Log.d(LOGTAG, path.getAbsolutePath()); } else {// if(sel.canRead()) { showToast("Path does not exist or cannot be read"); }// } else {//if(sel.canRead()) { }// if (sel.isDirectory()) { // File picked or an empty directory message clicked else {// if (sel.isDirectory()) { Log.d(LOGTAG, "item clicked"); if (!directoryShownIsEmpty) { Log.d(LOGTAG, "File selected:" + chosenFile); returnFileFinishActivity(sel.getAbsolutePath()); } }// else {//if (sel.isDirectory()) { }// public void onClick(DialogInterface dialog, int which) { });// lView.setOnClickListener( }// private void initializeFileListView() { private void returnDirectoryFinishActivity() { Intent retIntent = new Intent(); retIntent.putExtra(returnDirectoryParameter, path.getAbsolutePath()); this.setResult(RESULT_OK, retIntent); this.finish(); }// END private void returnDirectoryFinishActivity() { private void returnFileFinishActivity(String filePath) { Intent retIntent = new Intent(); retIntent.putExtra(returnFileParameter, filePath); this.setResult(RESULT_OK, retIntent); this.finish(); }// END private void returnDirectoryFinishActivity() { private void loadFileList() { try { path.mkdirs(); } catch (SecurityException e) { Log.e(LOGTAG, "unable to write on the sd card "); } fileList.clear(); if (path.exists() && path.canRead()) { FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String filename) { File sel = new File(dir, filename); boolean showReadableFile = showHiddenFilesAndDirs || sel.canRead(); // Filters based on whether the file is hidden or not if (currentAction == SELECT_DIRECTORY) { return (sel.isDirectory() && showReadableFile); } if (currentAction == SELECT_FILE) { // If it is a file check the extension if provided if (sel.isFile() && filterFileExtension != null) { return (showReadableFile && sel.getName().endsWith( filterFileExtension)); } return (showReadableFile); } return true; }// public boolean accept(File dir, String filename) { };// FilenameFilter filter = new FilenameFilter() { String[] fList = path.list(filter); this.directoryShownIsEmpty = false; for (int i = 0; i < fList.length; i++) { // Convert into file path File sel = new File(path, fList[i]); Log.d(LOGTAG, "File:" + fList[i] + " readable:" + (Boolean.valueOf(sel.canRead())).toString()); int drawableID = R.drawable.file_icon; boolean canRead = sel.canRead(); // Set drawables if (sel.isDirectory()) { if (canRead) { drawableID = R.drawable.folder_icon; } else { drawableID = R.drawable.folder_icon_light; } } fileList.add(i, new Item(fList[i], drawableID, canRead)); }// for (int i = 0; i < fList.length; i++) { if (fileList.size() == 0) { // Log.d(LOGTAG, "This directory is empty"); this.directoryShownIsEmpty = true; fileList.add(0, new Item("Directory is empty", -1, true)); } else {// sort non empty list Collections.sort(fileList, new ItemFileNameComparator()); } } else { Log.e(LOGTAG, "path does not exist or cannot be read"); } // Log.d(TAG, "loadFileList finished"); }// private void loadFileList() { private void createFileListAdapter() { adapter = new ArrayAdapter<Item>(this, android.R.layout.select_dialog_item, android.R.id.text1, fileList) { @Override public View getView(int position, View convertView, ViewGroup parent) { // creates view View view = super.getView(position, convertView, parent); TextView textView = (TextView) view .findViewById(android.R.id.text1); // put the image on the text view int drawableID = 0; if (fileList.get(position).icon != -1) { // If icon == -1, then directory is empty drawableID = fileList.get(position).icon; } textView.setCompoundDrawablesWithIntrinsicBounds(drawableID, 0, 0, 0); textView.setEllipsize(null); // add margin between image and text (support various screen // densities) // int dp5 = (int) (5 * // getResources().getDisplayMetrics().density + 0.5f); int dp3 = (int) (3 * getResources().getDisplayMetrics().density + 0.5f); // TODO: change next line for empty directory, so text will be // centered textView.setCompoundDrawablePadding(dp3); textView.setBackgroundColor(Color.LTGRAY); return view; }// public View getView(int position, View convertView, ViewGroup };// adapter = new ArrayAdapter<Item>(this, }// private createFileListAdapter(){ private class Item { public String file; public int icon; public boolean canRead; public Item(String file, Integer icon, boolean canRead) { this.file = file; this.icon = icon; } @Override public String toString() { return file; } }// END private class Item { private class ItemFileNameComparator implements Comparator<Item> { public int compare(Item lhs, Item rhs) { return lhs.file.toLowerCase().compareTo(rhs.file.toLowerCase()); } } public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { Log.d(LOGTAG, "ORIENTATION_LANDSCAPE"); } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { Log.d(LOGTAG, "ORIENTATION_PORTRAIT"); } // Layout apparently changes itself, only have to provide good onMeasure // in custom components // TODO: check with keyboard // if(newConfig.keyboard == Configuration.KEYBOARDHIDDEN_YES) }// END public void onConfigurationChanged(Configuration newConfig) { public static long getFreeSpace(String path) { StatFs stat = new StatFs(path); long availSize = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize(); return availSize; }// END public static long getFreeSpace(String path) { public static String formatBytes(long bytes) { // TODO: add flag to which part is needed (e.g. GB, MB, KB or bytes) String retStr = ""; // One binary gigabyte equals 1,073,741,824 bytes. if (bytes > 1073741824) {// Add GB long gbs = bytes / 1073741824; retStr += (new Long(gbs)).toString() + "GB "; bytes = bytes - (gbs * 1073741824); } // One MB - 1048576 bytes if (bytes > 1048576) {// Add GB long mbs = bytes / 1048576; retStr += (new Long(mbs)).toString() + "MB "; bytes = bytes - (mbs * 1048576); } if (bytes > 1024) { long kbs = bytes / 1024; retStr += (new Long(kbs)).toString() + "KB"; bytes = bytes - (kbs * 1024); } else retStr += (new Long(bytes)).toString() + " bytes"; return retStr; }// public static String formatBytes(long bytes){ }// END public class FileBrowserActivity extends Activity {
diff --git a/savant.snp/src/savant/snp/SNPFinderPlugin.java b/savant.snp/src/savant/snp/SNPFinderPlugin.java index 76adeea7..25349b32 100644 --- a/savant.snp/src/savant/snp/SNPFinderPlugin.java +++ b/savant.snp/src/savant/snp/SNPFinderPlugin.java @@ -1,643 +1,643 @@ /* * Copyright 2010 University of Toronto * * 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 savant.snp; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JTextArea; import javax.swing.JToolBar; import javax.swing.event.ChangeListener; import javax.swing.event.ChangeEvent; import net.sf.samtools.Cigar; import net.sf.samtools.CigarElement; import net.sf.samtools.CigarOperator; import net.sf.samtools.SAMRecord; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import savant.api.adapter.GenomeAdapter; import savant.api.adapter.TrackAdapter; import savant.api.util.BookmarkUtils; import savant.api.util.GenomeUtils; import savant.api.util.NavigationUtils; import savant.api.util.TrackUtils; import savant.controller.LocationController; import savant.controller.event.LocationChangeCompletedListener; import savant.controller.event.LocationChangedEvent; import savant.controller.event.TrackListChangedEvent; import savant.controller.event.TrackListChangedListener; import savant.data.types.BAMIntervalRecord; import savant.data.types.Record; import savant.file.DataFormat; import savant.plugin.SavantPanelPlugin; import savant.snp.Pileup.Nucleotide; public class SNPFinderPlugin extends SavantPanelPlugin implements LocationChangeCompletedListener, TrackListChangedListener { private static final Log LOG = LogFactory.getLog(SNPFinderPlugin.class); private final int MAX_RANGE_TO_SEARCH = 5000; private JTextArea info; private boolean isSNPFinderOn = true; private int sensitivity = 80; private int transparency = 50; private byte[] sequence; private Map<TrackAdapter, JPanel> trackToCanvasMap; private Map<TrackAdapter, List<Pileup>> trackToPilesMap; private Map<TrackAdapter, List<Pileup>> trackToSNPsMap; private Map<TrackAdapter, List<Pileup>> snpsFound; //private Map<Track,JPanel> lastTrackToCanvasMapDrawn; /* == INITIALIZATION == */ /* INITIALIZE THE SNP FINDER */ @Override public void init(JPanel canvas) { NavigationUtils.addLocationChangeListener(this); TrackUtils.addTracksChangedListener(this); snpsFound = new HashMap<TrackAdapter, List<Pileup>>(); setupGUI(canvas); addMessage("SNP finder initialized"); } @Override public String getTitle() { return "SNP Finder"; } /* INIT THE UI */ private void setupGUI(JPanel panel) { JToolBar tb = new JToolBar(); tb.setName("SNP Finder Toolbar"); JLabel lab_on = new JLabel("On: "); JCheckBox cb_on = new JCheckBox(); cb_on.setSelected(isSNPFinderOn); cb_on.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setIsOn(!isSNPFinderOn); addMessage("Turning SNP finder " + (isSNPFinderOn ? "on" : "off")); } }); JLabel lab_sensitivity = new JLabel("Sensitivity: "); final JSlider sens_slider = new JSlider(0, 100); sens_slider.setValue(sensitivity); final JLabel lab_sensitivity_status = new JLabel("" + sens_slider.getValue()); sens_slider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { lab_sensitivity_status.setText("" + sens_slider.getValue()); setSensitivity(sens_slider.getValue()); } }); sens_slider.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { addMessage("Changed sensitivity to " + sensitivity); } }); JLabel lab_trans = new JLabel("Transparency: "); final JSlider trans_slider = new JSlider(0, 100); trans_slider.setValue(transparency); final JLabel lab_transparency_status = new JLabel("" + trans_slider.getValue()); trans_slider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { lab_transparency_status.setText("" + trans_slider.getValue()); setTransparency(trans_slider.getValue()); } }); trans_slider.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { addMessage("Changed transparency to " + transparency); } }); panel.setLayout(new BorderLayout()); tb.add(lab_on); tb.add(cb_on); tb.add(new JToolBar.Separator()); tb.add(lab_sensitivity); tb.add(sens_slider); tb.add(lab_sensitivity_status); tb.add(new JToolBar.Separator()); tb.add(lab_trans); tb.add(trans_slider); tb.add(lab_transparency_status); panel.add(tb, BorderLayout.NORTH); info = new JTextArea(); JScrollPane scrollPane = new JScrollPane(info); panel.add(scrollPane, BorderLayout.CENTER); } /** * Add info to the UI. */ private void addMessage(String msg) { info.setText(String.format("%s[%tT] %s\n", info.getText(), new Date(), msg)); info.setCaretPosition(info.getText().length()); } /** * Retrieve canvases. * * @return */ private List<PileupPanel> getPileupPanels() { List<PileupPanel> panels = new ArrayList<PileupPanel>(); if (trackToCanvasMap != null) { for (JPanel p : this.trackToCanvasMap.values()) { try { panels.add((PileupPanel) p.getComponent(0)); } catch (ArrayIndexOutOfBoundsException e) {} } } return panels; } /** * Range change. * * @param event */ @Override public void locationChangeCompleted(LocationChangedEvent event) { setSequence(); if (sequence != null) { updateTrackCanvasMap(); runSNPFinder(); } } /** * Track change. */ @Override public void trackListChanged(TrackListChangedEvent event) { //updateTrackCanvasMap(); } /** * Refresh list of canvases. */ private void updateTrackCanvasMap() { if (trackToCanvasMap == null) { trackToCanvasMap = new HashMap<TrackAdapter, JPanel>(); } Map<TrackAdapter, JPanel> newmap = new HashMap<TrackAdapter, JPanel>(); for (TrackAdapter t : TrackUtils.getTracks()) { if (t.getDataSource().getDataFormat() == DataFormat.INTERVAL_BAM) { if(trackToCanvasMap.containsKey(t) && trackToCanvasMap.get(t) != null){ newmap.put(t, trackToCanvasMap.get(t)); } else { JPanel canvas = t.getLayerCanvas(); if(canvas != null){ newmap.put(t, canvas); } } } } trackToCanvasMap = newmap; } /** * Set this SNP finder on/off. * * @param isOn */ private void setIsOn(boolean isOn) { this.isSNPFinderOn = isOn; List<PileupPanel> panels = this.getPileupPanels(); for (PileupPanel p : panels) { p.setIsOn(isSNPFinderOn); } this.repaintPileupPanels(); } /** * Change the sensitivity of the finder. */ private void setSensitivity(int s) { sensitivity = s; this.doEverything(); } /** * Change the transparency of the renderer. */ private void setTransparency(int t) { transparency = t; List<PileupPanel> panels = this.getPileupPanels(); for (PileupPanel p : panels) { p.setTransparency(this.transparency); } repaintPileupPanels(); } /** * Run the finder. */ private void runSNPFinder() { if (isSNPFinderOn) { if (NavigationUtils.getCurrentRange().getLength() > MAX_RANGE_TO_SEARCH) { addMessage("Won't look for SNPs above range of " + MAX_RANGE_TO_SEARCH + " basepairs"); return; } //System.out.println("checking for snps"); doEverything(); } //System.out.println("done checking for snps"); } /** * Do everything. */ private void doEverything() { if (sequence == null) { setSequence(); } if (sequence != null) { updateTrackCanvasMap(); createPileups(); callSNPs(); drawPiles(); } } /** * Pile up. */ private void createPileups() { if (this.trackToPilesMap != null) { trackToPilesMap.clear(); } trackToPilesMap = new HashMap<TrackAdapter, List<Pileup>>(); for (TrackAdapter t : trackToCanvasMap.keySet()) { try { //List<Integer> snps = int startPosition = NavigationUtils.getCurrentRange().getFrom(); List<Pileup> piles = makePileupsFromSAMRecords(t.getName(), t.getDataInRange(), sequence, startPosition); this.trackToPilesMap.put(t, piles); //drawPiles(piles, trackToCanvasMap.get(t)); //addMessag(snps.) } catch (IOException ex) { addMessage("Error: " + ex.getMessage()); break; } //addMessag(snps.) } } /** * Make pileups for SAM records. */ private List<Pileup> makePileupsFromSAMRecords(String trackName, List<Record> samRecords, byte[] sequence, int startPosition) throws IOException { //addMessage("Examining each position"); List<Pileup> pileups = new ArrayList<Pileup>(); // make the pileups int length = sequence.length; for (int i = 0; i < length; i++) { pileups.add(new Pileup(trackName, startPosition + i, Pileup.getNucleotide(sequence[i]))); } //System.out.println("Pileup start: " + startPosition); //FIXME: this is here to prevent a null pointer exception seen once that //could not be reproduced. SamRecords should never be null... if(samRecords == null) return pileups; // go through the samrecords and edit the pileups for (Record r : samRecords) { SAMRecord sr = ((BAMIntervalRecord)r).getSamRecord(); updatePileupsFromSAMRecord(pileups, GenomeUtils.getGenome(), sr, startPosition); } //addMessage("Done examining each position"); return pileups; } /* UPDATE PILEUP INFORMATION FROM SAM RECORD */ private void updatePileupsFromSAMRecord(List<Pileup> pileups, GenomeAdapter genome, SAMRecord samRecord, int startPosition) throws IOException { // the start and end of the alignment int alignmentStart = samRecord.getAlignmentStart(); int alignmentEnd = samRecord.getAlignmentEnd(); // the read sequence byte[] readBases = samRecord.getReadBases(); boolean sequenceSaved = readBases.length > 0; // true iff read sequence is set // return if no bases (can't be used for SNP calling) if (!sequenceSaved) { return; } // the reference sequence //byte[] refSeq = genome.getSequence(new Range(alignmentStart, alignmentEnd)).getBytes(); - byte[] refSeq = genome.getSequence(NavigationUtils.getCurrentReferenceName(), NavigationUtils.createRange(alignmentStart, alignmentEnd)); + //byte[] refSeq = genome.getSequence(NavigationUtils.getCurrentReferenceName(), NavigationUtils.createRange(alignmentStart, alignmentEnd)); // get the cigar object for this alignment Cigar cigar = samRecord.getCigar(); // set cursors for the reference and read int sequenceCursor = alignmentStart; int readCursor = alignmentStart; //System.out.println("Alignment start: " + alignmentStart); int pileupcursor = (int) (alignmentStart - startPosition); // cigar variables CigarOperator operator; int operatorLength; // consider each cigar element for (CigarElement cigarElement : cigar.getCigarElements()) { operatorLength = cigarElement.getLength(); operator = cigarElement.getOperator(); // delete if (operator == CigarOperator.D) { // [ DRAW ] } // insert else if (operator == CigarOperator.I) { // [ DRAW ] } // match **or mismatch** else if (operator == CigarOperator.M) { // some SAM files do not contain the read bases if (sequenceSaved) { // determine if there's a mismatch for (int i = 0; i < operatorLength; i++) { int refIndex = sequenceCursor - alignmentStart + i; int readIndex = readCursor - alignmentStart + i; byte[] readBase = new byte[1]; readBase[0] = readBases[readIndex]; Nucleotide readN = Pileup.getNucleotide(readBase[0]); - int j = i + (int) (alignmentStart - startPosition); + int j = i + (int) (sequenceCursor - startPosition); //for (int j = pileupcursor; j < operatorLength; j++) { if (j >= 0 && j < pileups.size()) { Pileup p = pileups.get(j); p.pileOn(readN); // /System.out.println("(P) " + readN + "\t@\t" + p.getPosition()); } //} } } } // skipped else if (operator == CigarOperator.N) { // draw nothing } // padding else if (operator == CigarOperator.P) { // draw nothing } // hard clip else if (operator == CigarOperator.H) { // draw nothing } // soft clip else if (operator == CigarOperator.S) { // draw nothing } if (operator.consumesReadBases()) { readCursor += operatorLength; } if (operator.consumesReferenceBases()) { sequenceCursor += operatorLength; pileupcursor += operatorLength; } } } private void addSNPBookmarks() { } /** * Call SNPs for all tracks. */ private void callSNPs() { if (this.trackToSNPsMap != null) { this.trackToSNPsMap.clear(); } this.trackToSNPsMap = new HashMap<TrackAdapter, List<Pileup>>(); for (TrackAdapter t : trackToCanvasMap.keySet()) { List<Pileup> piles = trackToPilesMap.get(t); List<Pileup> snps = callSNPsFromPileups(piles, sequence); this.trackToSNPsMap.put(t, snps); addFoundSNPs(t, snps); } } /** * Call SNP for piles for current sequence. */ private List<Pileup> callSNPsFromPileups(List<Pileup> piles, byte[] sequence) { //addMessage("Calling SNPs"); List<Pileup> snps = new ArrayList<Pileup>(); int length = sequence.length; Pileup.Nucleotide n; Pileup p; for (int i = 0; i < length; i++) { n = Pileup.getNucleotide(sequence[i]); p = piles.get(i); double confidence = p.getSNPNucleotideConfidence()*100; /* System.out.println("Position: " + p.getPosition()); System.out.println("\tAverage coverage: " + p.getCoverageProportion(n)); System.out.println("\tAverage quality: " + p.getAverageQuality(n)); System.out.println("\tConfidence: " + confidence); System.out.println("\tSensitivity: " + sensitivity); */ if (confidence > 100-this.sensitivity) { //System.out.println("== Adding " + p.getPosition() + " as SNP"); snps.add(p); } } addMessage(snps.size() + " SNPs found"); //addMessage("Done calling SNPs"); return snps; } /* == RENDERING == */ /** * Repaint canvases (e.g. because of change in transparency). */ private void repaintPileupPanels() { List<PileupPanel> canvases = this.getPileupPanels(); for (PileupPanel c : canvases) { c.repaint(); c.revalidate(); } } /** * Draw piles on panels for all Tracks. */ private void drawPiles() { //lastTrackToCanvasMapDrawn = trackToCanvasMap; //System.out.println("Drawing annotations"); for (TrackAdapter t : trackToSNPsMap.keySet()) { List<Pileup> pile = trackToSNPsMap.get(t); drawPiles(pile, trackToCanvasMap.get(t)); } //System.out.println("Done drawing annotations"); } /** * Draw piles on panel. */ private void drawPiles(List<Pileup> piles, JPanel p) { p.removeAll(); PileupPanel pup = new PileupPanel(piles); pup.setTransparency(this.transparency); p.setLayout(new BorderLayout()); p.add(pup, BorderLayout.CENTER); this.repaintPileupPanels(); } /** * Set reference sequence. */ private void setSequence() { sequence = null; if (GenomeUtils.isGenomeLoaded() && LocationController.getInstance().getRange().getLength() < this.MAX_RANGE_TO_SEARCH) { try { sequence = GenomeUtils.getGenome().getSequence(NavigationUtils.getCurrentReferenceName(), NavigationUtils.getCurrentRange()); } catch (IOException ex) { addMessage("Error: could not get sequence"); return; } } else { addMessage("Error: no reference sequence loaded"); return; } } private boolean foundSNPAlready(TrackAdapter t, Pileup p) { if (snpsFound.containsKey(t) && snpsFound.get(t).contains(p)) { //System.out.println(p.getPosition() + " found already"); return true; } else { //System.out.println(p.getPosition() + " is new"); return false; } } private void addFoundSNPs(TrackAdapter t, List<Pileup> snps) { for (Pileup snp : snps) { addFoundSNP(t,snp); } } private void addFoundSNP(TrackAdapter t, Pileup snp) { if (!this.foundSNPAlready(t, snp)) { if (!snpsFound.containsKey(t)) { List<Pileup> snps = new ArrayList<Pileup>(); snpsFound.put(t, snps); } BookmarkUtils.addBookmark(BookmarkUtils.createBookmark(NavigationUtils.getCurrentReferenceName(), NavigationUtils.createRange(snp.getPosition(), snp.getPosition()), snp.getSNPNucleotide() + "/" + snp.getReferenceNucleotide() + " SNP " + (int) snp.getCoverage(snp.getSNPNucleotide()) + "/" + (int) snp.getCoverage(snp.getReferenceNucleotide()) + " = " + shortenPercentage(snp.getSNPNucleotideConfidence()) + " in " + t.getName())); snpsFound.get(t).add(snp); } } private String shortenPercentage(double p) { String s = ((int) Math.round(p*100)) + ""; return s + "%"; } }
false
true
private void updatePileupsFromSAMRecord(List<Pileup> pileups, GenomeAdapter genome, SAMRecord samRecord, int startPosition) throws IOException { // the start and end of the alignment int alignmentStart = samRecord.getAlignmentStart(); int alignmentEnd = samRecord.getAlignmentEnd(); // the read sequence byte[] readBases = samRecord.getReadBases(); boolean sequenceSaved = readBases.length > 0; // true iff read sequence is set // return if no bases (can't be used for SNP calling) if (!sequenceSaved) { return; } // the reference sequence //byte[] refSeq = genome.getSequence(new Range(alignmentStart, alignmentEnd)).getBytes(); byte[] refSeq = genome.getSequence(NavigationUtils.getCurrentReferenceName(), NavigationUtils.createRange(alignmentStart, alignmentEnd)); // get the cigar object for this alignment Cigar cigar = samRecord.getCigar(); // set cursors for the reference and read int sequenceCursor = alignmentStart; int readCursor = alignmentStart; //System.out.println("Alignment start: " + alignmentStart); int pileupcursor = (int) (alignmentStart - startPosition); // cigar variables CigarOperator operator; int operatorLength; // consider each cigar element for (CigarElement cigarElement : cigar.getCigarElements()) { operatorLength = cigarElement.getLength(); operator = cigarElement.getOperator(); // delete if (operator == CigarOperator.D) { // [ DRAW ] } // insert else if (operator == CigarOperator.I) { // [ DRAW ] } // match **or mismatch** else if (operator == CigarOperator.M) { // some SAM files do not contain the read bases if (sequenceSaved) { // determine if there's a mismatch for (int i = 0; i < operatorLength; i++) { int refIndex = sequenceCursor - alignmentStart + i; int readIndex = readCursor - alignmentStart + i; byte[] readBase = new byte[1]; readBase[0] = readBases[readIndex]; Nucleotide readN = Pileup.getNucleotide(readBase[0]); int j = i + (int) (alignmentStart - startPosition); //for (int j = pileupcursor; j < operatorLength; j++) { if (j >= 0 && j < pileups.size()) { Pileup p = pileups.get(j); p.pileOn(readN); // /System.out.println("(P) " + readN + "\t@\t" + p.getPosition()); } //} } } } // skipped else if (operator == CigarOperator.N) { // draw nothing } // padding else if (operator == CigarOperator.P) { // draw nothing } // hard clip else if (operator == CigarOperator.H) { // draw nothing } // soft clip else if (operator == CigarOperator.S) { // draw nothing } if (operator.consumesReadBases()) { readCursor += operatorLength; } if (operator.consumesReferenceBases()) { sequenceCursor += operatorLength; pileupcursor += operatorLength; } } }
private void updatePileupsFromSAMRecord(List<Pileup> pileups, GenomeAdapter genome, SAMRecord samRecord, int startPosition) throws IOException { // the start and end of the alignment int alignmentStart = samRecord.getAlignmentStart(); int alignmentEnd = samRecord.getAlignmentEnd(); // the read sequence byte[] readBases = samRecord.getReadBases(); boolean sequenceSaved = readBases.length > 0; // true iff read sequence is set // return if no bases (can't be used for SNP calling) if (!sequenceSaved) { return; } // the reference sequence //byte[] refSeq = genome.getSequence(new Range(alignmentStart, alignmentEnd)).getBytes(); //byte[] refSeq = genome.getSequence(NavigationUtils.getCurrentReferenceName(), NavigationUtils.createRange(alignmentStart, alignmentEnd)); // get the cigar object for this alignment Cigar cigar = samRecord.getCigar(); // set cursors for the reference and read int sequenceCursor = alignmentStart; int readCursor = alignmentStart; //System.out.println("Alignment start: " + alignmentStart); int pileupcursor = (int) (alignmentStart - startPosition); // cigar variables CigarOperator operator; int operatorLength; // consider each cigar element for (CigarElement cigarElement : cigar.getCigarElements()) { operatorLength = cigarElement.getLength(); operator = cigarElement.getOperator(); // delete if (operator == CigarOperator.D) { // [ DRAW ] } // insert else if (operator == CigarOperator.I) { // [ DRAW ] } // match **or mismatch** else if (operator == CigarOperator.M) { // some SAM files do not contain the read bases if (sequenceSaved) { // determine if there's a mismatch for (int i = 0; i < operatorLength; i++) { int refIndex = sequenceCursor - alignmentStart + i; int readIndex = readCursor - alignmentStart + i; byte[] readBase = new byte[1]; readBase[0] = readBases[readIndex]; Nucleotide readN = Pileup.getNucleotide(readBase[0]); int j = i + (int) (sequenceCursor - startPosition); //for (int j = pileupcursor; j < operatorLength; j++) { if (j >= 0 && j < pileups.size()) { Pileup p = pileups.get(j); p.pileOn(readN); // /System.out.println("(P) " + readN + "\t@\t" + p.getPosition()); } //} } } } // skipped else if (operator == CigarOperator.N) { // draw nothing } // padding else if (operator == CigarOperator.P) { // draw nothing } // hard clip else if (operator == CigarOperator.H) { // draw nothing } // soft clip else if (operator == CigarOperator.S) { // draw nothing } if (operator.consumesReadBases()) { readCursor += operatorLength; } if (operator.consumesReferenceBases()) { sequenceCursor += operatorLength; pileupcursor += operatorLength; } } }
diff --git a/kerberos-codec/src/main/java/org/apache/directory/shared/kerberos/codec/actions/AbstractReadHostAddress.java b/kerberos-codec/src/main/java/org/apache/directory/shared/kerberos/codec/actions/AbstractReadHostAddress.java index bdcaefd745..1fffb5c62f 100644 --- a/kerberos-codec/src/main/java/org/apache/directory/shared/kerberos/codec/actions/AbstractReadHostAddress.java +++ b/kerberos-codec/src/main/java/org/apache/directory/shared/kerberos/codec/actions/AbstractReadHostAddress.java @@ -1,110 +1,110 @@ /* * 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.directory.shared.kerberos.codec.actions; import org.apache.directory.shared.asn1.ber.Asn1Container; import org.apache.directory.shared.asn1.ber.Asn1Decoder; import org.apache.directory.shared.asn1.ber.grammar.GrammarAction; import org.apache.directory.shared.asn1.ber.tlv.TLV; import org.apache.directory.shared.asn1.codec.DecoderException; import org.apache.directory.shared.i18n.I18n; import org.apache.directory.shared.kerberos.codec.hostAddress.HostAddressContainer; import org.apache.directory.shared.kerberos.components.HostAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The action used to read the HostAddress * * @author <a href="mailto:[email protected]">Apache Directory Project</a> */ public abstract class AbstractReadHostAddress extends GrammarAction { /** The logger */ private static final Logger LOG = LoggerFactory.getLogger( AbstractReadHostAddress.class ); /** Speedup for logs */ private static final boolean IS_DEBUG = LOG.isDebugEnabled(); /** * Instantiates a new AbstractReadAddress action. */ public AbstractReadHostAddress( String name ) { super( name ); } protected abstract void setAddress( HostAddress hostAddress, Asn1Container container ); /** * {@inheritDoc} */ public void action( Asn1Container container ) throws DecoderException { TLV tlv = container.getCurrentTLV(); // The Length should not be null if ( tlv.getLength() == 0 ) { LOG.error( I18n.err( I18n.ERR_04066 ) ); // This will generate a PROTOCOL_ERROR throw new DecoderException( I18n.err( I18n.ERR_04067 ) ); } // Now, let's decode the HostAddress Asn1Decoder hostAddressDecoder = new Asn1Decoder(); HostAddressContainer hostAddressContainer = new HostAddressContainer(); // Passes the Stream to the decoder hostAddressContainer.setStream( container.getStream() ); - // Decode the HostAddresses PDU + // Decode the HostAddress PDU try { hostAddressDecoder.decode( container.getStream(), hostAddressContainer ); } catch ( DecoderException de ) { throw de; } - // Store the HostAddresses in the container + // Store the HostAddress in the container HostAddress hostAddress = hostAddressContainer.getHostAddress(); // Update the expected length for the current TLV tlv.setExpectedLength( tlv.getExpectedLength() - tlv.getLength() ); // Update the parent container.updateParent(); setAddress( hostAddress, container ); if ( IS_DEBUG ) { LOG.debug( "HostAddress : {}", hostAddress ); } } }
false
true
public void action( Asn1Container container ) throws DecoderException { TLV tlv = container.getCurrentTLV(); // The Length should not be null if ( tlv.getLength() == 0 ) { LOG.error( I18n.err( I18n.ERR_04066 ) ); // This will generate a PROTOCOL_ERROR throw new DecoderException( I18n.err( I18n.ERR_04067 ) ); } // Now, let's decode the HostAddress Asn1Decoder hostAddressDecoder = new Asn1Decoder(); HostAddressContainer hostAddressContainer = new HostAddressContainer(); // Passes the Stream to the decoder hostAddressContainer.setStream( container.getStream() ); // Decode the HostAddresses PDU try { hostAddressDecoder.decode( container.getStream(), hostAddressContainer ); } catch ( DecoderException de ) { throw de; } // Store the HostAddresses in the container HostAddress hostAddress = hostAddressContainer.getHostAddress(); // Update the expected length for the current TLV tlv.setExpectedLength( tlv.getExpectedLength() - tlv.getLength() ); // Update the parent container.updateParent(); setAddress( hostAddress, container ); if ( IS_DEBUG ) { LOG.debug( "HostAddress : {}", hostAddress ); } }
public void action( Asn1Container container ) throws DecoderException { TLV tlv = container.getCurrentTLV(); // The Length should not be null if ( tlv.getLength() == 0 ) { LOG.error( I18n.err( I18n.ERR_04066 ) ); // This will generate a PROTOCOL_ERROR throw new DecoderException( I18n.err( I18n.ERR_04067 ) ); } // Now, let's decode the HostAddress Asn1Decoder hostAddressDecoder = new Asn1Decoder(); HostAddressContainer hostAddressContainer = new HostAddressContainer(); // Passes the Stream to the decoder hostAddressContainer.setStream( container.getStream() ); // Decode the HostAddress PDU try { hostAddressDecoder.decode( container.getStream(), hostAddressContainer ); } catch ( DecoderException de ) { throw de; } // Store the HostAddress in the container HostAddress hostAddress = hostAddressContainer.getHostAddress(); // Update the expected length for the current TLV tlv.setExpectedLength( tlv.getExpectedLength() - tlv.getLength() ); // Update the parent container.updateParent(); setAddress( hostAddress, container ); if ( IS_DEBUG ) { LOG.debug( "HostAddress : {}", hostAddress ); } }
diff --git a/izpack-src/branches/branch-3-8/src/lib/com/izforge/izpack/installer/Unpacker.java b/izpack-src/branches/branch-3-8/src/lib/com/izforge/izpack/installer/Unpacker.java index 674a1290..ef53674d 100644 --- a/izpack-src/branches/branch-3-8/src/lib/com/izforge/izpack/installer/Unpacker.java +++ b/izpack-src/branches/branch-3-8/src/lib/com/izforge/izpack/installer/Unpacker.java @@ -1,1178 +1,1178 @@ /* * $Id$ * IzPack - Copyright 2001-2006 Julien Ponge, All Rights Reserved. * * http://www.izforge.com/izpack/ * http://developer.berlios.de/projects/izpack/ * * 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 java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.lang.reflect.Constructor; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Stack; import java.util.TreeSet; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.apache.regexp.RE; import org.apache.regexp.RECompiler; import org.apache.regexp.RESyntaxException; import com.izforge.izpack.ExecutableFile; import com.izforge.izpack.LocaleDatabase; import com.izforge.izpack.Pack; import com.izforge.izpack.PackFile; import com.izforge.izpack.ParsableFile; import com.izforge.izpack.UpdateCheck; import com.izforge.izpack.event.InstallerListener; import com.izforge.izpack.util.AbstractUIHandler; import com.izforge.izpack.util.AbstractUIProgressHandler; import com.izforge.izpack.util.FileExecutor; import com.izforge.izpack.util.IoHelper; import com.izforge.izpack.util.OsConstraint; import com.izforge.izpack.util.VariableSubstitutor; /** * Unpacker class. * * @author Julien Ponge * @author Johannes Lehtinen */ public class Unpacker extends Thread { /** The installdata. */ private AutomatedInstallData idata; /** The installer listener. */ private AbstractUIProgressHandler handler; /** The uninstallation data. */ private UninstallData udata; /** The variables substitutor. */ private VariableSubstitutor vs; /** The instances of the unpacker objects. */ private static HashMap instances = new HashMap(); /** The absolute path of the installation. (NOT the canonical!) */ private File absolute_installpath; /** The packs locale database. */ private LocaleDatabase langpack = null; /** Interrupt flag if global interrupt is desired. */ private static boolean interruptDesired = false; /** Do not perform a interrupt call. */ private static boolean discardInterrupt = false; /** The name of the XML file that specifies the panel langpack */ private static final String LANG_FILE_NAME = "packsLang.xml"; public static final String ALIVE = "alive"; public static final String INTERRUPT = "doInterrupt"; public static final String INTERRUPTED = "interruppted"; /** * The constructor. * * @param idata The installation data. * @param handler The installation progress handler. */ public Unpacker(AutomatedInstallData idata, AbstractUIProgressHandler handler) { super("IzPack - Unpacker thread"); try { String resource = LANG_FILE_NAME + "_" + idata.localeISO3; this.langpack = new LocaleDatabase(ResourceManager.getInstance().getInputStream( resource)); } catch (Throwable exception) {} this.idata = idata; this.handler = handler; // Initialize the variable substitutor vs = new VariableSubstitutor(idata.getVariables()); } /** * Returns a copy of the active unpacker instances. * * @return a copy of active unpacker instances */ public static HashMap getRunningInstances() { synchronized (instances) { // Return a shallow copy to prevent a // ConcurrentModificationException. return (HashMap) (instances.clone()); } } /** * Adds this to the map of all existent instances of Unpacker. */ private void addToInstances() { synchronized (instances) { instances.put(this, ALIVE); } } /** * Removes this from the map of all existent instances of Unpacker. */ private void removeFromInstances() { synchronized (instances) { instances.remove(this); } } /** * Initiate interrupt of all alive Unpacker. This method does not interrupt the Unpacker objects * else it sets only the interrupt flag for the Unpacker objects. The dispatching of interrupt * will be performed by the Unpacker objects self. */ private static void setInterruptAll() { synchronized (instances) { Iterator iter = instances.keySet().iterator(); while (iter.hasNext()) { Object key = iter.next(); if (instances.get(key).equals(ALIVE)) { instances.put(key, INTERRUPT); } } // Set global flag to allow detection of it in other classes. // Do not set it to thread because an exec will then be stoped. setInterruptDesired(true); } } /** * Initiate interrupt of all alive Unpacker and waits until all Unpacker are interrupted or the * wait time has arrived. If the doNotInterrupt flag in InstallerListener is set to true, the * interrupt will be discarded. * * @param waitTime wait time in millisecounds * @return true if the interrupt will be performed, false if the interrupt will be discarded */ public static boolean interruptAll(long waitTime) { long t0 = System.currentTimeMillis(); if (isDiscardInterrupt()) return (false); setInterruptAll(); while (!isInterruptReady()) { if (System.currentTimeMillis() - t0 > waitTime) return (true); try { Thread.sleep(100); } catch (InterruptedException e) {} } return (true); } private static boolean isInterruptReady() { synchronized (instances) { Iterator iter = instances.keySet().iterator(); while (iter.hasNext()) { Object key = iter.next(); if (!instances.get(key).equals(INTERRUPTED)) return (false); } return (true); } } /** * Sets the interrupt flag for this Unpacker to INTERRUPTED if the previos state was INTERRUPT * or INTERRUPTED and returns whether interrupt was initiate or not. * * @return whether interrupt was initiate or not */ private boolean performInterrupted() { synchronized (instances) { Object doIt = instances.get(this); if (doIt != null && (doIt.equals(INTERRUPT) || doIt.equals(INTERRUPTED))) { instances.put(this, INTERRUPTED); return (true); } return (false); } } /** * Returns whether interrupt was initiate or not for this Unpacker. * * @return whether interrupt was initiate or not */ private boolean shouldInterrupt() { synchronized (instances) { Object doIt = instances.get(this); if (doIt != null && (doIt.equals(INTERRUPT) || doIt.equals(INTERRUPTED))) { return (true); } return (false); } } /** The run method. */ public void run() { addToInstances(); try { // // Initialisations FileOutputStream out = null; ArrayList parsables = new ArrayList(); ArrayList executables = new ArrayList(); ArrayList updatechecks = new ArrayList(); 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, new Integer( npacks), handler); // 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)); // Custom action listener stuff --- beforePack ---- informListeners(customActions, InstallerListener.BEFORE_PACK, packs.get(i), new Integer(npacks), handler); ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(n)); // 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 || pack.id.equals(""))) { final String name = langpack.getString(pack.id); if (name != null && !name.equals("")) { stepname = name; } } handler.nextStep(stepname, i + 1, nfiles); for (int j = 0; j < nfiles; j++) { // We read the header PackFile pf = (PackFile) objIn.readObject(); 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(); 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); 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 + + " - " + 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 out = new FileOutputStream(pathFile); byte[] buffer = new byte[5120]; long bytesCopied = 0; InputStream pis = objIn; if (pf.isBackReference()) { InputStream is = getPackAsStream(pf.previousPackNumber); 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) { pis = new FileInputStream(pf.sourcePath); } 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"); out.write(buffer, 0, bytesInBuffer); bytesCopied += bytesInBuffer; } // Cleanings 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(); 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(); 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 = (String) 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), new Integer(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"); 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; } // The end :-) handler.stopAction(); } catch (Exception err) { // TODO: finer grained error handling with useful error messages handler.stopAction(); handler.emitError("An error occured", err.toString()); err.printStackTrace(); } finally { removeFromInstances(); } } /** * @param updatechecks */ private void performUpdateChecks(ArrayList updatechecks) { ArrayList include_patterns = new ArrayList(); ArrayList exclude_patterns = new ArrayList(); RECompiler recompiler = new RECompiler(); this.absolute_installpath = new File(idata.getInstallPath()).getAbsoluteFile(); // at first, collect all patterns for (Iterator iter = updatechecks.iterator(); iter.hasNext();) { UpdateCheck uc = (UpdateCheck) iter.next(); if (uc.includesList != null) include_patterns.addAll(preparePatterns(uc.includesList, recompiler)); if (uc.excludesList != null) exclude_patterns.addAll(preparePatterns(uc.excludesList, recompiler)); } // do nothing if no update checks were specified if (include_patterns.size() == 0) return; // now collect all files in the installation directory and figure // out files to check for deletion // use a treeset for fast access TreeSet installed_files = new TreeSet(); for (Iterator if_it = this.udata.getFilesList().iterator(); if_it.hasNext();) { String fname = (String) if_it.next(); File f = new File(fname); if (!f.isAbsolute()) { f = new File(this.absolute_installpath, fname); } installed_files.add(f.getAbsolutePath()); } // now scan installation directory (breadth first), contains Files of // directories to scan // (note: we'll recurse infinitely if there are circular links or // similar nasty things) Stack scanstack = new Stack(); // contains File objects determined for deletion ArrayList files_to_delete = new ArrayList(); try { scanstack.add(absolute_installpath); while (!scanstack.empty()) { File f = (File) scanstack.pop(); File[] files = f.listFiles(); if (files == null) { throw new IOException(f.getPath() + "is not a directory!"); } for (int i = 0; i < files.length; i++) { File newf = files[i]; String newfname = newf.getPath(); // skip files we just installed if (installed_files.contains(newfname)) continue; if (fileMatchesOnePattern(newfname, include_patterns) && (!fileMatchesOnePattern(newfname, exclude_patterns))) { files_to_delete.add(newf); } if (newf.isDirectory()) { scanstack.push(newf); } } } } catch (IOException e) { this.handler.emitError("error while performing update checks", e.toString()); } for (Iterator f_it = files_to_delete.iterator(); f_it.hasNext();) { File f = (File) f_it.next(); if (!f.isDirectory()) // skip directories - they cannot be removed safely yet { this.handler.emitNotification("deleting " + f.getPath()); f.delete(); } } } /** * @param filename * @param patterns * * @return true if the file matched one pattern, false if it did not */ private boolean fileMatchesOnePattern(String filename, ArrayList patterns) { // first check whether any include matches for (Iterator inc_it = patterns.iterator(); inc_it.hasNext();) { RE pattern = (RE) inc_it.next(); if (pattern.match(filename)) { return true; } } return false; } /** * @param list A list of file name patterns (in ant fileset syntax) * @param recompiler The regular expression compiler (used to speed up RE compiling). * * @return List of org.apache.regexp.RE */ private List preparePatterns(ArrayList list, RECompiler recompiler) { ArrayList result = new ArrayList(); for (Iterator iter = list.iterator(); iter.hasNext();) { String element = (String) iter.next(); if ((element != null) && (element.length() > 0)) { // substitute variables in the pattern element = this.vs.substitute(element, "plain"); // check whether the pattern is absolute or relative File f = new File(element); // if it is relative, make it absolute and prepend the // installation path // (this is a bit dangerous...) if (!f.isAbsolute()) { element = new File(this.absolute_installpath, element).toString(); } // now parse the element and construct a regular expression from // it // (we have to parse it one character after the next because // every // character should only be processed once - it's not possible // to get this // correct using regular expression replacing) StringBuffer element_re = new StringBuffer(); int lookahead = -1; int pos = 0; while (pos < element.length()) { char c; if (lookahead != -1) { c = (char) lookahead; lookahead = -1; } else c = element.charAt(pos++); switch (c) { case '/': { element_re.append(File.separator); break; } // escape backslash and dot case '\\': case '.': { element_re.append("\\"); element_re.append(c); break; } case '*': { if (pos == element.length()) { element_re.append("[^" + File.separator + "]*"); break; } lookahead = element.charAt(pos++); // check for "**" if (lookahead == '*') { element_re.append(".*"); // consume second star lookahead = -1; } else { element_re.append("[^" + File.separator + "]*"); // lookahead stays there } break; } default: { element_re.append(c); break; } } // switch } // make sure that the whole expression is matched element_re.append('$'); // replace \ by \\ and create a RE from the result try { result.add(new RE(recompiler.compile(element_re.toString()))); } catch (RESyntaxException e) { this.handler.emitNotification("internal error: pattern \"" + element + "\" produced invalid RE \"" + f.getPath() + "\""); } } } return result; } /** * Puts the uninstaller. * * @exception Exception Description of the Exception */ private void putUninstaller() throws Exception { // get the uninstaller base, returning if not found so that // idata.uninstallOutJar remains null InputStream[] in = new InputStream[2]; in[0] = Unpacker.class.getResourceAsStream("/res/IzPack.uninstaller"); if (in[0] == null) return; // The uninstaller extension is facultative; it will be exist only // if a native library was marked for uninstallation. in[1] = Unpacker.class.getResourceAsStream("/res/IzPack.uninstaller-ext"); // Me make the .uninstaller directory String dest = IoHelper.translatePath("$INSTALL_PATH", vs) + File.separator + "Uninstaller"; String jar = dest + File.separator + idata.info.getUninstallerName(); File pathMaker = new File(dest); pathMaker.mkdirs(); // We log the uninstaller deletion information udata.setUninstallerJarFilename(jar); udata.setUninstallerPath(dest); // We open our final jar file FileOutputStream out = new FileOutputStream(jar); // Intersect a buffer else byte for byte will be written to the file. BufferedOutputStream bos = new BufferedOutputStream(out); ZipOutputStream outJar = new ZipOutputStream(bos); idata.uninstallOutJar = outJar; outJar.setLevel(9); udata.addFile(jar); // We copy the uninstallers HashSet doubles = new HashSet(); for (int i = 0; i < in.length; ++i) { if (in[i] == null) continue; ZipInputStream inRes = new ZipInputStream(in[i]); ZipEntry zentry = inRes.getNextEntry(); while (zentry != null) { // Puts a new entry, but not twice like META-INF if (!doubles.contains(zentry.getName())) { doubles.add(zentry.getName()); outJar.putNextEntry(new ZipEntry(zentry.getName())); // Byte to byte copy int unc = inRes.read(); while (unc != -1) { outJar.write(unc); unc = inRes.read(); } // Next one please inRes.closeEntry(); outJar.closeEntry(); } zentry = inRes.getNextEntry(); } inRes.close(); } // We put the langpack InputStream in2 = Unpacker.class.getResourceAsStream("/langpacks/" + idata.localeISO3 + ".xml"); outJar.putNextEntry(new ZipEntry("langpack.xml")); int read = in2.read(); while (read != -1) { outJar.write(read); read = in2.read(); } outJar.closeEntry(); } /** * Returns a stream to a pack, location depending on if it's web based. * * @param n The pack number. * @return The stream or null if it could not be found. * @exception Exception Description of the Exception */ private InputStream getPackAsStream(int n) throws Exception { InputStream in = null; String webDirURL = idata.info.getWebDirURL(); if (webDirURL == null) // local { in = Unpacker.class.getResourceAsStream("/packs/pack" + n); } 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" + n + ".jar"; URL url = new URL("jar:" + packURL + "!/packs/pack" + n); // 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 FileNotFoundException(url.toString()); } if( in != null && idata.info.getPackDecoderClassName() != null ) { Class decoder = Class.forName(idata.info.getPackDecoderClassName()); Class[] paramsClasses = new Class[1]; paramsClasses[0] = Class.forName("java.io.InputStream"); Constructor 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; } // CUSTOM ACTION STUFF -------------- start ----------------- /** * Informs all listeners which would be informed at the given action type. * * @param customActions array of lists with the custom action objects * @param action identifier for which callback should be called * @param firstParam first parameter for the call * @param secondParam second parameter for the call * @param thirdParam third parameter for the call */ private void informListeners(List[] customActions, int action, Object firstParam, Object secondParam, Object thirdParam) throws Exception { List listener = null; // select the right action list. switch (action) { case InstallerListener.BEFORE_FILE: case InstallerListener.AFTER_FILE: case InstallerListener.BEFORE_DIR: case InstallerListener.AFTER_DIR: listener = customActions[customActions.length - 1]; break; default: listener = customActions[0]; break; } if (listener == null) return; // Iterate the action list. Iterator iter = listener.iterator(); while (iter.hasNext()) { if (shouldInterrupt()) return; InstallerListener il = (InstallerListener) iter.next(); switch (action) { case InstallerListener.BEFORE_FILE: il.beforeFile((File) firstParam, (PackFile) secondParam); break; case InstallerListener.AFTER_FILE: il.afterFile((File) firstParam, (PackFile) secondParam); break; case InstallerListener.BEFORE_DIR: il.beforeDir((File) firstParam, (PackFile) secondParam); break; case InstallerListener.AFTER_DIR: il.afterDir((File) firstParam, (PackFile) secondParam); break; case InstallerListener.BEFORE_PACK: il.beforePack((Pack) firstParam, (Integer) secondParam, (AbstractUIProgressHandler) thirdParam); break; case InstallerListener.AFTER_PACK: il.afterPack((Pack) firstParam, (Integer) secondParam, (AbstractUIProgressHandler) thirdParam); break; case InstallerListener.BEFORE_PACKS: il.beforePacks((AutomatedInstallData) firstParam, (Integer) secondParam, (AbstractUIProgressHandler) thirdParam); break; case InstallerListener.AFTER_PACKS: il.afterPacks((AutomatedInstallData) firstParam, (AbstractUIProgressHandler) secondParam); break; } } } /** * Returns the defined custom actions split into types including a constructed type for the file * related installer listeners. * * @return array of lists of custom action data like listeners */ private List[] getCustomActions() { String[] listenerNames = AutomatedInstallData.CUSTOM_ACTION_TYPES; List[] retval = new List[listenerNames.length + 1]; int i; for (i = 0; i < listenerNames.length; ++i) { retval[i] = (List) idata.customData.get(listenerNames[i]); if (retval[i] == null) // Make a dummy list, then iterator is ever callable. retval[i] = new ArrayList(); } if (retval[AutomatedInstallData.INSTALLER_LISTENER_INDEX].size() > 0) { // Installer listeners exist // Create file related installer listener list in the last // element of custom action array. i = retval.length - 1; // Should be so, but safe is safe ... retval[i] = new ArrayList(); Iterator iter = ((List) retval[AutomatedInstallData.INSTALLER_LISTENER_INDEX]) .iterator(); while (iter.hasNext()) { // If we get a class cast exception many is wrong and // we must fix it. InstallerListener li = (InstallerListener) iter.next(); if (li.isFileListener()) retval[i].add(li); } } return (retval); } /** * Adds additional unistall data to the uninstall data object. * * @param udata unistall data * @param customData array of lists of custom action data like uninstaller listeners */ private void handleAdditionalUninstallData(UninstallData udata, List[] customData) { // Handle uninstall libs udata.addAdditionalData("__uninstallLibs__", customData[AutomatedInstallData.UNINSTALLER_LIBS_INDEX]); // Handle uninstaller listeners udata.addAdditionalData("uninstallerListeners", customData[AutomatedInstallData.UNINSTALLER_LISTENER_INDEX]); // Handle uninstaller jars udata.addAdditionalData("uninstallerJars", customData[AutomatedInstallData.UNINSTALLER_JARS_INDEX]); } // This method is only used if a file related custom action exist. /** * Creates the given directory recursive and calls the method "afterDir" of each listener with * the current file object and the pack file object. On error an exception is raised. * * @param dest the directory which should be created * @param pf current pack file object * @param customActions all defined custom actions * @return false on error, true else * @throws Exception */ private boolean mkDirsWithEnhancement(File dest, PackFile pf, List[] customActions) throws Exception { String path = "unknown"; if (dest != null) path = dest.getAbsolutePath(); if (dest != null && !dest.exists() && dest.getParentFile() != null) { if (dest.getParentFile().exists()) informListeners(customActions, InstallerListener.BEFORE_DIR, dest, pf, null); if (!dest.mkdir()) { mkDirsWithEnhancement(dest.getParentFile(), pf, customActions); if (!dest.mkdir()) dest = null; } informListeners(customActions, InstallerListener.AFTER_DIR, dest, pf, null); } if (dest == null) { handler.emitError("Error creating directories", "Could not create directory\n" + path); handler.stopAction(); return (false); } return (true); } // CUSTOM ACTION STUFF -------------- end ----------------- /** * Returns whether an interrupt request should be discarded or not. * * @return Returns the discard interrupt flag */ public static synchronized boolean isDiscardInterrupt() { return discardInterrupt; } /** * Sets the discard interrupt flag. * * @param di the discard interrupt flag to set */ public static synchronized void setDiscardInterrupt(boolean di) { discardInterrupt = di; setInterruptDesired(false); } /** * Returns the interrupt desired state. * * @return the interrupt desired state */ public static boolean isInterruptDesired() { return interruptDesired; } /** * @param interruptDesired The interrupt desired flag to set */ private static void setInterruptDesired(boolean interruptDesired) { Unpacker.interruptDesired = interruptDesired; } }
true
true
public void run() { addToInstances(); try { // // Initialisations FileOutputStream out = null; ArrayList parsables = new ArrayList(); ArrayList executables = new ArrayList(); ArrayList updatechecks = new ArrayList(); 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, new Integer( npacks), handler); // 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)); // Custom action listener stuff --- beforePack ---- informListeners(customActions, InstallerListener.BEFORE_PACK, packs.get(i), new Integer(npacks), handler); ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(n)); // 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 || pack.id.equals(""))) { final String name = langpack.getString(pack.id); if (name != null && !name.equals("")) { stepname = name; } } handler.nextStep(stepname, i + 1, nfiles); for (int j = 0; j < nfiles; j++) { // We read the header PackFile pf = (PackFile) objIn.readObject(); 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(); 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); 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 out = new FileOutputStream(pathFile); byte[] buffer = new byte[5120]; long bytesCopied = 0; InputStream pis = objIn; if (pf.isBackReference()) { InputStream is = getPackAsStream(pf.previousPackNumber); 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) { pis = new FileInputStream(pf.sourcePath); } 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"); out.write(buffer, 0, bytesInBuffer); bytesCopied += bytesInBuffer; } // Cleanings 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(); 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(); 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 = (String) 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), new Integer(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"); 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; } // The end :-) handler.stopAction(); } catch (Exception err) { // TODO: finer grained error handling with useful error messages handler.stopAction(); handler.emitError("An error occured", err.toString()); err.printStackTrace(); } finally { removeFromInstances(); } }
public void run() { addToInstances(); try { // // Initialisations FileOutputStream out = null; ArrayList parsables = new ArrayList(); ArrayList executables = new ArrayList(); ArrayList updatechecks = new ArrayList(); 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, new Integer( npacks), handler); // 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)); // Custom action listener stuff --- beforePack ---- informListeners(customActions, InstallerListener.BEFORE_PACK, packs.get(i), new Integer(npacks), handler); ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(n)); // 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 || pack.id.equals(""))) { final String name = langpack.getString(pack.id); if (name != null && !name.equals("")) { stepname = name; } } handler.nextStep(stepname, i + 1, nfiles); for (int j = 0; j < nfiles; j++) { // We read the header PackFile pf = (PackFile) objIn.readObject(); 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(); 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); 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 out = new FileOutputStream(pathFile); byte[] buffer = new byte[5120]; long bytesCopied = 0; InputStream pis = objIn; if (pf.isBackReference()) { InputStream is = getPackAsStream(pf.previousPackNumber); 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) { pis = new FileInputStream(pf.sourcePath); } 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"); out.write(buffer, 0, bytesInBuffer); bytesCopied += bytesInBuffer; } // Cleanings 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(); 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(); 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 = (String) 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), new Integer(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"); 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; } // The end :-) handler.stopAction(); } catch (Exception err) { // TODO: finer grained error handling with useful error messages handler.stopAction(); handler.emitError("An error occured", err.toString()); err.printStackTrace(); } finally { removeFromInstances(); } }
diff --git a/src/org/drftpd/slave/PassiveConnection.java b/src/org/drftpd/slave/PassiveConnection.java index ee868c69..ac7d8e2f 100644 --- a/src/org/drftpd/slave/PassiveConnection.java +++ b/src/org/drftpd/slave/PassiveConnection.java @@ -1,85 +1,89 @@ /* * This file is part of DrFTPD, Distributed FTP Daemon. * * DrFTPD 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. * * DrFTPD 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 DrFTPD; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.drftpd.slave; import net.sf.drftpd.util.PortRange; import org.apache.log4j.Logger; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import javax.net.ServerSocketFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; /** * @author mog * @version $Id$ */ public class PassiveConnection extends Connection { private static final Logger logger = Logger.getLogger(PassiveConnection.class); private ServerSocket _serverSocket; public PassiveConnection(SSLContext ctx, PortRange portRange) throws IOException { if (ctx != null) { _serverSocket = portRange.getPort(ctx.getServerSocketFactory()); } else { _serverSocket = portRange.getPort(ServerSocketFactory.getDefault()); } _serverSocket.setSoTimeout(TIMEOUT); } public Socket connect() throws IOException { - Socket sock = _serverSocket.accept(); - _serverSocket.close(); - _serverSocket = null; + Socket sock = null; + try { + sock = _serverSocket.accept(); + } finally { + _serverSocket.close(); + _serverSocket = null; + } setSockOpts(sock); if (sock instanceof SSLSocket) { SSLSocket sslsock = (SSLSocket) sock; sslsock.setUseClientMode(false); sslsock.startHandshake(); } return sock; } public int getLocalPort() { if (_serverSocket == null) { throw new NullPointerException("_serverSocket == null"); } return _serverSocket.getLocalPort(); } public void abort() { try { _serverSocket.close(); } catch (IOException e) { logger.warn("failed to close() server socket", e); } _serverSocket = null; } }
true
true
public Socket connect() throws IOException { Socket sock = _serverSocket.accept(); _serverSocket.close(); _serverSocket = null; setSockOpts(sock); if (sock instanceof SSLSocket) { SSLSocket sslsock = (SSLSocket) sock; sslsock.setUseClientMode(false); sslsock.startHandshake(); } return sock; }
public Socket connect() throws IOException { Socket sock = null; try { sock = _serverSocket.accept(); } finally { _serverSocket.close(); _serverSocket = null; } setSockOpts(sock); if (sock instanceof SSLSocket) { SSLSocket sslsock = (SSLSocket) sock; sslsock.setUseClientMode(false); sslsock.startHandshake(); } return sock; }
diff --git a/src/org/yaaic/activity/AddServerActivity.java b/src/org/yaaic/activity/AddServerActivity.java index 0975ca0..00997fb 100644 --- a/src/org/yaaic/activity/AddServerActivity.java +++ b/src/org/yaaic/activity/AddServerActivity.java @@ -1,417 +1,417 @@ /* Yaaic - Yet Another Android IRC Client Copyright 2009-2010 Sebastian Kaspari This file is part of Yaaic. Yaaic 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. Yaaic 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 Yaaic. If not, see <http://www.gnu.org/licenses/>. */ package org.yaaic.activity; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.regex.Pattern; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import org.yaaic.R; import org.yaaic.Yaaic; import org.yaaic.db.Database; import org.yaaic.exception.ValidationException; import org.yaaic.model.Extra; import org.yaaic.model.Identity; import org.yaaic.model.Server; import org.yaaic.model.Status; /** * Add a new server to the list * * @author Sebastian Kaspari <[email protected]> */ public class AddServerActivity extends Activity implements OnClickListener { private static final int REQUEST_CODE_CHANNELS = 1; private static final int REQUEST_CODE_COMMANDS = 2; private static final int REQUEST_CODE_ALIASES = 3; private Server server; private ArrayList<String> aliases; private ArrayList<String> channels; private ArrayList<String> commands; /** * On create */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.serveradd); aliases = new ArrayList<String>(); channels = new ArrayList<String>(); commands = new ArrayList<String>(); ((Button) findViewById(R.id.add)).setOnClickListener(this); ((Button) findViewById(R.id.cancel)).setOnClickListener(this); ((Button) findViewById(R.id.aliases)).setOnClickListener(this); ((Button) findViewById(R.id.channels)).setOnClickListener(this); ((Button) findViewById(R.id.commands)).setOnClickListener(this); Spinner spinner = (Spinner) findViewById(R.id.charset); String[] charsets = getResources().getStringArray(R.array.charsets); ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, charsets); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); Bundle extras = getIntent().getExtras(); if (extras != null && extras.containsKey(Extra.SERVER)) { // Request to edit an existing server Database db = new Database(this); this.server = db.getServerById(extras.getInt(Extra.SERVER)); aliases.addAll(server.getIdentity().getAliases()); this.channels = db.getChannelsByServerId(server.getId()); this.commands = db.getCommandsByServerId(server.getId()); db.close(); // Set server values ((EditText) findViewById(R.id.title)).setText(server.getTitle()); ((EditText) findViewById(R.id.host)).setText(server.getHost()); ((EditText) findViewById(R.id.port)).setText(String.valueOf(server.getPort())); ((EditText) findViewById(R.id.password)).setText(server.getPassword()); ((EditText) findViewById(R.id.nickname)).setText(server.getIdentity().getNickname()); ((EditText) findViewById(R.id.ident)).setText(server.getIdentity().getIdent()); ((EditText) findViewById(R.id.realname)).setText(server.getIdentity().getRealName()); ((CheckBox) findViewById(R.id.useSSL)).setChecked(server.useSSL()); - ((Button) findViewById(R.id.add)).setText("Save"); + ((Button) findViewById(R.id.add)).setText(R.string.server_save); // Select charset if (server.getCharset() != null) { for (int i = 0; i < charsets.length; i++) { if (server.getCharset().equals(charsets[i])) { spinner.setSelection(i); break; } } } } Uri uri = getIntent().getData(); if (uri != null && uri.getScheme().equals("irc")) { // handling an irc:// uri ((EditText) findViewById(R.id.host)).setText(uri.getHost()); if (uri.getPort() != -1) { ((EditText) findViewById(R.id.port)).setText(String.valueOf(uri.getPort())); } } } /** * On activity result */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) { return; // ignore everything else } switch (requestCode) { case REQUEST_CODE_ALIASES: aliases.clear(); aliases.addAll(data.getExtras().getStringArrayList(Extra.ALIASES)); break; case REQUEST_CODE_CHANNELS: channels = data.getExtras().getStringArrayList(Extra.CHANNELS); break; case REQUEST_CODE_COMMANDS: commands = data.getExtras().getStringArrayList(Extra.COMMANDS); break; } } /** * On click add server or cancel activity */ public void onClick(View v) { switch (v.getId()) { case R.id.aliases: Intent aliasIntent = new Intent(this, AddAliasActivity.class); aliasIntent.putExtra(Extra.ALIASES, aliases); startActivityForResult(aliasIntent, REQUEST_CODE_ALIASES); break; case R.id.channels: Intent channelIntent = new Intent(this, AddChannelActivity.class); channelIntent.putExtra(Extra.CHANNELS, channels); startActivityForResult(channelIntent, REQUEST_CODE_CHANNELS); break; case R.id.commands: Intent commandsIntent = new Intent(this, AddCommandsActivity.class); commandsIntent.putExtra(Extra.COMMANDS, commands); startActivityForResult(commandsIntent, REQUEST_CODE_COMMANDS); break; case R.id.add: try { validateServer(); validateIdentity(); if (server == null) { addServer(); } else { updateServer(); } setResult(RESULT_OK); finish(); } catch(ValidationException e) { Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); } break; case R.id.cancel: setResult(RESULT_CANCELED); finish(); break; } } /** * Add server to database */ private void addServer() { Database db = new Database(this); Identity identity = getIdentityFromView(); long identityId = db.addIdentity( identity.getNickname(), identity.getIdent(), identity.getRealName(), identity.getAliases() ); Server server = getServerFromView(); long serverId = db.addServer( server.getTitle(), server.getHost(), server.getPort(), server.getPassword(), false, // auto connect server.useSSL(), identityId, server.getCharset() ); db.setChannels((int) serverId, channels); db.setCommands((int) serverId, commands); db.close(); server.setId((int) serverId); server.setIdentity(identity); server.setAutoJoinChannels(channels); server.setConnectCommands(commands); Yaaic.getInstance().addServer(server); } /** * Update server */ private void updateServer() { Database db = new Database(this); int serverId = this.server.getId(); int identityId = db.getIdentityIdByServerId(serverId); Server server = getServerFromView(); db.updateServer( serverId, server.getTitle(), server.getHost(), server.getPort(), server.getPassword(), false, // auto connect server.useSSL(), identityId, server.getCharset() ); Identity identity = getIdentityFromView(); db.updateIdentity( identityId, identity.getNickname(), identity.getIdent(), identity.getNickname(), identity.getAliases() ); db.setChannels(serverId, channels); db.setCommands(serverId, commands); db.close(); server.setId(this.server.getId()); server.setIdentity(identity); server.setAutoJoinChannels(channels); server.setConnectCommands(commands); Yaaic.getInstance().updateServer(server); } /** * Populate a server object from the data in the view * * @return The server object */ private Server getServerFromView() { String title = ((EditText) findViewById(R.id.title)).getText().toString().trim(); String host = ((EditText) findViewById(R.id.host)).getText().toString().trim(); int port = Integer.parseInt(((EditText) findViewById(R.id.port)).getText().toString().trim()); String password = ((EditText) findViewById(R.id.password)).getText().toString().trim(); String charset = ((Spinner) findViewById(R.id.charset)).getSelectedItem().toString(); Boolean useSSL = ((CheckBox) findViewById(R.id.useSSL)).isChecked(); // not in use yet //boolean autoConnect = ((CheckBox) findViewById(R.id.autoconnect)).isChecked(); Server server = new Server(); server.setHost(host); server.setPort(port); server.setPassword(password); server.setTitle(title); server.setCharset(charset); server.setUseSSL(useSSL); server.setStatus(Status.DISCONNECTED); return server; } /** * Populate an identity object from the data in the view * * @return The identity object */ private Identity getIdentityFromView() { String nickname = ((EditText) findViewById(R.id.nickname)).getText().toString().trim(); String ident = ((EditText) findViewById(R.id.ident)).getText().toString().trim(); String realname = ((EditText) findViewById(R.id.realname)).getText().toString().trim(); Identity identity = new Identity(); identity.setNickname(nickname); identity.setIdent(ident); identity.setRealName(realname); identity.setAliases(aliases); return identity; } /** * Validate the input for a server * * @throws ValidationException */ private void validateServer() throws ValidationException { String title = ((EditText) findViewById(R.id.title)).getText().toString(); String host = ((EditText) findViewById(R.id.host)).getText().toString(); String port = ((EditText) findViewById(R.id.port)).getText().toString(); String charset = ((Spinner) findViewById(R.id.charset)).getSelectedItem().toString(); if (title.trim().equals("")) { throw new ValidationException(getResources().getString(R.string.validation_blank_title)); } if (host.trim().equals("")) { // XXX: We should use some better host validation throw new ValidationException(getResources().getString(R.string.validation_blank_host)); } try { Integer.parseInt(port); } catch (NumberFormatException e) { throw new ValidationException(getResources().getString(R.string.validation_invalid_port)); } try { "".getBytes(charset); } catch (UnsupportedEncodingException e) { throw new ValidationException(getResources().getString(R.string.validation_unsupported_charset)); } Database db = new Database(this); if (db.isTitleUsed(title) && (server == null || !server.getTitle().equals(title))) { db.close(); throw new ValidationException(getResources().getString(R.string.validation_title_used)); } db.close(); } /** * Validate the input for a identity * * @throws ValidationException */ private void validateIdentity() throws ValidationException { String nickname = ((EditText) findViewById(R.id.nickname)).getText().toString(); String ident = ((EditText) findViewById(R.id.ident)).getText().toString(); String realname = ((EditText) findViewById(R.id.realname)).getText().toString(); if (nickname.trim().equals("")) { throw new ValidationException(getResources().getString(R.string.validation_blank_nickname)); } if (ident.trim().equals("")) { throw new ValidationException(getResources().getString(R.string.validation_blank_ident)); } if (realname.trim().equals("")) { throw new ValidationException(getResources().getString(R.string.validation_blank_realname)); } // RFC 1459: <nick> ::= <letter> { <letter> | <number> | <special> } // <special> ::= '-' | '[' | ']' | '\' | '`' | '^' | '{' | '}' // Chars that are not in RFC 1459 but are supported too: // | and _ Pattern nickPattern = Pattern.compile("^[a-zA-Z_][a-zA-Z0-9^\\-`\\[\\]{}|_\\\\]*$"); if (!nickPattern.matcher(nickname).matches()) { throw new ValidationException(getResources().getString(R.string.validation_invalid_nickname)); } // We currently only allow chars and numbers as ident Pattern identPattern = Pattern.compile("^[a-zA-Z0-9]+$"); if (!identPattern.matcher(ident).matches()) { throw new ValidationException(getResources().getString(R.string.validation_invalid_ident)); } } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.serveradd); aliases = new ArrayList<String>(); channels = new ArrayList<String>(); commands = new ArrayList<String>(); ((Button) findViewById(R.id.add)).setOnClickListener(this); ((Button) findViewById(R.id.cancel)).setOnClickListener(this); ((Button) findViewById(R.id.aliases)).setOnClickListener(this); ((Button) findViewById(R.id.channels)).setOnClickListener(this); ((Button) findViewById(R.id.commands)).setOnClickListener(this); Spinner spinner = (Spinner) findViewById(R.id.charset); String[] charsets = getResources().getStringArray(R.array.charsets); ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, charsets); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); Bundle extras = getIntent().getExtras(); if (extras != null && extras.containsKey(Extra.SERVER)) { // Request to edit an existing server Database db = new Database(this); this.server = db.getServerById(extras.getInt(Extra.SERVER)); aliases.addAll(server.getIdentity().getAliases()); this.channels = db.getChannelsByServerId(server.getId()); this.commands = db.getCommandsByServerId(server.getId()); db.close(); // Set server values ((EditText) findViewById(R.id.title)).setText(server.getTitle()); ((EditText) findViewById(R.id.host)).setText(server.getHost()); ((EditText) findViewById(R.id.port)).setText(String.valueOf(server.getPort())); ((EditText) findViewById(R.id.password)).setText(server.getPassword()); ((EditText) findViewById(R.id.nickname)).setText(server.getIdentity().getNickname()); ((EditText) findViewById(R.id.ident)).setText(server.getIdentity().getIdent()); ((EditText) findViewById(R.id.realname)).setText(server.getIdentity().getRealName()); ((CheckBox) findViewById(R.id.useSSL)).setChecked(server.useSSL()); ((Button) findViewById(R.id.add)).setText("Save"); // Select charset if (server.getCharset() != null) { for (int i = 0; i < charsets.length; i++) { if (server.getCharset().equals(charsets[i])) { spinner.setSelection(i); break; } } } } Uri uri = getIntent().getData(); if (uri != null && uri.getScheme().equals("irc")) { // handling an irc:// uri ((EditText) findViewById(R.id.host)).setText(uri.getHost()); if (uri.getPort() != -1) { ((EditText) findViewById(R.id.port)).setText(String.valueOf(uri.getPort())); } } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.serveradd); aliases = new ArrayList<String>(); channels = new ArrayList<String>(); commands = new ArrayList<String>(); ((Button) findViewById(R.id.add)).setOnClickListener(this); ((Button) findViewById(R.id.cancel)).setOnClickListener(this); ((Button) findViewById(R.id.aliases)).setOnClickListener(this); ((Button) findViewById(R.id.channels)).setOnClickListener(this); ((Button) findViewById(R.id.commands)).setOnClickListener(this); Spinner spinner = (Spinner) findViewById(R.id.charset); String[] charsets = getResources().getStringArray(R.array.charsets); ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, charsets); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); Bundle extras = getIntent().getExtras(); if (extras != null && extras.containsKey(Extra.SERVER)) { // Request to edit an existing server Database db = new Database(this); this.server = db.getServerById(extras.getInt(Extra.SERVER)); aliases.addAll(server.getIdentity().getAliases()); this.channels = db.getChannelsByServerId(server.getId()); this.commands = db.getCommandsByServerId(server.getId()); db.close(); // Set server values ((EditText) findViewById(R.id.title)).setText(server.getTitle()); ((EditText) findViewById(R.id.host)).setText(server.getHost()); ((EditText) findViewById(R.id.port)).setText(String.valueOf(server.getPort())); ((EditText) findViewById(R.id.password)).setText(server.getPassword()); ((EditText) findViewById(R.id.nickname)).setText(server.getIdentity().getNickname()); ((EditText) findViewById(R.id.ident)).setText(server.getIdentity().getIdent()); ((EditText) findViewById(R.id.realname)).setText(server.getIdentity().getRealName()); ((CheckBox) findViewById(R.id.useSSL)).setChecked(server.useSSL()); ((Button) findViewById(R.id.add)).setText(R.string.server_save); // Select charset if (server.getCharset() != null) { for (int i = 0; i < charsets.length; i++) { if (server.getCharset().equals(charsets[i])) { spinner.setSelection(i); break; } } } } Uri uri = getIntent().getData(); if (uri != null && uri.getScheme().equals("irc")) { // handling an irc:// uri ((EditText) findViewById(R.id.host)).setText(uri.getHost()); if (uri.getPort() != -1) { ((EditText) findViewById(R.id.port)).setText(String.valueOf(uri.getPort())); } } }
diff --git a/sources/android/src/org/ewol/EwolActivity.java b/sources/android/src/org/ewol/EwolActivity.java index 50643628..8e710628 100644 --- a/sources/android/src/org/ewol/EwolActivity.java +++ b/sources/android/src/org/ewol/EwolActivity.java @@ -1,238 +1,238 @@ /** ******************************************************************************* * @file EwolActivity.java * @brief Java EwolActivity code. * @author Edouard DUPIN, Kevin BILLONNEAU * @date 20/04/2012 * @par Project * ewol * * @par Copyright * Copyright 2011 Edouard DUPIN, all right reserved * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY. * * Licence summary : * You can modify and redistribute the sources code and binaries. * You can send me the bug-fix * * Term of the licence in in the file licence.txt. * ******************************************************************************* */ package org.ewol; import android.app.Activity; import android.content.Context; import android.opengl.GLSurfaceView; import android.os.Bundle; import android.view.MotionEvent; import android.view.KeyEvent; // For No Title : import android.view.Window; // For the full screen : import android.view.WindowManager; // for the keyboard event : import android.view.inputmethod.InputMethodManager; import java.io.File; import android.content.Context; import android.content.res.Configuration; // For the getting apk name : import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.util.DisplayMetrics; import java.io.IOException; import static org.ewol.Ewol.EWOL; /** * @brief Class : * */ public abstract class EwolActivity extends Activity implements EwolCallback, EwolConstants{ private EwolSurfaceViewGL mGLView; private EwolAudioTask mStreams; private Thread mAudioThread; static { System.loadLibrary("ewol"); } public void initApkPath(String org, String vendor, String project) { StringBuilder sb = new StringBuilder(); sb.append(org).append("."); sb.append(vendor).append("."); sb.append(project); String apkFilePath = null; ApplicationInfo appInfo = null; PackageManager packMgmr = getPackageManager(); try { appInfo = packMgmr.getApplicationInfo(sb.toString(), 0); } catch (NameNotFoundException e) { e.printStackTrace(); throw new RuntimeException("Unable to locate assets, aborting..."); } apkFilePath = appInfo.sourceDir; Ewol.paramSetArchiveDir(0, apkFilePath); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // set the java evironement in the C sources : Ewol.setJavaVirtualMachineStart(this); // Load the application directory Ewol.paramSetArchiveDir(1, getFilesDir().toString()); Ewol.paramSetArchiveDir(2, getCacheDir().toString()); // to enable extarnal storage: add in the manifest the restriction needed ... //packageManager.checkPermission("android.permission.READ_SMS", myPackage) == PERMISSION_GRANTED; //Ewol.paramSetArchiveDir(3, getExternalCacheDir().toString()); // return apk file path (or null on error) initApkPath("__PROJECT_TYPE__", "__PROJECT_VENDOR__", "__PROJECT_PACKAGE__"); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); EWOL.displayPropertyMetrics(metrics.xdpi, metrics.ydpi); // call C init ... EWOL.onCreate(); // Remove the title of the current display : requestWindowFeature(Window.FEATURE_NO_TITLE); // set full screen Mode : getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // display keyboard: //getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); // hide keyboard : getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // create bsurface system - mGLView = new EwolSurfaceViewGL(this, __CONF_OGL_ES_V__); + mGLView = new EwolSurfaceViewGL(this, 2); // create element audio ... mStreams = new EwolAudioTask(); setContentView(mGLView); } @Override protected void onStart() { super.onStart(); // call C EWOL.onStart(); } @Override protected void onRestart() { super.onRestart(); // call C EWOL.onReStart(); } @Override protected void onResume() { super.onResume(); mGLView.onResume(); mAudioThread = new Thread(mStreams); if (mAudioThread != null) { mAudioThread.start(); } // call C EWOL.onResume(); } @Override protected void onPause() { super.onPause(); mGLView.onPause(); if (mAudioThread != null) { // request audio stop mStreams.AutoStop(); // wait the thread ended ... try { mAudioThread.join(); } catch(InterruptedException e) { } } // call C EWOL.onPause(); } @Override protected void onStop() { super.onStop(); // call C EWOL.onStop(); } @Override protected void onDestroy() { super.onDestroy(); // call C EWOL.onDestroy(); // Remove the java Virtual machine pointer form the C code Ewol.setJavaVirtualMachineStop(); } @Override protected void finalize() throws Throwable { super.finalize(); // cleanup your object here } public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } @Override public void keyboardUpdate(boolean show) { final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if(show) { //EWOL.touchEvent(); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); } else { imm.toggleSoftInput(0 ,InputMethodManager.HIDE_IMPLICIT_ONLY + InputMethodManager.HIDE_NOT_ALWAYS); //imm.hideSoftInputFromWindow(view.getWindowToken(),0); } } @Override public void eventNotifier(String[] args) { // just for the test ... EWOL.touchEvent(); } public void orientationUpdate(int screenMode) { if (screenMode == EWOL_ORIENTATION_LANDSCAPE) { //Force landscape setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } else if (screenMode == EWOL_ORIENTATION_PORTRAIT) { //Force portrait setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { //Force auto Rotation setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } } }
true
true
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // set the java evironement in the C sources : Ewol.setJavaVirtualMachineStart(this); // Load the application directory Ewol.paramSetArchiveDir(1, getFilesDir().toString()); Ewol.paramSetArchiveDir(2, getCacheDir().toString()); // to enable extarnal storage: add in the manifest the restriction needed ... //packageManager.checkPermission("android.permission.READ_SMS", myPackage) == PERMISSION_GRANTED; //Ewol.paramSetArchiveDir(3, getExternalCacheDir().toString()); // return apk file path (or null on error) initApkPath("__PROJECT_TYPE__", "__PROJECT_VENDOR__", "__PROJECT_PACKAGE__"); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); EWOL.displayPropertyMetrics(metrics.xdpi, metrics.ydpi); // call C init ... EWOL.onCreate(); // Remove the title of the current display : requestWindowFeature(Window.FEATURE_NO_TITLE); // set full screen Mode : getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // display keyboard: //getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); // hide keyboard : getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // create bsurface system mGLView = new EwolSurfaceViewGL(this, __CONF_OGL_ES_V__); // create element audio ... mStreams = new EwolAudioTask(); setContentView(mGLView); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // set the java evironement in the C sources : Ewol.setJavaVirtualMachineStart(this); // Load the application directory Ewol.paramSetArchiveDir(1, getFilesDir().toString()); Ewol.paramSetArchiveDir(2, getCacheDir().toString()); // to enable extarnal storage: add in the manifest the restriction needed ... //packageManager.checkPermission("android.permission.READ_SMS", myPackage) == PERMISSION_GRANTED; //Ewol.paramSetArchiveDir(3, getExternalCacheDir().toString()); // return apk file path (or null on error) initApkPath("__PROJECT_TYPE__", "__PROJECT_VENDOR__", "__PROJECT_PACKAGE__"); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); EWOL.displayPropertyMetrics(metrics.xdpi, metrics.ydpi); // call C init ... EWOL.onCreate(); // Remove the title of the current display : requestWindowFeature(Window.FEATURE_NO_TITLE); // set full screen Mode : getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // display keyboard: //getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); // hide keyboard : getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // create bsurface system mGLView = new EwolSurfaceViewGL(this, 2); // create element audio ... mStreams = new EwolAudioTask(); setContentView(mGLView); }
diff --git a/cdm/src/test/java/ucar/nc2/iosp/hdf5/TestN4.java b/cdm/src/test/java/ucar/nc2/iosp/hdf5/TestN4.java index b330e5b7c..e58fe16f7 100644 --- a/cdm/src/test/java/ucar/nc2/iosp/hdf5/TestN4.java +++ b/cdm/src/test/java/ucar/nc2/iosp/hdf5/TestN4.java @@ -1,214 +1,214 @@ /* * Copyright 1998-2009 University Corporation for Atmospheric Research/Unidata * * Portions of this software were developed by the Unidata Program at the * University Corporation for Atmospheric Research. * * Access and use of this software shall impose the following obligations * and understandings on the user. The user is granted the right, without * any fee or cost, to use, copy, modify, alter, enhance and distribute * this software, and any derivative works thereof, and its supporting * documentation for any purpose whatsoever, provided that this entire * notice appears in all copies of the software, derivative works and * supporting documentation. Further, UCAR requests that the user credit * UCAR/Unidata in any publications that result from the use of this * software or in any product that includes this software. The names UCAR * and/or Unidata, however, may not be used in any advertising or publicity * to endorse or promote any products or commercial entity unless specific * written permission is obtained from UCAR/Unidata. The user also * understands that UCAR/Unidata is not obligated to provide the user with * any support, consulting, training or assistance of any kind with regard * to the use, operation and performance of this software nor to provide * the user with any updates, revisions, new versions or "bug fixes." * * THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "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 UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE. */ package ucar.nc2.iosp.hdf5; import junit.framework.*; import ucar.ma2.InvalidRangeException; import ucar.ma2.Section; import ucar.nc2.*; import ucar.ma2.Array; import ucar.nc2.dt.GridDatatype; import ucar.nc2.dt.grid.GridDataset; import java.io.*; import java.util.Collections; import java.util.List; /** * Test nc2 read JUnit framework. */ public class TestN4 extends TestCase { String testDir = TestAll.testdataDir + "netcdf4/"; public TestN4(String name) { super(name); } public void testGlobalHeapOverun() throws IOException { // Global Heap 1t 13059 runs out with no heap id = 0 String filename = testDir+"globalHeapOverrun.nc4"; NetcdfFile ncfile = TestNC2.open(filename); System.out.println("\n**** testGlobalHeapOverun done\n\n" + ncfile); List<Variable> vars = ncfile.getVariables(); Collections.sort(vars); for (Variable v : vars) System.out.println(" "+v.getName()); System.out.println("nvars = "+ncfile.getVariables().size()); ncfile.close(); } // [email protected] // I really don't think this is a problem with your code // may be bug in HDF5 1.8.4-patch1 public void utestTiling() throws IOException { // Global Heap 1t 13059 runs out with no heap id = 0 String filename = testDir+"tiling.nc4"; GridDataset gridDataset = GridDataset.open(filename); GridDatatype grid = gridDataset.findGridByName("Turbulence_SIGMET_AIRMET" ); System.out.printf("grid=%s%n", grid); grid.readDataSlice( 4, 13, 176, 216 ); // FAILS gridDataset.close(); } public void testOpen() throws IOException { //H5header.setDebugFlags(new ucar.nc2.util.DebugFlagsImpl("H5header/header")); String filename = testDir+"nc4/tst_enums.nc"; NetcdfFile ncfile = TestNC2.open(filename); System.out.println("\n**** testReadNetcdf4 done\n\n" + ncfile); List<Variable> vars = ncfile.getVariables(); Collections.sort(vars); for (Variable v : vars) System.out.println(" "+v.getName()); System.out.println("nvars = "+ncfile.getVariables().size()); ncfile.close(); } public void testReadAll() throws IOException { TestAll.readAllDir(testDir+"nc4", null); TestAll.readAllDir(testDir+"nc4-classic", null); TestAll.readAllDir(testDir+"files", null); } public void problem() throws IOException { //H5iosp.setDebugFlags(new ucar.nc2.util.DebugFlagsImpl("H5iosp/read")); //H5header.setDebugFlags(new ucar.nc2.util.DebugFlagsImpl("H5header/header")); String filename = testDir+"files/nctest_64bit_offset.nc"; TestAll.readAll(filename); NetcdfFile ncfile = TestNC2.open(filename); System.out.println(ncfile.toString()); //Variable v = ncfile.findVariable("cr"); //Array data = v.read(); } public void utestEnum() throws IOException { H5header.setDebugFlags(new ucar.nc2.util.DebugFlagsImpl("H5header/header")); String filename = testDir+"nc4/tst_enum_data.nc"; NetcdfFile ncfile = TestNC2.open(filename); Variable v = ncfile.findVariable("primary_cloud"); Array data = v.read(); System.out.println("\n**** testReadNetcdf4 done\n\n" + ncfile); NCdumpW.printArray(data, "primary_cloud", new PrintWriter( System.out), null); ncfile.close(); } public void testVlenStrings() throws IOException { //H5header.setDebugFlags(new ucar.nc2.util.DebugFlagsImpl("H5header/header")); String filename = testDir+"nc4/tst_strings.nc"; NetcdfFile ncfile = TestNC2.open(filename); System.out.println("\n**** testReadNetcdf4 done\n\n" + ncfile); Variable v = ncfile.findVariable("measure_for_measure_var"); Array data = v.read(); NCdumpW.printArray(data, "measure_for_measure_var", new PrintWriter( System.out), null); ncfile.close(); } public void testVlen() throws IOException, InvalidRangeException { //H5header.setDebugFlags(new ucar.nc2.util.DebugFlagsImpl("H5header/header")); - String filename = "C:/data/work/bruno/fpsc_d1wave_24-11.nc"; - //String filename = testDir+"vlen/fpcs_1dwave_2.nc"; + //String filename = "C:/data/work/bruno/fpsc_d1wave_24-11.nc"; + String filename = testDir+"vlen/fpcs_1dwave_2.nc"; NetcdfFile ncfile = TestNC2.open(filename); System.out.println("\n**** testReadNetcdf4 done\n\n" + ncfile); Variable v = ncfile.findVariable("levels"); Array data = v.read(); NCdumpW.printArray(data, "read()", new PrintWriter( System.out), null); int count = 0; while (data.hasNext()) { Array as = (Array) data.next(); NCdumpW.printArray(as, " "+count, new PrintWriter( System.out), null); count++; } // try subset data = v.read("0:9:2, :"); NCdumpW.printArray(data, "read(0:9:2,:)", new PrintWriter( System.out), null); data = v.read(new Section().appendRange(0,9,2).appendRange(null)); NCdumpW.printArray(data, "read(Section)", new PrintWriter( System.out), null); // fail //int[] origin = new int[] {0, 0}; //int[] size = new int[] {3, -1}; //data = v.read(origin, size); // from bruno int initialIndex = 5; int finalIndex = 5; data = v.read(initialIndex + ":" + finalIndex + ",:"); //NCdumpW.printArray(data, "read()", new PrintWriter(System.out), null); System.out.println("Size: " + data.getSize()); System.out.println("Data: " + data); System.out.println("Class: " + data.getClass().getName()); // loop over outer dimension int x = 0; while (data.hasNext()) { Array as = (Array) data.next(); // inner variable length array of short System.out.println("Shape: " + new Section(as.getShape())); System.out.println(as); } ncfile.close(); } // LOOK this ones failing public void utestCompoundVlens() throws IOException { //H5header.setDebugFlags(new ucar.nc2.util.DebugFlagsImpl("H5header/header")); String filename = testDir+"vlen/cdm_sea_soundings.nc4"; NetcdfFile ncfile = TestNC2.open(filename); System.out.println("\n**** testReadNetcdf4 done\n\n" + ncfile); Variable v = ncfile.findVariable("fun_soundings"); Array data = v.read(); NCdumpW.printArray(data, "fun_soundings", new PrintWriter( System.out), null); ncfile.close(); } public void testStrings() throws IOException { //H5header.setDebugFlags(new ucar.nc2.util.DebugFlagsImpl("H5header/header")); String filename = testDir+"files/nc_test_netcdf4.nc4"; NetcdfFile ncfile = TestNC2.open(filename); System.out.println("\n**** testReadNetcdf4 done\n\n" + ncfile); Variable v = ncfile.findVariable("d"); String attValue = ncfile.findAttValueIgnoreCase(v, "c", null); String s = H5header.showBytes(attValue.getBytes()); System.out.println(" d:c= ("+attValue+") = "+s); //Array data = v.read(); //NCdumpW.printArray(data, "cr", System.out, null); ncfile.close(); } public static void main(String args[]) throws IOException { new TestN4("").problem(); } }
true
true
public void testVlen() throws IOException, InvalidRangeException { //H5header.setDebugFlags(new ucar.nc2.util.DebugFlagsImpl("H5header/header")); String filename = "C:/data/work/bruno/fpsc_d1wave_24-11.nc"; //String filename = testDir+"vlen/fpcs_1dwave_2.nc"; NetcdfFile ncfile = TestNC2.open(filename); System.out.println("\n**** testReadNetcdf4 done\n\n" + ncfile); Variable v = ncfile.findVariable("levels"); Array data = v.read(); NCdumpW.printArray(data, "read()", new PrintWriter( System.out), null); int count = 0; while (data.hasNext()) { Array as = (Array) data.next(); NCdumpW.printArray(as, " "+count, new PrintWriter( System.out), null); count++; } // try subset data = v.read("0:9:2, :"); NCdumpW.printArray(data, "read(0:9:2,:)", new PrintWriter( System.out), null); data = v.read(new Section().appendRange(0,9,2).appendRange(null)); NCdumpW.printArray(data, "read(Section)", new PrintWriter( System.out), null); // fail //int[] origin = new int[] {0, 0}; //int[] size = new int[] {3, -1}; //data = v.read(origin, size); // from bruno int initialIndex = 5; int finalIndex = 5; data = v.read(initialIndex + ":" + finalIndex + ",:"); //NCdumpW.printArray(data, "read()", new PrintWriter(System.out), null); System.out.println("Size: " + data.getSize()); System.out.println("Data: " + data); System.out.println("Class: " + data.getClass().getName()); // loop over outer dimension int x = 0; while (data.hasNext()) { Array as = (Array) data.next(); // inner variable length array of short System.out.println("Shape: " + new Section(as.getShape())); System.out.println(as); } ncfile.close(); }
public void testVlen() throws IOException, InvalidRangeException { //H5header.setDebugFlags(new ucar.nc2.util.DebugFlagsImpl("H5header/header")); //String filename = "C:/data/work/bruno/fpsc_d1wave_24-11.nc"; String filename = testDir+"vlen/fpcs_1dwave_2.nc"; NetcdfFile ncfile = TestNC2.open(filename); System.out.println("\n**** testReadNetcdf4 done\n\n" + ncfile); Variable v = ncfile.findVariable("levels"); Array data = v.read(); NCdumpW.printArray(data, "read()", new PrintWriter( System.out), null); int count = 0; while (data.hasNext()) { Array as = (Array) data.next(); NCdumpW.printArray(as, " "+count, new PrintWriter( System.out), null); count++; } // try subset data = v.read("0:9:2, :"); NCdumpW.printArray(data, "read(0:9:2,:)", new PrintWriter( System.out), null); data = v.read(new Section().appendRange(0,9,2).appendRange(null)); NCdumpW.printArray(data, "read(Section)", new PrintWriter( System.out), null); // fail //int[] origin = new int[] {0, 0}; //int[] size = new int[] {3, -1}; //data = v.read(origin, size); // from bruno int initialIndex = 5; int finalIndex = 5; data = v.read(initialIndex + ":" + finalIndex + ",:"); //NCdumpW.printArray(data, "read()", new PrintWriter(System.out), null); System.out.println("Size: " + data.getSize()); System.out.println("Data: " + data); System.out.println("Class: " + data.getClass().getName()); // loop over outer dimension int x = 0; while (data.hasNext()) { Array as = (Array) data.next(); // inner variable length array of short System.out.println("Shape: " + new Section(as.getShape())); System.out.println(as); } ncfile.close(); }
diff --git a/behaviors/behavior-tutorial-repo/src/main/java/com/someco/behavior/Rating.java b/behaviors/behavior-tutorial-repo/src/main/java/com/someco/behavior/Rating.java index fff52de..e65bc31 100644 --- a/behaviors/behavior-tutorial-repo/src/main/java/com/someco/behavior/Rating.java +++ b/behaviors/behavior-tutorial-repo/src/main/java/com/someco/behavior/Rating.java @@ -1,130 +1,130 @@ package com.someco.behavior; import java.util.List; import org.alfresco.repo.node.NodeServicePolicies; import org.alfresco.repo.policy.Behaviour; import org.alfresco.repo.policy.JavaBehaviour; import org.alfresco.repo.policy.PolicyComponent; import org.alfresco.repo.policy.Behaviour.NotificationFrequency; import org.alfresco.service.cmr.repository.ChildAssociationRef; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.namespace.NamespaceService; import org.alfresco.service.namespace.QName; import org.apache.log4j.Logger; import com.someco.model.SomeCoRatingsModel; public class Rating implements NodeServicePolicies.OnDeleteNodePolicy, NodeServicePolicies.OnCreateNodePolicy { // Dependencies private NodeService nodeService; private PolicyComponent policyComponent; // Behaviours private Behaviour onCreateNode; private Behaviour onDeleteNode; private Logger logger = Logger.getLogger(Rating.class); public void init() { if (logger.isDebugEnabled()) logger.debug("Initializing rateable behaviors"); // Create behaviours this.onCreateNode = new JavaBehaviour(this, "onCreateNode", NotificationFrequency.TRANSACTION_COMMIT); this.onDeleteNode = new JavaBehaviour(this, "onDeleteNode", NotificationFrequency.TRANSACTION_COMMIT); // Bind behaviours to node policies this.policyComponent.bindClassBehaviour(QName.createQName(NamespaceService.ALFRESCO_URI, "onCreateNode"), QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.TYPE_SCR_RATING), this.onCreateNode); this.policyComponent.bindClassBehaviour(QName.createQName(NamespaceService.ALFRESCO_URI, "onDeleteNode"), QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.TYPE_SCR_RATING), this.onDeleteNode); } public void onCreateNode(ChildAssociationRef childAssocRef) { if (logger.isDebugEnabled()) logger.debug("Inside onCreateNode"); computeAverage(childAssocRef); } public void onDeleteNode(ChildAssociationRef childAssocRef, boolean isNodeArchived) { if (logger.isDebugEnabled()) logger.debug("Inside onDeleteNode"); computeAverage(childAssocRef); } public void computeAverage(ChildAssociationRef childAssocRef) { if (logger.isDebugEnabled()) logger.debug("Inside computeAverage"); // get the parent node NodeRef parentRef = childAssocRef.getParentRef(); // check the parent to make sure it has the right aspect - if (nodeService.hasAspect(parentRef, QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.ASPECT_SCR_RATEABLE))) { + if (nodeService.exists(parentRef) && nodeService.hasAspect(parentRef, QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.ASPECT_SCR_RATEABLE))) { // continue, this is what we want } else { if (logger.isDebugEnabled()) logger.debug("Rating's parent ref did not have rateable aspect."); return; } // get the parent node's children List<ChildAssociationRef> children = nodeService.getChildAssocs(parentRef); Double average = 0d; int count = 0; int total = 0; // This actually happens when the last rating is deleted if (children.size() == 0) { // No children so no work to do if (logger.isDebugEnabled()) logger.debug("No children found"); } else { // iterate through the children to compute the total for (ChildAssociationRef child : children) { if (!child.getTypeQName().isMatch(QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.ASSN_SCR_RATINGS))) { continue; } int rating = 0; rating = (Integer)nodeService.getProperty(child.getChildRef(), QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.PROP_RATING)); count += 1; total += rating; } // compute the average if (count != 0) { average = total / (count / 1.0d); } if (logger.isDebugEnabled()) logger.debug("Computed average:" + average); } // store the average on the parent node nodeService.setProperty(parentRef, QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.PROP_AVERAGE_RATING), average); nodeService.setProperty(parentRef, QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.PROP_TOTAL_RATING), total); nodeService.setProperty(parentRef, QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.PROP_RATING_COUNT), count); if (logger.isDebugEnabled()) logger.debug("Property set"); return; } public NodeService getNodeService() { return nodeService; } public void setNodeService(NodeService nodeService) { this.nodeService = nodeService; } public PolicyComponent getPolicyComponent() { return policyComponent; } public void setPolicyComponent(PolicyComponent policyComponent) { this.policyComponent = policyComponent; } }
true
true
public void computeAverage(ChildAssociationRef childAssocRef) { if (logger.isDebugEnabled()) logger.debug("Inside computeAverage"); // get the parent node NodeRef parentRef = childAssocRef.getParentRef(); // check the parent to make sure it has the right aspect if (nodeService.hasAspect(parentRef, QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.ASPECT_SCR_RATEABLE))) { // continue, this is what we want } else { if (logger.isDebugEnabled()) logger.debug("Rating's parent ref did not have rateable aspect."); return; } // get the parent node's children List<ChildAssociationRef> children = nodeService.getChildAssocs(parentRef); Double average = 0d; int count = 0; int total = 0; // This actually happens when the last rating is deleted if (children.size() == 0) { // No children so no work to do if (logger.isDebugEnabled()) logger.debug("No children found"); } else { // iterate through the children to compute the total for (ChildAssociationRef child : children) { if (!child.getTypeQName().isMatch(QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.ASSN_SCR_RATINGS))) { continue; } int rating = 0; rating = (Integer)nodeService.getProperty(child.getChildRef(), QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.PROP_RATING)); count += 1; total += rating; } // compute the average if (count != 0) { average = total / (count / 1.0d); } if (logger.isDebugEnabled()) logger.debug("Computed average:" + average); } // store the average on the parent node nodeService.setProperty(parentRef, QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.PROP_AVERAGE_RATING), average); nodeService.setProperty(parentRef, QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.PROP_TOTAL_RATING), total); nodeService.setProperty(parentRef, QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.PROP_RATING_COUNT), count); if (logger.isDebugEnabled()) logger.debug("Property set"); return; }
public void computeAverage(ChildAssociationRef childAssocRef) { if (logger.isDebugEnabled()) logger.debug("Inside computeAverage"); // get the parent node NodeRef parentRef = childAssocRef.getParentRef(); // check the parent to make sure it has the right aspect if (nodeService.exists(parentRef) && nodeService.hasAspect(parentRef, QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.ASPECT_SCR_RATEABLE))) { // continue, this is what we want } else { if (logger.isDebugEnabled()) logger.debug("Rating's parent ref did not have rateable aspect."); return; } // get the parent node's children List<ChildAssociationRef> children = nodeService.getChildAssocs(parentRef); Double average = 0d; int count = 0; int total = 0; // This actually happens when the last rating is deleted if (children.size() == 0) { // No children so no work to do if (logger.isDebugEnabled()) logger.debug("No children found"); } else { // iterate through the children to compute the total for (ChildAssociationRef child : children) { if (!child.getTypeQName().isMatch(QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.ASSN_SCR_RATINGS))) { continue; } int rating = 0; rating = (Integer)nodeService.getProperty(child.getChildRef(), QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.PROP_RATING)); count += 1; total += rating; } // compute the average if (count != 0) { average = total / (count / 1.0d); } if (logger.isDebugEnabled()) logger.debug("Computed average:" + average); } // store the average on the parent node nodeService.setProperty(parentRef, QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.PROP_AVERAGE_RATING), average); nodeService.setProperty(parentRef, QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.PROP_TOTAL_RATING), total); nodeService.setProperty(parentRef, QName.createQName(SomeCoRatingsModel.NAMESPACE_SOMECO_RATINGS_CONTENT_MODEL, SomeCoRatingsModel.PROP_RATING_COUNT), count); if (logger.isDebugEnabled()) logger.debug("Property set"); return; }
diff --git a/src/org/protege/editor/owl/ui/view/SelectedEntityCardView.java b/src/org/protege/editor/owl/ui/view/SelectedEntityCardView.java index 1748be80..87c65207 100644 --- a/src/org/protege/editor/owl/ui/view/SelectedEntityCardView.java +++ b/src/org/protege/editor/owl/ui/view/SelectedEntityCardView.java @@ -1,155 +1,155 @@ package org.protege.editor.owl.ui.view; import org.protege.editor.core.ui.view.ViewsPane; import org.protege.editor.core.ui.view.ViewsPaneMemento; import org.protege.editor.owl.model.selection.OWLSelectionModelListener; import org.semanticweb.owl.model.*; import javax.swing.*; import java.awt.*; import java.net.URL; /* * Copyright (C) 2007, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Author: Matthew Horridge<br> * The University Of Manchester<br> * Bio-Health Informatics Group<br> * Date: 02-Mar-2007<br><br> */ public class SelectedEntityCardView extends AbstractOWLViewComponent { public static final String ID = "org.protege.editor.owl.SelectedEntityView"; private CardLayout cardLayout = new CardLayout(); private JPanel cardPanel; private ViewsPane classesViewsPane; private ViewsPane objectPropertiesViewsPane; private ViewsPane dataPropertiesViewsPane; private ViewsPane individualViewsPane; private static final String CLASSES_PANEL = "Classes"; private static final String BLANK_PANEL = "Blank"; private static final String OBJECT_PROPERTIES_PANEL = "ObjectProperties"; private static final String DATA_PROPERTIES_PANEL = "DataProperties"; private static final String INDIVIDUALS_PANEL = "Individual"; protected void initialiseOWLView() throws Exception { setLayout(new BorderLayout()); cardPanel = new JPanel(); add(cardPanel); cardPanel.setLayout(cardLayout); cardPanel.add(new JPanel(), BLANK_PANEL); URL clsURL = getClass().getResource("/selected-entity-view-class-panel.xml"); classesViewsPane = new ViewsPane(getOWLWorkspace(), new ViewsPaneMemento(clsURL, "org.protege.editor.owl.ui.view.selectedentityview.classes")); cardPanel.add(classesViewsPane, CLASSES_PANEL); URL objPropURL = getClass().getResource("/selected-entity-view-objectproperty-panel.xml"); objectPropertiesViewsPane = new ViewsPane(getOWLWorkspace(), new ViewsPaneMemento(objPropURL, "org.protege.editor.owl.ui.view.selectedentityview.objectproperties")); cardPanel.add(objectPropertiesViewsPane, OBJECT_PROPERTIES_PANEL); URL dataPropURL = getClass().getResource("/selected-entity-view-dataproperty-panel.xml"); dataPropertiesViewsPane = new ViewsPane(getOWLWorkspace(), new ViewsPaneMemento(dataPropURL, - "org.protege.editor.owl.ui.view.selectedentityview.objectproperties")); + "org.protege.editor.owl.ui.view.selectedentityview.dataproperties")); cardPanel.add(dataPropertiesViewsPane, DATA_PROPERTIES_PANEL); URL indURL = getClass().getResource("/selected-entity-view-individual-panel.xml"); individualViewsPane = new ViewsPane(getOWLWorkspace(), new ViewsPaneMemento(indURL, "org.protege.editor.owl.ui.view.selectedentityview.individuals")); cardPanel.add(individualViewsPane, INDIVIDUALS_PANEL); getOWLWorkspace().getOWLSelectionModel().addListener(new OWLSelectionModelListener() { public void selectionChanged() throws Exception { processSelection(); } }); // getView().setShowViewBar(false); processSelection(); } private void processSelection() { OWLEntity entity = getOWLWorkspace().getOWLSelectionModel().getSelectedEntity(); if (entity == null) { selectPanel(BLANK_PANEL); } else { entity.accept(new OWLEntityVisitor() { public void visit(OWLClass cls) { selectPanel(CLASSES_PANEL); } public void visit(OWLObjectProperty property) { selectPanel(OBJECT_PROPERTIES_PANEL); } public void visit(OWLDataProperty property) { selectPanel(DATA_PROPERTIES_PANEL); } public void visit(OWLIndividual individual) { selectPanel(INDIVIDUALS_PANEL); } public void visit(OWLDataType dataType) { } }); } } private void selectPanel(String name) { cardLayout.show(cardPanel, name); } protected void disposeOWLView() { classesViewsPane.saveViews(); classesViewsPane.dispose(); objectPropertiesViewsPane.saveViews(); objectPropertiesViewsPane.dispose(); dataPropertiesViewsPane.saveViews(); dataPropertiesViewsPane.dispose(); individualViewsPane.saveViews(); individualViewsPane.dispose(); } }
true
true
protected void initialiseOWLView() throws Exception { setLayout(new BorderLayout()); cardPanel = new JPanel(); add(cardPanel); cardPanel.setLayout(cardLayout); cardPanel.add(new JPanel(), BLANK_PANEL); URL clsURL = getClass().getResource("/selected-entity-view-class-panel.xml"); classesViewsPane = new ViewsPane(getOWLWorkspace(), new ViewsPaneMemento(clsURL, "org.protege.editor.owl.ui.view.selectedentityview.classes")); cardPanel.add(classesViewsPane, CLASSES_PANEL); URL objPropURL = getClass().getResource("/selected-entity-view-objectproperty-panel.xml"); objectPropertiesViewsPane = new ViewsPane(getOWLWorkspace(), new ViewsPaneMemento(objPropURL, "org.protege.editor.owl.ui.view.selectedentityview.objectproperties")); cardPanel.add(objectPropertiesViewsPane, OBJECT_PROPERTIES_PANEL); URL dataPropURL = getClass().getResource("/selected-entity-view-dataproperty-panel.xml"); dataPropertiesViewsPane = new ViewsPane(getOWLWorkspace(), new ViewsPaneMemento(dataPropURL, "org.protege.editor.owl.ui.view.selectedentityview.objectproperties")); cardPanel.add(dataPropertiesViewsPane, DATA_PROPERTIES_PANEL); URL indURL = getClass().getResource("/selected-entity-view-individual-panel.xml"); individualViewsPane = new ViewsPane(getOWLWorkspace(), new ViewsPaneMemento(indURL, "org.protege.editor.owl.ui.view.selectedentityview.individuals")); cardPanel.add(individualViewsPane, INDIVIDUALS_PANEL); getOWLWorkspace().getOWLSelectionModel().addListener(new OWLSelectionModelListener() { public void selectionChanged() throws Exception { processSelection(); } }); // getView().setShowViewBar(false); processSelection(); }
protected void initialiseOWLView() throws Exception { setLayout(new BorderLayout()); cardPanel = new JPanel(); add(cardPanel); cardPanel.setLayout(cardLayout); cardPanel.add(new JPanel(), BLANK_PANEL); URL clsURL = getClass().getResource("/selected-entity-view-class-panel.xml"); classesViewsPane = new ViewsPane(getOWLWorkspace(), new ViewsPaneMemento(clsURL, "org.protege.editor.owl.ui.view.selectedentityview.classes")); cardPanel.add(classesViewsPane, CLASSES_PANEL); URL objPropURL = getClass().getResource("/selected-entity-view-objectproperty-panel.xml"); objectPropertiesViewsPane = new ViewsPane(getOWLWorkspace(), new ViewsPaneMemento(objPropURL, "org.protege.editor.owl.ui.view.selectedentityview.objectproperties")); cardPanel.add(objectPropertiesViewsPane, OBJECT_PROPERTIES_PANEL); URL dataPropURL = getClass().getResource("/selected-entity-view-dataproperty-panel.xml"); dataPropertiesViewsPane = new ViewsPane(getOWLWorkspace(), new ViewsPaneMemento(dataPropURL, "org.protege.editor.owl.ui.view.selectedentityview.dataproperties")); cardPanel.add(dataPropertiesViewsPane, DATA_PROPERTIES_PANEL); URL indURL = getClass().getResource("/selected-entity-view-individual-panel.xml"); individualViewsPane = new ViewsPane(getOWLWorkspace(), new ViewsPaneMemento(indURL, "org.protege.editor.owl.ui.view.selectedentityview.individuals")); cardPanel.add(individualViewsPane, INDIVIDUALS_PANEL); getOWLWorkspace().getOWLSelectionModel().addListener(new OWLSelectionModelListener() { public void selectionChanged() throws Exception { processSelection(); } }); // getView().setShowViewBar(false); processSelection(); }
diff --git a/src/com/aokp/romcontrol/fragments/UserInterface.java b/src/com/aokp/romcontrol/fragments/UserInterface.java index 5ad3f79..0b181bb 100644 --- a/src/com/aokp/romcontrol/fragments/UserInterface.java +++ b/src/com/aokp/romcontrol/fragments/UserInterface.java @@ -1,740 +1,734 @@ package com.aokp.romcontrol.fragments; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.util.Random; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Point; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.Rect; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemProperties; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceGroup; import android.preference.PreferenceScreen; import android.provider.MediaStore; import android.provider.Settings; import android.text.Spannable; import android.util.Log; import android.view.Display; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.Window; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import com.aokp.romcontrol.AOKPPreferenceFragment; import com.aokp.romcontrol.R; import com.aokp.romcontrol.util.CMDProcessor; import com.aokp.romcontrol.util.Helpers; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class UserInterface extends AOKPPreferenceFragment { public static final String TAG = "UserInterface"; private static final String PREF_180 = "rotate_180"; private static final String PREF_STATUS_BAR_NOTIF_COUNT = "status_bar_notif_count"; private static final String PREF_NOTIFICATION_WALLPAPER = "notification_wallpaper"; private static final String PREF_NOTIFICATION_WALLPAPER_ALPHA = "notification_wallpaper_alpha"; private static final String PREF_CUSTOM_CARRIER_LABEL = "custom_carrier_label"; private static final String PREF_IME_SWITCHER = "ime_switcher"; private static final String PREF_RECENT_KILL_ALL = "recent_kill_all"; private static final String PREF_RAM_USAGE_BAR = "ram_usage_bar"; private static final String PREF_KILL_APP_LONGPRESS_BACK = "kill_app_longpress_back"; private static final String PREF_MODE_TABLET_UI = "mode_tabletui"; private static final String PREF_HIDE_EXTRAS = "hide_extras"; private static final String PREF_FORCE_DUAL_PANEL = "force_dualpanel"; private static final String PREF_USE_ALT_RESOLVER = "use_alt_resolver"; private static final String PREF_SHOW_OVERFLOW = "show_overflow"; private static final String PREF_VIBRATE_NOTIF_EXPAND = "vibrate_notif_expand"; private static final int REQUEST_PICK_WALLPAPER = 201; private static final int REQUEST_PICK_CUSTOM_ICON = 202; private static final int REQUEST_PICK_BOOT_ANIMATION = 203; private static final int SELECT_ACTIVITY = 4; private static final int SELECT_WALLPAPER = 5; private static final String WALLPAPER_NAME = "notification_wallpaper.jpg"; CheckBoxPreference mAllow180Rotation; CheckBoxPreference mDisableBootAnimation; CheckBoxPreference mStatusBarNotifCount; Preference mNotificationWallpaper; Preference mCustomBootAnimation; Preference mWallpaperAlpha; Preference mCustomLabel; CheckBoxPreference mShowImeSwitcher; CheckBoxPreference mRecentKillAll; CheckBoxPreference mRamBar; CheckBoxPreference mKillAppLongpressBack; CheckBoxPreference mUseAltResolver; ImageView view; TextView error; CheckBoxPreference mShowActionOverflow; CheckBoxPreference mTabletui; CheckBoxPreference mHideExtras; CheckBoxPreference mDualpane; CheckBoxPreference mVibrateOnExpand; Preference mLcdDensity; private AnimationDrawable mAnimationPart1; private AnimationDrawable mAnimationPart2; private String mPartName1; private String mPartName2; private int delay; private int height; private int width; private String errormsg; private String bootAniPath; Random randomGenerator = new Random(); private int seekbarProgress; String mCustomLabelText = null; int newDensityValue; DensityChanger densityFragment; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.title_ui); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.prefs_ui); PreferenceScreen prefs = getPreferenceScreen(); mAllow180Rotation = (CheckBoxPreference) findPreference(PREF_180); mAllow180Rotation.setChecked(Settings.System.getInt(mContext .getContentResolver(), Settings.System.ACCELEROMETER_ROTATION_ANGLES, (1 | 2 | 8)) == (1 | 2 | 4 | 8)); mStatusBarNotifCount = (CheckBoxPreference) findPreference(PREF_STATUS_BAR_NOTIF_COUNT); mStatusBarNotifCount.setChecked(Settings.System.getBoolean(mContext .getContentResolver(), Settings.System.STATUS_BAR_NOTIF_COUNT, false)); mDisableBootAnimation = (CheckBoxPreference)findPreference("disable_bootanimation"); mDisableBootAnimation.setChecked(!new File("/system/media/bootanimation.zip").exists()); if (mDisableBootAnimation.isChecked()) { Resources res = mContext.getResources(); String[] insults = res.getStringArray(R.array.disable_bootanimation_insults); int randomInt = randomGenerator.nextInt(insults.length); mDisableBootAnimation.setSummary(insults[randomInt]); } mLcdDensity = findPreference("lcd_density_setup"); String currentProperty = SystemProperties.get("ro.sf.lcd_density"); try { newDensityValue = Integer.parseInt(currentProperty); } catch (Exception e) { getPreferenceScreen().removePreference(mLcdDensity); } mLcdDensity.setSummary(getResources().getString(R.string.current_lcd_density) + currentProperty); mCustomBootAnimation = findPreference("custom_bootanimation"); mCustomLabel = findPreference(PREF_CUSTOM_CARRIER_LABEL); updateCustomLabelTextSummary(); mShowImeSwitcher = (CheckBoxPreference) findPreference(PREF_IME_SWITCHER); mShowImeSwitcher.setChecked(Settings.System.getBoolean(mContext.getContentResolver(), Settings.System.SHOW_STATUSBAR_IME_SWITCHER, true)); mRecentKillAll = (CheckBoxPreference) findPreference(PREF_RECENT_KILL_ALL); mRecentKillAll.setChecked(Settings.System.getBoolean(getActivity ().getContentResolver(), Settings.System.RECENT_KILL_ALL_BUTTON, false)); mRamBar = (CheckBoxPreference) findPreference(PREF_RAM_USAGE_BAR); mRamBar.setChecked(Settings.System.getBoolean(getActivity ().getContentResolver(), Settings.System.RAM_USAGE_BAR, false)); mKillAppLongpressBack = (CheckBoxPreference) findPreference(PREF_KILL_APP_LONGPRESS_BACK); updateKillAppLongpressBackOptions(); mShowActionOverflow = (CheckBoxPreference) findPreference(PREF_SHOW_OVERFLOW); mShowActionOverflow.setChecked((Settings.System.getInt(getActivity(). getApplicationContext().getContentResolver(), Settings.System.UI_FORCE_OVERFLOW_BUTTON, 0) == 1)); mTabletui = (CheckBoxPreference) findPreference(PREF_MODE_TABLET_UI); mTabletui.setChecked(Settings.System.getBoolean(mContext.getContentResolver(), Settings.System.MODE_TABLET_UI, false)); mHideExtras = (CheckBoxPreference) findPreference(PREF_HIDE_EXTRAS); mHideExtras.setChecked(Settings.System.getBoolean(mContext.getContentResolver(), Settings.System.HIDE_EXTRAS_SYSTEM_BAR, false)); mUseAltResolver = (CheckBoxPreference) findPreference(PREF_USE_ALT_RESOLVER); mUseAltResolver.setChecked(Settings.System.getBoolean(mContext.getContentResolver(), Settings.System.ACTIVITY_RESOLVER_USE_ALT, false)); mDualpane = (CheckBoxPreference) findPreference(PREF_FORCE_DUAL_PANEL); mDualpane.setChecked(Settings.System.getBoolean(mContext.getContentResolver(), Settings.System.FORCE_DUAL_PANEL, getResources().getBoolean( com.android.internal.R.bool.preferences_prefer_dual_pane))); boolean hasNavBarByDefault = mContext.getResources().getBoolean( com.android.internal.R.bool.config_showNavigationBar); if (hasNavBarByDefault || mTablet) { ((PreferenceGroup) findPreference("navbar")).removePreference(mKillAppLongpressBack); } mNotificationWallpaper = findPreference(PREF_NOTIFICATION_WALLPAPER); mWallpaperAlpha = (Preference) findPreference(PREF_NOTIFICATION_WALLPAPER_ALPHA); mVibrateOnExpand = (CheckBoxPreference) findPreference(PREF_VIBRATE_NOTIF_EXPAND); mVibrateOnExpand.setChecked(Settings.System.getBoolean(mContext.getContentResolver(), Settings.System.VIBRATE_NOTIF_EXPAND, true)); if (mTablet) { prefs.removePreference(mNotificationWallpaper); prefs.removePreference(mWallpaperAlpha); } else { prefs.removePreference(mTabletui); } setHasOptionsMenu(true); } private void writeKillAppLongpressBackOptions() { Settings.System.putInt(getActivity().getContentResolver(), Settings.System.KILL_APP_LONGPRESS_BACK, mKillAppLongpressBack.isChecked() ? 1 : 0); } private void updateKillAppLongpressBackOptions() { mKillAppLongpressBack.setChecked(Settings.System.getInt(getActivity().getContentResolver(), Settings.System.KILL_APP_LONGPRESS_BACK, 0) != 0); } private void updateCustomLabelTextSummary() { mCustomLabelText = Settings.System.getString(getActivity().getContentResolver(), Settings.System.CUSTOM_CARRIER_LABEL); if (mCustomLabelText == null || mCustomLabelText.length() == 0) { mCustomLabel.setSummary(R.string.custom_carrier_label_notset); } else { mCustomLabel.setSummary(mCustomLabelText); } } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (preference == mAllow180Rotation) { boolean checked = ((CheckBoxPreference) preference).isChecked(); Settings.System.putInt(mContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION_ANGLES, checked ? (1 | 2 | 4 | 8) : (1 | 2 | 8 )); return true; } else if (preference == mStatusBarNotifCount) { Settings.System.putBoolean(mContext.getContentResolver(), Settings.System.STATUS_BAR_NOTIF_COUNT, ((CheckBoxPreference) preference).isChecked()); return true; } else if (preference == mDisableBootAnimation) { boolean checked = ((CheckBoxPreference) preference).isChecked(); if (checked) { Helpers.getMount("rw"); new CMDProcessor().su .runWaitFor("mv /system/media/bootanimation.zip /system/media/bootanimation.backup"); Helpers.getMount("ro"); Resources res = mContext.getResources(); String[] insults = res.getStringArray(R.array.disable_bootanimation_insults); int randomInt = randomGenerator.nextInt(insults.length); preference.setSummary(insults[randomInt]); } else { Helpers.getMount("rw"); new CMDProcessor().su .runWaitFor("mv /system/media/bootanimation.backup /system/media/bootanimation.zip"); Helpers.getMount("ro"); preference.setSummary(""); } return true; } else if (preference == mShowActionOverflow) { boolean enabled = mShowActionOverflow.isChecked(); Settings.System.putInt(getContentResolver(), Settings.System.UI_FORCE_OVERFLOW_BUTTON, enabled ? 1 : 0); // Show toast appropriately if (enabled) { Toast.makeText(getActivity(), R.string.show_overflow_toast_enable, Toast.LENGTH_LONG).show(); } else { Toast.makeText(getActivity(), R.string.show_overflow_toast_disable, Toast.LENGTH_LONG).show(); } return true; } else if (preference == mTabletui) { Settings.System.putBoolean(mContext.getContentResolver(), Settings.System.MODE_TABLET_UI, ((CheckBoxPreference) preference).isChecked()); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.STATUSBAR_TOGGLES_BRIGHTNESS_LOC, 3); return true; } else if (preference == mHideExtras) { Settings.System.putBoolean(mContext.getContentResolver(), Settings.System.HIDE_EXTRAS_SYSTEM_BAR, ((CheckBoxPreference) preference).isChecked()); Helpers.restartSystemUI(); return true; } else if (preference == mDualpane) { Settings.System.putBoolean(mContext.getContentResolver(), Settings.System.FORCE_DUAL_PANEL, ((CheckBoxPreference) preference).isChecked()); return true; } else if (preference == mCustomBootAnimation) { PackageManager packageManager = getActivity().getPackageManager(); Intent test = new Intent(Intent.ACTION_GET_CONTENT); test.setType("file/*"); List<ResolveInfo> list = packageManager.queryIntentActivities(test, PackageManager.GET_ACTIVITIES); if(list.size() > 0) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("file/*"); startActivityForResult(intent, REQUEST_PICK_BOOT_ANIMATION); } else { //No app installed to handle the intent - file explorer required Toast.makeText(mContext, R.string.install_file_manager_error, Toast.LENGTH_SHORT).show(); } return true; } else if (preference == mNotificationWallpaper) { Display display = getActivity().getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); - Rect rect = new Rect(); - Window window = getActivity().getWindow(); - window.getDecorView().getWindowVisibleDisplayFrame(rect); - int statusBarHeight = rect.top; - int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT).getTop(); - int titleBarHeight = contentViewTop - statusBarHeight; Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("image/*"); intent.putExtra("crop", "true"); boolean isPortrait = getResources() .getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; - intent.putExtra("aspectX", isPortrait ? width : height - titleBarHeight); - intent.putExtra("aspectY", isPortrait ? height - titleBarHeight : width); + intent.putExtra("aspectX", isPortrait ? width : height); + intent.putExtra("aspectY", isPortrait ? height : width); intent.putExtra("outputX", width); intent.putExtra("outputY", height); intent.putExtra("scale", true); intent.putExtra("scaleUpIfNeeded", true); intent.putExtra(MediaStore.EXTRA_OUTPUT, getNotificationExternalUri()); intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString()); startActivityForResult(intent, REQUEST_PICK_WALLPAPER); return true; } else if (preference == mWallpaperAlpha) { Resources res = getActivity().getResources(); String cancel = res.getString(R.string.cancel); String ok = res.getString(R.string.ok); String title = res.getString(R.string.alpha_dialog_title); float savedProgress = Settings.System.getFloat(getActivity() .getContentResolver(), Settings.System.NOTIF_WALLPAPER_ALPHA, 1.0f); LayoutInflater factory = LayoutInflater.from(getActivity()); final View alphaDialog = factory.inflate(R.layout.seekbar_dialog, null); SeekBar seekbar = (SeekBar) alphaDialog.findViewById(R.id.seek_bar); OnSeekBarChangeListener seekBarChangeListener = new OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) { seekbarProgress = seekbar.getProgress(); } @Override public void onStopTrackingTouch(SeekBar seekbar) { } @Override public void onStartTrackingTouch(SeekBar seekbar) { } }; seekbar.setProgress((int) (savedProgress * 100)); seekbar.setMax(100); seekbar.setOnSeekBarChangeListener(seekBarChangeListener); new AlertDialog.Builder(getActivity()) .setTitle(title) .setView(alphaDialog) .setNegativeButton(cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // nothing } }) .setPositiveButton(ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { float val = ((float) seekbarProgress / 100); Settings.System.putFloat(getActivity().getContentResolver(), Settings.System.NOTIF_WALLPAPER_ALPHA, val); Helpers.restartSystemUI(); } }) .create() .show(); return true; } else if (preference == mShowImeSwitcher) { Settings.System.putBoolean(getActivity().getContentResolver(), Settings.System.SHOW_STATUSBAR_IME_SWITCHER, isCheckBoxPrefernceChecked(preference)); return true; } else if (preference == mRecentKillAll) { boolean checked = ((CheckBoxPreference)preference).isChecked(); Settings.System.putBoolean(getActivity().getContentResolver(), Settings.System.RECENT_KILL_ALL_BUTTON, checked ? true : false); return true; } else if (preference == mRamBar) { boolean checked = ((CheckBoxPreference)preference).isChecked(); Settings.System.putBoolean(getActivity().getContentResolver(), Settings.System.RAM_USAGE_BAR, checked ? true : false); return true; } else if (preference == mKillAppLongpressBack) { writeKillAppLongpressBackOptions(); } else if (preference == mCustomLabel) { AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setTitle(R.string.custom_carrier_label_title); alert.setMessage(R.string.custom_carrier_label_explain); // Set an EditText view to get user input final EditText input = new EditText(getActivity()); input.setText(mCustomLabelText != null ? mCustomLabelText : ""); alert.setView(input); alert.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String value = ((Spannable) input.getText()).toString(); Settings.System.putString(getActivity().getContentResolver(), Settings.System.CUSTOM_CARRIER_LABEL, value); updateCustomLabelTextSummary(); Intent i = new Intent(); i.setAction("com.aokp.romcontrol.LABEL_CHANGED"); mContext.sendBroadcast(i); } }); alert.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Canceled. } }); alert.show(); } else if (preference == mLcdDensity) { ((PreferenceActivity) getActivity()) .startPreferenceFragment(new DensityChanger(), true); return true; } else if (preference == mUseAltResolver) { Settings.System.putBoolean(getActivity().getContentResolver(), Settings.System.ACTIVITY_RESOLVER_USE_ALT, isCheckBoxPrefernceChecked(preference)); return true; } else if (preference == mVibrateOnExpand) { Settings.System.putBoolean(mContext.getContentResolver(), Settings.System.VIBRATE_NOTIF_EXPAND, ((CheckBoxPreference) preference).isChecked()); Helpers.restartSystemUI(); return true; } return super.onPreferenceTreeClick(preferenceScreen, preference); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.user_interface, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case R.id.remove_wallpaper: File f = new File(mContext.getFilesDir(), WALLPAPER_NAME); mContext.deleteFile(WALLPAPER_NAME); Helpers.restartSystemUI(); return true; default: return super.onContextItemSelected(item); } } private Uri getNotificationExternalUri() { File dir = mContext.getExternalCacheDir(); File wallpaper = new File(dir, WALLPAPER_NAME); return Uri.fromFile(wallpaper); } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { if (requestCode == REQUEST_PICK_WALLPAPER) { FileOutputStream wallpaperStream = null; try { wallpaperStream = mContext.openFileOutput(WALLPAPER_NAME, Context.MODE_WORLD_READABLE); } catch (FileNotFoundException e) { return; // NOOOOO } Uri selectedImageUri = getNotificationExternalUri(); Bitmap bitmap = BitmapFactory.decodeFile(selectedImageUri.getPath()); bitmap.compress(Bitmap.CompressFormat.PNG, 100, wallpaperStream); Helpers.restartSystemUI(); } else if (requestCode == REQUEST_PICK_BOOT_ANIMATION) { if (data==null) { //Nothing returned by user, probably pressed back button in file manager return; } bootAniPath = data.getData().getEncodedPath(); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.bootanimation_preview); builder.setPositiveButton(R.string.apply, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Helpers.getMount("rw"); //backup old boot animation new CMDProcessor().su.runWaitFor("mv /system/media/bootanimation.zip /system/media/bootanimation.backup"); //Copy new bootanimation, give proper permissions new CMDProcessor().su.runWaitFor("cp "+ bootAniPath +" /system/media/bootanimation.zip"); new CMDProcessor().su.runWaitFor("chmod 644 /system/media/bootanimation.zip"); //Update setting to reflect that boot animation is now enabled mDisableBootAnimation.setChecked(false); Helpers.getMount("ro"); dialog.dismiss(); } }); builder.setNegativeButton(com.android.internal.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(getActivity().LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.dialog_bootanimation_preview, (ViewGroup) getActivity().findViewById(R.id.bootanimation_layout_root)); error = (TextView) layout.findViewById(R.id.textViewError); view = (ImageView) layout.findViewById(R.id.imageViewPreview); view.setVisibility(View.GONE); Display display = getActivity().getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); view.setLayoutParams(new LinearLayout.LayoutParams(size.x/2, size.y/2)); error.setText(R.string.creating_preview); builder.setView(layout); AlertDialog dialog = builder.create(); dialog.setOwnerActivity(getActivity()); dialog.show(); Thread thread = new Thread(new Runnable() { @Override public void run() { createPreview(bootAniPath); } }); thread.start(); } } } public void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dst); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } private void createPreview(String path) { File zip = new File(path); ZipFile zipfile = null; String desc = ""; try { zipfile = new ZipFile(zip); ZipEntry ze = zipfile.getEntry("desc.txt"); InputStream in = zipfile.getInputStream(ze); InputStreamReader is = new InputStreamReader(in); StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(is); String read = br.readLine(); while(read != null) { sb.append(read); sb.append("\n"); read = br.readLine(); } desc = sb.toString(); br.close(); is.close(); in.close(); } catch (Exception e1) { errormsg = getActivity().getString(R.string.error_reading_zip_file); errorHandler.sendEmptyMessage(0); return; } String[] info = desc.replace("\\r", "").split("\\n"); width = Integer.parseInt(info[0].split(" ")[0]); height = Integer.parseInt(info[0].split(" ")[1]); delay = Integer.parseInt(info[0].split(" ")[2]); mPartName1 = info[1].split(" ")[3]; try { if (info.length > 2) { mPartName2 = info[2].split(" ")[3]; } else { mPartName2 = ""; } } catch (Exception e) { mPartName2 = ""; } BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inSampleSize = 4; mAnimationPart1 = new AnimationDrawable(); mAnimationPart2 = new AnimationDrawable(); try { for (Enumeration<? extends ZipEntry> e = zipfile.entries(); e.hasMoreElements();) { ZipEntry entry = (ZipEntry) e.nextElement(); if (entry.isDirectory()) { continue; } String partname = entry.getName().split("/")[0]; if (mPartName1.equalsIgnoreCase(partname)) { InputStream is = zipfile.getInputStream(entry); mAnimationPart1.addFrame(new BitmapDrawable(getResources(), BitmapFactory.decodeStream(is, null, opt)), delay); is.close(); } else if (mPartName2.equalsIgnoreCase(partname)) { InputStream is = zipfile.getInputStream(entry); mAnimationPart2.addFrame(new BitmapDrawable(getResources(), BitmapFactory.decodeStream(is, null, opt)), delay); is.close(); } } } catch (IOException e1) { errormsg = getActivity().getString(R.string.error_creating_preview); errorHandler.sendEmptyMessage(0); return; } if (mPartName2.length() > 0) { Log.d(TAG, "Multipart Animation"); mAnimationPart1.setOneShot(false); mAnimationPart2.setOneShot(false); mAnimationPart1.setOnAnimationFinishedListener(new AnimationDrawable.OnAnimationFinishedListener() { @Override public void onAnimationFinished() { Log.d(TAG, "First part finished"); view.setImageDrawable(mAnimationPart2); mAnimationPart1.stop(); mAnimationPart2.start(); } }); } else { mAnimationPart1.setOneShot(false); } finishedHandler.sendEmptyMessage(0); } private Handler errorHandler = new Handler() { @Override public void handleMessage(Message msg) { view.setVisibility(View.GONE); error.setText(errormsg); } }; private Handler finishedHandler = new Handler() { @Override public void handleMessage(Message msg) { view.setImageDrawable(mAnimationPart1); view.setVisibility(View.VISIBLE); error.setVisibility(View.GONE); mAnimationPart1.start(); } }; }
false
true
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (preference == mAllow180Rotation) { boolean checked = ((CheckBoxPreference) preference).isChecked(); Settings.System.putInt(mContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION_ANGLES, checked ? (1 | 2 | 4 | 8) : (1 | 2 | 8 )); return true; } else if (preference == mStatusBarNotifCount) { Settings.System.putBoolean(mContext.getContentResolver(), Settings.System.STATUS_BAR_NOTIF_COUNT, ((CheckBoxPreference) preference).isChecked()); return true; } else if (preference == mDisableBootAnimation) { boolean checked = ((CheckBoxPreference) preference).isChecked(); if (checked) { Helpers.getMount("rw"); new CMDProcessor().su .runWaitFor("mv /system/media/bootanimation.zip /system/media/bootanimation.backup"); Helpers.getMount("ro"); Resources res = mContext.getResources(); String[] insults = res.getStringArray(R.array.disable_bootanimation_insults); int randomInt = randomGenerator.nextInt(insults.length); preference.setSummary(insults[randomInt]); } else { Helpers.getMount("rw"); new CMDProcessor().su .runWaitFor("mv /system/media/bootanimation.backup /system/media/bootanimation.zip"); Helpers.getMount("ro"); preference.setSummary(""); } return true; } else if (preference == mShowActionOverflow) { boolean enabled = mShowActionOverflow.isChecked(); Settings.System.putInt(getContentResolver(), Settings.System.UI_FORCE_OVERFLOW_BUTTON, enabled ? 1 : 0); // Show toast appropriately if (enabled) { Toast.makeText(getActivity(), R.string.show_overflow_toast_enable, Toast.LENGTH_LONG).show(); } else { Toast.makeText(getActivity(), R.string.show_overflow_toast_disable, Toast.LENGTH_LONG).show(); } return true; } else if (preference == mTabletui) { Settings.System.putBoolean(mContext.getContentResolver(), Settings.System.MODE_TABLET_UI, ((CheckBoxPreference) preference).isChecked()); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.STATUSBAR_TOGGLES_BRIGHTNESS_LOC, 3); return true; } else if (preference == mHideExtras) { Settings.System.putBoolean(mContext.getContentResolver(), Settings.System.HIDE_EXTRAS_SYSTEM_BAR, ((CheckBoxPreference) preference).isChecked()); Helpers.restartSystemUI(); return true; } else if (preference == mDualpane) { Settings.System.putBoolean(mContext.getContentResolver(), Settings.System.FORCE_DUAL_PANEL, ((CheckBoxPreference) preference).isChecked()); return true; } else if (preference == mCustomBootAnimation) { PackageManager packageManager = getActivity().getPackageManager(); Intent test = new Intent(Intent.ACTION_GET_CONTENT); test.setType("file/*"); List<ResolveInfo> list = packageManager.queryIntentActivities(test, PackageManager.GET_ACTIVITIES); if(list.size() > 0) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("file/*"); startActivityForResult(intent, REQUEST_PICK_BOOT_ANIMATION); } else { //No app installed to handle the intent - file explorer required Toast.makeText(mContext, R.string.install_file_manager_error, Toast.LENGTH_SHORT).show(); } return true; } else if (preference == mNotificationWallpaper) { Display display = getActivity().getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); Rect rect = new Rect(); Window window = getActivity().getWindow(); window.getDecorView().getWindowVisibleDisplayFrame(rect); int statusBarHeight = rect.top; int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT).getTop(); int titleBarHeight = contentViewTop - statusBarHeight; Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("image/*"); intent.putExtra("crop", "true"); boolean isPortrait = getResources() .getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; intent.putExtra("aspectX", isPortrait ? width : height - titleBarHeight); intent.putExtra("aspectY", isPortrait ? height - titleBarHeight : width); intent.putExtra("outputX", width); intent.putExtra("outputY", height); intent.putExtra("scale", true); intent.putExtra("scaleUpIfNeeded", true); intent.putExtra(MediaStore.EXTRA_OUTPUT, getNotificationExternalUri()); intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString()); startActivityForResult(intent, REQUEST_PICK_WALLPAPER); return true; } else if (preference == mWallpaperAlpha) { Resources res = getActivity().getResources(); String cancel = res.getString(R.string.cancel); String ok = res.getString(R.string.ok); String title = res.getString(R.string.alpha_dialog_title); float savedProgress = Settings.System.getFloat(getActivity() .getContentResolver(), Settings.System.NOTIF_WALLPAPER_ALPHA, 1.0f); LayoutInflater factory = LayoutInflater.from(getActivity()); final View alphaDialog = factory.inflate(R.layout.seekbar_dialog, null); SeekBar seekbar = (SeekBar) alphaDialog.findViewById(R.id.seek_bar); OnSeekBarChangeListener seekBarChangeListener = new OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) { seekbarProgress = seekbar.getProgress(); } @Override public void onStopTrackingTouch(SeekBar seekbar) { } @Override public void onStartTrackingTouch(SeekBar seekbar) { } }; seekbar.setProgress((int) (savedProgress * 100)); seekbar.setMax(100); seekbar.setOnSeekBarChangeListener(seekBarChangeListener); new AlertDialog.Builder(getActivity()) .setTitle(title) .setView(alphaDialog) .setNegativeButton(cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // nothing } }) .setPositiveButton(ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { float val = ((float) seekbarProgress / 100); Settings.System.putFloat(getActivity().getContentResolver(), Settings.System.NOTIF_WALLPAPER_ALPHA, val); Helpers.restartSystemUI(); } }) .create() .show(); return true; } else if (preference == mShowImeSwitcher) { Settings.System.putBoolean(getActivity().getContentResolver(), Settings.System.SHOW_STATUSBAR_IME_SWITCHER, isCheckBoxPrefernceChecked(preference)); return true; } else if (preference == mRecentKillAll) { boolean checked = ((CheckBoxPreference)preference).isChecked(); Settings.System.putBoolean(getActivity().getContentResolver(), Settings.System.RECENT_KILL_ALL_BUTTON, checked ? true : false); return true; } else if (preference == mRamBar) { boolean checked = ((CheckBoxPreference)preference).isChecked(); Settings.System.putBoolean(getActivity().getContentResolver(), Settings.System.RAM_USAGE_BAR, checked ? true : false); return true; } else if (preference == mKillAppLongpressBack) { writeKillAppLongpressBackOptions(); } else if (preference == mCustomLabel) { AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setTitle(R.string.custom_carrier_label_title); alert.setMessage(R.string.custom_carrier_label_explain); // Set an EditText view to get user input final EditText input = new EditText(getActivity()); input.setText(mCustomLabelText != null ? mCustomLabelText : ""); alert.setView(input); alert.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String value = ((Spannable) input.getText()).toString(); Settings.System.putString(getActivity().getContentResolver(), Settings.System.CUSTOM_CARRIER_LABEL, value); updateCustomLabelTextSummary(); Intent i = new Intent(); i.setAction("com.aokp.romcontrol.LABEL_CHANGED"); mContext.sendBroadcast(i); } }); alert.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Canceled. } }); alert.show(); } else if (preference == mLcdDensity) { ((PreferenceActivity) getActivity()) .startPreferenceFragment(new DensityChanger(), true); return true; } else if (preference == mUseAltResolver) { Settings.System.putBoolean(getActivity().getContentResolver(), Settings.System.ACTIVITY_RESOLVER_USE_ALT, isCheckBoxPrefernceChecked(preference)); return true; } else if (preference == mVibrateOnExpand) { Settings.System.putBoolean(mContext.getContentResolver(), Settings.System.VIBRATE_NOTIF_EXPAND, ((CheckBoxPreference) preference).isChecked()); Helpers.restartSystemUI(); return true; } return super.onPreferenceTreeClick(preferenceScreen, preference); }
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (preference == mAllow180Rotation) { boolean checked = ((CheckBoxPreference) preference).isChecked(); Settings.System.putInt(mContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION_ANGLES, checked ? (1 | 2 | 4 | 8) : (1 | 2 | 8 )); return true; } else if (preference == mStatusBarNotifCount) { Settings.System.putBoolean(mContext.getContentResolver(), Settings.System.STATUS_BAR_NOTIF_COUNT, ((CheckBoxPreference) preference).isChecked()); return true; } else if (preference == mDisableBootAnimation) { boolean checked = ((CheckBoxPreference) preference).isChecked(); if (checked) { Helpers.getMount("rw"); new CMDProcessor().su .runWaitFor("mv /system/media/bootanimation.zip /system/media/bootanimation.backup"); Helpers.getMount("ro"); Resources res = mContext.getResources(); String[] insults = res.getStringArray(R.array.disable_bootanimation_insults); int randomInt = randomGenerator.nextInt(insults.length); preference.setSummary(insults[randomInt]); } else { Helpers.getMount("rw"); new CMDProcessor().su .runWaitFor("mv /system/media/bootanimation.backup /system/media/bootanimation.zip"); Helpers.getMount("ro"); preference.setSummary(""); } return true; } else if (preference == mShowActionOverflow) { boolean enabled = mShowActionOverflow.isChecked(); Settings.System.putInt(getContentResolver(), Settings.System.UI_FORCE_OVERFLOW_BUTTON, enabled ? 1 : 0); // Show toast appropriately if (enabled) { Toast.makeText(getActivity(), R.string.show_overflow_toast_enable, Toast.LENGTH_LONG).show(); } else { Toast.makeText(getActivity(), R.string.show_overflow_toast_disable, Toast.LENGTH_LONG).show(); } return true; } else if (preference == mTabletui) { Settings.System.putBoolean(mContext.getContentResolver(), Settings.System.MODE_TABLET_UI, ((CheckBoxPreference) preference).isChecked()); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.STATUSBAR_TOGGLES_BRIGHTNESS_LOC, 3); return true; } else if (preference == mHideExtras) { Settings.System.putBoolean(mContext.getContentResolver(), Settings.System.HIDE_EXTRAS_SYSTEM_BAR, ((CheckBoxPreference) preference).isChecked()); Helpers.restartSystemUI(); return true; } else if (preference == mDualpane) { Settings.System.putBoolean(mContext.getContentResolver(), Settings.System.FORCE_DUAL_PANEL, ((CheckBoxPreference) preference).isChecked()); return true; } else if (preference == mCustomBootAnimation) { PackageManager packageManager = getActivity().getPackageManager(); Intent test = new Intent(Intent.ACTION_GET_CONTENT); test.setType("file/*"); List<ResolveInfo> list = packageManager.queryIntentActivities(test, PackageManager.GET_ACTIVITIES); if(list.size() > 0) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("file/*"); startActivityForResult(intent, REQUEST_PICK_BOOT_ANIMATION); } else { //No app installed to handle the intent - file explorer required Toast.makeText(mContext, R.string.install_file_manager_error, Toast.LENGTH_SHORT).show(); } return true; } else if (preference == mNotificationWallpaper) { Display display = getActivity().getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("image/*"); intent.putExtra("crop", "true"); boolean isPortrait = getResources() .getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; intent.putExtra("aspectX", isPortrait ? width : height); intent.putExtra("aspectY", isPortrait ? height : width); intent.putExtra("outputX", width); intent.putExtra("outputY", height); intent.putExtra("scale", true); intent.putExtra("scaleUpIfNeeded", true); intent.putExtra(MediaStore.EXTRA_OUTPUT, getNotificationExternalUri()); intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString()); startActivityForResult(intent, REQUEST_PICK_WALLPAPER); return true; } else if (preference == mWallpaperAlpha) { Resources res = getActivity().getResources(); String cancel = res.getString(R.string.cancel); String ok = res.getString(R.string.ok); String title = res.getString(R.string.alpha_dialog_title); float savedProgress = Settings.System.getFloat(getActivity() .getContentResolver(), Settings.System.NOTIF_WALLPAPER_ALPHA, 1.0f); LayoutInflater factory = LayoutInflater.from(getActivity()); final View alphaDialog = factory.inflate(R.layout.seekbar_dialog, null); SeekBar seekbar = (SeekBar) alphaDialog.findViewById(R.id.seek_bar); OnSeekBarChangeListener seekBarChangeListener = new OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) { seekbarProgress = seekbar.getProgress(); } @Override public void onStopTrackingTouch(SeekBar seekbar) { } @Override public void onStartTrackingTouch(SeekBar seekbar) { } }; seekbar.setProgress((int) (savedProgress * 100)); seekbar.setMax(100); seekbar.setOnSeekBarChangeListener(seekBarChangeListener); new AlertDialog.Builder(getActivity()) .setTitle(title) .setView(alphaDialog) .setNegativeButton(cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // nothing } }) .setPositiveButton(ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { float val = ((float) seekbarProgress / 100); Settings.System.putFloat(getActivity().getContentResolver(), Settings.System.NOTIF_WALLPAPER_ALPHA, val); Helpers.restartSystemUI(); } }) .create() .show(); return true; } else if (preference == mShowImeSwitcher) { Settings.System.putBoolean(getActivity().getContentResolver(), Settings.System.SHOW_STATUSBAR_IME_SWITCHER, isCheckBoxPrefernceChecked(preference)); return true; } else if (preference == mRecentKillAll) { boolean checked = ((CheckBoxPreference)preference).isChecked(); Settings.System.putBoolean(getActivity().getContentResolver(), Settings.System.RECENT_KILL_ALL_BUTTON, checked ? true : false); return true; } else if (preference == mRamBar) { boolean checked = ((CheckBoxPreference)preference).isChecked(); Settings.System.putBoolean(getActivity().getContentResolver(), Settings.System.RAM_USAGE_BAR, checked ? true : false); return true; } else if (preference == mKillAppLongpressBack) { writeKillAppLongpressBackOptions(); } else if (preference == mCustomLabel) { AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setTitle(R.string.custom_carrier_label_title); alert.setMessage(R.string.custom_carrier_label_explain); // Set an EditText view to get user input final EditText input = new EditText(getActivity()); input.setText(mCustomLabelText != null ? mCustomLabelText : ""); alert.setView(input); alert.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String value = ((Spannable) input.getText()).toString(); Settings.System.putString(getActivity().getContentResolver(), Settings.System.CUSTOM_CARRIER_LABEL, value); updateCustomLabelTextSummary(); Intent i = new Intent(); i.setAction("com.aokp.romcontrol.LABEL_CHANGED"); mContext.sendBroadcast(i); } }); alert.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Canceled. } }); alert.show(); } else if (preference == mLcdDensity) { ((PreferenceActivity) getActivity()) .startPreferenceFragment(new DensityChanger(), true); return true; } else if (preference == mUseAltResolver) { Settings.System.putBoolean(getActivity().getContentResolver(), Settings.System.ACTIVITY_RESOLVER_USE_ALT, isCheckBoxPrefernceChecked(preference)); return true; } else if (preference == mVibrateOnExpand) { Settings.System.putBoolean(mContext.getContentResolver(), Settings.System.VIBRATE_NOTIF_EXPAND, ((CheckBoxPreference) preference).isChecked()); Helpers.restartSystemUI(); return true; } return super.onPreferenceTreeClick(preferenceScreen, preference); }
diff --git a/Code/Part1/src/core/ParseCallgraph.java b/Code/Part1/src/core/ParseCallgraph.java index bd2d175..fe699a3 100644 --- a/Code/Part1/src/core/ParseCallgraph.java +++ b/Code/Part1/src/core/ParseCallgraph.java @@ -1,193 +1,193 @@ package core; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.NumberFormat; import java.math.RoundingMode; import java.util.HashMap; import java.util.Map.Entry; import java.util.TreeMap; import java.util.TreeSet; import java.util.Map; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Parse the callgraph generated by LLVM. */ public class ParseCallgraph { // REGEX pattern for function name public static final Pattern nodePattern = Pattern .compile("Call graph node for function: '(.*?)'<<(.*?)>> #uses=(\\d*).*"); // REGEX pattern for callsite public static final Pattern callsitePattern = Pattern .compile("\\s*CS<(.*?)> calls function '(.*?)'.*"); /** * I don't think we need to overcomplicate things. Java can just perform * Runtime.getRuntime().exec() * * @param filePart * Part of the filename that matches directory and file naming * format (eg. filePart="test3" will be mapped to * ../test3/test3.bc) * @param thresholdSupport * Minimum amount of support for the relationship. * @param thresholdConfidence * Confidence of bug necessary in decimal format < 1 (eg. * thresholdConfidence=0.85 means 85%) */ public void intra(String filePart, int thresholdSupport, double thresholdConfidence) { String currentLine = null; String caller = null; // used in inter-processing HashMap<String, TreeSet<String>> functionMapIntra = new HashMap<String, TreeSet<String>>(); try { // multi-threads resolve process deadlock problem final Process process = Runtime.getRuntime().exec( - "opt -interprocedural-basic-aa ../" + filePart + "/main.bc"); + "opt -print-callgraph ../" + filePart + "/main.bc"); new Thread() { public void run() { InputStream stdout = process.getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(stdout)); try { while (reader.readLine() != null) ; } catch (IOException e) { e.printStackTrace(); } } }.start(); InputStream errorStream = process.getErrorStream(); BufferedReader errorBuffReader = new BufferedReader( new InputStreamReader(errorStream)); // While we're able to step through LLVM callgraph output while ((currentLine = errorBuffReader.readLine()) != null) { // Check if we're at a caller Matcher nodeMatcher = nodePattern.matcher(currentLine); if (nodeMatcher.find()) { caller = nodeMatcher.group(1); } // Check if we're at a callee Matcher callsiteMatcher = callsitePattern.matcher(currentLine); if (callsiteMatcher.find() && caller == null) { String callee = callsiteMatcher.group(2); functionMapIntra.put(callee, new TreeSet<String>()); } else if (callsiteMatcher.find() && caller != null) { // update String callee = callsiteMatcher.group(2); if (functionMapIntra.get(callee) == null) { functionMapIntra.put(callee, new TreeSet<String>()); } functionMapIntra.get(callee).add(caller); } System.out.println(currentLine); } /* * Please see PairConfidence.java for details. It contains function, * function pair, support, and confidence. PairCofidence is a key * used in TreeMap, and the value is a TreeSet which has the * functions with bugs The complexity of my current algorithm is * still n square. May need some optimization. THe current run time * of test3 is only 2 to 3 sec. The order of our output is not * important. It will be sorted before comparing with gold file. */ TreeMap<PairConfidence, TreeSet<String>> pairs = new TreeMap<PairConfidence, TreeSet<String>>(); ArrayList<String> functions = new ArrayList<String>(); functions.addAll(functionMapIntra.keySet()); for (int i = 0; i < functions.size(); i++) { String function1 = functions.get(i); TreeSet<String> callerList = functionMapIntra.get(functions .get(i)); int support = functionMapIntra.get(functions.get(i)).size(); if (support == 0) { continue; } for (int j = 0; j < functions.size(); j++) { if (i == j) { continue; } String function2 = functions.get(j); TreeSet<String> tmp = new TreeSet<String>(); tmp.addAll(callerList); TreeSet<String> remain = new TreeSet<String>(); remain.addAll(tmp); tmp.retainAll(functionMapIntra.get(functions.get(j))); remain.removeAll(tmp); int supportPair = tmp.size(); if (supportPair < thresholdSupport) { continue; } double confidence = ((double) supportPair) / ((double) support); if (confidence < thresholdConfidence) { continue; } String pair = ""; if (function1.compareTo(function2) < 0) { pair = "(" + function1 + " " + function2 + ") "; } else { pair = "(" + function2 + " " + function1 + ") "; } PairConfidence pc = new PairConfidence(function1, pair, supportPair, confidence); pairs.put(pc, remain); } } System.out.println("RESULTS:"); System.out.println("--------"); NumberFormat numf = NumberFormat.getNumberInstance(); numf.setMaximumFractionDigits(2); numf.setRoundingMode(RoundingMode.HALF_EVEN); // only for local test. The actual output on ECE machine will be // sorted automatically. TreeMap<String, String> display = new TreeMap<String, String>(); for (Entry<PairConfidence, TreeSet<String>> entry : pairs .entrySet()) { String function = entry.getKey().getFunction(); String header = "bug: " + function + " in "; for (String s : pairs.get(entry.getKey())) { String message = header + s + ((PairConfidence) entry.getKey()).toString(); // System.out.println(message); // will be used on ECE // machine. // only for local test. The actual output on ECE machine // will be sorted automatically. display.put( message.replaceAll("_", "").replaceAll(" ", ""), message); } } // only for local test. The actual output on ECE machine will be // sorted automatically. for (Entry<String, String> entry : display.entrySet()) { System.out.println(entry.getValue()); } System.exit(0); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } }
true
true
public void intra(String filePart, int thresholdSupport, double thresholdConfidence) { String currentLine = null; String caller = null; // used in inter-processing HashMap<String, TreeSet<String>> functionMapIntra = new HashMap<String, TreeSet<String>>(); try { // multi-threads resolve process deadlock problem final Process process = Runtime.getRuntime().exec( "opt -interprocedural-basic-aa ../" + filePart + "/main.bc"); new Thread() { public void run() { InputStream stdout = process.getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(stdout)); try { while (reader.readLine() != null) ; } catch (IOException e) { e.printStackTrace(); } } }.start(); InputStream errorStream = process.getErrorStream(); BufferedReader errorBuffReader = new BufferedReader( new InputStreamReader(errorStream)); // While we're able to step through LLVM callgraph output while ((currentLine = errorBuffReader.readLine()) != null) { // Check if we're at a caller Matcher nodeMatcher = nodePattern.matcher(currentLine); if (nodeMatcher.find()) { caller = nodeMatcher.group(1); } // Check if we're at a callee Matcher callsiteMatcher = callsitePattern.matcher(currentLine); if (callsiteMatcher.find() && caller == null) { String callee = callsiteMatcher.group(2); functionMapIntra.put(callee, new TreeSet<String>()); } else if (callsiteMatcher.find() && caller != null) { // update String callee = callsiteMatcher.group(2); if (functionMapIntra.get(callee) == null) { functionMapIntra.put(callee, new TreeSet<String>()); } functionMapIntra.get(callee).add(caller); } System.out.println(currentLine); } /* * Please see PairConfidence.java for details. It contains function, * function pair, support, and confidence. PairCofidence is a key * used in TreeMap, and the value is a TreeSet which has the * functions with bugs The complexity of my current algorithm is * still n square. May need some optimization. THe current run time * of test3 is only 2 to 3 sec. The order of our output is not * important. It will be sorted before comparing with gold file. */ TreeMap<PairConfidence, TreeSet<String>> pairs = new TreeMap<PairConfidence, TreeSet<String>>(); ArrayList<String> functions = new ArrayList<String>(); functions.addAll(functionMapIntra.keySet()); for (int i = 0; i < functions.size(); i++) { String function1 = functions.get(i); TreeSet<String> callerList = functionMapIntra.get(functions .get(i)); int support = functionMapIntra.get(functions.get(i)).size(); if (support == 0) { continue; } for (int j = 0; j < functions.size(); j++) { if (i == j) { continue; } String function2 = functions.get(j); TreeSet<String> tmp = new TreeSet<String>(); tmp.addAll(callerList); TreeSet<String> remain = new TreeSet<String>(); remain.addAll(tmp); tmp.retainAll(functionMapIntra.get(functions.get(j))); remain.removeAll(tmp); int supportPair = tmp.size(); if (supportPair < thresholdSupport) { continue; } double confidence = ((double) supportPair) / ((double) support); if (confidence < thresholdConfidence) { continue; } String pair = ""; if (function1.compareTo(function2) < 0) { pair = "(" + function1 + " " + function2 + ") "; } else { pair = "(" + function2 + " " + function1 + ") "; } PairConfidence pc = new PairConfidence(function1, pair, supportPair, confidence); pairs.put(pc, remain); } } System.out.println("RESULTS:"); System.out.println("--------"); NumberFormat numf = NumberFormat.getNumberInstance(); numf.setMaximumFractionDigits(2); numf.setRoundingMode(RoundingMode.HALF_EVEN); // only for local test. The actual output on ECE machine will be // sorted automatically. TreeMap<String, String> display = new TreeMap<String, String>(); for (Entry<PairConfidence, TreeSet<String>> entry : pairs .entrySet()) { String function = entry.getKey().getFunction(); String header = "bug: " + function + " in "; for (String s : pairs.get(entry.getKey())) { String message = header + s + ((PairConfidence) entry.getKey()).toString(); // System.out.println(message); // will be used on ECE // machine. // only for local test. The actual output on ECE machine // will be sorted automatically. display.put( message.replaceAll("_", "").replaceAll(" ", ""), message); } } // only for local test. The actual output on ECE machine will be // sorted automatically. for (Entry<String, String> entry : display.entrySet()) { System.out.println(entry.getValue()); } System.exit(0); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } }
public void intra(String filePart, int thresholdSupport, double thresholdConfidence) { String currentLine = null; String caller = null; // used in inter-processing HashMap<String, TreeSet<String>> functionMapIntra = new HashMap<String, TreeSet<String>>(); try { // multi-threads resolve process deadlock problem final Process process = Runtime.getRuntime().exec( "opt -print-callgraph ../" + filePart + "/main.bc"); new Thread() { public void run() { InputStream stdout = process.getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(stdout)); try { while (reader.readLine() != null) ; } catch (IOException e) { e.printStackTrace(); } } }.start(); InputStream errorStream = process.getErrorStream(); BufferedReader errorBuffReader = new BufferedReader( new InputStreamReader(errorStream)); // While we're able to step through LLVM callgraph output while ((currentLine = errorBuffReader.readLine()) != null) { // Check if we're at a caller Matcher nodeMatcher = nodePattern.matcher(currentLine); if (nodeMatcher.find()) { caller = nodeMatcher.group(1); } // Check if we're at a callee Matcher callsiteMatcher = callsitePattern.matcher(currentLine); if (callsiteMatcher.find() && caller == null) { String callee = callsiteMatcher.group(2); functionMapIntra.put(callee, new TreeSet<String>()); } else if (callsiteMatcher.find() && caller != null) { // update String callee = callsiteMatcher.group(2); if (functionMapIntra.get(callee) == null) { functionMapIntra.put(callee, new TreeSet<String>()); } functionMapIntra.get(callee).add(caller); } System.out.println(currentLine); } /* * Please see PairConfidence.java for details. It contains function, * function pair, support, and confidence. PairCofidence is a key * used in TreeMap, and the value is a TreeSet which has the * functions with bugs The complexity of my current algorithm is * still n square. May need some optimization. THe current run time * of test3 is only 2 to 3 sec. The order of our output is not * important. It will be sorted before comparing with gold file. */ TreeMap<PairConfidence, TreeSet<String>> pairs = new TreeMap<PairConfidence, TreeSet<String>>(); ArrayList<String> functions = new ArrayList<String>(); functions.addAll(functionMapIntra.keySet()); for (int i = 0; i < functions.size(); i++) { String function1 = functions.get(i); TreeSet<String> callerList = functionMapIntra.get(functions .get(i)); int support = functionMapIntra.get(functions.get(i)).size(); if (support == 0) { continue; } for (int j = 0; j < functions.size(); j++) { if (i == j) { continue; } String function2 = functions.get(j); TreeSet<String> tmp = new TreeSet<String>(); tmp.addAll(callerList); TreeSet<String> remain = new TreeSet<String>(); remain.addAll(tmp); tmp.retainAll(functionMapIntra.get(functions.get(j))); remain.removeAll(tmp); int supportPair = tmp.size(); if (supportPair < thresholdSupport) { continue; } double confidence = ((double) supportPair) / ((double) support); if (confidence < thresholdConfidence) { continue; } String pair = ""; if (function1.compareTo(function2) < 0) { pair = "(" + function1 + " " + function2 + ") "; } else { pair = "(" + function2 + " " + function1 + ") "; } PairConfidence pc = new PairConfidence(function1, pair, supportPair, confidence); pairs.put(pc, remain); } } System.out.println("RESULTS:"); System.out.println("--------"); NumberFormat numf = NumberFormat.getNumberInstance(); numf.setMaximumFractionDigits(2); numf.setRoundingMode(RoundingMode.HALF_EVEN); // only for local test. The actual output on ECE machine will be // sorted automatically. TreeMap<String, String> display = new TreeMap<String, String>(); for (Entry<PairConfidence, TreeSet<String>> entry : pairs .entrySet()) { String function = entry.getKey().getFunction(); String header = "bug: " + function + " in "; for (String s : pairs.get(entry.getKey())) { String message = header + s + ((PairConfidence) entry.getKey()).toString(); // System.out.println(message); // will be used on ECE // machine. // only for local test. The actual output on ECE machine // will be sorted automatically. display.put( message.replaceAll("_", "").replaceAll(" ", ""), message); } } // only for local test. The actual output on ECE machine will be // sorted automatically. for (Entry<String, String> entry : display.entrySet()) { System.out.println(entry.getValue()); } System.exit(0); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } }
diff --git a/org.jcryptool.visual.sig/src/org/jcryptool/visual/sig/ui/wizards/ShowSig.java b/org.jcryptool.visual.sig/src/org/jcryptool/visual/sig/ui/wizards/ShowSig.java index 9ee9180..d994d55 100644 --- a/org.jcryptool.visual.sig/src/org/jcryptool/visual/sig/ui/wizards/ShowSig.java +++ b/org.jcryptool.visual.sig/src/org/jcryptool/visual/sig/ui/wizards/ShowSig.java @@ -1,477 +1,477 @@ package org.jcryptool.visual.sig.ui.wizards; import java.io.BufferedOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; public class ShowSig extends Shell { private Label txtT; private Label txtT_2; private Label txtT_1; private Label text; private Label text_1; private Label text_2; private Label txtSig; private Label txtLnge; private Label txtSignedMes; private Label txtLngeMes; private Table table; private TableColumn tblclmnAddress; private TableColumn tblclmnHex; private TableColumn tblclmnAscii; private Table table_1; private TableColumn tblclmnAddress_1; private TableColumn tblclmnHex_1; private TableColumn tblclmnAscii_1; private Label txtSigNum; private int sigLen = org.jcryptool.visual.sig.algorithm.Input.signature.length; //private String sigStrLen = Integer.toString(sigLen); //Bytes!!!! private int mesLen = org.jcryptool.visual.sig.algorithm.Input.data.length; //private String mesStrLen = Integer.toString(mesLen); //Bytes!!!! private Label lblNewLabel; private String userName; private int sLen = sigLen * 8; private int mLen = mesLen * 8; /** * Create the shell. * @param display */ public ShowSig(Display display, String sig) { super(display, SWT.CLOSE | SWT.MIN | SWT.MAX | SWT.TITLE | SWT.APPLICATION_MODAL); Composite composite = new Composite(this, SWT.NONE); composite.setBounds(10, 10, 485, 661); txtT = new Label(composite, SWT.READ_ONLY | SWT.WRAP); txtT.setText(Messages.ShowSig_ownerTitle); txtT.setBounds(0, 0, 176, 21); txtT_2 = new Label(composite, SWT.READ_ONLY); txtT_2.setText(Messages.ShowSig_keyTitle); txtT_2.setBounds(0, 24, 176, 21); txtT_1 = new Label(composite, SWT.READ_ONLY); txtT_1.setText(Messages.ShowSig_methodTitle); txtT_1.setBounds(0, 48, 176, 21); // get owner of the key if ((org.jcryptool.visual.sig.algorithm.Input.privateKey == null) && (org.jcryptool.visual.sig.algorithm.Input.key == null)) { userName = "-"; } else { if (org.jcryptool.visual.sig.algorithm.Input.key != null) { userName = org.jcryptool.visual.sig.algorithm.Input.key.getContactName(); } else { userName = org.jcryptool.visual.sig.algorithm.Input.privateKey.getContactName(); } } text = new Label(composite, SWT.READ_ONLY | SWT.WRAP); text.setText(userName); text.setBounds(182, 0, 302, 21); // get information about the key text_1 = new Label(composite, SWT.READ_ONLY); if ((org.jcryptool.visual.sig.algorithm.Input.privateKey == null) && (org.jcryptool.visual.sig.algorithm.Input.key == null)) { if (sig.contains("ECDSA")) { text_1.setText("ANSI X9.62 prime256v1 (256 bits)"); } else { text_1.setText("-"); } } else { if (org.jcryptool.visual.sig.algorithm.Input.key != null) { text_1.setText(org.jcryptool.visual.sig.algorithm.Input.key.getClassName()); } else { text_1.setText(org.jcryptool.visual.sig.algorithm.Input.privateKey.getClassName()); } } text_1.setBounds(182, 24, 302, 21); text_2 = new Label(composite, SWT.READ_ONLY); text_2.setText(sig); text_2.setBounds(182, 48, 302, 21); txtSig = new Label(composite, SWT.READ_ONLY); txtSig.setText(Messages.ShowSig_grpSignature); txtSig.setBounds(0, 77, 137, 21); txtLnge = new Label(composite, SWT.READ_ONLY); txtLnge.setText(Messages.ShowSig_lengthSig + sLen + " Bits"); txtLnge.setBounds(0, 253, 430, 21); Group grpOption = new Group(composite, SWT.NONE); grpOption.setText(Messages.ShowSig_grpOption); grpOption.setBounds(0, 280, 484, 73); grpOption.setLayout(null); txtSignedMes = new Label(composite, SWT.READ_ONLY); txtSignedMes.setText(Messages.ShowSig_grpMessage); txtSignedMes.setBounds(0, 373, 137, 21); txtLngeMes = new Label(composite, SWT.READ_ONLY); txtLngeMes.setText(Messages.ShowSig_lengthMessage + mLen + " Bits"); txtLngeMes.setBounds(0, 548, 430, 21); // create table to show the generated signature table = new Table(composite, SWT.BORDER | SWT.FULL_SELECTION); table.setLinesVisible(true); table.setHeaderVisible(true); table.setBounds(0, 98, 484, 151); tblclmnAddress = new TableColumn(table, SWT.NONE); tblclmnAddress.setResizable(false); tblclmnAddress.setWidth(60); tblclmnAddress.setToolTipText(""); tblclmnAddress.setText(Messages.ShowSig_tblAdr); tblclmnHex = new TableColumn(table, SWT.NONE); tblclmnHex.setResizable(false); tblclmnHex.setWidth(250); tblclmnHex.setText(Messages.ShowSig_tblHex); tblclmnAscii = new TableColumn(table, SWT.NONE); tblclmnAscii.setResizable(false); tblclmnAscii.setWidth(150); tblclmnAscii.setText(Messages.ShowSig_tblAscii); int stepSize = 14; int len1 = org.jcryptool.visual.sig.algorithm.Input.signatureHex.length(); String asciistr = convertHexToString(org.jcryptool.visual.sig.algorithm.Input.signatureHex); for (int i1 = 0; i1 < (Math.ceil((double)len1/(stepSize*2))) ; i1++) { TableItem item = new TableItem(table, SWT.NONE); // column 1 - address item.setText(0, getAddress(i1, stepSize)); // column 2 - hex int start1 = i1 * (stepSize*2); int end1 = i1 * (stepSize*2) + (stepSize*2); end1 = end1 >= len1 ? len1 : end1; StringBuffer bufferS1 = new StringBuffer(); for (int m1 = 0; m1 < (end1-start1)/2 ; m1++){ bufferS1.append(org.jcryptool.visual.sig.algorithm.Input.signatureHex.charAt((2*m1)+start1)); bufferS1.append(org.jcryptool.visual.sig.algorithm.Input.signatureHex.charAt((2*m1+1)+start1)); bufferS1.append(" "); } item.setText(1, bufferS1.toString()); // column 3 - ascii StringBuffer bufferS2 = new StringBuffer(); bufferS2.append(asciistr, start1/2, end1/2); item.setText(2, bufferS2.toString()); } // create table to show signed message table_1 = new Table(composite, SWT.BORDER | SWT.FULL_SELECTION); table_1.setLinesVisible(true); table_1.setHeaderVisible(true); table_1.setBounds(0, 394, 484, 150); tblclmnAddress_1 = new TableColumn(table_1, SWT.NONE); tblclmnAddress_1.setResizable(false); tblclmnAddress_1.setWidth(60); tblclmnAddress_1.setToolTipText(""); tblclmnAddress_1.setText(Messages.ShowSig_tblAdr); tblclmnHex_1 = new TableColumn(table_1, SWT.NONE); tblclmnHex_1.setResizable(false); tblclmnHex_1.setWidth(250); tblclmnHex_1.setText(Messages.ShowSig_tblHex); tblclmnAscii_1 = new TableColumn(table_1, SWT.NONE); tblclmnAscii_1.setResizable(false); tblclmnAscii_1.setWidth(150); tblclmnAscii_1.setText(Messages.ShowSig_tblAscii); int len2 = org.jcryptool.visual.sig.algorithm.Input.data.length; String asciistr2 = convertHexToString(org.jcryptool.visual.sig.algorithm.Input.dataHex); // for (int i2 = 0; i2 < (Math.ceil((double)len2/(stepSize*2))) ; i2++) { // to show the whole message // shows only 6 rows - optimize performance for (int i2 = 0; i2 < 6 ; i2++) { //Create one item for each row TableItem item = new TableItem(table_1, SWT.NONE); // column 1 - address item.setText(0, getAddress(i2, stepSize));//Column, string // column 2 - int start2 = i2 * (stepSize*2); int end2 = i2 * (stepSize*2) + (stepSize*2); end2 = end2 >= len2 ? len2 : end2; StringBuffer bufferD1 = new StringBuffer(); for (int n1 = 0; n1 < (end2-start2)/2 ; n1++){ bufferD1.append(org.jcryptool.visual.sig.algorithm.Input.dataHex.charAt((2*n1)+start2)); bufferD1.append(org.jcryptool.visual.sig.algorithm.Input.dataHex.charAt((2*n1+1)+start2)); bufferD1.append(" "); } item.setText(1, bufferD1.toString()); // column 3 - ascii StringBuffer bufferD2 = new StringBuffer(); bufferD2.append(asciistr2, start2/2, end2/2); item.setText(2, bufferD2.toString()); } // text field to show signature as hex, octal or decimal txtSigNum = new Label(composite, SWT.BORDER | SWT.WRAP); txtSigNum.setBounds(0, 98, 484, 151); txtSigNum.setBackground(new Color(Display.getCurrent(), 255, 255, 255)); // display options Button btnOkt = new Button(grpOption, SWT.RADIO); btnOkt.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { table.setVisible(false); txtSigNum.setVisible(true); txtSigNum.setText(org.jcryptool.visual.sig.algorithm.Input.signatureOct); } }); btnOkt.setBounds(186, 30, 70, 16); btnOkt.setText(Messages.ShowSig_octal); Button btnDez = new Button(grpOption, SWT.RADIO); btnDez.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { table.setVisible(false); txtSigNum.setVisible(true); txtSigNum.setText(hexToDecimal(org.jcryptool.visual.sig.algorithm.Input.signatureHex)); } }); btnDez.setBounds(262, 30, 80, 16); btnDez.setText(Messages.ShowSig_decimal); Button btnHex = new Button(grpOption, SWT.RADIO); btnHex.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { table.setVisible(false); txtSigNum.setVisible(true); txtSigNum.setText(org.jcryptool.visual.sig.algorithm.Input.signatureHex); } }); btnHex.setBounds(348, 30, 70, 16); btnHex.setText(Messages.ShowSig_hex); Button btnHexdump = new Button(grpOption, SWT.RADIO); btnHexdump.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { txtSigNum.setVisible(false); table.setVisible(true); } }); btnHexdump.setSelection(true); btnHexdump.setBounds(10, 30, 170, 16); btnHexdump.setText(Messages.ShowSig_hexDump); // close window Button btnNewButton = new Button(composite, SWT.NONE); btnNewButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ShowSig.this.close(); } }); btnNewButton.setBounds(389, 633, 95, 28); btnNewButton.setText(Messages.ShowSig_btnClose); // open hex editor Button btnOpen = new Button(composite, SWT.NONE); btnOpen.setEnabled(false); btnOpen.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // TODO //Call the helper function to format the output (this is madness?!) //saveToFile(); openHexEditor(); } }); btnOpen.setBounds(145, 635, 140, 25); btnOpen.setText(Messages.ShowSig_btnOpen); Label lblTextopeneditor = new Label(composite, SWT.WRAP | SWT.CENTER); lblTextopeneditor.setAlignment(SWT.LEFT); lblTextopeneditor.setBounds(2, 584, 475, 32); lblTextopeneditor.setText(Messages.ShowSig_editorDescripton); lblTextopeneditor.setBackground(new Color(Display.getCurrent(), 255, 255, 255)); lblNewLabel = new Label(composite, SWT.NONE); lblNewLabel.setBounds(0, 578, 484, 44); lblNewLabel.setBackground(new Color(Display.getCurrent(), 255, 255, 255)); Button btnSave = new Button(composite, SWT.NONE); btnSave.setBounds(289, 633, 95, 28); btnSave.setText(Messages.ShowSig_btnSave); btnSave.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { //Open File save dialog FileDialog dialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE); dialog.setFileName("signature_and_message"); String savePath = dialog.open(); //Write the file if (savePath != null) { try { OutputStream output = null; try { output = new BufferedOutputStream(new FileOutputStream(savePath)); output.write(sLen); output.write(org.jcryptool.visual.sig.algorithm.Input.signature); - output.write(org.jcryptool.visual.sig.algorithm.Input.data.toString().getBytes()); + output.write(org.jcryptool.visual.sig.algorithm.Input.data); }//end try finally { output.close(); }//end finally }//end try catch(FileNotFoundException ex){ //LogUtil.logError(SigPlugin.PLUGIN_ID, ex); }//end catch catch(IOException ex){ //LogUtil.logError(SigPlugin.PLUGIN_ID, ex); }//end catch MessageBox messageBox = new MessageBox(new Shell(Display.getCurrent()), SWT.ICON_INFORMATION | SWT.OK); messageBox.setText(Messages.ShowSig_MessageBoxTitle); messageBox.setMessage(Messages.ShowSig_MessageBoxText); messageBox.open(); }//end if }//end widgetSelected }); createContents(); } /** * Create contents of the shell. */ protected void createContents() { setText(Messages.ShowSig_title); setSize(512, 710); } @Override protected void checkSubclass() { // Disable the check that prevents subclassing of SWT components } /** * Returns a string to get the address in the hex-dump-table. * * @param i Row of table * @param stepSize Difference between digits in the row. * @return a string containing the address in the table */ protected String getAddress(int i, int stepSize){ return String.format("%05X", (i*stepSize) & 0xFFFFF); } /** * Returns the ascii representation of an hexadecimal string. * * @param hex * @return a string containing the ascii representation */ public String convertHexToString(String hex){ StringBuilder sb = new StringBuilder(); for( int i=0; i<hex.length()-1; i+=2 ){ //grab the hex in pairs String output = hex.substring(i, (i + 2)); //convert hex to decimal int decimal = Integer.parseInt(output, 16); //convert the decimal to character sb.append((char)decimal); } return sb.toString(); } /** * Returns the decimal representation of an hexadecimal string. * * @param hex * @return */ public String hexToDecimal(String hex) { StringBuilder sb = new StringBuilder(); for( int i=0; i<hex.length()-1; i+=2 ){ //grab the hex in pairs String output = hex.substring(i, (i + 2)); //convert hex to decimal int decimal = Integer.parseInt(output, 16); sb.append(decimal); } return sb.toString(); } //Saves message + info to file...save as what? Save where?? Huh? // private void saveToFile () { // PrintStream out = null; // try { // out = new PrintStream(new FileOutputStream("SignedMessage.txt")); // out.print("Signature: " + // org.jcryptool.visual.sig.algorithm.Input.signatureHex + // " Signature length: " + // sigStrLen + // " Function: " + // org.jcryptool.visual.sig.algorithm.Input.chosenHash + // " Key: " + // org.jcryptool.visual.sig.algorithm.Input.key.getClassName() + // " Owner: " + // org.jcryptool.visual.sig.algorithm.Input.key.getContactName() + // " Message: " + // new String(org.jcryptool.visual.sig.algorithm.Input.data)); // // MessageBox messageBox = new MessageBox(new // Shell(Display.getCurrent()), SWT.ICON_INFORMATION | SWT.OK); // messageBox.setText("Saved"); // messageBox.setMessage("Saved to " + System.getProperty("user.dir")); // messageBox.open(); // } // catch (Exception e){ // e.printStackTrace(); // } // finally { // if (out != null) out.close(); // } // // System.out.println("I am here: " + System.getProperty("user.dir")); // } private void openHexEditor() { //String str = org.jcryptool.visual.sig.algorithm.Input.signatureHex; } }
true
true
public ShowSig(Display display, String sig) { super(display, SWT.CLOSE | SWT.MIN | SWT.MAX | SWT.TITLE | SWT.APPLICATION_MODAL); Composite composite = new Composite(this, SWT.NONE); composite.setBounds(10, 10, 485, 661); txtT = new Label(composite, SWT.READ_ONLY | SWT.WRAP); txtT.setText(Messages.ShowSig_ownerTitle); txtT.setBounds(0, 0, 176, 21); txtT_2 = new Label(composite, SWT.READ_ONLY); txtT_2.setText(Messages.ShowSig_keyTitle); txtT_2.setBounds(0, 24, 176, 21); txtT_1 = new Label(composite, SWT.READ_ONLY); txtT_1.setText(Messages.ShowSig_methodTitle); txtT_1.setBounds(0, 48, 176, 21); // get owner of the key if ((org.jcryptool.visual.sig.algorithm.Input.privateKey == null) && (org.jcryptool.visual.sig.algorithm.Input.key == null)) { userName = "-"; } else { if (org.jcryptool.visual.sig.algorithm.Input.key != null) { userName = org.jcryptool.visual.sig.algorithm.Input.key.getContactName(); } else { userName = org.jcryptool.visual.sig.algorithm.Input.privateKey.getContactName(); } } text = new Label(composite, SWT.READ_ONLY | SWT.WRAP); text.setText(userName); text.setBounds(182, 0, 302, 21); // get information about the key text_1 = new Label(composite, SWT.READ_ONLY); if ((org.jcryptool.visual.sig.algorithm.Input.privateKey == null) && (org.jcryptool.visual.sig.algorithm.Input.key == null)) { if (sig.contains("ECDSA")) { text_1.setText("ANSI X9.62 prime256v1 (256 bits)"); } else { text_1.setText("-"); } } else { if (org.jcryptool.visual.sig.algorithm.Input.key != null) { text_1.setText(org.jcryptool.visual.sig.algorithm.Input.key.getClassName()); } else { text_1.setText(org.jcryptool.visual.sig.algorithm.Input.privateKey.getClassName()); } } text_1.setBounds(182, 24, 302, 21); text_2 = new Label(composite, SWT.READ_ONLY); text_2.setText(sig); text_2.setBounds(182, 48, 302, 21); txtSig = new Label(composite, SWT.READ_ONLY); txtSig.setText(Messages.ShowSig_grpSignature); txtSig.setBounds(0, 77, 137, 21); txtLnge = new Label(composite, SWT.READ_ONLY); txtLnge.setText(Messages.ShowSig_lengthSig + sLen + " Bits"); txtLnge.setBounds(0, 253, 430, 21); Group grpOption = new Group(composite, SWT.NONE); grpOption.setText(Messages.ShowSig_grpOption); grpOption.setBounds(0, 280, 484, 73); grpOption.setLayout(null); txtSignedMes = new Label(composite, SWT.READ_ONLY); txtSignedMes.setText(Messages.ShowSig_grpMessage); txtSignedMes.setBounds(0, 373, 137, 21); txtLngeMes = new Label(composite, SWT.READ_ONLY); txtLngeMes.setText(Messages.ShowSig_lengthMessage + mLen + " Bits"); txtLngeMes.setBounds(0, 548, 430, 21); // create table to show the generated signature table = new Table(composite, SWT.BORDER | SWT.FULL_SELECTION); table.setLinesVisible(true); table.setHeaderVisible(true); table.setBounds(0, 98, 484, 151); tblclmnAddress = new TableColumn(table, SWT.NONE); tblclmnAddress.setResizable(false); tblclmnAddress.setWidth(60); tblclmnAddress.setToolTipText(""); tblclmnAddress.setText(Messages.ShowSig_tblAdr); tblclmnHex = new TableColumn(table, SWT.NONE); tblclmnHex.setResizable(false); tblclmnHex.setWidth(250); tblclmnHex.setText(Messages.ShowSig_tblHex); tblclmnAscii = new TableColumn(table, SWT.NONE); tblclmnAscii.setResizable(false); tblclmnAscii.setWidth(150); tblclmnAscii.setText(Messages.ShowSig_tblAscii); int stepSize = 14; int len1 = org.jcryptool.visual.sig.algorithm.Input.signatureHex.length(); String asciistr = convertHexToString(org.jcryptool.visual.sig.algorithm.Input.signatureHex); for (int i1 = 0; i1 < (Math.ceil((double)len1/(stepSize*2))) ; i1++) { TableItem item = new TableItem(table, SWT.NONE); // column 1 - address item.setText(0, getAddress(i1, stepSize)); // column 2 - hex int start1 = i1 * (stepSize*2); int end1 = i1 * (stepSize*2) + (stepSize*2); end1 = end1 >= len1 ? len1 : end1; StringBuffer bufferS1 = new StringBuffer(); for (int m1 = 0; m1 < (end1-start1)/2 ; m1++){ bufferS1.append(org.jcryptool.visual.sig.algorithm.Input.signatureHex.charAt((2*m1)+start1)); bufferS1.append(org.jcryptool.visual.sig.algorithm.Input.signatureHex.charAt((2*m1+1)+start1)); bufferS1.append(" "); } item.setText(1, bufferS1.toString()); // column 3 - ascii StringBuffer bufferS2 = new StringBuffer(); bufferS2.append(asciistr, start1/2, end1/2); item.setText(2, bufferS2.toString()); } // create table to show signed message table_1 = new Table(composite, SWT.BORDER | SWT.FULL_SELECTION); table_1.setLinesVisible(true); table_1.setHeaderVisible(true); table_1.setBounds(0, 394, 484, 150); tblclmnAddress_1 = new TableColumn(table_1, SWT.NONE); tblclmnAddress_1.setResizable(false); tblclmnAddress_1.setWidth(60); tblclmnAddress_1.setToolTipText(""); tblclmnAddress_1.setText(Messages.ShowSig_tblAdr); tblclmnHex_1 = new TableColumn(table_1, SWT.NONE); tblclmnHex_1.setResizable(false); tblclmnHex_1.setWidth(250); tblclmnHex_1.setText(Messages.ShowSig_tblHex); tblclmnAscii_1 = new TableColumn(table_1, SWT.NONE); tblclmnAscii_1.setResizable(false); tblclmnAscii_1.setWidth(150); tblclmnAscii_1.setText(Messages.ShowSig_tblAscii); int len2 = org.jcryptool.visual.sig.algorithm.Input.data.length; String asciistr2 = convertHexToString(org.jcryptool.visual.sig.algorithm.Input.dataHex); // for (int i2 = 0; i2 < (Math.ceil((double)len2/(stepSize*2))) ; i2++) { // to show the whole message // shows only 6 rows - optimize performance for (int i2 = 0; i2 < 6 ; i2++) { //Create one item for each row TableItem item = new TableItem(table_1, SWT.NONE); // column 1 - address item.setText(0, getAddress(i2, stepSize));//Column, string // column 2 - int start2 = i2 * (stepSize*2); int end2 = i2 * (stepSize*2) + (stepSize*2); end2 = end2 >= len2 ? len2 : end2; StringBuffer bufferD1 = new StringBuffer(); for (int n1 = 0; n1 < (end2-start2)/2 ; n1++){ bufferD1.append(org.jcryptool.visual.sig.algorithm.Input.dataHex.charAt((2*n1)+start2)); bufferD1.append(org.jcryptool.visual.sig.algorithm.Input.dataHex.charAt((2*n1+1)+start2)); bufferD1.append(" "); } item.setText(1, bufferD1.toString()); // column 3 - ascii StringBuffer bufferD2 = new StringBuffer(); bufferD2.append(asciistr2, start2/2, end2/2); item.setText(2, bufferD2.toString()); } // text field to show signature as hex, octal or decimal txtSigNum = new Label(composite, SWT.BORDER | SWT.WRAP); txtSigNum.setBounds(0, 98, 484, 151); txtSigNum.setBackground(new Color(Display.getCurrent(), 255, 255, 255)); // display options Button btnOkt = new Button(grpOption, SWT.RADIO); btnOkt.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { table.setVisible(false); txtSigNum.setVisible(true); txtSigNum.setText(org.jcryptool.visual.sig.algorithm.Input.signatureOct); } }); btnOkt.setBounds(186, 30, 70, 16); btnOkt.setText(Messages.ShowSig_octal); Button btnDez = new Button(grpOption, SWT.RADIO); btnDez.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { table.setVisible(false); txtSigNum.setVisible(true); txtSigNum.setText(hexToDecimal(org.jcryptool.visual.sig.algorithm.Input.signatureHex)); } }); btnDez.setBounds(262, 30, 80, 16); btnDez.setText(Messages.ShowSig_decimal); Button btnHex = new Button(grpOption, SWT.RADIO); btnHex.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { table.setVisible(false); txtSigNum.setVisible(true); txtSigNum.setText(org.jcryptool.visual.sig.algorithm.Input.signatureHex); } }); btnHex.setBounds(348, 30, 70, 16); btnHex.setText(Messages.ShowSig_hex); Button btnHexdump = new Button(grpOption, SWT.RADIO); btnHexdump.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { txtSigNum.setVisible(false); table.setVisible(true); } }); btnHexdump.setSelection(true); btnHexdump.setBounds(10, 30, 170, 16); btnHexdump.setText(Messages.ShowSig_hexDump); // close window Button btnNewButton = new Button(composite, SWT.NONE); btnNewButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ShowSig.this.close(); } }); btnNewButton.setBounds(389, 633, 95, 28); btnNewButton.setText(Messages.ShowSig_btnClose); // open hex editor Button btnOpen = new Button(composite, SWT.NONE); btnOpen.setEnabled(false); btnOpen.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // TODO //Call the helper function to format the output (this is madness?!) //saveToFile(); openHexEditor(); } }); btnOpen.setBounds(145, 635, 140, 25); btnOpen.setText(Messages.ShowSig_btnOpen); Label lblTextopeneditor = new Label(composite, SWT.WRAP | SWT.CENTER); lblTextopeneditor.setAlignment(SWT.LEFT); lblTextopeneditor.setBounds(2, 584, 475, 32); lblTextopeneditor.setText(Messages.ShowSig_editorDescripton); lblTextopeneditor.setBackground(new Color(Display.getCurrent(), 255, 255, 255)); lblNewLabel = new Label(composite, SWT.NONE); lblNewLabel.setBounds(0, 578, 484, 44); lblNewLabel.setBackground(new Color(Display.getCurrent(), 255, 255, 255)); Button btnSave = new Button(composite, SWT.NONE); btnSave.setBounds(289, 633, 95, 28); btnSave.setText(Messages.ShowSig_btnSave); btnSave.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { //Open File save dialog FileDialog dialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE); dialog.setFileName("signature_and_message"); String savePath = dialog.open(); //Write the file if (savePath != null) { try { OutputStream output = null; try { output = new BufferedOutputStream(new FileOutputStream(savePath)); output.write(sLen); output.write(org.jcryptool.visual.sig.algorithm.Input.signature); output.write(org.jcryptool.visual.sig.algorithm.Input.data.toString().getBytes()); }//end try finally { output.close(); }//end finally }//end try catch(FileNotFoundException ex){ //LogUtil.logError(SigPlugin.PLUGIN_ID, ex); }//end catch catch(IOException ex){ //LogUtil.logError(SigPlugin.PLUGIN_ID, ex); }//end catch MessageBox messageBox = new MessageBox(new Shell(Display.getCurrent()), SWT.ICON_INFORMATION | SWT.OK); messageBox.setText(Messages.ShowSig_MessageBoxTitle); messageBox.setMessage(Messages.ShowSig_MessageBoxText); messageBox.open(); }//end if }//end widgetSelected }); createContents(); }
public ShowSig(Display display, String sig) { super(display, SWT.CLOSE | SWT.MIN | SWT.MAX | SWT.TITLE | SWT.APPLICATION_MODAL); Composite composite = new Composite(this, SWT.NONE); composite.setBounds(10, 10, 485, 661); txtT = new Label(composite, SWT.READ_ONLY | SWT.WRAP); txtT.setText(Messages.ShowSig_ownerTitle); txtT.setBounds(0, 0, 176, 21); txtT_2 = new Label(composite, SWT.READ_ONLY); txtT_2.setText(Messages.ShowSig_keyTitle); txtT_2.setBounds(0, 24, 176, 21); txtT_1 = new Label(composite, SWT.READ_ONLY); txtT_1.setText(Messages.ShowSig_methodTitle); txtT_1.setBounds(0, 48, 176, 21); // get owner of the key if ((org.jcryptool.visual.sig.algorithm.Input.privateKey == null) && (org.jcryptool.visual.sig.algorithm.Input.key == null)) { userName = "-"; } else { if (org.jcryptool.visual.sig.algorithm.Input.key != null) { userName = org.jcryptool.visual.sig.algorithm.Input.key.getContactName(); } else { userName = org.jcryptool.visual.sig.algorithm.Input.privateKey.getContactName(); } } text = new Label(composite, SWT.READ_ONLY | SWT.WRAP); text.setText(userName); text.setBounds(182, 0, 302, 21); // get information about the key text_1 = new Label(composite, SWT.READ_ONLY); if ((org.jcryptool.visual.sig.algorithm.Input.privateKey == null) && (org.jcryptool.visual.sig.algorithm.Input.key == null)) { if (sig.contains("ECDSA")) { text_1.setText("ANSI X9.62 prime256v1 (256 bits)"); } else { text_1.setText("-"); } } else { if (org.jcryptool.visual.sig.algorithm.Input.key != null) { text_1.setText(org.jcryptool.visual.sig.algorithm.Input.key.getClassName()); } else { text_1.setText(org.jcryptool.visual.sig.algorithm.Input.privateKey.getClassName()); } } text_1.setBounds(182, 24, 302, 21); text_2 = new Label(composite, SWT.READ_ONLY); text_2.setText(sig); text_2.setBounds(182, 48, 302, 21); txtSig = new Label(composite, SWT.READ_ONLY); txtSig.setText(Messages.ShowSig_grpSignature); txtSig.setBounds(0, 77, 137, 21); txtLnge = new Label(composite, SWT.READ_ONLY); txtLnge.setText(Messages.ShowSig_lengthSig + sLen + " Bits"); txtLnge.setBounds(0, 253, 430, 21); Group grpOption = new Group(composite, SWT.NONE); grpOption.setText(Messages.ShowSig_grpOption); grpOption.setBounds(0, 280, 484, 73); grpOption.setLayout(null); txtSignedMes = new Label(composite, SWT.READ_ONLY); txtSignedMes.setText(Messages.ShowSig_grpMessage); txtSignedMes.setBounds(0, 373, 137, 21); txtLngeMes = new Label(composite, SWT.READ_ONLY); txtLngeMes.setText(Messages.ShowSig_lengthMessage + mLen + " Bits"); txtLngeMes.setBounds(0, 548, 430, 21); // create table to show the generated signature table = new Table(composite, SWT.BORDER | SWT.FULL_SELECTION); table.setLinesVisible(true); table.setHeaderVisible(true); table.setBounds(0, 98, 484, 151); tblclmnAddress = new TableColumn(table, SWT.NONE); tblclmnAddress.setResizable(false); tblclmnAddress.setWidth(60); tblclmnAddress.setToolTipText(""); tblclmnAddress.setText(Messages.ShowSig_tblAdr); tblclmnHex = new TableColumn(table, SWT.NONE); tblclmnHex.setResizable(false); tblclmnHex.setWidth(250); tblclmnHex.setText(Messages.ShowSig_tblHex); tblclmnAscii = new TableColumn(table, SWT.NONE); tblclmnAscii.setResizable(false); tblclmnAscii.setWidth(150); tblclmnAscii.setText(Messages.ShowSig_tblAscii); int stepSize = 14; int len1 = org.jcryptool.visual.sig.algorithm.Input.signatureHex.length(); String asciistr = convertHexToString(org.jcryptool.visual.sig.algorithm.Input.signatureHex); for (int i1 = 0; i1 < (Math.ceil((double)len1/(stepSize*2))) ; i1++) { TableItem item = new TableItem(table, SWT.NONE); // column 1 - address item.setText(0, getAddress(i1, stepSize)); // column 2 - hex int start1 = i1 * (stepSize*2); int end1 = i1 * (stepSize*2) + (stepSize*2); end1 = end1 >= len1 ? len1 : end1; StringBuffer bufferS1 = new StringBuffer(); for (int m1 = 0; m1 < (end1-start1)/2 ; m1++){ bufferS1.append(org.jcryptool.visual.sig.algorithm.Input.signatureHex.charAt((2*m1)+start1)); bufferS1.append(org.jcryptool.visual.sig.algorithm.Input.signatureHex.charAt((2*m1+1)+start1)); bufferS1.append(" "); } item.setText(1, bufferS1.toString()); // column 3 - ascii StringBuffer bufferS2 = new StringBuffer(); bufferS2.append(asciistr, start1/2, end1/2); item.setText(2, bufferS2.toString()); } // create table to show signed message table_1 = new Table(composite, SWT.BORDER | SWT.FULL_SELECTION); table_1.setLinesVisible(true); table_1.setHeaderVisible(true); table_1.setBounds(0, 394, 484, 150); tblclmnAddress_1 = new TableColumn(table_1, SWT.NONE); tblclmnAddress_1.setResizable(false); tblclmnAddress_1.setWidth(60); tblclmnAddress_1.setToolTipText(""); tblclmnAddress_1.setText(Messages.ShowSig_tblAdr); tblclmnHex_1 = new TableColumn(table_1, SWT.NONE); tblclmnHex_1.setResizable(false); tblclmnHex_1.setWidth(250); tblclmnHex_1.setText(Messages.ShowSig_tblHex); tblclmnAscii_1 = new TableColumn(table_1, SWT.NONE); tblclmnAscii_1.setResizable(false); tblclmnAscii_1.setWidth(150); tblclmnAscii_1.setText(Messages.ShowSig_tblAscii); int len2 = org.jcryptool.visual.sig.algorithm.Input.data.length; String asciistr2 = convertHexToString(org.jcryptool.visual.sig.algorithm.Input.dataHex); // for (int i2 = 0; i2 < (Math.ceil((double)len2/(stepSize*2))) ; i2++) { // to show the whole message // shows only 6 rows - optimize performance for (int i2 = 0; i2 < 6 ; i2++) { //Create one item for each row TableItem item = new TableItem(table_1, SWT.NONE); // column 1 - address item.setText(0, getAddress(i2, stepSize));//Column, string // column 2 - int start2 = i2 * (stepSize*2); int end2 = i2 * (stepSize*2) + (stepSize*2); end2 = end2 >= len2 ? len2 : end2; StringBuffer bufferD1 = new StringBuffer(); for (int n1 = 0; n1 < (end2-start2)/2 ; n1++){ bufferD1.append(org.jcryptool.visual.sig.algorithm.Input.dataHex.charAt((2*n1)+start2)); bufferD1.append(org.jcryptool.visual.sig.algorithm.Input.dataHex.charAt((2*n1+1)+start2)); bufferD1.append(" "); } item.setText(1, bufferD1.toString()); // column 3 - ascii StringBuffer bufferD2 = new StringBuffer(); bufferD2.append(asciistr2, start2/2, end2/2); item.setText(2, bufferD2.toString()); } // text field to show signature as hex, octal or decimal txtSigNum = new Label(composite, SWT.BORDER | SWT.WRAP); txtSigNum.setBounds(0, 98, 484, 151); txtSigNum.setBackground(new Color(Display.getCurrent(), 255, 255, 255)); // display options Button btnOkt = new Button(grpOption, SWT.RADIO); btnOkt.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { table.setVisible(false); txtSigNum.setVisible(true); txtSigNum.setText(org.jcryptool.visual.sig.algorithm.Input.signatureOct); } }); btnOkt.setBounds(186, 30, 70, 16); btnOkt.setText(Messages.ShowSig_octal); Button btnDez = new Button(grpOption, SWT.RADIO); btnDez.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { table.setVisible(false); txtSigNum.setVisible(true); txtSigNum.setText(hexToDecimal(org.jcryptool.visual.sig.algorithm.Input.signatureHex)); } }); btnDez.setBounds(262, 30, 80, 16); btnDez.setText(Messages.ShowSig_decimal); Button btnHex = new Button(grpOption, SWT.RADIO); btnHex.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { table.setVisible(false); txtSigNum.setVisible(true); txtSigNum.setText(org.jcryptool.visual.sig.algorithm.Input.signatureHex); } }); btnHex.setBounds(348, 30, 70, 16); btnHex.setText(Messages.ShowSig_hex); Button btnHexdump = new Button(grpOption, SWT.RADIO); btnHexdump.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { txtSigNum.setVisible(false); table.setVisible(true); } }); btnHexdump.setSelection(true); btnHexdump.setBounds(10, 30, 170, 16); btnHexdump.setText(Messages.ShowSig_hexDump); // close window Button btnNewButton = new Button(composite, SWT.NONE); btnNewButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ShowSig.this.close(); } }); btnNewButton.setBounds(389, 633, 95, 28); btnNewButton.setText(Messages.ShowSig_btnClose); // open hex editor Button btnOpen = new Button(composite, SWT.NONE); btnOpen.setEnabled(false); btnOpen.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // TODO //Call the helper function to format the output (this is madness?!) //saveToFile(); openHexEditor(); } }); btnOpen.setBounds(145, 635, 140, 25); btnOpen.setText(Messages.ShowSig_btnOpen); Label lblTextopeneditor = new Label(composite, SWT.WRAP | SWT.CENTER); lblTextopeneditor.setAlignment(SWT.LEFT); lblTextopeneditor.setBounds(2, 584, 475, 32); lblTextopeneditor.setText(Messages.ShowSig_editorDescripton); lblTextopeneditor.setBackground(new Color(Display.getCurrent(), 255, 255, 255)); lblNewLabel = new Label(composite, SWT.NONE); lblNewLabel.setBounds(0, 578, 484, 44); lblNewLabel.setBackground(new Color(Display.getCurrent(), 255, 255, 255)); Button btnSave = new Button(composite, SWT.NONE); btnSave.setBounds(289, 633, 95, 28); btnSave.setText(Messages.ShowSig_btnSave); btnSave.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { //Open File save dialog FileDialog dialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE); dialog.setFileName("signature_and_message"); String savePath = dialog.open(); //Write the file if (savePath != null) { try { OutputStream output = null; try { output = new BufferedOutputStream(new FileOutputStream(savePath)); output.write(sLen); output.write(org.jcryptool.visual.sig.algorithm.Input.signature); output.write(org.jcryptool.visual.sig.algorithm.Input.data); }//end try finally { output.close(); }//end finally }//end try catch(FileNotFoundException ex){ //LogUtil.logError(SigPlugin.PLUGIN_ID, ex); }//end catch catch(IOException ex){ //LogUtil.logError(SigPlugin.PLUGIN_ID, ex); }//end catch MessageBox messageBox = new MessageBox(new Shell(Display.getCurrent()), SWT.ICON_INFORMATION | SWT.OK); messageBox.setText(Messages.ShowSig_MessageBoxTitle); messageBox.setMessage(Messages.ShowSig_MessageBoxText); messageBox.open(); }//end if }//end widgetSelected }); createContents(); }
diff --git a/source/src/net/grinder/engine/process/instrumenter/dcr/Jython22Instrumenter.java b/source/src/net/grinder/engine/process/instrumenter/dcr/Jython22Instrumenter.java index fef51118..be7edce9 100644 --- a/source/src/net/grinder/engine/process/instrumenter/dcr/Jython22Instrumenter.java +++ b/source/src/net/grinder/engine/process/instrumenter/dcr/Jython22Instrumenter.java @@ -1,160 +1,161 @@ // Copyright (C) 2009 Philip Aston // All rights reserved. // // This file is part of The Grinder software distribution. Refer to // the file LICENSE which is part of The Grinder distribution for // licensing details. The Grinder distribution is available on the // Internet at http://grinder.sourceforge.net/ // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. package net.grinder.engine.process.instrumenter.dcr; import java.lang.reflect.Method; import net.grinder.engine.process.ScriptEngine.Recorder; import net.grinder.script.NotWrappableTypeException; import net.grinder.util.weave.Weaver; import net.grinder.util.weave.Weaver.TargetSource; import org.python.core.PyClass; import org.python.core.PyFunction; import org.python.core.PyInstance; import org.python.core.PyMethod; import org.python.core.PyObject; import org.python.core.PyProxy; import org.python.core.PyReflectedFunction; /** * DCRInstrumenter for Jython 2.1, 2.2. * * @author Philip Aston * @version $Revision:$ */ final class Jython22Instrumenter extends DCRInstrumenter { /** * Constructor for DCRInstrumenter. * * @param weaver The weaver. * @param recorderRegistry The recorder registry. */ public Jython22Instrumenter(Weaver weaver, RecorderRegistry recorderRegistry) { super(weaver, recorderRegistry); } /** * {@inheritDoc} */ public String getDescription() { return "byte code transforming instrumenter for Jython 2.1/2.2"; } @Override protected Object instrument(Object target, Recorder recorder) throws NotWrappableTypeException { if (target instanceof PyObject) { // Jython object. if (target instanceof PyInstance) { instrumentPublicMethodsByName(target, "invoke", TargetSource.FIRST_PARAMETER, recorder, true); } else if (target instanceof PyFunction) { instrumentPublicMethodsByName(target, "__call__", TargetSource.FIRST_PARAMETER, recorder, false); } else if (target instanceof PyMethod) { instrumentPublicMethodsByName(target, "__call__", TargetSource.FIRST_PARAMETER, recorder, false); } else if (target instanceof PyReflectedFunction) { final Method callMethod; try { callMethod = PyReflectedFunction.class.getMethod("__call__", - PyObject.class); + PyObject[].class, + String[].class); } catch (Exception e) { throw new NotWrappableTypeException( "Correct version of Jython?: " + e.getLocalizedMessage()); } instrument(target, callMethod, TargetSource.FIRST_PARAMETER, recorder); } else if (target instanceof PyClass) { instrumentPublicMethodsByName(target, "__call__", TargetSource.FIRST_PARAMETER, recorder, false); } else { // Fail, rather than guess a generic approach. throw new NotWrappableTypeException("Unknown PyObject:" + target.getClass()); } } else if (target instanceof PyProxy) { // Jython object that extends a Java class. // We can't just use the Java wrapping, since then we'd miss the // Jython methods. final PyObject pyInstance = ((PyProxy)target)._getPyInstance(); instrumentPublicMethodsByName(pyInstance, "invoke", TargetSource.FIRST_PARAMETER, recorder, true); } else { return null; } return target; } private void instrumentPublicMethodsByName(Object target, String methodName, TargetSource targetSource, Recorder recorder, boolean includeSuperClassMethods) throws NotWrappableTypeException { // getMethods() includes superclass methods. for (Method method : target.getClass().getMethods()) { if (!includeSuperClassMethods && target.getClass() != method.getDeclaringClass()) { continue; } if (!method.getName().equals(methodName)) { continue; } instrument(target, method, targetSource, recorder); } } }
true
true
protected Object instrument(Object target, Recorder recorder) throws NotWrappableTypeException { if (target instanceof PyObject) { // Jython object. if (target instanceof PyInstance) { instrumentPublicMethodsByName(target, "invoke", TargetSource.FIRST_PARAMETER, recorder, true); } else if (target instanceof PyFunction) { instrumentPublicMethodsByName(target, "__call__", TargetSource.FIRST_PARAMETER, recorder, false); } else if (target instanceof PyMethod) { instrumentPublicMethodsByName(target, "__call__", TargetSource.FIRST_PARAMETER, recorder, false); } else if (target instanceof PyReflectedFunction) { final Method callMethod; try { callMethod = PyReflectedFunction.class.getMethod("__call__", PyObject.class); } catch (Exception e) { throw new NotWrappableTypeException( "Correct version of Jython?: " + e.getLocalizedMessage()); } instrument(target, callMethod, TargetSource.FIRST_PARAMETER, recorder); } else if (target instanceof PyClass) { instrumentPublicMethodsByName(target, "__call__", TargetSource.FIRST_PARAMETER, recorder, false); } else { // Fail, rather than guess a generic approach. throw new NotWrappableTypeException("Unknown PyObject:" + target.getClass()); } } else if (target instanceof PyProxy) { // Jython object that extends a Java class. // We can't just use the Java wrapping, since then we'd miss the // Jython methods. final PyObject pyInstance = ((PyProxy)target)._getPyInstance(); instrumentPublicMethodsByName(pyInstance, "invoke", TargetSource.FIRST_PARAMETER, recorder, true); } else { return null; } return target; }
protected Object instrument(Object target, Recorder recorder) throws NotWrappableTypeException { if (target instanceof PyObject) { // Jython object. if (target instanceof PyInstance) { instrumentPublicMethodsByName(target, "invoke", TargetSource.FIRST_PARAMETER, recorder, true); } else if (target instanceof PyFunction) { instrumentPublicMethodsByName(target, "__call__", TargetSource.FIRST_PARAMETER, recorder, false); } else if (target instanceof PyMethod) { instrumentPublicMethodsByName(target, "__call__", TargetSource.FIRST_PARAMETER, recorder, false); } else if (target instanceof PyReflectedFunction) { final Method callMethod; try { callMethod = PyReflectedFunction.class.getMethod("__call__", PyObject[].class, String[].class); } catch (Exception e) { throw new NotWrappableTypeException( "Correct version of Jython?: " + e.getLocalizedMessage()); } instrument(target, callMethod, TargetSource.FIRST_PARAMETER, recorder); } else if (target instanceof PyClass) { instrumentPublicMethodsByName(target, "__call__", TargetSource.FIRST_PARAMETER, recorder, false); } else { // Fail, rather than guess a generic approach. throw new NotWrappableTypeException("Unknown PyObject:" + target.getClass()); } } else if (target instanceof PyProxy) { // Jython object that extends a Java class. // We can't just use the Java wrapping, since then we'd miss the // Jython methods. final PyObject pyInstance = ((PyProxy)target)._getPyInstance(); instrumentPublicMethodsByName(pyInstance, "invoke", TargetSource.FIRST_PARAMETER, recorder, true); } else { return null; } return target; }
diff --git a/src/org/basex/core/proc/Set.java b/src/org/basex/core/proc/Set.java index 135926484..f947528c8 100644 --- a/src/org/basex/core/proc/Set.java +++ b/src/org/basex/core/proc/Set.java @@ -1,123 +1,125 @@ package org.basex.core.proc; import static org.basex.Text.*; import org.basex.core.Prop; import org.basex.io.IO; import org.basex.util.Token; /** * Evaluates the 'set' command. Sets internal processing options. * * @author Workgroup DBIS, University of Konstanz 2005-08, ISC License * @author Christian Gruen */ public final class Set extends Proc { /** Set option. */ public static final String CHOP = "chop"; /** Set option. */ public static final String DEBUG = "debug"; /** Set option. */ public static final String ENTITY = "entity"; /** Set option. */ public static final String FTINDEX = "ftindex"; /** Set option. */ public static final String TXTINDEX = "textindex"; /** Set option. */ public static final String ATTRINDEX = "attrindex"; /** Set option. */ public static final String RUNS = "runs"; /** Set option. */ public static final String MAINMEM = "mainmem"; /** Set option. */ public static final String SERIALIZE = "serialize"; /** Set option. */ public static final String INFO = "info"; /** Set option. */ public static final String XMLOUTPUT = "xmloutput"; /** Set option. */ public static final String DBPATH = "dbpath"; /** All flag. */ public static final String ALL = "ALL"; @Override protected boolean exec() { final String option = cmd.arg(0).toLowerCase(); final String ext = cmd.arg(1); if(option.equals(CHOP)) { Prop.chop = toggle(Prop.chop, INFOCHOP, ext); } else if(option.equals(DEBUG)) { Prop.debug = toggle(Prop.debug, INFODEBUG, ext); } else if(option.equals(ENTITY)) { Prop.entity = toggle(Prop.entity, INFOENTITIES, ext); } else if(option.equals(FTINDEX)) { Prop.ftindex = toggle(Prop.ftindex, INFOFTINDEX, ext); } else if(option.equals(TXTINDEX)) { Prop.textindex = toggle(Prop.textindex, INFOTXTINDEX, ext); } else if(option.equals(ATTRINDEX)) { Prop.attrindex = toggle(Prop.attrindex, INFOATVINDEX, ext); } else if(option.equals(MAINMEM)) { Prop.mainmem = toggle(Prop.mainmem, INFOMAINMEM, ext); } else if(option.equals(RUNS)) { Prop.runs = Math.max(1, Token.toInt(ext)); info(INFORUNS + ": " + Prop.runs); } else if(option.equals(SERIALIZE)) { Prop.serialize = toggle(Prop.serialize, INFOSERIALIZE, ext); } else if(option.equals(INFO)) { Prop.allInfo = ext.equalsIgnoreCase(ALL); if(Prop.allInfo) info(INFOINFO + INFOON + INFOALL); Prop.info = Prop.allInfo ? true : toggle(Prop.info, INFOINFO, ext); } else if(option.equals(XMLOUTPUT)) { Prop.xmloutput = toggle(Prop.xmloutput, INFOXMLOUTPUT, ext); } else if(option.equals(DBPATH)) { if(!new IO(ext).exists()) return error(INFOPATHERR + ext); Prop.dbpath = ext; info(INFONEWPATH + ext); // the following options are kinda hidden } else if(option.equals("fscont")) { Prop.fscont = toggle(Prop.fscont, option + " ", ext); } else if(option.equals("fsmeta")) { Prop.fsmeta = toggle(Prop.fsmeta, option + " ", ext); } else if(option.equals("fstextmax")) { Prop.fstextmax = Math.max(1, Token.toInt(ext)); info(option + ": " + Prop.fstextmax); } else if(option.equals("xqerrcode")) { Prop.xqerrcode = toggle(Prop.xqerrcode, option + " ", ext); } else if(option.equals("onthefly")) { Prop.onthefly = toggle(Prop.onthefly, option + " ", ext); } else if(option.equals("intparse")) { Prop.intparse = toggle(Prop.intparse, option + " ", ext); + } else if(option.equals("lserr")) { + Prop.lserr = Math.max(1, Token.toInt(ext)); } else if(option.equals("language")) { Prop.language = ext; info(option + ": " + ext); } else { throw new IllegalArgumentException(); } return true; } /** * Toggles the specified flag and returns the result. * @param f flag to be toggled * @param m info message * @param e extended value * @return result of toggling */ private boolean toggle(final boolean f, final String m, final String e) { final boolean val = e.length() == 0 ? !f : e.equalsIgnoreCase(ON) || !e.equalsIgnoreCase(OFF); info(flag(m, val)); return val; } /** * Returns an info message for the specified flag. * @param feature name of feature * @param flag current flag status * @return ON/OFF message */ protected static String flag(final String feature, final boolean flag) { return feature + (flag ? INFOON : INFOOFF); } }
true
true
protected boolean exec() { final String option = cmd.arg(0).toLowerCase(); final String ext = cmd.arg(1); if(option.equals(CHOP)) { Prop.chop = toggle(Prop.chop, INFOCHOP, ext); } else if(option.equals(DEBUG)) { Prop.debug = toggle(Prop.debug, INFODEBUG, ext); } else if(option.equals(ENTITY)) { Prop.entity = toggle(Prop.entity, INFOENTITIES, ext); } else if(option.equals(FTINDEX)) { Prop.ftindex = toggle(Prop.ftindex, INFOFTINDEX, ext); } else if(option.equals(TXTINDEX)) { Prop.textindex = toggle(Prop.textindex, INFOTXTINDEX, ext); } else if(option.equals(ATTRINDEX)) { Prop.attrindex = toggle(Prop.attrindex, INFOATVINDEX, ext); } else if(option.equals(MAINMEM)) { Prop.mainmem = toggle(Prop.mainmem, INFOMAINMEM, ext); } else if(option.equals(RUNS)) { Prop.runs = Math.max(1, Token.toInt(ext)); info(INFORUNS + ": " + Prop.runs); } else if(option.equals(SERIALIZE)) { Prop.serialize = toggle(Prop.serialize, INFOSERIALIZE, ext); } else if(option.equals(INFO)) { Prop.allInfo = ext.equalsIgnoreCase(ALL); if(Prop.allInfo) info(INFOINFO + INFOON + INFOALL); Prop.info = Prop.allInfo ? true : toggle(Prop.info, INFOINFO, ext); } else if(option.equals(XMLOUTPUT)) { Prop.xmloutput = toggle(Prop.xmloutput, INFOXMLOUTPUT, ext); } else if(option.equals(DBPATH)) { if(!new IO(ext).exists()) return error(INFOPATHERR + ext); Prop.dbpath = ext; info(INFONEWPATH + ext); // the following options are kinda hidden } else if(option.equals("fscont")) { Prop.fscont = toggle(Prop.fscont, option + " ", ext); } else if(option.equals("fsmeta")) { Prop.fsmeta = toggle(Prop.fsmeta, option + " ", ext); } else if(option.equals("fstextmax")) { Prop.fstextmax = Math.max(1, Token.toInt(ext)); info(option + ": " + Prop.fstextmax); } else if(option.equals("xqerrcode")) { Prop.xqerrcode = toggle(Prop.xqerrcode, option + " ", ext); } else if(option.equals("onthefly")) { Prop.onthefly = toggle(Prop.onthefly, option + " ", ext); } else if(option.equals("intparse")) { Prop.intparse = toggle(Prop.intparse, option + " ", ext); } else if(option.equals("language")) { Prop.language = ext; info(option + ": " + ext); } else { throw new IllegalArgumentException(); } return true; }
protected boolean exec() { final String option = cmd.arg(0).toLowerCase(); final String ext = cmd.arg(1); if(option.equals(CHOP)) { Prop.chop = toggle(Prop.chop, INFOCHOP, ext); } else if(option.equals(DEBUG)) { Prop.debug = toggle(Prop.debug, INFODEBUG, ext); } else if(option.equals(ENTITY)) { Prop.entity = toggle(Prop.entity, INFOENTITIES, ext); } else if(option.equals(FTINDEX)) { Prop.ftindex = toggle(Prop.ftindex, INFOFTINDEX, ext); } else if(option.equals(TXTINDEX)) { Prop.textindex = toggle(Prop.textindex, INFOTXTINDEX, ext); } else if(option.equals(ATTRINDEX)) { Prop.attrindex = toggle(Prop.attrindex, INFOATVINDEX, ext); } else if(option.equals(MAINMEM)) { Prop.mainmem = toggle(Prop.mainmem, INFOMAINMEM, ext); } else if(option.equals(RUNS)) { Prop.runs = Math.max(1, Token.toInt(ext)); info(INFORUNS + ": " + Prop.runs); } else if(option.equals(SERIALIZE)) { Prop.serialize = toggle(Prop.serialize, INFOSERIALIZE, ext); } else if(option.equals(INFO)) { Prop.allInfo = ext.equalsIgnoreCase(ALL); if(Prop.allInfo) info(INFOINFO + INFOON + INFOALL); Prop.info = Prop.allInfo ? true : toggle(Prop.info, INFOINFO, ext); } else if(option.equals(XMLOUTPUT)) { Prop.xmloutput = toggle(Prop.xmloutput, INFOXMLOUTPUT, ext); } else if(option.equals(DBPATH)) { if(!new IO(ext).exists()) return error(INFOPATHERR + ext); Prop.dbpath = ext; info(INFONEWPATH + ext); // the following options are kinda hidden } else if(option.equals("fscont")) { Prop.fscont = toggle(Prop.fscont, option + " ", ext); } else if(option.equals("fsmeta")) { Prop.fsmeta = toggle(Prop.fsmeta, option + " ", ext); } else if(option.equals("fstextmax")) { Prop.fstextmax = Math.max(1, Token.toInt(ext)); info(option + ": " + Prop.fstextmax); } else if(option.equals("xqerrcode")) { Prop.xqerrcode = toggle(Prop.xqerrcode, option + " ", ext); } else if(option.equals("onthefly")) { Prop.onthefly = toggle(Prop.onthefly, option + " ", ext); } else if(option.equals("intparse")) { Prop.intparse = toggle(Prop.intparse, option + " ", ext); } else if(option.equals("lserr")) { Prop.lserr = Math.max(1, Token.toInt(ext)); } else if(option.equals("language")) { Prop.language = ext; info(option + ": " + ext); } else { throw new IllegalArgumentException(); } return true; }
diff --git a/src/main/java/org/testng/reporters/JUnitReportReporter.java b/src/main/java/org/testng/reporters/JUnitReportReporter.java index 518393e3..6e7691af 100644 --- a/src/main/java/org/testng/reporters/JUnitReportReporter.java +++ b/src/main/java/org/testng/reporters/JUnitReportReporter.java @@ -1,188 +1,188 @@ package org.testng.reporters; import org.testng.IReporter; import org.testng.ISuite; import org.testng.ISuiteResult; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.collections.Lists; import org.testng.collections.Maps; import org.testng.internal.Utils; import org.testng.internal.annotations.Sets; import org.testng.xml.XmlSuite; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.DecimalFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; public class JUnitReportReporter implements IReporter { @Override public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String defaultOutputDirectory) { String outputDirectory = defaultOutputDirectory + File.separator + "junitreports"; Map<Class<?>, Set<ITestResult>> results = Maps.newHashMap(); Map<Class<?>, Set<ITestResult>> failedConfigurations = Maps.newHashMap(); for (ISuite suite : suites) { Map<String, ISuiteResult> suiteResults = suite.getResults(); for (ISuiteResult sr : suiteResults.values()) { ITestContext tc = sr.getTestContext(); addResults(tc.getPassedTests().getAllResults(), results); addResults(tc.getFailedTests().getAllResults(), results); addResults(tc.getSkippedTests().getAllResults(), results); addResults(tc.getFailedConfigurations().getAllResults(), failedConfigurations); } } for (Map.Entry<Class<?>, Set<ITestResult>> entry : results.entrySet()) { Class<?> cls = entry.getKey(); Properties p1 = new Properties(); p1.setProperty("name", cls.getName()); Date timeStamp = Calendar.getInstance().getTime(); p1.setProperty(XMLConstants.ATTR_TIMESTAMP, timeStamp.toGMTString()); List<TestTag> testCases = Lists.newArrayList(); int failures = 0; int errors = 0; int testCount = 0; float totalTime = 0; for (ITestResult tr: entry.getValue()) { TestTag testTag = new TestTag(); boolean isSuccess = tr.getStatus() == ITestResult.SUCCESS; - if (isSuccess) { + if (! isSuccess) { if (tr.getThrowable() instanceof AssertionError) { errors++; } else { failures++; } } Properties p2 = new Properties(); p2.setProperty("classname", cls.getName()); p2.setProperty("name", tr.getMethod().getMethodName()); long time = tr.getEndMillis() - tr.getStartMillis(); p2.setProperty("time", "" + formatTime(time)); Throwable t = getThrowable(tr, failedConfigurations); if (! isSuccess && t != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); testTag.message = t.getMessage(); testTag.type = t.getClass().getName(); testTag.stackTrace = sw.toString(); testTag.errorTag = tr.getThrowable() instanceof AssertionError ? "error" : "failure"; } totalTime += time; testCount++; testTag.properties = p2; testCases.add(testTag); } p1.setProperty("failures", "" + failures); p1.setProperty("errors", "" + errors); p1.setProperty("name", cls.getName()); p1.setProperty("tests", "" + testCount); p1.setProperty("time", "" + formatTime(totalTime)); try { p1.setProperty(XMLConstants.ATTR_HOSTNAME, InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { // ignore } // // Now that we have all the information we need, generate the file // XMLStringBuffer xsb = new XMLStringBuffer(); xsb.addComment("Generated by " + getClass().getName()); xsb.push("testsuite", p1); for (TestTag testTag : testCases) { if (testTag.stackTrace == null) { xsb.addEmptyElement("testcase", testTag.properties); } else { xsb.push("testcase", testTag.properties); Properties p = new Properties(); if (testTag.message != null) { p.setProperty("message", testTag.message); } p.setProperty("type", testTag.type); xsb.push(testTag.errorTag, p); xsb.addCDATA(testTag.stackTrace); xsb.pop(testTag.errorTag); xsb.pop("testcase"); } } xsb.pop("testsuite"); String fileName = "TEST-" + cls.getName() + ".xml"; Utils.writeFile(outputDirectory, fileName, xsb.toXML()); } // System.out.println(xsb.toXML()); // System.out.println(""); } private String formatTime(float time) { DecimalFormat format = new DecimalFormat("#.###"); format.setMinimumFractionDigits(3); return format.format(time / 1000.0f); } private Throwable getThrowable(ITestResult tr, Map<Class<?>, Set<ITestResult>> failedConfigurations) { Throwable result = tr.getThrowable(); if (result == null && tr.getStatus() == ITestResult.SKIP) { // Attempt to grab the stack trace from the configuration failure for (Set<ITestResult> failures : failedConfigurations.values()) { for (ITestResult failure : failures) { // Naive implementation for now, eventually, we need to try to find // out if it's this failure that caused the skip since (maybe by // seeing if the class of the configuration method is assignable to // the class of the test method, although that's not 100% fool proof if (failure.getThrowable() != null) { return failure.getThrowable(); } } } } return result; } class TestTag { public Properties properties; public String message; public String type; public String stackTrace; public String errorTag; } private void addResults(Set<ITestResult> allResults, Map<Class<?>, Set<ITestResult>> out) { for (ITestResult tr : allResults) { Class<?> cls = tr.getMethod().getTestClass().getRealClass(); Set<ITestResult> l = out.get(cls); if (l == null) { l = Sets.newHashSet(); out.put(cls, l); } l.add(tr); } } }
true
true
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String defaultOutputDirectory) { String outputDirectory = defaultOutputDirectory + File.separator + "junitreports"; Map<Class<?>, Set<ITestResult>> results = Maps.newHashMap(); Map<Class<?>, Set<ITestResult>> failedConfigurations = Maps.newHashMap(); for (ISuite suite : suites) { Map<String, ISuiteResult> suiteResults = suite.getResults(); for (ISuiteResult sr : suiteResults.values()) { ITestContext tc = sr.getTestContext(); addResults(tc.getPassedTests().getAllResults(), results); addResults(tc.getFailedTests().getAllResults(), results); addResults(tc.getSkippedTests().getAllResults(), results); addResults(tc.getFailedConfigurations().getAllResults(), failedConfigurations); } } for (Map.Entry<Class<?>, Set<ITestResult>> entry : results.entrySet()) { Class<?> cls = entry.getKey(); Properties p1 = new Properties(); p1.setProperty("name", cls.getName()); Date timeStamp = Calendar.getInstance().getTime(); p1.setProperty(XMLConstants.ATTR_TIMESTAMP, timeStamp.toGMTString()); List<TestTag> testCases = Lists.newArrayList(); int failures = 0; int errors = 0; int testCount = 0; float totalTime = 0; for (ITestResult tr: entry.getValue()) { TestTag testTag = new TestTag(); boolean isSuccess = tr.getStatus() == ITestResult.SUCCESS; if (isSuccess) { if (tr.getThrowable() instanceof AssertionError) { errors++; } else { failures++; } } Properties p2 = new Properties(); p2.setProperty("classname", cls.getName()); p2.setProperty("name", tr.getMethod().getMethodName()); long time = tr.getEndMillis() - tr.getStartMillis(); p2.setProperty("time", "" + formatTime(time)); Throwable t = getThrowable(tr, failedConfigurations); if (! isSuccess && t != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); testTag.message = t.getMessage(); testTag.type = t.getClass().getName(); testTag.stackTrace = sw.toString(); testTag.errorTag = tr.getThrowable() instanceof AssertionError ? "error" : "failure"; } totalTime += time; testCount++; testTag.properties = p2; testCases.add(testTag); } p1.setProperty("failures", "" + failures); p1.setProperty("errors", "" + errors); p1.setProperty("name", cls.getName()); p1.setProperty("tests", "" + testCount); p1.setProperty("time", "" + formatTime(totalTime)); try { p1.setProperty(XMLConstants.ATTR_HOSTNAME, InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { // ignore } // // Now that we have all the information we need, generate the file // XMLStringBuffer xsb = new XMLStringBuffer(); xsb.addComment("Generated by " + getClass().getName()); xsb.push("testsuite", p1); for (TestTag testTag : testCases) { if (testTag.stackTrace == null) { xsb.addEmptyElement("testcase", testTag.properties); } else { xsb.push("testcase", testTag.properties); Properties p = new Properties(); if (testTag.message != null) { p.setProperty("message", testTag.message); } p.setProperty("type", testTag.type); xsb.push(testTag.errorTag, p); xsb.addCDATA(testTag.stackTrace); xsb.pop(testTag.errorTag); xsb.pop("testcase"); } } xsb.pop("testsuite"); String fileName = "TEST-" + cls.getName() + ".xml"; Utils.writeFile(outputDirectory, fileName, xsb.toXML()); } // System.out.println(xsb.toXML()); // System.out.println(""); }
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String defaultOutputDirectory) { String outputDirectory = defaultOutputDirectory + File.separator + "junitreports"; Map<Class<?>, Set<ITestResult>> results = Maps.newHashMap(); Map<Class<?>, Set<ITestResult>> failedConfigurations = Maps.newHashMap(); for (ISuite suite : suites) { Map<String, ISuiteResult> suiteResults = suite.getResults(); for (ISuiteResult sr : suiteResults.values()) { ITestContext tc = sr.getTestContext(); addResults(tc.getPassedTests().getAllResults(), results); addResults(tc.getFailedTests().getAllResults(), results); addResults(tc.getSkippedTests().getAllResults(), results); addResults(tc.getFailedConfigurations().getAllResults(), failedConfigurations); } } for (Map.Entry<Class<?>, Set<ITestResult>> entry : results.entrySet()) { Class<?> cls = entry.getKey(); Properties p1 = new Properties(); p1.setProperty("name", cls.getName()); Date timeStamp = Calendar.getInstance().getTime(); p1.setProperty(XMLConstants.ATTR_TIMESTAMP, timeStamp.toGMTString()); List<TestTag> testCases = Lists.newArrayList(); int failures = 0; int errors = 0; int testCount = 0; float totalTime = 0; for (ITestResult tr: entry.getValue()) { TestTag testTag = new TestTag(); boolean isSuccess = tr.getStatus() == ITestResult.SUCCESS; if (! isSuccess) { if (tr.getThrowable() instanceof AssertionError) { errors++; } else { failures++; } } Properties p2 = new Properties(); p2.setProperty("classname", cls.getName()); p2.setProperty("name", tr.getMethod().getMethodName()); long time = tr.getEndMillis() - tr.getStartMillis(); p2.setProperty("time", "" + formatTime(time)); Throwable t = getThrowable(tr, failedConfigurations); if (! isSuccess && t != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); testTag.message = t.getMessage(); testTag.type = t.getClass().getName(); testTag.stackTrace = sw.toString(); testTag.errorTag = tr.getThrowable() instanceof AssertionError ? "error" : "failure"; } totalTime += time; testCount++; testTag.properties = p2; testCases.add(testTag); } p1.setProperty("failures", "" + failures); p1.setProperty("errors", "" + errors); p1.setProperty("name", cls.getName()); p1.setProperty("tests", "" + testCount); p1.setProperty("time", "" + formatTime(totalTime)); try { p1.setProperty(XMLConstants.ATTR_HOSTNAME, InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { // ignore } // // Now that we have all the information we need, generate the file // XMLStringBuffer xsb = new XMLStringBuffer(); xsb.addComment("Generated by " + getClass().getName()); xsb.push("testsuite", p1); for (TestTag testTag : testCases) { if (testTag.stackTrace == null) { xsb.addEmptyElement("testcase", testTag.properties); } else { xsb.push("testcase", testTag.properties); Properties p = new Properties(); if (testTag.message != null) { p.setProperty("message", testTag.message); } p.setProperty("type", testTag.type); xsb.push(testTag.errorTag, p); xsb.addCDATA(testTag.stackTrace); xsb.pop(testTag.errorTag); xsb.pop("testcase"); } } xsb.pop("testsuite"); String fileName = "TEST-" + cls.getName() + ".xml"; Utils.writeFile(outputDirectory, fileName, xsb.toXML()); } // System.out.println(xsb.toXML()); // System.out.println(""); }
diff --git a/src/test/java/edu/ucla/sspace/matrix/factorization/SingularValueDecompositionTestUtil.java b/src/test/java/edu/ucla/sspace/matrix/factorization/SingularValueDecompositionTestUtil.java index 7b844106..e001907b 100644 --- a/src/test/java/edu/ucla/sspace/matrix/factorization/SingularValueDecompositionTestUtil.java +++ b/src/test/java/edu/ucla/sspace/matrix/factorization/SingularValueDecompositionTestUtil.java @@ -1,108 +1,108 @@ /* * Copyright (c) 2011, Lawrence Livermore National Security, LLC. Produced at * the Lawrence Livermore National Laboratory. Written by Keith Stevens, * [email protected] OCEC-10-073 All rights reserved. * * This file is part of the S-Space package and is covered under the terms and * conditions therein. * * The S-Space package is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation and distributed hereunder to you. * * THIS SOFTWARE IS PROVIDED "AS IS" AND NO REPRESENTATIONS OR WARRANTIES, * EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE * NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY * PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION * WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER * RIGHTS. * * 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 edu.ucla.sspace.matrix.factorization; import edu.ucla.sspace.matrix.Matrix; import edu.ucla.sspace.matrix.MatrixFactorization; import edu.ucla.sspace.matrix.MatrixFile; import edu.ucla.sspace.matrix.MatrixIO; import edu.ucla.sspace.matrix.MatrixIO.Format; import edu.ucla.sspace.matrix.SparseMatrix; import edu.ucla.sspace.matrix.YaleSparseMatrix; import java.io.File; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.*; /** * @author Keith Stevens */ public class SingularValueDecompositionTestUtil { public static final double[][] VALUES = { {1, 1, 0, 0, 0, 0, 1}, {0, 1, 1, 0, 0, 0, 0}, {1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 1, 0}, {0, 0, 0, 1, 0, 1, 1}, }; public static final SparseMatrix matrix = new YaleSparseMatrix(VALUES); public static final double[][] EXPECTED_U = { {0.38846, -0.73615}, {0.117616, -0.425017}, {0.0902812, -0.26945}, {0.596357, 0.425017}, {0.686639, 0.155567}, }; public static final double[] EXPECTED_S = {2.30278, 1.93185}; public static final double[][] EXPECTED_V = { {0.207897,0.219768,0.0510758,0.557152,0.258973,0.557152,0.466871}, {-0.520537,-0.601064,-0.220005,0.300532,0.220005,0.300532,-0.300532}, }; public static void testReductionFile(MatrixFactorization reducer, Format format) { try { File mFile = File.createTempFile("TestSvdMatrix", "dat"); mFile.deleteOnExit(); MatrixIO.writeMatrix(matrix, mFile, format); reducer.factorize(new MatrixFile(mFile, format), 2); } catch (Exception ioe) { ioe.printStackTrace(); } validateResults(reducer); } public static void testReductionMatrix(MatrixFactorization reducer) { reducer.factorize(matrix, 2); validateResults(reducer); } public static void validateResults(MatrixFactorization reducer) { Matrix U = reducer.dataClasses(); assertEquals(matrix.rows(), U.rows()); assertEquals(2, U.columns()); for (int r = 0; r < matrix.rows(); ++r) for (int c = 0; c < 2; ++c) - assertEquals(EXPECTED_U[r][c] * EXPECTED_S[c],U.get(r,c),.001); + assertEquals(Math.abs(EXPECTED_U[r][c] * EXPECTED_S[c]),Math.abs(U.get(r,c)),.001); Matrix V = reducer.classFeatures(); assertEquals(2, V.rows()); assertEquals(matrix.columns(), V.columns()); for (int r = 0; r < 2; ++r) for (int c = 0; c < matrix.columns(); ++c) - assertEquals(EXPECTED_V[r][c] * EXPECTED_S[r],V.get(r,c),.001); + assertEquals(Math.abs(EXPECTED_V[r][c] * EXPECTED_S[r]),Math.abs(V.get(r,c)),.001); } }
false
true
public static void validateResults(MatrixFactorization reducer) { Matrix U = reducer.dataClasses(); assertEquals(matrix.rows(), U.rows()); assertEquals(2, U.columns()); for (int r = 0; r < matrix.rows(); ++r) for (int c = 0; c < 2; ++c) assertEquals(EXPECTED_U[r][c] * EXPECTED_S[c],U.get(r,c),.001); Matrix V = reducer.classFeatures(); assertEquals(2, V.rows()); assertEquals(matrix.columns(), V.columns()); for (int r = 0; r < 2; ++r) for (int c = 0; c < matrix.columns(); ++c) assertEquals(EXPECTED_V[r][c] * EXPECTED_S[r],V.get(r,c),.001); }
public static void validateResults(MatrixFactorization reducer) { Matrix U = reducer.dataClasses(); assertEquals(matrix.rows(), U.rows()); assertEquals(2, U.columns()); for (int r = 0; r < matrix.rows(); ++r) for (int c = 0; c < 2; ++c) assertEquals(Math.abs(EXPECTED_U[r][c] * EXPECTED_S[c]),Math.abs(U.get(r,c)),.001); Matrix V = reducer.classFeatures(); assertEquals(2, V.rows()); assertEquals(matrix.columns(), V.columns()); for (int r = 0; r < 2; ++r) for (int c = 0; c < matrix.columns(); ++c) assertEquals(Math.abs(EXPECTED_V[r][c] * EXPECTED_S[r]),Math.abs(V.get(r,c)),.001); }
diff --git a/source/src/main/java/com/redcats/tst/serviceEngine/impl/ControlService.java b/source/src/main/java/com/redcats/tst/serviceEngine/impl/ControlService.java index 5fd092245..d7ce79b76 100644 --- a/source/src/main/java/com/redcats/tst/serviceEngine/impl/ControlService.java +++ b/source/src/main/java/com/redcats/tst/serviceEngine/impl/ControlService.java @@ -1,497 +1,497 @@ package com.redcats.tst.serviceEngine.impl; import com.redcats.tst.entity.MessageEvent; import com.redcats.tst.entity.MessageEventEnum; import com.redcats.tst.entity.MessageGeneral; import com.redcats.tst.entity.TestCaseStepActionControlExecution; import com.redcats.tst.exception.CerberusEventException; import com.redcats.tst.log.MyLogger; import com.redcats.tst.serviceEngine.IControlService; import com.redcats.tst.serviceEngine.IPropertyService; import com.redcats.tst.serviceEngine.ISeleniumService; import com.redcats.tst.util.StringUtil; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.log4j.Level; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriverException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * {Insert class description here} * * @author Tiago Bernardes * @version 1.0, 24/01/2013 * @since 2.0.0 */ @Service public class ControlService implements IControlService { @Autowired private ISeleniumService seleniumService; @Autowired private IPropertyService propertyService; @Override public TestCaseStepActionControlExecution doControl(TestCaseStepActionControlExecution testCaseStepActionControlExecution) { /** * Decode the 2 fields property and values before doing the control. */ if (testCaseStepActionControlExecution.getControlProperty().contains("%")) { String decodedValue = propertyService.decodeValue(testCaseStepActionControlExecution.getControlProperty(), testCaseStepActionControlExecution.getTestCaseStepActionExecution().getTestCaseExecutionDataList(), testCaseStepActionControlExecution.getTestCaseStepActionExecution().getTestCaseStepExecution().gettCExecution()); testCaseStepActionControlExecution.setControlProperty(decodedValue); } if (testCaseStepActionControlExecution.getControlValue().contains("%")) { String decodedValue = propertyService.decodeValue(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getTestCaseStepActionExecution().getTestCaseExecutionDataList(), testCaseStepActionControlExecution.getTestCaseStepActionExecution().getTestCaseStepExecution().gettCExecution()); testCaseStepActionControlExecution.setControlValue(decodedValue); } /** * Timestamp starts after the decode. TODO protect when property is * null. */ testCaseStepActionControlExecution.setStart(new Date().getTime()); MessageEvent res; try { //TODO On JDK 7 implement switch with string if (testCaseStepActionControlExecution.getControlType().equals("verifyStringEqual")) { res = this.verifyStringEqual(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyStringDifferent")) { res = this.verifyStringDifferent(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyStringGreater")) { - res = this.verifyStringGreater(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getControlProperty()); + res = this.verifyStringGreater(testCaseStepActionControlExecution.getControlProperty(), testCaseStepActionControlExecution.getControlValue()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyStringMinor")) { - res = this.verifyStringMinor(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getControlProperty()); + res = this.verifyStringMinor(testCaseStepActionControlExecution.getControlProperty(), testCaseStepActionControlExecution.getControlValue()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyIntegerGreater")) { - res = this.verifyIntegerGreater(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getControlProperty()); + res = this.verifyIntegerGreater(testCaseStepActionControlExecution.getControlProperty(), testCaseStepActionControlExecution.getControlValue()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyIntegerMinor")) { - res = this.verifyIntegerMinor(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getControlProperty()); + res = this.verifyIntegerMinor(testCaseStepActionControlExecution.getControlProperty(), testCaseStepActionControlExecution.getControlValue()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyElementPresent")) { //TODO validate properties res = this.verifyElementPresent(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyElementNotPresent")) { //TODO validate properties res = this.verifyElementNotPresent(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyElementVisible")) { //TODO validate properties res = this.verifyElementVisible(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyTextInElement")) { res = this.VerifyTextInElement(testCaseStepActionControlExecution.getControlProperty(), testCaseStepActionControlExecution.getControlValue()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyRegexInElement")) { res = this.VerifyRegexInElement(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyTextInPage")) { res = this.VerifyTextInPage(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyTextNotInPage")) { res = this.VerifyTextNotInPage(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyTitle")) { res = this.verifyTitle(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyUrl")) { res = this.verifyUrl(testCaseStepActionControlExecution.getControlProperty()); } else { res = new MessageEvent(MessageEventEnum.CONTROL_FAILED_UNKNOWNCONTROL); res.setDescription(res.getDescription().replaceAll("%CONTROL%", testCaseStepActionControlExecution.getControlType())); } testCaseStepActionControlExecution.setControlResultMessage(res); /** * Updating Control result message only if control is not * successful. This is to keep the last KO information and * preventing KO to be transformed to OK. */ if (!(res.equals(new MessageEvent(MessageEventEnum.CONTROL_SUCCESS)))) { testCaseStepActionControlExecution.setExecutionResultMessage(new MessageGeneral(res.getMessage())); } /** * We only stop the test if Control Event message is in stop status * AND the control is FATAL. If control is not fatal, we continue * the test but refresh the Execution status. */ if (res.isStopTest()) { if (testCaseStepActionControlExecution.getFatal().equals("Y")) { testCaseStepActionControlExecution.setStopExecution(true); } } } catch (CerberusEventException exception) { testCaseStepActionControlExecution.setControlResultMessage(exception.getMessageError()); } testCaseStepActionControlExecution.setEnd(new Date().getTime()); return testCaseStepActionControlExecution; } private MessageEvent verifyStringDifferent(String object, String property) { MessageEvent mes; if (!object.equalsIgnoreCase(property)) { mes = new MessageEvent(MessageEventEnum.CONTROL_SUCCESS_DIFFERENT); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", object)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", property)); return mes; } mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_DIFFERENT); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", object)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", property)); return mes; } private MessageEvent verifyStringEqual(String object, String property) { MessageEvent mes; if (object.equalsIgnoreCase(property)) { mes = new MessageEvent(MessageEventEnum.CONTROL_SUCCESS_EQUAL); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", object)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", property)); return mes; } mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_EQUAL); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", object)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", property)); return mes; } private MessageEvent verifyStringGreater(String property, String value) { MessageEvent mes; if (property.compareToIgnoreCase(value) > 0) { mes = new MessageEvent(MessageEventEnum.CONTROL_SUCCESS_GREATER); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", property)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", value)); return mes; } else { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_GREATER); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", property)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", value)); return mes; } } private MessageEvent verifyStringMinor(String property, String value) { MessageEvent mes; if (property.compareToIgnoreCase(value) < 0) { mes = new MessageEvent(MessageEventEnum.CONTROL_SUCCESS_MINOR); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", property)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", value)); return mes; } else { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_MINOR); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", property)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", value)); return mes; } } private MessageEvent verifyIntegerGreater(String property, String value) { MessageEvent mes; if (StringUtil.isNumeric(property) && StringUtil.isNumeric(value)) { int prop = Integer.parseInt(property); int val = Integer.parseInt(value); if (prop > val) { mes = new MessageEvent(MessageEventEnum.CONTROL_SUCCESS_GREATER); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", property)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", value)); return mes; } else { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_GREATER); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", property)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", value)); return mes; } } return new MessageEvent(MessageEventEnum.CONTROL_FAILED_PROPERTY_NOTNUMERIC); } private MessageEvent verifyIntegerMinor(String property, String value) { MessageEvent mes; if (StringUtil.isNumeric(property) && StringUtil.isNumeric(value)) { int prop = Integer.parseInt(property); int val = Integer.parseInt(value); if (prop < val) { mes = new MessageEvent(MessageEventEnum.CONTROL_SUCCESS_MINOR); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", property)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", value)); return mes; } else { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_MINOR); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", property)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", value)); return mes; } } return new MessageEvent(MessageEventEnum.CONTROL_FAILED_PROPERTY_NOTNUMERIC); } private MessageEvent verifyElementPresent(String html) { MyLogger.log(ControlService.class.getName(), Level.DEBUG, "Control : verifyElementPresent on : " + html); MessageEvent mes; if (!StringUtil.isNull(html)) { try { if (this.seleniumService.isElementPresent(html)) { mes = new MessageEvent(MessageEventEnum.CONTROL_SUCCESS_PRESENT); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", html)); return mes; } else { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_PRESENT); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", html)); return mes; } } catch (WebDriverException exception) { MyLogger.log(SeleniumService.class.getName(), Level.FATAL, exception.toString()); return new MessageEvent(MessageEventEnum.CONTROL_FAILED_SELENIUM_CONNECTIVITY); } } else { return new MessageEvent(MessageEventEnum.CONTROL_FAILED_PRESENT_NULL); } } private MessageEvent verifyElementNotPresent(String html) { MyLogger.log(ControlService.class.getName(), Level.DEBUG, "Control : verifyElementNotPresent on : " + html); MessageEvent mes; if (!StringUtil.isNull(html)) { try { if (!this.seleniumService.isElementPresent(html)) { mes = new MessageEvent(MessageEventEnum.CONTROL_SUCCESS_NOTPRESENT); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", html)); return mes; } else { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_NOTPRESENT); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", html)); return mes; } } catch (WebDriverException exception) { MyLogger.log(SeleniumService.class.getName(), Level.FATAL, exception.toString()); return new MessageEvent(MessageEventEnum.CONTROL_FAILED_SELENIUM_CONNECTIVITY); } } else { return new MessageEvent(MessageEventEnum.CONTROL_FAILED_NOTPRESENT_NULL); } } private MessageEvent verifyElementVisible(String html) { MyLogger.log(ControlService.class.getName(), Level.DEBUG, "Control : verifyElementVisible on : " + html); MessageEvent mes; if (!StringUtil.isNull(html)) { try { if (this.seleniumService.isElementVisible(html)) { mes = new MessageEvent(MessageEventEnum.CONTROL_SUCCESS_VISIBLE); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", html)); return mes; } else { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_VISIBLE); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", html)); return mes; } } catch (WebDriverException exception) { MyLogger.log(SeleniumService.class.getName(), Level.FATAL, exception.toString()); return new MessageEvent(MessageEventEnum.CONTROL_FAILED_SELENIUM_CONNECTIVITY); } } else { return new MessageEvent(MessageEventEnum.CONTROL_FAILED_VISIBLE_NULL); } } private MessageEvent VerifyTextInElement(String html, String value) { MyLogger.log(ControlService.class.getName(), Level.DEBUG, "Control : VerifyTextInElement on : " + html + " element against value : " + value); MessageEvent mes; try { String str = this.seleniumService.getValueFromHTML(html); MyLogger.log(ControlService.class.getName(), Level.DEBUG, "Control : VerifyTextInElement element : " + html + " has value : " + str); if (str != null) { if (str.equalsIgnoreCase(value)) { mes = new MessageEvent(MessageEventEnum.CONTROL_SUCCESS_TEXTINELEMENT); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", html)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", str)); mes.setDescription(mes.getDescription().replaceAll("%STRING3%", value)); return mes; } else { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_TEXTINELEMENT); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", html)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", str)); mes.setDescription(mes.getDescription().replaceAll("%STRING3%", value)); return mes; } } else { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_TEXTINELEMENT_NULL); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", html)); return mes; } } catch (NoSuchElementException exception) { MyLogger.log(ControlService.class.getName(), Level.ERROR, exception.toString()); mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_TEXTINELEMENT_NO_SUCH_ELEMENT); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", html)); return mes; } catch (WebDriverException exception) { MyLogger.log(SeleniumService.class.getName(), Level.FATAL, exception.toString()); return new MessageEvent(MessageEventEnum.CONTROL_FAILED_SELENIUM_CONNECTIVITY); } } private MessageEvent VerifyRegexInElement(String html, String regex) { MyLogger.log(ControlService.class.getName(), Level.DEBUG, "Control : verifyRegexInElement on : " + html + " element against value : " + regex); MessageEvent mes; try { String str = this.seleniumService.getValueFromHTML(html); MyLogger.log(ControlService.class.getName(), Level.DEBUG, "Control : verifyRegexInElement element : " + html + " has value : " + str); if (str != null) { try { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str); if (matcher.find()) { mes = new MessageEvent(MessageEventEnum.CONTROL_SUCCESS_REGEXINELEMENT); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", html)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", str)); mes.setDescription(mes.getDescription().replaceAll("%STRING3%", regex)); return mes; } else { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_REGEXINELEMENT); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", html)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", str)); mes.setDescription(mes.getDescription().replaceAll("%STRING3%", regex)); return mes; } } catch (PatternSyntaxException e) { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_REGEXINELEMENT_INVALIDPATERN); mes.setDescription(mes.getDescription().replaceAll("%PATERN%", regex)); mes.setDescription(mes.getDescription().replaceAll("%ERROR%", e.getMessage())); return mes; } } else { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_REGEXINELEMENT_NULL); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", html)); return mes; } } catch (NoSuchElementException exception) { MyLogger.log(ControlService.class.getName(), Level.ERROR, exception.toString()); mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_REGEXINELEMENT_NO_SUCH_ELEMENT); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", html)); return mes; } catch (WebDriverException exception) { MyLogger.log(SeleniumService.class.getName(), Level.FATAL, exception.toString()); return new MessageEvent(MessageEventEnum.CONTROL_FAILED_SELENIUM_CONNECTIVITY); } } private MessageEvent VerifyTextInPage(String regex) { MyLogger.log(ControlService.class.getName(), Level.DEBUG, "Control : verifyTextInPage on : " + regex); MessageEvent mes; String pageSource; try { pageSource = this.seleniumService.getPageSource(); MyLogger.log(SeleniumService.class.getName(), Level.DEBUG, pageSource); try { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(pageSource); if (matcher.find()) { mes = new MessageEvent(MessageEventEnum.CONTROL_SUCCESS_TEXTINPAGE); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", regex)); return mes; } else { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_TEXTINPAGE); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", regex)); return mes; } } catch (PatternSyntaxException e) { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_TEXTINPAGE_INVALIDPATERN); mes.setDescription(mes.getDescription().replaceAll("%PATERN%", regex)); mes.setDescription(mes.getDescription().replaceAll("%ERROR%", e.getMessage())); return mes; } } catch (WebDriverException exception) { MyLogger.log(SeleniumService.class.getName(), Level.FATAL, exception.toString()); return new MessageEvent(MessageEventEnum.CONTROL_FAILED_SELENIUM_CONNECTIVITY); } } private MessageEvent VerifyTextNotInPage(String regex) { MyLogger.log(ControlService.class.getName(), Level.DEBUG, "Control : VerifyTextNotInPage on : " + regex); MessageEvent mes; String pageSource; try { pageSource = this.seleniumService.getPageSource(); MyLogger.log(SeleniumService.class.getName(), Level.DEBUG, pageSource); try { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(pageSource); if (!(matcher.find())) { mes = new MessageEvent(MessageEventEnum.CONTROL_SUCCESS_TEXTNOTINPAGE); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", regex)); return mes; } else { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_TEXTNOTINPAGE); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", regex)); return mes; } } catch (PatternSyntaxException e) { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_TEXTNOTINPAGE_INVALIDPATERN); mes.setDescription(mes.getDescription().replaceAll("%PATERN%", regex)); mes.setDescription(mes.getDescription().replaceAll("%ERROR%", e.getMessage())); return mes; } } catch (WebDriverException exception) { MyLogger.log(SeleniumService.class.getName(), Level.FATAL, exception.toString()); return new MessageEvent(MessageEventEnum.CONTROL_FAILED_SELENIUM_CONNECTIVITY); } } private MessageEvent verifyUrl(String page) throws CerberusEventException { MyLogger.log(ControlService.class.getName(), Level.DEBUG, "Control : verifyUrl on : " + page); MessageEvent mes; try { String url = this.seleniumService.getCurrentUrl(); if (url.equalsIgnoreCase(page)) { mes = new MessageEvent(MessageEventEnum.CONTROL_SUCCESS_URL); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", url)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", page)); return mes; } else { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_URL); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", url)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", page)); return mes; } } catch (WebDriverException exception) { MyLogger.log(SeleniumService.class.getName(), Level.FATAL, exception.toString()); return new MessageEvent(MessageEventEnum.CONTROL_FAILED_SELENIUM_CONNECTIVITY); } } private MessageEvent verifyTitle(String title) { MyLogger.log(ControlService.class.getName(), Level.DEBUG, "Control : verifyTitle on : " + title); MessageEvent mes; try { String pageTitle = this.seleniumService.getTitle(); if (pageTitle.equalsIgnoreCase(title)) { mes = new MessageEvent(MessageEventEnum.CONTROL_SUCCESS_TITLE); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", pageTitle)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", title)); return mes; } else { mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_TITLE); mes.setDescription(mes.getDescription().replaceAll("%STRING1%", pageTitle)); mes.setDescription(mes.getDescription().replaceAll("%STRING2%", title)); return mes; } } catch (WebDriverException exception) { MyLogger.log(SeleniumService.class.getName(), Level.FATAL, exception.toString()); return new MessageEvent(MessageEventEnum.CONTROL_FAILED_SELENIUM_CONNECTIVITY); } } }
false
true
public TestCaseStepActionControlExecution doControl(TestCaseStepActionControlExecution testCaseStepActionControlExecution) { /** * Decode the 2 fields property and values before doing the control. */ if (testCaseStepActionControlExecution.getControlProperty().contains("%")) { String decodedValue = propertyService.decodeValue(testCaseStepActionControlExecution.getControlProperty(), testCaseStepActionControlExecution.getTestCaseStepActionExecution().getTestCaseExecutionDataList(), testCaseStepActionControlExecution.getTestCaseStepActionExecution().getTestCaseStepExecution().gettCExecution()); testCaseStepActionControlExecution.setControlProperty(decodedValue); } if (testCaseStepActionControlExecution.getControlValue().contains("%")) { String decodedValue = propertyService.decodeValue(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getTestCaseStepActionExecution().getTestCaseExecutionDataList(), testCaseStepActionControlExecution.getTestCaseStepActionExecution().getTestCaseStepExecution().gettCExecution()); testCaseStepActionControlExecution.setControlValue(decodedValue); } /** * Timestamp starts after the decode. TODO protect when property is * null. */ testCaseStepActionControlExecution.setStart(new Date().getTime()); MessageEvent res; try { //TODO On JDK 7 implement switch with string if (testCaseStepActionControlExecution.getControlType().equals("verifyStringEqual")) { res = this.verifyStringEqual(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyStringDifferent")) { res = this.verifyStringDifferent(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyStringGreater")) { res = this.verifyStringGreater(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyStringMinor")) { res = this.verifyStringMinor(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyIntegerGreater")) { res = this.verifyIntegerGreater(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyIntegerMinor")) { res = this.verifyIntegerMinor(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyElementPresent")) { //TODO validate properties res = this.verifyElementPresent(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyElementNotPresent")) { //TODO validate properties res = this.verifyElementNotPresent(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyElementVisible")) { //TODO validate properties res = this.verifyElementVisible(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyTextInElement")) { res = this.VerifyTextInElement(testCaseStepActionControlExecution.getControlProperty(), testCaseStepActionControlExecution.getControlValue()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyRegexInElement")) { res = this.VerifyRegexInElement(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyTextInPage")) { res = this.VerifyTextInPage(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyTextNotInPage")) { res = this.VerifyTextNotInPage(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyTitle")) { res = this.verifyTitle(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyUrl")) { res = this.verifyUrl(testCaseStepActionControlExecution.getControlProperty()); } else { res = new MessageEvent(MessageEventEnum.CONTROL_FAILED_UNKNOWNCONTROL); res.setDescription(res.getDescription().replaceAll("%CONTROL%", testCaseStepActionControlExecution.getControlType())); } testCaseStepActionControlExecution.setControlResultMessage(res); /** * Updating Control result message only if control is not * successful. This is to keep the last KO information and * preventing KO to be transformed to OK. */ if (!(res.equals(new MessageEvent(MessageEventEnum.CONTROL_SUCCESS)))) { testCaseStepActionControlExecution.setExecutionResultMessage(new MessageGeneral(res.getMessage())); } /** * We only stop the test if Control Event message is in stop status * AND the control is FATAL. If control is not fatal, we continue * the test but refresh the Execution status. */ if (res.isStopTest()) { if (testCaseStepActionControlExecution.getFatal().equals("Y")) { testCaseStepActionControlExecution.setStopExecution(true); } } } catch (CerberusEventException exception) { testCaseStepActionControlExecution.setControlResultMessage(exception.getMessageError()); } testCaseStepActionControlExecution.setEnd(new Date().getTime()); return testCaseStepActionControlExecution; }
public TestCaseStepActionControlExecution doControl(TestCaseStepActionControlExecution testCaseStepActionControlExecution) { /** * Decode the 2 fields property and values before doing the control. */ if (testCaseStepActionControlExecution.getControlProperty().contains("%")) { String decodedValue = propertyService.decodeValue(testCaseStepActionControlExecution.getControlProperty(), testCaseStepActionControlExecution.getTestCaseStepActionExecution().getTestCaseExecutionDataList(), testCaseStepActionControlExecution.getTestCaseStepActionExecution().getTestCaseStepExecution().gettCExecution()); testCaseStepActionControlExecution.setControlProperty(decodedValue); } if (testCaseStepActionControlExecution.getControlValue().contains("%")) { String decodedValue = propertyService.decodeValue(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getTestCaseStepActionExecution().getTestCaseExecutionDataList(), testCaseStepActionControlExecution.getTestCaseStepActionExecution().getTestCaseStepExecution().gettCExecution()); testCaseStepActionControlExecution.setControlValue(decodedValue); } /** * Timestamp starts after the decode. TODO protect when property is * null. */ testCaseStepActionControlExecution.setStart(new Date().getTime()); MessageEvent res; try { //TODO On JDK 7 implement switch with string if (testCaseStepActionControlExecution.getControlType().equals("verifyStringEqual")) { res = this.verifyStringEqual(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyStringDifferent")) { res = this.verifyStringDifferent(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyStringGreater")) { res = this.verifyStringGreater(testCaseStepActionControlExecution.getControlProperty(), testCaseStepActionControlExecution.getControlValue()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyStringMinor")) { res = this.verifyStringMinor(testCaseStepActionControlExecution.getControlProperty(), testCaseStepActionControlExecution.getControlValue()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyIntegerGreater")) { res = this.verifyIntegerGreater(testCaseStepActionControlExecution.getControlProperty(), testCaseStepActionControlExecution.getControlValue()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyIntegerMinor")) { res = this.verifyIntegerMinor(testCaseStepActionControlExecution.getControlProperty(), testCaseStepActionControlExecution.getControlValue()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyElementPresent")) { //TODO validate properties res = this.verifyElementPresent(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyElementNotPresent")) { //TODO validate properties res = this.verifyElementNotPresent(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyElementVisible")) { //TODO validate properties res = this.verifyElementVisible(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyTextInElement")) { res = this.VerifyTextInElement(testCaseStepActionControlExecution.getControlProperty(), testCaseStepActionControlExecution.getControlValue()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyRegexInElement")) { res = this.VerifyRegexInElement(testCaseStepActionControlExecution.getControlValue(), testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyTextInPage")) { res = this.VerifyTextInPage(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyTextNotInPage")) { res = this.VerifyTextNotInPage(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyTitle")) { res = this.verifyTitle(testCaseStepActionControlExecution.getControlProperty()); } else if (testCaseStepActionControlExecution.getControlType().equals("verifyUrl")) { res = this.verifyUrl(testCaseStepActionControlExecution.getControlProperty()); } else { res = new MessageEvent(MessageEventEnum.CONTROL_FAILED_UNKNOWNCONTROL); res.setDescription(res.getDescription().replaceAll("%CONTROL%", testCaseStepActionControlExecution.getControlType())); } testCaseStepActionControlExecution.setControlResultMessage(res); /** * Updating Control result message only if control is not * successful. This is to keep the last KO information and * preventing KO to be transformed to OK. */ if (!(res.equals(new MessageEvent(MessageEventEnum.CONTROL_SUCCESS)))) { testCaseStepActionControlExecution.setExecutionResultMessage(new MessageGeneral(res.getMessage())); } /** * We only stop the test if Control Event message is in stop status * AND the control is FATAL. If control is not fatal, we continue * the test but refresh the Execution status. */ if (res.isStopTest()) { if (testCaseStepActionControlExecution.getFatal().equals("Y")) { testCaseStepActionControlExecution.setStopExecution(true); } } } catch (CerberusEventException exception) { testCaseStepActionControlExecution.setControlResultMessage(exception.getMessageError()); } testCaseStepActionControlExecution.setEnd(new Date().getTime()); return testCaseStepActionControlExecution; }
diff --git a/src/com/zgy/ringforu/util/ContactsUtil.java b/src/com/zgy/ringforu/util/ContactsUtil.java index bcb974c..9cb0dbd 100644 --- a/src/com/zgy/ringforu/util/ContactsUtil.java +++ b/src/com/zgy/ringforu/util/ContactsUtil.java @@ -1,170 +1,172 @@ package com.zgy.ringforu.util; import java.util.ArrayList; import com.zgy.ringforu.R; import com.zgy.ringforu.bean.ContactInfo; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import android.provider.Contacts.People; import android.util.Log; public class ContactsUtil { // /** // * �����ϵ�������ص绰 // * // */ // public static ArrayList<ContactInfo> getContactList(Context con) { // // ArrayList<ContactInfo> list = new ArrayList<ContactInfo>(); // // String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER }; // Cursor cursor = con.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null); // if (cursor != null && cursor.getCount() > 0) { // cursor.moveToFirst(); // String newNumber = ""; // do { // newNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); // if (newNumber != null) { // newNumber = MainUtil.getRidofSpeciall(newNumber); // //���˵��ظ��ĵ绰���룬 �����Ż� , �����ٶȻ���ͦ���TODO // boolean exist = false; // for (ContactInfo a : list) { // if(a.getNum().equals(newNumber)) { // exist = true; // } // } // if(!exist) { // ContactInfo info = new ContactInfo(); // String name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)); // if (name == null) { // name = con.getString(R.string.name_null); // } // info.name = name; // info.num = newNumber; // list.add(info); // } // } // // } while (cursor.moveToNext()); // cursor.close(); // } // // return list; // } // // /** // * ���ݺ�������ϵ������ // * // * @Description: // * @param con // * @param number // * @return // * @see: // * @since: // * @author: zgy // * @date:2012-8-29 // */ // //TODO ���Ӵ�sim�����ȡ // public static String getNameFromPhone(Context con, String number) { // String name = number; // String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER }; // Cursor cursor = con.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null); // if (cursor != null && cursor.getCount() > 0) { // cursor.moveToFirst(); // String newNumber = ""; // do { // newNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); // if (newNumber.contains(number) || number.contains(newNumber)) { // name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)) + ":" + newNumber; // break; // } // } while (cursor.moveToNext()); // cursor.close(); // } // // return name; // } /** * ���ݺ�������ϵ������ * * @Description: * @param con * @param number * @return * @see: * @since: * @author: zgy * @date:2012-8-29 */ public static String getNameFromContactsByNumber(Context con, String number) { String name = null; // ���ֻ�ͨѶ¼���� String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER }; Cursor cursor = null; try { cursor = con.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); String newNumber = ""; do { newNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); - Log.v("", " newNumber =" + newNumber); + newNumber = StringUtil.getRidofSpeciall(newNumber); +// Log.v("", " newNumber =" + newNumber); if (newNumber.contains(number) || number.contains(newNumber)) { name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)); break; } } while (cursor.moveToNext()); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } // δ��ȡ�����������Դ�sim�����ȡ if (StringUtil.isNull(name)) { Cursor cur = null; try { cur = con.getContentResolver().query(Uri.parse("content://icc/adn"), null, null, null, null); if (cur != null && cur.getCount() > 0) { cur.moveToFirst(); String num = ""; do { num = cur.getString(cur.getColumnIndex(People.NUMBER)); + num = StringUtil.getRidofSpeciall(num); if (num.contains(number) || number.contains(num)) { name = cur.getString(cur.getColumnIndex(People.NAME)) + ":" + num; break; } } while (cur.moveToNext()); } } catch (Exception e) { e.printStackTrace(); } finally { if (cur != null) { cur.close(); } } } return name; } }
false
true
public static String getNameFromContactsByNumber(Context con, String number) { String name = null; // ���ֻ�ͨѶ¼���� String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER }; Cursor cursor = null; try { cursor = con.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); String newNumber = ""; do { newNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); Log.v("", " newNumber =" + newNumber); if (newNumber.contains(number) || number.contains(newNumber)) { name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)); break; } } while (cursor.moveToNext()); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } // δ��ȡ�����������Դ�sim�����ȡ if (StringUtil.isNull(name)) { Cursor cur = null; try { cur = con.getContentResolver().query(Uri.parse("content://icc/adn"), null, null, null, null); if (cur != null && cur.getCount() > 0) { cur.moveToFirst(); String num = ""; do { num = cur.getString(cur.getColumnIndex(People.NUMBER)); if (num.contains(number) || number.contains(num)) { name = cur.getString(cur.getColumnIndex(People.NAME)) + ":" + num; break; } } while (cur.moveToNext()); } } catch (Exception e) { e.printStackTrace(); } finally { if (cur != null) { cur.close(); } } } return name; }
public static String getNameFromContactsByNumber(Context con, String number) { String name = null; // ���ֻ�ͨѶ¼���� String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER }; Cursor cursor = null; try { cursor = con.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); String newNumber = ""; do { newNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); newNumber = StringUtil.getRidofSpeciall(newNumber); // Log.v("", " newNumber =" + newNumber); if (newNumber.contains(number) || number.contains(newNumber)) { name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)); break; } } while (cursor.moveToNext()); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } // δ��ȡ�����������Դ�sim�����ȡ if (StringUtil.isNull(name)) { Cursor cur = null; try { cur = con.getContentResolver().query(Uri.parse("content://icc/adn"), null, null, null, null); if (cur != null && cur.getCount() > 0) { cur.moveToFirst(); String num = ""; do { num = cur.getString(cur.getColumnIndex(People.NUMBER)); num = StringUtil.getRidofSpeciall(num); if (num.contains(number) || number.contains(num)) { name = cur.getString(cur.getColumnIndex(People.NAME)) + ":" + num; break; } } while (cur.moveToNext()); } } catch (Exception e) { e.printStackTrace(); } finally { if (cur != null) { cur.close(); } } } return name; }
diff --git a/projects/cahoots-eclipse/src/main/java/com/cahoots/eclipse/optransformation/OpMemento.java b/projects/cahoots-eclipse/src/main/java/com/cahoots/eclipse/optransformation/OpMemento.java index 55166ea..474250f 100644 --- a/projects/cahoots-eclipse/src/main/java/com/cahoots/eclipse/optransformation/OpMemento.java +++ b/projects/cahoots-eclipse/src/main/java/com/cahoots/eclipse/optransformation/OpMemento.java @@ -1,155 +1,154 @@ package com.cahoots.eclipse.optransformation; import java.util.NoSuchElementException; import java.util.TreeSet; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.viewers.ISelectionProvider; import com.cahoots.connection.serialize.receive.OpDeleteMessage; import com.cahoots.connection.serialize.receive.OpInsertMessage; import com.cahoots.connection.serialize.receive.OpReplaceMessage; import com.cahoots.util.Log; public class OpMemento { private final OpDocument document; private final TreeSet<OpTransformation> transformations; public OpMemento(final OpDocument document) { this.document = document; this.transformations = new TreeSet<OpTransformation>(); } public OpDocument getDocument() { return document; } public synchronized ITextSelection addTransformation( final OpTransformation transformation) { final ISelectionProvider selectionProvider = document.getTextEditor() .getSelectionProvider(); final ITextSelection selection = (ITextSelection)selectionProvider.getSelection(); int curPosition = selection.getOffset(); final int curLength = selection.getLength(); transformations.add(transformation); boolean found = false; for (final OpTransformation other : transformations) { if (other == transformation) { found = true; continue; } if (found) { int length = 0; if (transformation.getStart() > other.getStart()) { continue; } if (transformation instanceof OpInsertMessage) { final OpInsertMessage opInsertMessage = (OpInsertMessage) transformation; - length = opInsertMessage.getContent().length() - - opInsertMessage.getStart(); + length = opInsertMessage.getContent().length(); } else if (transformation instanceof OpReplaceMessage) { final OpReplaceMessage opReplaceMessage = (OpReplaceMessage) transformation; if (opReplaceMessage.getEnd() == Integer.MAX_VALUE) { length = opReplaceMessage.getContent().length(); } else { length = opReplaceMessage.getContent().length() - (opReplaceMessage.getEnd() - opReplaceMessage.getStart()); } } else if (transformation instanceof OpDeleteMessage) { final OpDeleteMessage opDeleteMessage = (OpDeleteMessage) transformation; length = -(opDeleteMessage.getEnd() - opDeleteMessage.getStart()); } curPosition += length; if (other instanceof OpInsertMessage) { final OpInsertMessage opInsertMessage = (OpInsertMessage) other; opInsertMessage.setStart(opInsertMessage.getStart() + length); } else if (other instanceof OpReplaceMessage) { final OpReplaceMessage opReplaceMessage = (OpReplaceMessage) other; opReplaceMessage.setStart(opReplaceMessage.getStart() + length); final int end = (opReplaceMessage.getEnd() == Integer.MAX_VALUE) ? opReplaceMessage.getContent().length() : opReplaceMessage.getEnd(); opReplaceMessage.setEnd(end + length); } else if (other instanceof OpDeleteMessage) { final OpDeleteMessage opDeleteMessage = (OpDeleteMessage) other; opDeleteMessage.setStart(opDeleteMessage.getStart() + length); opDeleteMessage.setEnd(opDeleteMessage.getEnd() + length); } } } transformation.setApplied(true); return new TextSelection(curPosition, curLength); } public TreeSet<OpTransformation> getTransformations() { return transformations; } public long getLatestTimestamp() { try { return transformations.first().getTickStamp(); } catch (final NoSuchElementException e) { return 0L; } } public synchronized String getContent() { final StringBuilder sb = new StringBuilder(); for (final OpTransformation t : transformations) { System.out.println(String.format("%s: %d", t, t.getTickStamp())); } for (final OpTransformation transformation : transformations) { if (transformation instanceof OpInsertMessage) { final OpInsertMessage msg = (OpInsertMessage) transformation; final int start = msg.getStart(); final String content = msg.getContent(); Log.global().debug("%s, %d - %d", transformation, start); sb.insert(start, content); } else if (transformation instanceof OpReplaceMessage) { final OpReplaceMessage msg = (OpReplaceMessage) transformation; final int start = Math.min(msg.getStart(), sb.length()); final int end = Math.min(msg.getEnd(), sb.length()); final String content = msg.getContent(); Log.global().debug("%s, %d - %d", transformation, start, end); sb.replace(start, end, content); } else if (transformation instanceof OpDeleteMessage) { final OpDeleteMessage msg = (OpDeleteMessage) transformation; final Integer start = msg.getStart(); final int end = Math.min(msg.getEnd(), sb.length()); Log.global().debug("%s, %d - %d", transformation, start, end); sb.delete(start, end); } } return sb.toString(); } public void fixCursor(final ITextSelection selection) { final ISelectionProvider selectionProvider = document.getTextEditor() .getSelectionProvider(); selectionProvider.setSelection(selection); } }
true
true
public synchronized ITextSelection addTransformation( final OpTransformation transformation) { final ISelectionProvider selectionProvider = document.getTextEditor() .getSelectionProvider(); final ITextSelection selection = (ITextSelection)selectionProvider.getSelection(); int curPosition = selection.getOffset(); final int curLength = selection.getLength(); transformations.add(transformation); boolean found = false; for (final OpTransformation other : transformations) { if (other == transformation) { found = true; continue; } if (found) { int length = 0; if (transformation.getStart() > other.getStart()) { continue; } if (transformation instanceof OpInsertMessage) { final OpInsertMessage opInsertMessage = (OpInsertMessage) transformation; length = opInsertMessage.getContent().length() - opInsertMessage.getStart(); } else if (transformation instanceof OpReplaceMessage) { final OpReplaceMessage opReplaceMessage = (OpReplaceMessage) transformation; if (opReplaceMessage.getEnd() == Integer.MAX_VALUE) { length = opReplaceMessage.getContent().length(); } else { length = opReplaceMessage.getContent().length() - (opReplaceMessage.getEnd() - opReplaceMessage.getStart()); } } else if (transformation instanceof OpDeleteMessage) { final OpDeleteMessage opDeleteMessage = (OpDeleteMessage) transformation; length = -(opDeleteMessage.getEnd() - opDeleteMessage.getStart()); } curPosition += length; if (other instanceof OpInsertMessage) { final OpInsertMessage opInsertMessage = (OpInsertMessage) other; opInsertMessage.setStart(opInsertMessage.getStart() + length); } else if (other instanceof OpReplaceMessage) { final OpReplaceMessage opReplaceMessage = (OpReplaceMessage) other; opReplaceMessage.setStart(opReplaceMessage.getStart() + length); final int end = (opReplaceMessage.getEnd() == Integer.MAX_VALUE) ? opReplaceMessage.getContent().length() : opReplaceMessage.getEnd(); opReplaceMessage.setEnd(end + length); } else if (other instanceof OpDeleteMessage) { final OpDeleteMessage opDeleteMessage = (OpDeleteMessage) other; opDeleteMessage.setStart(opDeleteMessage.getStart() + length); opDeleteMessage.setEnd(opDeleteMessage.getEnd() + length); } } } transformation.setApplied(true); return new TextSelection(curPosition, curLength); }
public synchronized ITextSelection addTransformation( final OpTransformation transformation) { final ISelectionProvider selectionProvider = document.getTextEditor() .getSelectionProvider(); final ITextSelection selection = (ITextSelection)selectionProvider.getSelection(); int curPosition = selection.getOffset(); final int curLength = selection.getLength(); transformations.add(transformation); boolean found = false; for (final OpTransformation other : transformations) { if (other == transformation) { found = true; continue; } if (found) { int length = 0; if (transformation.getStart() > other.getStart()) { continue; } if (transformation instanceof OpInsertMessage) { final OpInsertMessage opInsertMessage = (OpInsertMessage) transformation; length = opInsertMessage.getContent().length(); } else if (transformation instanceof OpReplaceMessage) { final OpReplaceMessage opReplaceMessage = (OpReplaceMessage) transformation; if (opReplaceMessage.getEnd() == Integer.MAX_VALUE) { length = opReplaceMessage.getContent().length(); } else { length = opReplaceMessage.getContent().length() - (opReplaceMessage.getEnd() - opReplaceMessage.getStart()); } } else if (transformation instanceof OpDeleteMessage) { final OpDeleteMessage opDeleteMessage = (OpDeleteMessage) transformation; length = -(opDeleteMessage.getEnd() - opDeleteMessage.getStart()); } curPosition += length; if (other instanceof OpInsertMessage) { final OpInsertMessage opInsertMessage = (OpInsertMessage) other; opInsertMessage.setStart(opInsertMessage.getStart() + length); } else if (other instanceof OpReplaceMessage) { final OpReplaceMessage opReplaceMessage = (OpReplaceMessage) other; opReplaceMessage.setStart(opReplaceMessage.getStart() + length); final int end = (opReplaceMessage.getEnd() == Integer.MAX_VALUE) ? opReplaceMessage.getContent().length() : opReplaceMessage.getEnd(); opReplaceMessage.setEnd(end + length); } else if (other instanceof OpDeleteMessage) { final OpDeleteMessage opDeleteMessage = (OpDeleteMessage) other; opDeleteMessage.setStart(opDeleteMessage.getStart() + length); opDeleteMessage.setEnd(opDeleteMessage.getEnd() + length); } } } transformation.setApplied(true); return new TextSelection(curPosition, curLength); }
diff --git a/source/tests-src/net/grinder/engine/agent/TestFileStore.java b/source/tests-src/net/grinder/engine/agent/TestFileStore.java index fa587f73..9e8347ac 100755 --- a/source/tests-src/net/grinder/engine/agent/TestFileStore.java +++ b/source/tests-src/net/grinder/engine/agent/TestFileStore.java @@ -1,256 +1,259 @@ // Copyright (C) 2004, 2005, 2006 Philip Aston // All rights reserved. // // This file is part of The Grinder software distribution. Refer to // the file LICENSE which is part of The Grinder distribution for // licensing details. The Grinder distribution is available on the // Internet at http://grinder.sourceforge.net/ // // 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 // REGENTS 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 net.grinder.engine.agent; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.Random; import net.grinder.common.Logger; import net.grinder.common.LoggerStubFactory; import net.grinder.communication.CommunicationException; import net.grinder.communication.Message; import net.grinder.communication.MessageDispatchSender; import net.grinder.communication.SimpleMessage; import net.grinder.engine.messages.ClearCacheMessage; import net.grinder.engine.messages.DistributeFileMessage; import net.grinder.testutility.AbstractFileTestCase; import net.grinder.testutility.FileUtilities; import net.grinder.util.Directory; import net.grinder.util.FileContents; /** * Unit tests for <code>FileStore</code>. * * @author Philip Aston * @version $Revision$ */ public class TestFileStore extends AbstractFileTestCase { public void testConstruction() throws Exception { File.createTempFile("file", "", getDirectory()); assertEquals(1, getDirectory().list().length); final FileStore fileStore = new FileStore(getDirectory(), null); final File currentDirectory = fileStore.getDirectory().getFile(); assertNotNull(currentDirectory); assertTrue( currentDirectory.getPath().startsWith(getDirectory().getPath())); // No messages have been received, so no physical directories will // have been created yet. assertEquals(1, getDirectory().list().length); assertTrue(!currentDirectory.exists()); // Can't use a plain file. final File file1 = File.createTempFile("file", "", getDirectory()); try { new FileStore(file1, null); fail("Expected FileStoreException"); } catch (FileStore.FileStoreException e) { } // Nor a directory that contains a plain file clashing with one // of the subdirectory names. file1.delete(); file1.mkdir(); new File(file1, "current").createNewFile(); try { new FileStore(file1, null); fail("Expected FileStoreException"); } catch (FileStore.FileStoreException e) { } // Can't use a read-only directory. final File readOnlyDirectory = new File(getDirectory(), "directory"); readOnlyDirectory.mkdir(); readOnlyDirectory.setReadOnly(); try { new FileStore(readOnlyDirectory, null); fail("Expected FileStoreException"); } catch (FileStore.FileStoreException e) { } // Perfectly fine to create a FileStore around a directory that // doens't yet exist. final File notThere = new File(getDirectory(), "notThere"); new FileStore(notThere, null); } public void testSender() throws Exception { final LoggerStubFactory loggerStubFactory = new LoggerStubFactory(); final Logger logger = loggerStubFactory.getLogger(); final FileStore fileStore = new FileStore(getDirectory(), logger); final MessageDispatchSender messageDispatcher = new MessageDispatchSender(); fileStore.registerMessageHandlers(messageDispatcher); // Other Messages get ignored. final Message message0 = new SimpleMessage(); messageDispatcher.send(message0); loggerStubFactory.assertNoMoreCalls(); // Shutdown does nothing. messageDispatcher.shutdown(); loggerStubFactory.assertNoMoreCalls(); // Test with a good message. final File sourceDirectory = new File(getDirectory(), "source"); sourceDirectory.mkdirs(); final File file0 = new File(sourceDirectory, "dir/file0"); file0.getParentFile().mkdirs(); final OutputStream outputStream = new FileOutputStream(file0); final byte[] bytes = new byte[500]; new Random().nextBytes(bytes); outputStream.write(bytes); outputStream.close(); final FileContents fileContents0 = new FileContents(sourceDirectory, new File("dir/file0")); final File readmeFile = new File(getDirectory(), "README.txt"); final File incomingDirectoryFile = new File(getDirectory(), "incoming"); final File currentDirectoryFile = new File(getDirectory(), "current"); assertEquals(currentDirectoryFile, fileStore.getDirectory().getFile()); // Before message sent, none of our files or directories exist. assertTrue(!readmeFile.exists()); assertTrue(!incomingDirectoryFile.exists()); assertTrue(!currentDirectoryFile.exists()); final Message message1 = new DistributeFileMessage(fileContents0); // Can't receive a DFM if the incoming directory can't be created. FileUtilities.setCanAccess(getDirectory(), false); try { messageDispatcher.send(message1); fail("Expected CommunicationException"); } catch (CommunicationException e) { } FileUtilities.setCanAccess(getDirectory(), true); //loggerStubFactory.assertSuccess("output", new Class[] { String.class }); loggerStubFactory.assertSuccess("error", new Class[] { String.class }); loggerStubFactory.assertNoMoreCalls(); incomingDirectoryFile.delete(); messageDispatcher.send(message1); loggerStubFactory.assertSuccess("output", new Class[] { String.class }); loggerStubFactory.assertNoMoreCalls(); // Message has been sent, the incoming directory and the read me exist. assertTrue(readmeFile.exists()); assertTrue(incomingDirectoryFile.exists()); assertTrue(!currentDirectoryFile.exists()); final File targetFile = new File(incomingDirectoryFile, "dir/file0"); assertTrue(targetFile.canRead()); assertEquals(currentDirectoryFile, fileStore.getDirectory().getFile()); // Now getDirectory() has been called, both directories exist. assertTrue(readmeFile.exists()); assertTrue(incomingDirectoryFile.exists()); assertTrue(currentDirectoryFile.exists()); // Frig with currentDirectory so that getDirectory() fails. new Directory(currentDirectoryFile).deleteContents(); currentDirectoryFile.delete(); currentDirectoryFile.createNewFile(); try { fileStore.getDirectory(); fail("Expected FileStoreException"); } catch (FileStore.FileStoreException e) { } // Put things back again. currentDirectoryFile.delete(); fileStore.getDirectory(); // Test with a bad message. targetFile.setReadOnly(); try { messageDispatcher.send(message1); fail("Expected CommunicationException"); } catch (CommunicationException e) { } loggerStubFactory.assertSuccess("output", new Class[] { String.class }); loggerStubFactory.assertSuccess("error", new Class[] { String.class }); loggerStubFactory.assertNoMoreCalls(); final Message message2 = new ClearCacheMessage(); FileUtilities.setCanAccess(targetFile, false); + // UNIX: Permission to remove a file is set on directory. + FileUtilities.setCanAccess(targetFile.getParentFile(), false); try { messageDispatcher.send(message2); fail("Expected CommunicationException"); } catch (CommunicationException e) { } + FileUtilities.setCanAccess(targetFile.getParentFile(), true); FileUtilities.setCanAccess(targetFile, true); loggerStubFactory.assertSuccess("output", new Class[] { String.class }); loggerStubFactory.assertSuccess("error", new Class[] { String.class }); loggerStubFactory.assertNoMoreCalls(); messageDispatcher.send(message2); loggerStubFactory.assertSuccess("output", new Class[] { String.class }); loggerStubFactory.assertNoMoreCalls(); assertTrue(!targetFile.canRead()); assertEquals(currentDirectoryFile, fileStore.getDirectory().getFile()); } public void testFileStoreException() throws Exception { final Exception nested = new Exception(""); final FileStore.FileStoreException e = new FileStore.FileStoreException("bite me", nested); assertEquals(nested, e.getCause()); } }
false
true
public void testSender() throws Exception { final LoggerStubFactory loggerStubFactory = new LoggerStubFactory(); final Logger logger = loggerStubFactory.getLogger(); final FileStore fileStore = new FileStore(getDirectory(), logger); final MessageDispatchSender messageDispatcher = new MessageDispatchSender(); fileStore.registerMessageHandlers(messageDispatcher); // Other Messages get ignored. final Message message0 = new SimpleMessage(); messageDispatcher.send(message0); loggerStubFactory.assertNoMoreCalls(); // Shutdown does nothing. messageDispatcher.shutdown(); loggerStubFactory.assertNoMoreCalls(); // Test with a good message. final File sourceDirectory = new File(getDirectory(), "source"); sourceDirectory.mkdirs(); final File file0 = new File(sourceDirectory, "dir/file0"); file0.getParentFile().mkdirs(); final OutputStream outputStream = new FileOutputStream(file0); final byte[] bytes = new byte[500]; new Random().nextBytes(bytes); outputStream.write(bytes); outputStream.close(); final FileContents fileContents0 = new FileContents(sourceDirectory, new File("dir/file0")); final File readmeFile = new File(getDirectory(), "README.txt"); final File incomingDirectoryFile = new File(getDirectory(), "incoming"); final File currentDirectoryFile = new File(getDirectory(), "current"); assertEquals(currentDirectoryFile, fileStore.getDirectory().getFile()); // Before message sent, none of our files or directories exist. assertTrue(!readmeFile.exists()); assertTrue(!incomingDirectoryFile.exists()); assertTrue(!currentDirectoryFile.exists()); final Message message1 = new DistributeFileMessage(fileContents0); // Can't receive a DFM if the incoming directory can't be created. FileUtilities.setCanAccess(getDirectory(), false); try { messageDispatcher.send(message1); fail("Expected CommunicationException"); } catch (CommunicationException e) { } FileUtilities.setCanAccess(getDirectory(), true); //loggerStubFactory.assertSuccess("output", new Class[] { String.class }); loggerStubFactory.assertSuccess("error", new Class[] { String.class }); loggerStubFactory.assertNoMoreCalls(); incomingDirectoryFile.delete(); messageDispatcher.send(message1); loggerStubFactory.assertSuccess("output", new Class[] { String.class }); loggerStubFactory.assertNoMoreCalls(); // Message has been sent, the incoming directory and the read me exist. assertTrue(readmeFile.exists()); assertTrue(incomingDirectoryFile.exists()); assertTrue(!currentDirectoryFile.exists()); final File targetFile = new File(incomingDirectoryFile, "dir/file0"); assertTrue(targetFile.canRead()); assertEquals(currentDirectoryFile, fileStore.getDirectory().getFile()); // Now getDirectory() has been called, both directories exist. assertTrue(readmeFile.exists()); assertTrue(incomingDirectoryFile.exists()); assertTrue(currentDirectoryFile.exists()); // Frig with currentDirectory so that getDirectory() fails. new Directory(currentDirectoryFile).deleteContents(); currentDirectoryFile.delete(); currentDirectoryFile.createNewFile(); try { fileStore.getDirectory(); fail("Expected FileStoreException"); } catch (FileStore.FileStoreException e) { } // Put things back again. currentDirectoryFile.delete(); fileStore.getDirectory(); // Test with a bad message. targetFile.setReadOnly(); try { messageDispatcher.send(message1); fail("Expected CommunicationException"); } catch (CommunicationException e) { } loggerStubFactory.assertSuccess("output", new Class[] { String.class }); loggerStubFactory.assertSuccess("error", new Class[] { String.class }); loggerStubFactory.assertNoMoreCalls(); final Message message2 = new ClearCacheMessage(); FileUtilities.setCanAccess(targetFile, false); try { messageDispatcher.send(message2); fail("Expected CommunicationException"); } catch (CommunicationException e) { } FileUtilities.setCanAccess(targetFile, true); loggerStubFactory.assertSuccess("output", new Class[] { String.class }); loggerStubFactory.assertSuccess("error", new Class[] { String.class }); loggerStubFactory.assertNoMoreCalls(); messageDispatcher.send(message2); loggerStubFactory.assertSuccess("output", new Class[] { String.class }); loggerStubFactory.assertNoMoreCalls(); assertTrue(!targetFile.canRead()); assertEquals(currentDirectoryFile, fileStore.getDirectory().getFile()); }
public void testSender() throws Exception { final LoggerStubFactory loggerStubFactory = new LoggerStubFactory(); final Logger logger = loggerStubFactory.getLogger(); final FileStore fileStore = new FileStore(getDirectory(), logger); final MessageDispatchSender messageDispatcher = new MessageDispatchSender(); fileStore.registerMessageHandlers(messageDispatcher); // Other Messages get ignored. final Message message0 = new SimpleMessage(); messageDispatcher.send(message0); loggerStubFactory.assertNoMoreCalls(); // Shutdown does nothing. messageDispatcher.shutdown(); loggerStubFactory.assertNoMoreCalls(); // Test with a good message. final File sourceDirectory = new File(getDirectory(), "source"); sourceDirectory.mkdirs(); final File file0 = new File(sourceDirectory, "dir/file0"); file0.getParentFile().mkdirs(); final OutputStream outputStream = new FileOutputStream(file0); final byte[] bytes = new byte[500]; new Random().nextBytes(bytes); outputStream.write(bytes); outputStream.close(); final FileContents fileContents0 = new FileContents(sourceDirectory, new File("dir/file0")); final File readmeFile = new File(getDirectory(), "README.txt"); final File incomingDirectoryFile = new File(getDirectory(), "incoming"); final File currentDirectoryFile = new File(getDirectory(), "current"); assertEquals(currentDirectoryFile, fileStore.getDirectory().getFile()); // Before message sent, none of our files or directories exist. assertTrue(!readmeFile.exists()); assertTrue(!incomingDirectoryFile.exists()); assertTrue(!currentDirectoryFile.exists()); final Message message1 = new DistributeFileMessage(fileContents0); // Can't receive a DFM if the incoming directory can't be created. FileUtilities.setCanAccess(getDirectory(), false); try { messageDispatcher.send(message1); fail("Expected CommunicationException"); } catch (CommunicationException e) { } FileUtilities.setCanAccess(getDirectory(), true); //loggerStubFactory.assertSuccess("output", new Class[] { String.class }); loggerStubFactory.assertSuccess("error", new Class[] { String.class }); loggerStubFactory.assertNoMoreCalls(); incomingDirectoryFile.delete(); messageDispatcher.send(message1); loggerStubFactory.assertSuccess("output", new Class[] { String.class }); loggerStubFactory.assertNoMoreCalls(); // Message has been sent, the incoming directory and the read me exist. assertTrue(readmeFile.exists()); assertTrue(incomingDirectoryFile.exists()); assertTrue(!currentDirectoryFile.exists()); final File targetFile = new File(incomingDirectoryFile, "dir/file0"); assertTrue(targetFile.canRead()); assertEquals(currentDirectoryFile, fileStore.getDirectory().getFile()); // Now getDirectory() has been called, both directories exist. assertTrue(readmeFile.exists()); assertTrue(incomingDirectoryFile.exists()); assertTrue(currentDirectoryFile.exists()); // Frig with currentDirectory so that getDirectory() fails. new Directory(currentDirectoryFile).deleteContents(); currentDirectoryFile.delete(); currentDirectoryFile.createNewFile(); try { fileStore.getDirectory(); fail("Expected FileStoreException"); } catch (FileStore.FileStoreException e) { } // Put things back again. currentDirectoryFile.delete(); fileStore.getDirectory(); // Test with a bad message. targetFile.setReadOnly(); try { messageDispatcher.send(message1); fail("Expected CommunicationException"); } catch (CommunicationException e) { } loggerStubFactory.assertSuccess("output", new Class[] { String.class }); loggerStubFactory.assertSuccess("error", new Class[] { String.class }); loggerStubFactory.assertNoMoreCalls(); final Message message2 = new ClearCacheMessage(); FileUtilities.setCanAccess(targetFile, false); // UNIX: Permission to remove a file is set on directory. FileUtilities.setCanAccess(targetFile.getParentFile(), false); try { messageDispatcher.send(message2); fail("Expected CommunicationException"); } catch (CommunicationException e) { } FileUtilities.setCanAccess(targetFile.getParentFile(), true); FileUtilities.setCanAccess(targetFile, true); loggerStubFactory.assertSuccess("output", new Class[] { String.class }); loggerStubFactory.assertSuccess("error", new Class[] { String.class }); loggerStubFactory.assertNoMoreCalls(); messageDispatcher.send(message2); loggerStubFactory.assertSuccess("output", new Class[] { String.class }); loggerStubFactory.assertNoMoreCalls(); assertTrue(!targetFile.canRead()); assertEquals(currentDirectoryFile, fileStore.getDirectory().getFile()); }
diff --git a/java/tools/src/com/jopdesign/build/BuildVT.java b/java/tools/src/com/jopdesign/build/BuildVT.java index bf5b9875..302d1456 100644 --- a/java/tools/src/com/jopdesign/build/BuildVT.java +++ b/java/tools/src/com/jopdesign/build/BuildVT.java @@ -1,256 +1,256 @@ /* * Created on 04.06.2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.jopdesign.build; import java.util.*; import org.apache.bcel.classfile.*; import org.apache.bcel.generic.*; /** * * Build virtual method tables and the one and only interface table. * * @author martin * */ public class BuildVT extends MyVisitor { Map mapClVT = new HashMap(); Map mapClFT = new HashMap(); public BuildVT(JOPizer jz) { super(jz); } public void visitJavaClass(JavaClass clazz) { super.visitJavaClass(clazz); // don't get confused in the build process cli = null; // TODO: if (!array class) ... buildVT(clazz); if (clazz.isInterface()) { buildIT(clazz); } } /** * Called recursive to build the VTs top down. * * @param clazz */ private void buildVT(JavaClass clazz) { int i, j; // System.err.println("invoke buildVT on class: "+clazz); ClassInfo cli; cli = (ClassInfo) ClassInfo.mapClassNames.get(clazz.getClassName()); // System.err.println("build VT on class: "+cli.clazz); /* * TODO: we have TWO mappings of clazzes: in JOPWriter AND in ClassInfo * However, they are not consistent! * The following results in a null pointer for java.lang.Object: cli = jz.getClassInfo(clazz); System.err.println("build VT on class: "+cli.clazz); */ ClassInfo.ClVT supVt = null; ClassInfo.ClFT supFt = null; if (clazz.getClassName().equals(clazz.getSuperclassName())) { ; // now we'r Object } else { ClassInfo clisup = ClassInfo.getClassInfo(clazz.getSuperclassName()); // JavaClass superClazz = clazz.getSuperClass(); // System.err.println("super: "+superClazz); JavaClass superClazz = clisup.clazz; String superName = superClazz.getClassName(); // System.err.println("super name: "+superName); if (mapClVT.get(superName)==null) { // System.err.println("rec. invoke buildVT with: "+superClazz); buildVT(superClazz); // first build super VT } supVt = (ClassInfo.ClVT) mapClVT.get(superName); supFt = (ClassInfo.ClFT) mapClFT.get(superName); } // System.err.println("build VT on: "+clazz.getClassName()); String clazzName = clazz.getClassName(); if (mapClVT.get(clazzName)!=null) { return; // allready done! } // this also tries to load from application CLASSPATH // int intfCount = clazz.getInterfaces().length; // System.err.println(cli); ClassInfo.ClVT clvt = cli.getClVT(); ClassInfo.ClFT clft = cli.getClFT(); mapClVT.put(clazzName, clvt); mapClFT.put(clazzName, clft); Method m[] = clazz.getMethods(); int methodCount = m.length; int maxLen = methodCount; if (supVt!=null) maxLen += supVt.len; clvt.len = 0; clvt.key = new String[maxLen]; // clvt.ptr = new int[maxLen]; clvt.mi = new MethodInfo[maxLen]; Field f[] = clazz.getFields(); maxLen = f.length; // if (supFt!=null) maxLen += supFt.len; clft.len = 0; clft.key = new String[maxLen]; clft.idx = new int[maxLen]; clft.size = new int[maxLen]; clft.isStatic = new boolean[maxLen]; clft.isReference = new boolean[maxLen]; // System.out.println("// VT: "+clazzName); if (supVt!=null) { for (i=0; i<supVt.len; ++i) { clvt.key[i] = supVt.key[i]; // System.out.println("//super: "+clvt.key[i]); clvt.mi[i] = supVt.mi[i]; } clvt.len = supVt.len; } /* if (supFt!=null) { for (i=0; i<supFt.len; ++i) { // copy only the non static fields if (!supFt.isStatic[i]) { clft.key[clft.len] = supFt.key[i]; clft.idx[clft.len] = supFt.idx[i]; clft.size[clft.len] = supFt.size[i]; clft.isStatic[clft.len] = supFt.isStatic[i]; clft.isReference[clft.len] = supFt.isReference[i]; ++clft.len; } } } */ for (i = 0; i < methodCount; i++) { Method meth = m[i]; String methodId = meth.getName()+meth.getSignature(); MethodInfo mi = cli.getMethodInfo(methodId); for (j=0; j<clvt.len; ++j) { if (clvt.key[j].equals(methodId)) { // override method //System.out.println("override "+methodId); clvt.mi[j] = mi; break; } } if (j==clvt.len) { // new method clvt.key[clvt.len] = methodId; //System.out.println("new "+methodId); clvt.mi[clvt.len] = mi; ++clvt.len; } } //System.out.println("The VT of "+clazzName); //for (i=0; i<clvt.len; i++) { // System.out.println("//\t"+clvt.meth[i].cli.clazz.getClassName()+"."+clvt.key[i]); //} // this is strange!!! // BTW we copied only the non static fields.... int nextFieldIndex = 0; int nextStaticIndex = 0; /* for (j=0; j<clft.len; ++j) { int size = clft.size[j]; if (clft.isStatic[j]) { nextStaticIndex += size; } else { nextFieldIndex += size; } } */ if (supFt!=null) { for (i=0; i<supFt.len; ++i) { if (supFt.isStatic[i]) { - if (supFt.idx[i]>nextStaticIndex) { + if (supFt.idx[i]>=nextStaticIndex) { nextStaticIndex = supFt.idx[i]+1; } } else { - if (supFt.idx[i]>nextFieldIndex) { + if (supFt.idx[i]>=nextFieldIndex) { nextFieldIndex = supFt.idx[i]+1; } } } } for (i=0; i<f.length; ++i) { Field field = f[i]; int size = field.getType().getSize(); String fieldId = field.getName()+field.getSignature(); clft.key[clft.len] = fieldId; clft.size[clft.len] = size; clft.isReference[clft.len] = field.getType() instanceof ReferenceType; if (field.isStatic()) { clft.idx[clft.len] = nextStaticIndex; clft.isStatic[clft.len] = true; nextStaticIndex += size; } else { clft.idx[clft.len] = nextFieldIndex; clft.isStatic[clft.len] = false; nextFieldIndex += size; } clft.len++; } cli.setInstanceSize(nextFieldIndex); } private void buildIT(JavaClass clazz) { int i, j; ClassInfo cli = ClassInfo.getClassInfo(clazz.getClassName()); String clazzName = clazz.getClassName(); Method m[] = clazz.getMethods(); int methodCount = m.length; // // build global interface table // for (i = 0; i < methodCount; i++) { Method meth = m[i]; String methodId = meth.getName()+meth.getSignature(); MethodInfo mi = cli.getMethodInfo(methodId); ClassInfo.IT it = ClassInfo.getITObject(); it.nr = ClassInfo.listIT.size(); it.key = methodId; // System.out.println("Add to IT: "+it.nr+" "+it.key); it.meth = mi; ClassInfo.listIT.add(it); } } }
false
true
private void buildVT(JavaClass clazz) { int i, j; // System.err.println("invoke buildVT on class: "+clazz); ClassInfo cli; cli = (ClassInfo) ClassInfo.mapClassNames.get(clazz.getClassName()); // System.err.println("build VT on class: "+cli.clazz); /* * TODO: we have TWO mappings of clazzes: in JOPWriter AND in ClassInfo * However, they are not consistent! * The following results in a null pointer for java.lang.Object: cli = jz.getClassInfo(clazz); System.err.println("build VT on class: "+cli.clazz); */ ClassInfo.ClVT supVt = null; ClassInfo.ClFT supFt = null; if (clazz.getClassName().equals(clazz.getSuperclassName())) { ; // now we'r Object } else { ClassInfo clisup = ClassInfo.getClassInfo(clazz.getSuperclassName()); // JavaClass superClazz = clazz.getSuperClass(); // System.err.println("super: "+superClazz); JavaClass superClazz = clisup.clazz; String superName = superClazz.getClassName(); // System.err.println("super name: "+superName); if (mapClVT.get(superName)==null) { // System.err.println("rec. invoke buildVT with: "+superClazz); buildVT(superClazz); // first build super VT } supVt = (ClassInfo.ClVT) mapClVT.get(superName); supFt = (ClassInfo.ClFT) mapClFT.get(superName); } // System.err.println("build VT on: "+clazz.getClassName()); String clazzName = clazz.getClassName(); if (mapClVT.get(clazzName)!=null) { return; // allready done! } // this also tries to load from application CLASSPATH // int intfCount = clazz.getInterfaces().length; // System.err.println(cli); ClassInfo.ClVT clvt = cli.getClVT(); ClassInfo.ClFT clft = cli.getClFT(); mapClVT.put(clazzName, clvt); mapClFT.put(clazzName, clft); Method m[] = clazz.getMethods(); int methodCount = m.length; int maxLen = methodCount; if (supVt!=null) maxLen += supVt.len; clvt.len = 0; clvt.key = new String[maxLen]; // clvt.ptr = new int[maxLen]; clvt.mi = new MethodInfo[maxLen]; Field f[] = clazz.getFields(); maxLen = f.length; // if (supFt!=null) maxLen += supFt.len; clft.len = 0; clft.key = new String[maxLen]; clft.idx = new int[maxLen]; clft.size = new int[maxLen]; clft.isStatic = new boolean[maxLen]; clft.isReference = new boolean[maxLen]; // System.out.println("// VT: "+clazzName); if (supVt!=null) { for (i=0; i<supVt.len; ++i) { clvt.key[i] = supVt.key[i]; // System.out.println("//super: "+clvt.key[i]); clvt.mi[i] = supVt.mi[i]; } clvt.len = supVt.len; } /* if (supFt!=null) { for (i=0; i<supFt.len; ++i) { // copy only the non static fields if (!supFt.isStatic[i]) { clft.key[clft.len] = supFt.key[i]; clft.idx[clft.len] = supFt.idx[i]; clft.size[clft.len] = supFt.size[i]; clft.isStatic[clft.len] = supFt.isStatic[i]; clft.isReference[clft.len] = supFt.isReference[i]; ++clft.len; } } } */ for (i = 0; i < methodCount; i++) { Method meth = m[i]; String methodId = meth.getName()+meth.getSignature(); MethodInfo mi = cli.getMethodInfo(methodId); for (j=0; j<clvt.len; ++j) { if (clvt.key[j].equals(methodId)) { // override method //System.out.println("override "+methodId); clvt.mi[j] = mi; break; } } if (j==clvt.len) { // new method clvt.key[clvt.len] = methodId; //System.out.println("new "+methodId); clvt.mi[clvt.len] = mi; ++clvt.len; } } //System.out.println("The VT of "+clazzName); //for (i=0; i<clvt.len; i++) { // System.out.println("//\t"+clvt.meth[i].cli.clazz.getClassName()+"."+clvt.key[i]); //} // this is strange!!! // BTW we copied only the non static fields.... int nextFieldIndex = 0; int nextStaticIndex = 0; /* for (j=0; j<clft.len; ++j) { int size = clft.size[j]; if (clft.isStatic[j]) { nextStaticIndex += size; } else { nextFieldIndex += size; } } */ if (supFt!=null) { for (i=0; i<supFt.len; ++i) { if (supFt.isStatic[i]) { if (supFt.idx[i]>nextStaticIndex) { nextStaticIndex = supFt.idx[i]+1; } } else { if (supFt.idx[i]>nextFieldIndex) { nextFieldIndex = supFt.idx[i]+1; } } } } for (i=0; i<f.length; ++i) { Field field = f[i]; int size = field.getType().getSize(); String fieldId = field.getName()+field.getSignature(); clft.key[clft.len] = fieldId; clft.size[clft.len] = size; clft.isReference[clft.len] = field.getType() instanceof ReferenceType; if (field.isStatic()) { clft.idx[clft.len] = nextStaticIndex; clft.isStatic[clft.len] = true; nextStaticIndex += size; } else { clft.idx[clft.len] = nextFieldIndex; clft.isStatic[clft.len] = false; nextFieldIndex += size; } clft.len++; } cli.setInstanceSize(nextFieldIndex); }
private void buildVT(JavaClass clazz) { int i, j; // System.err.println("invoke buildVT on class: "+clazz); ClassInfo cli; cli = (ClassInfo) ClassInfo.mapClassNames.get(clazz.getClassName()); // System.err.println("build VT on class: "+cli.clazz); /* * TODO: we have TWO mappings of clazzes: in JOPWriter AND in ClassInfo * However, they are not consistent! * The following results in a null pointer for java.lang.Object: cli = jz.getClassInfo(clazz); System.err.println("build VT on class: "+cli.clazz); */ ClassInfo.ClVT supVt = null; ClassInfo.ClFT supFt = null; if (clazz.getClassName().equals(clazz.getSuperclassName())) { ; // now we'r Object } else { ClassInfo clisup = ClassInfo.getClassInfo(clazz.getSuperclassName()); // JavaClass superClazz = clazz.getSuperClass(); // System.err.println("super: "+superClazz); JavaClass superClazz = clisup.clazz; String superName = superClazz.getClassName(); // System.err.println("super name: "+superName); if (mapClVT.get(superName)==null) { // System.err.println("rec. invoke buildVT with: "+superClazz); buildVT(superClazz); // first build super VT } supVt = (ClassInfo.ClVT) mapClVT.get(superName); supFt = (ClassInfo.ClFT) mapClFT.get(superName); } // System.err.println("build VT on: "+clazz.getClassName()); String clazzName = clazz.getClassName(); if (mapClVT.get(clazzName)!=null) { return; // allready done! } // this also tries to load from application CLASSPATH // int intfCount = clazz.getInterfaces().length; // System.err.println(cli); ClassInfo.ClVT clvt = cli.getClVT(); ClassInfo.ClFT clft = cli.getClFT(); mapClVT.put(clazzName, clvt); mapClFT.put(clazzName, clft); Method m[] = clazz.getMethods(); int methodCount = m.length; int maxLen = methodCount; if (supVt!=null) maxLen += supVt.len; clvt.len = 0; clvt.key = new String[maxLen]; // clvt.ptr = new int[maxLen]; clvt.mi = new MethodInfo[maxLen]; Field f[] = clazz.getFields(); maxLen = f.length; // if (supFt!=null) maxLen += supFt.len; clft.len = 0; clft.key = new String[maxLen]; clft.idx = new int[maxLen]; clft.size = new int[maxLen]; clft.isStatic = new boolean[maxLen]; clft.isReference = new boolean[maxLen]; // System.out.println("// VT: "+clazzName); if (supVt!=null) { for (i=0; i<supVt.len; ++i) { clvt.key[i] = supVt.key[i]; // System.out.println("//super: "+clvt.key[i]); clvt.mi[i] = supVt.mi[i]; } clvt.len = supVt.len; } /* if (supFt!=null) { for (i=0; i<supFt.len; ++i) { // copy only the non static fields if (!supFt.isStatic[i]) { clft.key[clft.len] = supFt.key[i]; clft.idx[clft.len] = supFt.idx[i]; clft.size[clft.len] = supFt.size[i]; clft.isStatic[clft.len] = supFt.isStatic[i]; clft.isReference[clft.len] = supFt.isReference[i]; ++clft.len; } } } */ for (i = 0; i < methodCount; i++) { Method meth = m[i]; String methodId = meth.getName()+meth.getSignature(); MethodInfo mi = cli.getMethodInfo(methodId); for (j=0; j<clvt.len; ++j) { if (clvt.key[j].equals(methodId)) { // override method //System.out.println("override "+methodId); clvt.mi[j] = mi; break; } } if (j==clvt.len) { // new method clvt.key[clvt.len] = methodId; //System.out.println("new "+methodId); clvt.mi[clvt.len] = mi; ++clvt.len; } } //System.out.println("The VT of "+clazzName); //for (i=0; i<clvt.len; i++) { // System.out.println("//\t"+clvt.meth[i].cli.clazz.getClassName()+"."+clvt.key[i]); //} // this is strange!!! // BTW we copied only the non static fields.... int nextFieldIndex = 0; int nextStaticIndex = 0; /* for (j=0; j<clft.len; ++j) { int size = clft.size[j]; if (clft.isStatic[j]) { nextStaticIndex += size; } else { nextFieldIndex += size; } } */ if (supFt!=null) { for (i=0; i<supFt.len; ++i) { if (supFt.isStatic[i]) { if (supFt.idx[i]>=nextStaticIndex) { nextStaticIndex = supFt.idx[i]+1; } } else { if (supFt.idx[i]>=nextFieldIndex) { nextFieldIndex = supFt.idx[i]+1; } } } } for (i=0; i<f.length; ++i) { Field field = f[i]; int size = field.getType().getSize(); String fieldId = field.getName()+field.getSignature(); clft.key[clft.len] = fieldId; clft.size[clft.len] = size; clft.isReference[clft.len] = field.getType() instanceof ReferenceType; if (field.isStatic()) { clft.idx[clft.len] = nextStaticIndex; clft.isStatic[clft.len] = true; nextStaticIndex += size; } else { clft.idx[clft.len] = nextFieldIndex; clft.isStatic[clft.len] = false; nextFieldIndex += size; } clft.len++; } cli.setInstanceSize(nextFieldIndex); }
diff --git a/EnappShop-war/src/java/ch/hslu/enappwebshop/web/ProductBean.java b/EnappShop-war/src/java/ch/hslu/enappwebshop/web/ProductBean.java index fae7440..b4e6684 100644 --- a/EnappShop-war/src/java/ch/hslu/enappwebshop/web/ProductBean.java +++ b/EnappShop-war/src/java/ch/hslu/enappwebshop/web/ProductBean.java @@ -1,60 +1,60 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ch.hslu.enappwebshop.web; import ch.hslu.enappwebshop.ejb.ProductSessionLocal; import ch.hslu.enappwebshop.entities.Product; import java.io.Serializable; import java.util.List; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; /** * * @author zimmbi */ @ManagedBean(name = "product") @SessionScoped public class ProductBean implements Serializable { @EJB private ProductSessionLocal productSession; private Product product; /** Creates a new instance of ProductBean */ public ProductBean() { } public List<Product> getProducts() { return productSession.getProducts(); } public Product getProduct() { return null; } - public Product newProduct() { + public Product getNewProduct() { Product p = new Product(); this.product = p; return p; } public String saveProduct() { productSession.mergeProduct(product); return null; } public String select(Product p) { product = p; return "DETAILS"; } public Product getDetails() { return product; } }
true
true
public Product newProduct() { Product p = new Product(); this.product = p; return p; }
public Product getNewProduct() { Product p = new Product(); this.product = p; return p; }
diff --git a/src/main/java/me/ase34/citylanterns/listener/LanternSelectListener.java b/src/main/java/me/ase34/citylanterns/listener/LanternSelectListener.java index 8b7bc3e..12f1973 100644 --- a/src/main/java/me/ase34/citylanterns/listener/LanternSelectListener.java +++ b/src/main/java/me/ase34/citylanterns/listener/LanternSelectListener.java @@ -1,45 +1,45 @@ package me.ase34.citylanterns.listener; import me.ase34.citylanterns.CityLanterns; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerInteractEvent; public class LanternSelectListener implements Listener { private CityLanterns plugin; public LanternSelectListener(CityLanterns plugin) { super(); this.plugin = plugin; } @EventHandler public void onPlayerInteractBlock(PlayerInteractEvent ev) { if (ev.isBlockInHand()) { return; } if (plugin.getSelectingPlayers().contains(ev.getPlayer().getName())) { if (ev.getClickedBlock() == null) { return; } - if (ev.getClickedBlock().getType() != Material.REDSTONE_LAMP_OFF) { + if (ev.getClickedBlock().getType() != Material.REDSTONE_LAMP_OFF && ev.getClickedBlock().getType() != Material.REDSTONE_LAMP_ON) { ev.getPlayer().sendMessage(ChatColor.GOLD + "This is not a redstone lamp!"); return; } Location loc = ev.getClickedBlock().getLocation(); if (plugin.getLanterns().contains(loc)) { plugin.getLanterns().remove(loc); ev.getPlayer().sendMessage(ChatColor.GOLD + "Removed this lantern!"); } else { plugin.getLanterns().add(loc); ev.getPlayer().sendMessage(ChatColor.GOLD + "Added this lantern!"); } ev.setCancelled(true); } } }
true
true
public void onPlayerInteractBlock(PlayerInteractEvent ev) { if (ev.isBlockInHand()) { return; } if (plugin.getSelectingPlayers().contains(ev.getPlayer().getName())) { if (ev.getClickedBlock() == null) { return; } if (ev.getClickedBlock().getType() != Material.REDSTONE_LAMP_OFF) { ev.getPlayer().sendMessage(ChatColor.GOLD + "This is not a redstone lamp!"); return; } Location loc = ev.getClickedBlock().getLocation(); if (plugin.getLanterns().contains(loc)) { plugin.getLanterns().remove(loc); ev.getPlayer().sendMessage(ChatColor.GOLD + "Removed this lantern!"); } else { plugin.getLanterns().add(loc); ev.getPlayer().sendMessage(ChatColor.GOLD + "Added this lantern!"); } ev.setCancelled(true); } }
public void onPlayerInteractBlock(PlayerInteractEvent ev) { if (ev.isBlockInHand()) { return; } if (plugin.getSelectingPlayers().contains(ev.getPlayer().getName())) { if (ev.getClickedBlock() == null) { return; } if (ev.getClickedBlock().getType() != Material.REDSTONE_LAMP_OFF && ev.getClickedBlock().getType() != Material.REDSTONE_LAMP_ON) { ev.getPlayer().sendMessage(ChatColor.GOLD + "This is not a redstone lamp!"); return; } Location loc = ev.getClickedBlock().getLocation(); if (plugin.getLanterns().contains(loc)) { plugin.getLanterns().remove(loc); ev.getPlayer().sendMessage(ChatColor.GOLD + "Removed this lantern!"); } else { plugin.getLanterns().add(loc); ev.getPlayer().sendMessage(ChatColor.GOLD + "Added this lantern!"); } ev.setCancelled(true); } }
diff --git a/backend/transparent/core/Module.java b/backend/transparent/core/Module.java index aa8568f..dbfd9c9 100644 --- a/backend/transparent/core/Module.java +++ b/backend/transparent/core/Module.java @@ -1,224 +1,225 @@ package transparent.core; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import transparent.core.database.Database; public class Module { /* contains the full command to execute the module, or the remote URL */ private final String path; /* name of source for which this module is a parser */ private final String sourceName; /* unique name of module */ private final String moduleName; /* specifies whether the module is remote */ private final boolean remote; /* specifies whether websites should be downloaded in blocks or all at once */ private final boolean useBlockedDownload; /* unique integer identifier for the module */ private final long id; /* the output log associated with this module */ private final PrintStream log; /* indicates whether activity should be logged to standard out */ private boolean logActivity; public Module(long id, String path, String moduleName, String sourceName, PrintStream log, boolean isRemote, boolean blockedDownload) { this.path = path; this.sourceName = sourceName; this.moduleName = moduleName; this.remote = isRemote; this.useBlockedDownload = blockedDownload; this.id = id; this.log = log; } public long getId() { return id; } public String getPath() { return path; } public String getSourceName() { return sourceName; } public String getModuleName() { return moduleName; } public boolean isRemote() { return remote; } public boolean blockedDownload() { return useBlockedDownload; } public boolean isLoggingActivity() { return logActivity; } public void setLoggingActivity(boolean logActivity) { this.logActivity = logActivity; } public PrintStream getLogStream() { return log; } public void logInfo(String className, String methodName, String message) { log.println(className + '.' + methodName + ": " + message); if (logActivity) { System.out.println("Module " + id + " (name: '" + moduleName + "') information:"); System.out.println("\t" + className + '.' + methodName + ": " + message); System.out.flush(); } } public void logError(String className, String methodName, String message) { log.println(className + '.' + methodName + " ERROR: " + message); if (logActivity) { System.out.println("Module " + id + " (name: '" + moduleName + "') reported error:"); System.out.println("\t" + className + '.' + methodName + " ERROR: " + message); System.out.flush(); } } public void logUserAgentChange(String newUserAgent) { if (logActivity) { System.out.println("Module " + id + " (name: '" + moduleName + "') changed user agent to: " + newUserAgent); System.out.flush(); } } public void logHttpGetRequest(String url) { if (logActivity) { System.out.println("Module " + id + " (name: '" + moduleName + "') requested HTTP GET: " + url); System.out.flush(); } } public void logHttpPostRequest(String url, byte[] post) { if (logActivity) { System.out.println("Module " + id + " (name: '" + moduleName + "') requested HTTP POST:"); System.out.println("\tURL: " + url); System.out.print("\tPOST data: "); try { System.out.write(post); } catch (IOException e) { System.out.print("<unable to write data>"); } System.out.println(); System.out.flush(); } } public void logDownloadProgress(int downloaded) { if (logActivity) { System.out.println("Module " + id + " (name: '" + moduleName + "') downloading: " + downloaded + " bytes"); System.out.flush(); } } public void logDownloadCompleted(int downloaded) { if (logActivity) { System.out.println("Module " + id + " (name: '" + moduleName + "') completed download: " + downloaded + " bytes"); System.out.flush(); } } public void logDownloadAborted() { if (logActivity) { System.out.println("Module " + id + " (name: '" + moduleName + "') aborted download due to download size limit."); System.out.flush(); } } public static Module load(Database database, int index) { long id = -1; String name = "<unknown>"; try { id = Long.parseLong(database.getMetadata("module." + index + ".id")); String path = database.getMetadata("module." + index + ".path"); name = database.getMetadata("module." + index + ".name"); String source = database.getMetadata("module." + index + ".source"); String blockedString = database.getMetadata("module." + index + ".blocked"); String remoteString = database.getMetadata("module." + index + ".remote"); boolean blocked = true; boolean remote = true; if (blockedString.equals("0")) blocked = false; if (remoteString.equals("0")) remote = false; PrintStream log = new PrintStream(new FileOutputStream( "log/" + name + "." + id + ".log", true)); return new Module(id, path, name, source, log, remote, blocked); } catch (RuntimeException e) { System.err.println("Module.load ERROR: " + "Error loading module id."); return null; } catch (IOException e) { System.err.println("Module.load ERROR: " + "Unable to initialize output log. " - + "(name = " + name + ", id = " + id + ")"); + + "(name = " + name + ", id = " + id + + ", exception: " + e.getMessage() + ")"); return null; } } public boolean save(Database database, int index) { return (database.setMetadata( "module." + index + ".id", Long.toString(id)) && database.setMetadata( "module." + index + "path", path) && database.setMetadata( "module." + index + ".name", moduleName) && database.setMetadata( "module." + index + ".source", sourceName) && database.setMetadata( "module." + index + ".remote", remote ? "1" : "0") && database.setMetadata( "module." + index + ".blocked", useBlockedDownload ? "1" : "0")); } }
true
true
public static Module load(Database database, int index) { long id = -1; String name = "<unknown>"; try { id = Long.parseLong(database.getMetadata("module." + index + ".id")); String path = database.getMetadata("module." + index + ".path"); name = database.getMetadata("module." + index + ".name"); String source = database.getMetadata("module." + index + ".source"); String blockedString = database.getMetadata("module." + index + ".blocked"); String remoteString = database.getMetadata("module." + index + ".remote"); boolean blocked = true; boolean remote = true; if (blockedString.equals("0")) blocked = false; if (remoteString.equals("0")) remote = false; PrintStream log = new PrintStream(new FileOutputStream( "log/" + name + "." + id + ".log", true)); return new Module(id, path, name, source, log, remote, blocked); } catch (RuntimeException e) { System.err.println("Module.load ERROR: " + "Error loading module id."); return null; } catch (IOException e) { System.err.println("Module.load ERROR: " + "Unable to initialize output log. " + "(name = " + name + ", id = " + id + ")"); return null; } }
public static Module load(Database database, int index) { long id = -1; String name = "<unknown>"; try { id = Long.parseLong(database.getMetadata("module." + index + ".id")); String path = database.getMetadata("module." + index + ".path"); name = database.getMetadata("module." + index + ".name"); String source = database.getMetadata("module." + index + ".source"); String blockedString = database.getMetadata("module." + index + ".blocked"); String remoteString = database.getMetadata("module." + index + ".remote"); boolean blocked = true; boolean remote = true; if (blockedString.equals("0")) blocked = false; if (remoteString.equals("0")) remote = false; PrintStream log = new PrintStream(new FileOutputStream( "log/" + name + "." + id + ".log", true)); return new Module(id, path, name, source, log, remote, blocked); } catch (RuntimeException e) { System.err.println("Module.load ERROR: " + "Error loading module id."); return null; } catch (IOException e) { System.err.println("Module.load ERROR: " + "Unable to initialize output log. " + "(name = " + name + ", id = " + id + ", exception: " + e.getMessage() + ")"); return null; } }
diff --git a/CustomMusicDiscs/src/org/vanillaworld/CustomMusicDiscs/Main.java b/CustomMusicDiscs/src/org/vanillaworld/CustomMusicDiscs/Main.java index f591c93..40ee89a 100644 --- a/CustomMusicDiscs/src/org/vanillaworld/CustomMusicDiscs/Main.java +++ b/CustomMusicDiscs/src/org/vanillaworld/CustomMusicDiscs/Main.java @@ -1,153 +1,157 @@ package org.vanillaworld.CustomMusicDiscs; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.block.Jukebox; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.Location; public class Main extends JavaPlugin implements Listener { public static JavaPlugin plugin; public static List<Disc> discs; Map<Location, Disc> playing = new HashMap<Location, Disc>(); public void onEnable() { plugin = this; Setup.setupFolders(); // Setup the folder structure discs = Setup.getDiscs(); // Load discs this.getServer().getPluginManager().registerEvents(this, this); } public void onDisable() { discs = null; plugin = null; } @SuppressWarnings("deprecation") public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(cmd.getName().equalsIgnoreCase("music")) { if(args.length == 3) { if(args[0].equalsIgnoreCase("give")) { Player p = Bukkit.getPlayerExact(args[1]); if(p == null) { sender.sendMessage(ChatColor.RED + "The player must be online to give a music disc!"); } else { if(discs.size() > 0) { for(Disc disc : discs) { if(disc.name.equalsIgnoreCase(args[2])) { p.getInventory().addItem(disc.disc); p.updateInventory(); return true; } } } sender.sendMessage(ChatColor.RED + "That disc does not exist!"); } } else { sender.sendMessage(ChatColor.RED + "Invaild command. Correct usage: /music give <player> <disc>"); } } else { sender.sendMessage(ChatColor.RED + "To many/few args. Correct usage: /music give <player> <disc>"); } return true; } return false; } @EventHandler (priority=EventPriority.HIGHEST) private void PlayerInteract(PlayerInteractEvent event) { if(event.getClickedBlock() != null) { if(event.getClickedBlock().getType().equals(Material.JUKEBOX) && event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { final Jukebox jukebox = (Jukebox) event.getClickedBlock().getState(); if(playing.containsKey(jukebox.getLocation())) { jukebox.getLocation().getWorld().dropItem(jukebox.getLocation(), playing.get(jukebox.getLocation()).disc); playing.get(jukebox.getLocation()).stop(jukebox.getLocation()); playing.remove(jukebox.getLocation()); return; } ItemStack item = event.getPlayer().getItemInHand(); if(item != null) { ItemMeta meta = item.getItemMeta(); + if(meta == null) + { + return; + } if(meta.getLore() != null) { if(meta.getLore().contains("*Custom Disc*")) { String name = meta.getLore().get(1); if(discs.size() > 0) { for(Disc disc : discs) { if((ChatColor.RESET + "" + ChatColor.GRAY + disc.name).equalsIgnoreCase(name)) { this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { public void run() { jukebox.setPlaying(null); } }, 2); disc.play(jukebox.getLocation()); playing.put(jukebox.getLocation(), disc); } } } } } } } } } @EventHandler private void BlockBreak(BlockBreakEvent event) { if(event.getBlock().getType().equals(Material.JUKEBOX)) { Jukebox jukebox = (Jukebox) event.getBlock().getState(); if(playing.containsKey(jukebox.getLocation())) { jukebox.getLocation().getWorld().dropItem(jukebox.getLocation(), playing.get(jukebox.getLocation()).disc); playing.get(jukebox.getLocation()).stop(jukebox.getLocation()); playing.remove(jukebox.getLocation()); return; } } } }
true
true
private void PlayerInteract(PlayerInteractEvent event) { if(event.getClickedBlock() != null) { if(event.getClickedBlock().getType().equals(Material.JUKEBOX) && event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { final Jukebox jukebox = (Jukebox) event.getClickedBlock().getState(); if(playing.containsKey(jukebox.getLocation())) { jukebox.getLocation().getWorld().dropItem(jukebox.getLocation(), playing.get(jukebox.getLocation()).disc); playing.get(jukebox.getLocation()).stop(jukebox.getLocation()); playing.remove(jukebox.getLocation()); return; } ItemStack item = event.getPlayer().getItemInHand(); if(item != null) { ItemMeta meta = item.getItemMeta(); if(meta.getLore() != null) { if(meta.getLore().contains("*Custom Disc*")) { String name = meta.getLore().get(1); if(discs.size() > 0) { for(Disc disc : discs) { if((ChatColor.RESET + "" + ChatColor.GRAY + disc.name).equalsIgnoreCase(name)) { this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { public void run() { jukebox.setPlaying(null); } }, 2); disc.play(jukebox.getLocation()); playing.put(jukebox.getLocation(), disc); } } } } } } } } }
private void PlayerInteract(PlayerInteractEvent event) { if(event.getClickedBlock() != null) { if(event.getClickedBlock().getType().equals(Material.JUKEBOX) && event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { final Jukebox jukebox = (Jukebox) event.getClickedBlock().getState(); if(playing.containsKey(jukebox.getLocation())) { jukebox.getLocation().getWorld().dropItem(jukebox.getLocation(), playing.get(jukebox.getLocation()).disc); playing.get(jukebox.getLocation()).stop(jukebox.getLocation()); playing.remove(jukebox.getLocation()); return; } ItemStack item = event.getPlayer().getItemInHand(); if(item != null) { ItemMeta meta = item.getItemMeta(); if(meta == null) { return; } if(meta.getLore() != null) { if(meta.getLore().contains("*Custom Disc*")) { String name = meta.getLore().get(1); if(discs.size() > 0) { for(Disc disc : discs) { if((ChatColor.RESET + "" + ChatColor.GRAY + disc.name).equalsIgnoreCase(name)) { this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { public void run() { jukebox.setPlaying(null); } }, 2); disc.play(jukebox.getLocation()); playing.put(jukebox.getLocation(), disc); } } } } } } } } }