lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
59b8d2982b8fcfb2d3ced8215c5fb1de607a0f22
0
apache/commons-net,apache/commons-net,codolutions/commons-net,codolutions/commons-net,mohanaraosv/commons-net,mohanaraosv/commons-net
/* * 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.net.nntp; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Vector; import org.apache.commons.net.MalformedServerReplyException; import org.apache.commons.net.io.DotTerminatedMessageReader; import org.apache.commons.net.io.DotTerminatedMessageWriter; import org.apache.commons.net.io.Util; /*** * NNTPClient encapsulates all the functionality necessary to post and * retrieve articles from an NNTP server. As with all classes derived * from {@link org.apache.commons.net.SocketClient}, * you must first connect to the server with * {@link org.apache.commons.net.SocketClient#connect connect } * before doing anything, and finally * {@link org.apache.commons.net.nntp.NNTP#disconnect disconnect() } * after you're completely finished interacting with the server. * Remember that the * {@link org.apache.commons.net.nntp.NNTP#isAllowedToPost isAllowedToPost()} * method is defined in * {@link org.apache.commons.net.nntp.NNTP}. * <p> * You should keep in mind that the NNTP server may choose to prematurely * close a connection if the client has been idle for longer than a * given time period or if the server is being shutdown by the operator or * some other reason. The NNTP class will detect a * premature NNTP server connection closing when it receives a * {@link org.apache.commons.net.nntp.NNTPReply#SERVICE_DISCONTINUED NNTPReply.SERVICE_DISCONTINUED } * response to a command. * When that occurs, the NNTP class method encountering that reply will throw * an {@link org.apache.commons.net.nntp.NNTPConnectionClosedException} * . * <code>NNTPConectionClosedException</code> * is a subclass of <code> IOException </code> and therefore need not be * caught separately, but if you are going to catch it separately, its * catch block must appear before the more general <code> IOException </code> * catch block. When you encounter an * {@link org.apache.commons.net.nntp.NNTPConnectionClosedException} * , you must disconnect the connection with * {@link org.apache.commons.net.nntp.NNTP#disconnect disconnect() } * to properly clean up the * system resources used by NNTP. Before disconnecting, you may check the * last reply code and text with * {@link org.apache.commons.net.nntp.NNTP#getReplyCode getReplyCode } and * {@link org.apache.commons.net.nntp.NNTP#getReplyString getReplyString }. * <p> * Rather than list it separately for each method, we mention here that * every method communicating with the server and throwing an IOException * can also throw a * {@link org.apache.commons.net.MalformedServerReplyException} * , which is a subclass * of IOException. A MalformedServerReplyException will be thrown when * the reply received from the server deviates enough from the protocol * specification that it cannot be interpreted in a useful manner despite * attempts to be as lenient as possible. * <p> * <p> * @author Daniel F. Savarese * @author Rory Winston * @author Ted Wise * @see NNTP * @see NNTPConnectionClosedException * @see org.apache.commons.net.MalformedServerReplyException ***/ public class NNTPClient extends NNTP { // reply will consist of 22n nnn <aaa> private void __parseArticlePointer(String reply, ArticlePointer pointer) throws MalformedServerReplyException { String tokens[] = reply.split(" "); if (tokens.length >= 3) { // OK, we can parset the line int i = 1; // skip reply code try { // Get article number pointer.articleNumber = Long.parseLong(tokens[i++]); // Get article id pointer.articleId = tokens[i++]; return; // done } catch (NumberFormatException e) { // drop through and raise exception } } throw new MalformedServerReplyException( "Could not parse article pointer.\nServer reply: " + reply); } /* * 211 n f l s group selected * (n = estimated number of articles in group, * f = first article number in the group, * l = last article number in the group, * s = name of the group.) */ private static void __parseGroupReply(String reply, NewsgroupInfo info) throws MalformedServerReplyException { String tokens[] = reply.split(" "); if (tokens.length >= 5) { int i = 1; // Skip numeric response value try { // Get estimated article count info._setArticleCount(Long.parseLong(tokens[i++])); // Get first article number info._setFirstArticle(Long.parseLong(tokens[i++])); // Get last article number info._setLastArticle(Long.parseLong(tokens[i++])); // Get newsgroup name info._setNewsgroup(tokens[i++]); info._setPostingPermission(NewsgroupInfo.UNKNOWN_POSTING_PERMISSION); return ; } catch (NumberFormatException e) { // drop through to report error } } throw new MalformedServerReplyException( "Could not parse newsgroup info.\nServer reply: " + reply); } // Format: group last first p static NewsgroupInfo __parseNewsgroupListEntry(String entry) { String tokens[] = entry.split(" "); if (tokens.length < 4) { return null; } NewsgroupInfo result = new NewsgroupInfo(); int i = 0; result._setNewsgroup(tokens[i++]); try { long lastNum = Long.parseLong(tokens[i++]); long firstNum = Long.parseLong(tokens[i++]); result._setFirstArticle(firstNum); result._setLastArticle(lastNum); if((firstNum == 0) && (lastNum == 0)) result._setArticleCount(0); else result._setArticleCount(lastNum - firstNum + 1); } catch (NumberFormatException e) { return null; } switch (tokens[i++].charAt(0)) { case 'y': case 'Y': result._setPostingPermission( NewsgroupInfo.PERMITTED_POSTING_PERMISSION); break; case 'n': case 'N': result._setPostingPermission( NewsgroupInfo.PROHIBITED_POSTING_PERMISSION); break; case 'm': case 'M': result._setPostingPermission( NewsgroupInfo.MODERATED_POSTING_PERMISSION); break; default: result._setPostingPermission( NewsgroupInfo.UNKNOWN_POSTING_PERMISSION); break; } return result; } /** * Parse a response line from {@link #retrieveArticleInfo(long, long)}. * * @param line a response line * @return the parsed {@link Article}, if unparseable then isDummy() * will be true, and the subject will contain the raw info. * @since 3.0 */ static Article __parseArticleEntry(String line) { // Extract the article information // Mandatory format (from NNTP RFC 2980) is : // articleNumber\tSubject\tAuthor\tDate\tID\tReference(s)\tByte Count\tLine Count Article article = new Article(); article.setSubject(line); // in case parsing fails String parts[] = line.split("\t"); if (parts.length > 6) { int i = 0; try { article.setArticleNumber(Long.parseLong(parts[i++])); article.setSubject(parts[i++]); article.setFrom(parts[i++]); article.setDate(parts[i++]); article.setArticleId(parts[i++]); article.addReference(parts[i++]); } catch (NumberFormatException e) { // ignored, already handled } } return article; } private NewsgroupInfo[] __readNewsgroupListing() throws IOException { int size; String line; Vector<NewsgroupInfo> list; BufferedReader reader; NewsgroupInfo tmp, info[]; reader = new BufferedReader(new DotTerminatedMessageReader(_reader_)); // Start of with a big vector because we may be reading a very large // amount of groups. list = new Vector<NewsgroupInfo>(2048); while ((line = reader.readLine()) != null) { tmp = __parseNewsgroupListEntry(line); if (tmp != null) list.addElement(tmp); else throw new MalformedServerReplyException(line); } if ((size = list.size()) < 1) return new NewsgroupInfo[0]; info = new NewsgroupInfo[size]; list.copyInto(info); return info; } private Reader __retrieve(int command, String articleId, ArticlePointer pointer) throws IOException { Reader reader; if (articleId != null) { if (!NNTPReply.isPositiveCompletion(sendCommand(command, articleId))) return null; } else { if (!NNTPReply.isPositiveCompletion(sendCommand(command))) return null; } if (pointer != null) __parseArticlePointer(getReplyString(), pointer); reader = new DotTerminatedMessageReader(_reader_); return reader; } private Reader __retrieve(int command, int articleNumber, ArticlePointer pointer) throws IOException { Reader reader; if (!NNTPReply.isPositiveCompletion(sendCommand(command, Integer.toString(articleNumber)))) return null; if (pointer != null) __parseArticlePointer(getReplyString(), pointer); reader = new DotTerminatedMessageReader(_reader_); return reader; } /*** * Retrieves an article from the NNTP server. The article is referenced * by its unique article identifier (including the enclosing &lt and &gt). * The article number and identifier contained in the server reply * are returned through an ArticlePointer. The <code> articleId </code> * field of the ArticlePointer cannot always be trusted because some * NNTP servers do not correctly follow the RFC 977 reply format. * <p> * A DotTerminatedMessageReader is returned from which the article can * be read. If the article does not exist, null is returned. * <p> * You must not issue any commands to the NNTP server (i.e., call any * other methods) until you finish reading the message from the returned * Reader instance. * The NNTP protocol uses the same stream for issuing commands as it does * for returning results. Therefore the returned Reader actually reads * directly from the NNTP connection. After the end of message has been * reached, new commands can be executed and their replies read. If * you do not follow these requirements, your program will not work * properly. * <p> * @param articleId The unique article identifier of the article to * retrieve. If this parameter is null, the currently selected * article is retrieved. * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return A DotTerminatedMessageReader instance from which the article * be read. null if the article does not exist. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public Reader retrieveArticle(String articleId, ArticlePointer pointer) throws IOException { return __retrieve(NNTPCommand.ARTICLE, articleId, pointer); } /*** Same as <code> retrieveArticle(articleId, null) </code> ***/ public Reader retrieveArticle(String articleId) throws IOException { return retrieveArticle(articleId, null); } /*** Same as <code> retrieveArticle(null) </code> ***/ public Reader retrieveArticle() throws IOException { return retrieveArticle(null); } /*** * Retrieves an article from the currently selected newsgroup. The * article is referenced by its article number. * The article number and identifier contained in the server reply * are returned through an ArticlePointer. The <code> articleId </code> * field of the ArticlePointer cannot always be trusted because some * NNTP servers do not correctly follow the RFC 977 reply format. * <p> * A DotTerminatedMessageReader is returned from which the article can * be read. If the article does not exist, null is returned. * <p> * You must not issue any commands to the NNTP server (i.e., call any * other methods) until you finish reading the message from the returned * Reader instance. * The NNTP protocol uses the same stream for issuing commands as it does * for returning results. Therefore the returned Reader actually reads * directly from the NNTP connection. After the end of message has been * reached, new commands can be executed and their replies read. If * you do not follow these requirements, your program will not work * properly. * <p> * @param articleNumber The number of the the article to * retrieve. * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return A DotTerminatedMessageReader instance from which the article * be read. null if the article does not exist. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public Reader retrieveArticle(int articleNumber, ArticlePointer pointer) throws IOException { return __retrieve(NNTPCommand.ARTICLE, articleNumber, pointer); } /*** Same as <code> retrieveArticle(articleNumber, null) </code> ***/ public Reader retrieveArticle(int articleNumber) throws IOException { return retrieveArticle(articleNumber, null); } /*** * Retrieves an article header from the NNTP server. The article is * referenced * by its unique article identifier (including the enclosing &lt and &gt). * The article number and identifier contained in the server reply * are returned through an ArticlePointer. The <code> articleId </code> * field of the ArticlePointer cannot always be trusted because some * NNTP servers do not correctly follow the RFC 977 reply format. * <p> * A DotTerminatedMessageReader is returned from which the article can * be read. If the article does not exist, null is returned. * <p> * You must not issue any commands to the NNTP server (i.e., call any * other methods) until you finish reading the message from the returned * Reader instance. * The NNTP protocol uses the same stream for issuing commands as it does * for returning results. Therefore the returned Reader actually reads * directly from the NNTP connection. After the end of message has been * reached, new commands can be executed and their replies read. If * you do not follow these requirements, your program will not work * properly. * <p> * @param articleId The unique article identifier of the article whose * header is being retrieved. If this parameter is null, the * header of the currently selected article is retrieved. * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return A DotTerminatedMessageReader instance from which the article * header can be read. null if the article does not exist. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public Reader retrieveArticleHeader(String articleId, ArticlePointer pointer) throws IOException { return __retrieve(NNTPCommand.HEAD, articleId, pointer); } /*** Same as <code> retrieveArticleHeader(articleId, null) </code> ***/ public Reader retrieveArticleHeader(String articleId) throws IOException { return retrieveArticleHeader(articleId, null); } /*** Same as <code> retrieveArticleHeader(null) </code> ***/ public Reader retrieveArticleHeader() throws IOException { return retrieveArticleHeader(null); } /*** * Retrieves an article header from the currently selected newsgroup. The * article is referenced by its article number. * The article number and identifier contained in the server reply * are returned through an ArticlePointer. The <code> articleId </code> * field of the ArticlePointer cannot always be trusted because some * NNTP servers do not correctly follow the RFC 977 reply format. * <p> * A DotTerminatedMessageReader is returned from which the article can * be read. If the article does not exist, null is returned. * <p> * You must not issue any commands to the NNTP server (i.e., call any * other methods) until you finish reading the message from the returned * Reader instance. * The NNTP protocol uses the same stream for issuing commands as it does * for returning results. Therefore the returned Reader actually reads * directly from the NNTP connection. After the end of message has been * reached, new commands can be executed and their replies read. If * you do not follow these requirements, your program will not work * properly. * <p> * @param articleNumber The number of the the article whose header is * being retrieved. * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return A DotTerminatedMessageReader instance from which the article * header can be read. null if the article does not exist. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public Reader retrieveArticleHeader(int articleNumber, ArticlePointer pointer) throws IOException { return __retrieve(NNTPCommand.HEAD, articleNumber, pointer); } /*** Same as <code> retrieveArticleHeader(articleNumber, null) </code> ***/ public Reader retrieveArticleHeader(int articleNumber) throws IOException { return retrieveArticleHeader(articleNumber, null); } /*** * Retrieves an article body from the NNTP server. The article is * referenced * by its unique article identifier (including the enclosing &lt and &gt). * The article number and identifier contained in the server reply * are returned through an ArticlePointer. The <code> articleId </code> * field of the ArticlePointer cannot always be trusted because some * NNTP servers do not correctly follow the RFC 977 reply format. * <p> * A DotTerminatedMessageReader is returned from which the article can * be read. If the article does not exist, null is returned. * <p> * You must not issue any commands to the NNTP server (i.e., call any * other methods) until you finish reading the message from the returned * Reader instance. * The NNTP protocol uses the same stream for issuing commands as it does * for returning results. Therefore the returned Reader actually reads * directly from the NNTP connection. After the end of message has been * reached, new commands can be executed and their replies read. If * you do not follow these requirements, your program will not work * properly. * <p> * @param articleId The unique article identifier of the article whose * body is being retrieved. If this parameter is null, the * body of the currently selected article is retrieved. * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return A DotTerminatedMessageReader instance from which the article * body can be read. null if the article does not exist. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public Reader retrieveArticleBody(String articleId, ArticlePointer pointer) throws IOException { return __retrieve(NNTPCommand.BODY, articleId, pointer); } /*** Same as <code> retrieveArticleBody(articleId, null) </code> ***/ public Reader retrieveArticleBody(String articleId) throws IOException { return retrieveArticleBody(articleId, null); } /*** Same as <code> retrieveArticleBody(null) </code> ***/ public Reader retrieveArticleBody() throws IOException { return retrieveArticleBody(null); } /*** * Retrieves an article body from the currently selected newsgroup. The * article is referenced by its article number. * The article number and identifier contained in the server reply * are returned through an ArticlePointer. The <code> articleId </code> * field of the ArticlePointer cannot always be trusted because some * NNTP servers do not correctly follow the RFC 977 reply format. * <p> * A DotTerminatedMessageReader is returned from which the article can * be read. If the article does not exist, null is returned. * <p> * You must not issue any commands to the NNTP server (i.e., call any * other methods) until you finish reading the message from the returned * Reader instance. * The NNTP protocol uses the same stream for issuing commands as it does * for returning results. Therefore the returned Reader actually reads * directly from the NNTP connection. After the end of message has been * reached, new commands can be executed and their replies read. If * you do not follow these requirements, your program will not work * properly. * <p> * @param articleNumber The number of the the article whose body is * being retrieved. * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return A DotTerminatedMessageReader instance from which the article * body can be read. null if the article does not exist. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public Reader retrieveArticleBody(int articleNumber, ArticlePointer pointer) throws IOException { return __retrieve(NNTPCommand.BODY, articleNumber, pointer); } /*** Same as <code> retrieveArticleBody(articleNumber, null) </code> ***/ public Reader retrieveArticleBody(int articleNumber) throws IOException { return retrieveArticleBody(articleNumber, null); } /*** * Select the specified newsgroup to be the target of for future article * retrieval and posting operations. Also return the newsgroup * information contained in the server reply through the info parameter. * <p> * @param newsgroup The newsgroup to select. * @param info A parameter through which the newsgroup information of * the selected newsgroup contained in the server reply is returned. * Set this to null if you do not desire this information. * @return True if the newsgroup exists and was selected, false otherwise. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean selectNewsgroup(String newsgroup, NewsgroupInfo info) throws IOException { if (!NNTPReply.isPositiveCompletion(group(newsgroup))) return false; if (info != null) __parseGroupReply(getReplyString(), info); return true; } /*** Same as <code> selectNewsgroup(newsgroup, null) </code> ***/ public boolean selectNewsgroup(String newsgroup) throws IOException { return selectNewsgroup(newsgroup, null); } /*** * List the command help from the server. * <p> * @return The sever help information. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public String listHelp() throws IOException { StringWriter help; Reader reader; if (!NNTPReply.isInformational(help())) return null; help = new StringWriter(); reader = new DotTerminatedMessageReader(_reader_); Util.copyReader(reader, help); reader.close(); help.close(); return help.toString(); } /** * Send a "LIST OVERVIEW.FMT" command to the server. * * @return the contents of the Overview format, of {@code null} if the command failed * @throws IOException */ public String[] listOverviewFmt() throws IOException { if (!NNTPReply.isPositiveCompletion(sendCommand("LIST", "OVERVIEW.FMT"))){ return null; } BufferedReader reader = new BufferedReader(new DotTerminatedMessageReader(_reader_)); String line; ArrayList<String> list = new ArrayList<String>(); while((line=reader.readLine()) != null) { list.add(line); } reader.close(); return list.toArray(new String[list.size()]); } /*** * Select an article by its unique identifier (including enclosing * &lt and &gt) and return its article number and id through the * pointer parameter. This is achieved through the STAT command. * According to RFC 977, this will NOT set the current article pointer * on the server. To do that, you must reference the article by its * number. * <p> * @param articleId The unique article identifier of the article that * is being selectedd. If this parameter is null, the * body of the current article is selected * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return True if successful, false if not. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean selectArticle(String articleId, ArticlePointer pointer) throws IOException { if (articleId != null) { if (!NNTPReply.isPositiveCompletion(stat(articleId))) return false; } else { if (!NNTPReply.isPositiveCompletion(stat())) return false; } if (pointer != null) __parseArticlePointer(getReplyString(), pointer); return true; } /**** Same as <code> selectArticle(articleId, null) </code> ***/ public boolean selectArticle(String articleId) throws IOException { return selectArticle(articleId, null); } /**** * Same as <code> selectArticle(null, articleId) </code>. Useful * for retrieving the current article number. ***/ public boolean selectArticle(ArticlePointer pointer) throws IOException { return selectArticle(null, pointer); } /*** * Select an article in the currently selected newsgroup by its number. * and return its article number and id through the * pointer parameter. This is achieved through the STAT command. * According to RFC 977, this WILL set the current article pointer * on the server. Use this command to select an article before retrieving * it, or to obtain an article's unique identifier given its number. * <p> * @param articleNumber The number of the article to select from the * currently selected newsgroup. * @param pointer A parameter through which to return the article's * number and unique id. Although the articleId field cannot always * be trusted because of server deviations from RFC 977 reply formats, * we haven't found a server that misformats this information in response * to this particular command. You may set this parameter to null if * you do not desire to retrieve the returned article information. * @return True if successful, false if not. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean selectArticle(long articleNumber, ArticlePointer pointer) throws IOException { if (!NNTPReply.isPositiveCompletion(stat(articleNumber))) return false; if (pointer != null) __parseArticlePointer(getReplyString(), pointer); return true; } /*** Same as <code> selectArticle(articleNumber, null) </code> ***/ public boolean selectArticle(long articleNumber) throws IOException { return selectArticle(articleNumber, null); } /*** * Select the article preceeding the currently selected article in the * currently selected newsgroup and return its number and unique id * through the pointer parameter. Because of deviating server * implementations, the articleId information cannot be trusted. To * obtain the article identifier, issue a * <code> selectArticle(pointer.articleNumber, pointer) </code> immediately * afterward. * <p> * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return True if successful, false if not (e.g., there is no previous * article). * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean selectPreviousArticle(ArticlePointer pointer) throws IOException { if (!NNTPReply.isPositiveCompletion(last())) return false; if (pointer != null) __parseArticlePointer(getReplyString(), pointer); return true; } /*** Same as <code> selectPreviousArticle(null) </code> ***/ public boolean selectPreviousArticle() throws IOException { return selectPreviousArticle(null); } /*** * Select the article following the currently selected article in the * currently selected newsgroup and return its number and unique id * through the pointer parameter. Because of deviating server * implementations, the articleId information cannot be trusted. To * obtain the article identifier, issue a * <code> selectArticle(pointer.articleNumber, pointer) </code> immediately * afterward. * <p> * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return True if successful, false if not (e.g., there is no following * article). * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean selectNextArticle(ArticlePointer pointer) throws IOException { if (!NNTPReply.isPositiveCompletion(next())) return false; if (pointer != null) __parseArticlePointer(getReplyString(), pointer); return true; } /*** Same as <code> selectNextArticle(null) </code> ***/ public boolean selectNextArticle() throws IOException { return selectNextArticle(null); } /*** * List all newsgroups served by the NNTP server. If no newsgroups * are served, a zero length array will be returned. If the command * fails, null will be returned. * <p> * @return An array of NewsgroupInfo instances containing the information * for each newsgroup served by the NNTP server. If no newsgroups * are served, a zero length array will be returned. If the command * fails, null will be returned. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * @see #iterateNewsgroupListing() * @see #iterateNewsgroups() ***/ public NewsgroupInfo[] listNewsgroups() throws IOException { if (!NNTPReply.isPositiveCompletion(list())) return null; return __readNewsgroupListing(); } /** * List all newsgroups served by the NNTP server. If no newsgroups * are served, no entries will be returned. * <p> * @return An iterable of NewsgroupInfo instances containing the information * for each newsgroup served by the NNTP server. If no newsgroups * are served, no entries will be returned. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * @since 3.0 */ public Iterable<String> iterateNewsgroupListing() throws IOException { if (NNTPReply.isPositiveCompletion(list())) { return new ReplyIterator(_reader_); } throw new IOException("LIST command failed: "+getReplyString()); } /** * List all newsgroups served by the NNTP server. If no newsgroups * are served, no entries will be returned. * <p> * @return An iterable of Strings containing the raw information * for each newsgroup served by the NNTP server. If no newsgroups * are served, no entries will be returned. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * @since 3.0 */ public Iterable<NewsgroupInfo> iterateNewsgroups() throws IOException { return new NewsgroupIterator(iterateNewsgroupListing()); } /** * List the newsgroups that match a given pattern. * Uses the LIST ACTIVE command. * <p> * @param wildmat a pseudo-regex pattern (cf. RFC 2980) * @return An array of NewsgroupInfo instances containing the information * for each newsgroup served by the NNTP server corresponding to the * supplied pattern. If no such newsgroups are served, a zero length * array will be returned. If the command fails, null will be returned. * @throws IOException * @see #iterateNewsgroupListing(String) * @see #iterateNewsgroups(String) */ public NewsgroupInfo[] listNewsgroups(String wildmat) throws IOException { if(!NNTPReply.isPositiveCompletion(listActive(wildmat))) return null; return __readNewsgroupListing(); } /** * List the newsgroups that match a given pattern. * Uses the LIST ACTIVE command. * <p> * @param wildmat a pseudo-regex pattern (cf. RFC 2980) * @return An iterable of Strings containing the raw information * for each newsgroup served by the NNTP server corresponding to the * supplied pattern. If no such newsgroups are served, no entries * will be returned. * @throws IOException * @since 3.0 */ public Iterable<String> iterateNewsgroupListing(String wildmat) throws IOException { if(NNTPReply.isPositiveCompletion(listActive(wildmat))) { return new ReplyIterator(_reader_); } throw new IOException("LIST ACTIVE "+wildmat+" command failed: "+getReplyString()); } /** * List the newsgroups that match a given pattern. * Uses the LIST ACTIVE command. * <p> * @param wildmat a pseudo-regex pattern (cf. RFC 2980) * @return An iterable NewsgroupInfo instances containing the information * for each newsgroup served by the NNTP server corresponding to the * supplied pattern. If no such newsgroups are served, no entries * will be returned. * @throws IOException * @since 3.0 */ public Iterable<NewsgroupInfo> iterateNewsgroups(String wildmat) throws IOException { return new NewsgroupIterator(iterateNewsgroupListing(wildmat)); } /*** * List all new newsgroups added to the NNTP server since a particular * date subject to the conditions of the specified query. If no new * newsgroups were added, a zero length array will be returned. If the * command fails, null will be returned. * <p> * @param query The query restricting how to search for new newsgroups. * @return An array of NewsgroupInfo instances containing the information * for each new newsgroup added to the NNTP server. If no newsgroups * were added, a zero length array will be returned. If the command * fails, null will be returned. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * @see #iterateNewNewsgroups(NewGroupsOrNewsQuery) * @see #iterateNewNewsgroupListing(NewGroupsOrNewsQuery) ***/ public NewsgroupInfo[] listNewNewsgroups(NewGroupsOrNewsQuery query) throws IOException { if (!NNTPReply.isPositiveCompletion(newgroups( query.getDate(), query.getTime(), query.isGMT(), query.getDistributions()))) return null; return __readNewsgroupListing(); } /** * List all new newsgroups added to the NNTP server since a particular * date subject to the conditions of the specified query. If no new * newsgroups were added, no entries will be returned. * <p> * @param query The query restricting how to search for new newsgroups. * @return An iterable of Strings containing the raw information * for each new newsgroup added to the NNTP server. If no newsgroups * were added, no entries will be returned. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * @since 3.0 */ public Iterable<String> iterateNewNewsgroupListing(NewGroupsOrNewsQuery query) throws IOException { if (NNTPReply.isPositiveCompletion(newgroups( query.getDate(), query.getTime(), query.isGMT(), query.getDistributions()))) { return new ReplyIterator(_reader_); } throw new IOException("NEWSGROUPS command failed: "+getReplyString()); } /** * List all new newsgroups added to the NNTP server since a particular * date subject to the conditions of the specified query. If no new * newsgroups were added, no entries will be returned. * <p> * @param query The query restricting how to search for new newsgroups. * @return An iterable of NewsgroupInfo instances containing the information * for each new newsgroup added to the NNTP server. If no newsgroups * were added, no entries will be returned. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * @since 3.0 */ public Iterable<NewsgroupInfo> iterateNewNewsgroups(NewGroupsOrNewsQuery query) throws IOException { return new NewsgroupIterator(iterateNewNewsgroupListing(query)); } /*** * List all new articles added to the NNTP server since a particular * date subject to the conditions of the specified query. If no new * new news is found, a zero length array will be returned. If the * command fails, null will be returned. You must add at least one * newsgroup to the query, else the command will fail. Each String * in the returned array is a unique message identifier including the * enclosing &lt and &gt. * <p> * @param query The query restricting how to search for new news. You * must add at least one newsgroup to the query. * @return An array of String instances containing the unique message * identifiers for each new article added to the NNTP server. If no * new news is found, a zero length array will be returned. If the * command fails, null will be returned. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * * @see #iterateNewNews(NewGroupsOrNewsQuery) ***/ public String[] listNewNews(NewGroupsOrNewsQuery query) throws IOException { int size; String line; Vector<String> list; String[] result; BufferedReader reader; if (!NNTPReply.isPositiveCompletion(newnews( query.getNewsgroups(), query.getDate(), query.getTime(), query.isGMT(), query.getDistributions()))) return null; list = new Vector<String>(); reader = new BufferedReader(new DotTerminatedMessageReader(_reader_)); while ((line = reader.readLine()) != null) list.addElement(line); size = list.size(); if (size < 1) return new String[0]; result = new String[size]; list.copyInto(result); return result; } /** * List all new articles added to the NNTP server since a particular * date subject to the conditions of the specified query. If no new * new news is found, no entries will be returned. * This uses the "NEWNEWS" command. * You must add at least one newsgroup to the query, else the command will fail. * Each String which is returned is a unique message identifier including the * enclosing &lt and &gt. * <p> * @param query The query restricting how to search for new news. You * must add at least one newsgroup to the query. * @return An iterator of String instances containing the unique message * identifiers for each new article added to the NNTP server. If no * new news is found, no strings will be returned. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * @since 3.0 */ public Iterable<String> iterateNewNews(NewGroupsOrNewsQuery query) throws IOException { if (NNTPReply.isPositiveCompletion(newnews( query.getNewsgroups(), query.getDate(), query.getTime(), query.isGMT(), query.getDistributions()))) { return new ReplyIterator(_reader_); } throw new IOException("NEWNEWS command failed: "+getReplyString()); } /*** * There are a few NNTPClient methods that do not complete the * entire sequence of NNTP commands to complete a transaction. These * commands require some action by the programmer after the reception * of a positive preliminary command. After the programmer's code * completes its actions, it must call this method to receive * the completion reply from the server and verify the success of the * entire transaction. * <p> * For example * <pre> * writer = client.postArticle(); * if(writer == null) // failure * return false; * header = new SimpleNNTPHeader("[email protected]", "Just testing"); * header.addNewsgroup("alt.test"); * writer.write(header.toString()); * writer.write("This is just a test"); * writer.close(); * if(!client.completePendingCommand()) // failure * return false; * </pre> * <p> * @return True if successfully completed, false if not. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean completePendingCommand() throws IOException { return NNTPReply.isPositiveCompletion(getReply()); } /*** * Post an article to the NNTP server. This method returns a * DotTerminatedMessageWriter instance to which the article can be * written. Null is returned if the posting attempt fails. You * should check {@link NNTP#isAllowedToPost isAllowedToPost() } * before trying to post. However, a posting * attempt can fail due to malformed headers. * <p> * You must not issue any commands to the NNTP server (i.e., call any * (other methods) until you finish writing to the returned Writer * instance and close it. The NNTP protocol uses the same stream for * issuing commands as it does for returning results. Therefore the * returned Writer actually writes directly to the NNTP connection. * After you close the writer, you can execute new commands. If you * do not follow these requirements your program will not work properly. * <p> * Different NNTP servers will require different header formats, but * you can use the provided * {@link org.apache.commons.net.nntp.SimpleNNTPHeader} * class to construct the bare minimum acceptable header for most * news readers. To construct more complicated headers you should * refer to RFC 822. When the Java Mail API is finalized, you will be * able to use it to compose fully compliant Internet text messages. * The DotTerminatedMessageWriter takes care of doubling line-leading * dots and ending the message with a single dot upon closing, so all * you have to worry about is writing the header and the message. * <p> * Upon closing the returned Writer, you need to call * {@link #completePendingCommand completePendingCommand() } * to finalize the posting and verify its success or failure from * the server reply. * <p> * @return A DotTerminatedMessageWriter to which the article (including * header) can be written. Returns null if the command fails. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public Writer postArticle() throws IOException { if (!NNTPReply.isPositiveIntermediate(post())) return null; return new DotTerminatedMessageWriter(_writer_); } public Writer forwardArticle(String articleId) throws IOException { if (!NNTPReply.isPositiveIntermediate(ihave(articleId))) return null; return new DotTerminatedMessageWriter(_writer_); } /*** * Logs out of the news server gracefully by sending the QUIT command. * However, you must still disconnect from the server before you can open * a new connection. * <p> * @return True if successfully completed, false if not. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean logout() throws IOException { return NNTPReply.isPositiveCompletion(quit()); } /** * Log into a news server by sending the AUTHINFO USER/AUTHINFO * PASS command sequence. This is usually sent in response to a * 480 reply code from the NNTP server. * <p> * @param username a valid username * @param password the corresponding password * @return True for successful login, false for a failure * @throws IOException */ public boolean authenticate(String username, String password) throws IOException { int replyCode = authinfoUser(username); if (replyCode == NNTPReply.MORE_AUTH_INFO_REQUIRED) { replyCode = authinfoPass(password); if (replyCode == NNTPReply.AUTHENTICATION_ACCEPTED) { _isAllowedToPost = true; return true; } } return false; } /*** * Private implementation of XOVER functionality. * * See {@link NNTP#xover} * for legal agument formats. Alternatively, read RFC 2980 :-) * <p> * @param articleRange * @return Returns a DotTerminatedMessageReader if successful, null * otherwise * @exception IOException */ private Reader __retrieveArticleInfo(String articleRange) throws IOException { if (!NNTPReply.isPositiveCompletion(xover(articleRange))) return null; return new DotTerminatedMessageReader(_reader_); } /** * Return article headers for a specified post. * <p> * @param articleNumber the article to retrieve headers for * @return a DotTerminatedReader if successful, null otherwise * @throws IOException */ public Reader retrieveArticleInfo(int articleNumber) throws IOException { return __retrieveArticleInfo(Integer.toString(articleNumber)); } /** * Return article headers for all articles between lowArticleNumber * and highArticleNumber, inclusively. Uses the XOVER command. * <p> * @param lowArticleNumber * @param highArticleNumber * @return a DotTerminatedReader if successful, null otherwise * @throws IOException */ public Reader retrieveArticleInfo(long lowArticleNumber, long highArticleNumber) throws IOException { return __retrieveArticleInfo(lowArticleNumber + "-" + highArticleNumber); } /** * Return article headers for all articles between lowArticleNumber * and highArticleNumber, inclusively, using the XOVER command. * <p> * @param lowArticleNumber * @param highArticleNumber * @return an Iterable of Articles * @throws IOException if the command failed * @since 3.0 */ public Iterable<Article> iterateArticleInfo(long lowArticleNumber, long highArticleNumber) throws IOException { Reader info = retrieveArticleInfo(lowArticleNumber,highArticleNumber); if (info == null) { throw new IOException("XOVER command failed: "+getReplyString()); } // N.B. info is already DotTerminated, so don't rewrap return new ArticleIterator(new ReplyIterator(info, false)); } /*** * Private implementation of XHDR functionality. * * See {@link NNTP#xhdr} * for legal agument formats. Alternatively, read RFC 1036. * <p> * @param header * @param articleRange * @return Returns a DotTerminatedMessageReader if successful, null * otherwise * @exception IOException */ private Reader __retrieveHeader(String header, String articleRange) throws IOException { if (!NNTPReply.isPositiveCompletion(xhdr(header, articleRange))) return null; return new DotTerminatedMessageReader(_reader_); } /** * Return an article header for a specified post. * <p> * @param header the header to retrieve * @param articleNumber the article to retrieve the header for * @return a DotTerminatedReader if successful, null otherwise * @throws IOException */ public Reader retrieveHeader(String header, long articleNumber) throws IOException { return __retrieveHeader(header, Long.toString(articleNumber)); } /** * Return an article header for all articles between lowArticleNumber * and highArticleNumber, inclusively. * <p> * @param header * @param lowArticleNumber * @param highArticleNumber * @return a DotTerminatedReader if successful, null otherwise * @throws IOException */ public Reader retrieveHeader(String header, int lowArticleNumber, int highArticleNumber) throws IOException { return __retrieveHeader(header,lowArticleNumber + "-" + highArticleNumber); } } /* Emacs configuration * Local variables: ** * mode: java ** * c-basic-offset: 4 ** * indent-tabs-mode: nil ** * End: ** */
src/main/java/org/apache/commons/net/nntp/NNTPClient.java
/* * 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.net.nntp; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Vector; import org.apache.commons.net.MalformedServerReplyException; import org.apache.commons.net.io.DotTerminatedMessageReader; import org.apache.commons.net.io.DotTerminatedMessageWriter; import org.apache.commons.net.io.Util; /*** * NNTPClient encapsulates all the functionality necessary to post and * retrieve articles from an NNTP server. As with all classes derived * from {@link org.apache.commons.net.SocketClient}, * you must first connect to the server with * {@link org.apache.commons.net.SocketClient#connect connect } * before doing anything, and finally * {@link org.apache.commons.net.nntp.NNTP#disconnect disconnect() } * after you're completely finished interacting with the server. * Remember that the * {@link org.apache.commons.net.nntp.NNTP#isAllowedToPost isAllowedToPost()} * method is defined in * {@link org.apache.commons.net.nntp.NNTP}. * <p> * You should keep in mind that the NNTP server may choose to prematurely * close a connection if the client has been idle for longer than a * given time period or if the server is being shutdown by the operator or * some other reason. The NNTP class will detect a * premature NNTP server connection closing when it receives a * {@link org.apache.commons.net.nntp.NNTPReply#SERVICE_DISCONTINUED NNTPReply.SERVICE_DISCONTINUED } * response to a command. * When that occurs, the NNTP class method encountering that reply will throw * an {@link org.apache.commons.net.nntp.NNTPConnectionClosedException} * . * <code>NNTPConectionClosedException</code> * is a subclass of <code> IOException </code> and therefore need not be * caught separately, but if you are going to catch it separately, its * catch block must appear before the more general <code> IOException </code> * catch block. When you encounter an * {@link org.apache.commons.net.nntp.NNTPConnectionClosedException} * , you must disconnect the connection with * {@link org.apache.commons.net.nntp.NNTP#disconnect disconnect() } * to properly clean up the * system resources used by NNTP. Before disconnecting, you may check the * last reply code and text with * {@link org.apache.commons.net.nntp.NNTP#getReplyCode getReplyCode } and * {@link org.apache.commons.net.nntp.NNTP#getReplyString getReplyString }. * <p> * Rather than list it separately for each method, we mention here that * every method communicating with the server and throwing an IOException * can also throw a * {@link org.apache.commons.net.MalformedServerReplyException} * , which is a subclass * of IOException. A MalformedServerReplyException will be thrown when * the reply received from the server deviates enough from the protocol * specification that it cannot be interpreted in a useful manner despite * attempts to be as lenient as possible. * <p> * <p> * @author Daniel F. Savarese * @author Rory Winston * @author Ted Wise * @see NNTP * @see NNTPConnectionClosedException * @see org.apache.commons.net.MalformedServerReplyException ***/ public class NNTPClient extends NNTP { // reply will consist of 22n nnn <aaa> private void __parseArticlePointer(String reply, ArticlePointer pointer) throws MalformedServerReplyException { String tokens[] = reply.split(" "); if (tokens.length >= 3) { // OK, we can parset the line int i = 1; // skip reply code try { // Get article number pointer.articleNumber = Long.parseLong(tokens[i++]); // Get article id pointer.articleId = tokens[i++]; return; // done } catch (NumberFormatException e) { // drop through and raise exception } } throw new MalformedServerReplyException( "Could not parse article pointer.\nServer reply: " + reply); } /* * 211 n f l s group selected * (n = estimated number of articles in group, * f = first article number in the group, * l = last article number in the group, * s = name of the group.) */ private static void __parseGroupReply(String reply, NewsgroupInfo info) throws MalformedServerReplyException { String tokens[] = reply.split(" "); if (tokens.length >= 5) { int i = 1; // Skip numeric response value try { // Get estimated article count info._setArticleCount(Long.parseLong(tokens[i++])); // Get first article number info._setFirstArticle(Long.parseLong(tokens[i++])); // Get last article number info._setLastArticle(Long.parseLong(tokens[i++])); // Get newsgroup name info._setNewsgroup(tokens[i++]); info._setPostingPermission(NewsgroupInfo.UNKNOWN_POSTING_PERMISSION); return ; } catch (NumberFormatException e) { // drop through to report error } } throw new MalformedServerReplyException( "Could not parse newsgroup info.\nServer reply: " + reply); } // Format: group last first p static NewsgroupInfo __parseNewsgroupListEntry(String entry) { String tokens[] = entry.split(" "); if (tokens.length < 4) { return null; } NewsgroupInfo result = new NewsgroupInfo(); int i = 0; result._setNewsgroup(tokens[i++]); try { long lastNum = Long.parseLong(tokens[i++]); long firstNum = Long.parseLong(tokens[i++]); result._setFirstArticle(firstNum); result._setLastArticle(lastNum); if((firstNum == 0) && (lastNum == 0)) result._setArticleCount(0); else result._setArticleCount(lastNum - firstNum + 1); } catch (NumberFormatException e) { return null; } switch (tokens[i++].charAt(0)) { case 'y': case 'Y': result._setPostingPermission( NewsgroupInfo.PERMITTED_POSTING_PERMISSION); break; case 'n': case 'N': result._setPostingPermission( NewsgroupInfo.PROHIBITED_POSTING_PERMISSION); break; case 'm': case 'M': result._setPostingPermission( NewsgroupInfo.MODERATED_POSTING_PERMISSION); break; default: result._setPostingPermission( NewsgroupInfo.UNKNOWN_POSTING_PERMISSION); break; } return result; } /** * Parse a response line from {@link #retrieveArticleInfo(long, long)}. * * @param line a response line * @return the parsed {@link Article}, if unparseable then isDummy() * will be true, and the subject will contain the raw info. * @since 3.0 */ static Article __parseArticleEntry(String line) { // Extract the article information // Mandatory format (from NNTP RFC 2980) is : // articleNumber\tSubject\tAuthor\tDate\tID\tReference(s)\tByte Count\tLine Count Article article = new Article(); article.setSubject(line); // in case parsing fails String parts[] = line.split("\t"); if (parts.length > 6) { int i = 0; try { article.setArticleNumber(Long.parseLong(parts[i++])); article.setSubject(parts[i++]); article.setFrom(parts[i++]); article.setDate(parts[i++]); article.setArticleId(parts[i++]); article.addReference(parts[i++]); } catch (NumberFormatException e) { // ignored, already handled } } return article; } private NewsgroupInfo[] __readNewsgroupListing() throws IOException { int size; String line; Vector<NewsgroupInfo> list; BufferedReader reader; NewsgroupInfo tmp, info[]; reader = new BufferedReader(new DotTerminatedMessageReader(_reader_)); // Start of with a big vector because we may be reading a very large // amount of groups. list = new Vector<NewsgroupInfo>(2048); while ((line = reader.readLine()) != null) { tmp = __parseNewsgroupListEntry(line); if (tmp != null) list.addElement(tmp); else throw new MalformedServerReplyException(line); } if ((size = list.size()) < 1) return new NewsgroupInfo[0]; info = new NewsgroupInfo[size]; list.copyInto(info); return info; } private Reader __retrieve(int command, String articleId, ArticlePointer pointer) throws IOException { Reader reader; if (articleId != null) { if (!NNTPReply.isPositiveCompletion(sendCommand(command, articleId))) return null; } else { if (!NNTPReply.isPositiveCompletion(sendCommand(command))) return null; } if (pointer != null) __parseArticlePointer(getReplyString(), pointer); reader = new DotTerminatedMessageReader(_reader_); return reader; } private Reader __retrieve(int command, int articleNumber, ArticlePointer pointer) throws IOException { Reader reader; if (!NNTPReply.isPositiveCompletion(sendCommand(command, Integer.toString(articleNumber)))) return null; if (pointer != null) __parseArticlePointer(getReplyString(), pointer); reader = new DotTerminatedMessageReader(_reader_); return reader; } /*** * Retrieves an article from the NNTP server. The article is referenced * by its unique article identifier (including the enclosing &lt and &gt). * The article number and identifier contained in the server reply * are returned through an ArticlePointer. The <code> articleId </code> * field of the ArticlePointer cannot always be trusted because some * NNTP servers do not correctly follow the RFC 977 reply format. * <p> * A DotTerminatedMessageReader is returned from which the article can * be read. If the article does not exist, null is returned. * <p> * You must not issue any commands to the NNTP server (i.e., call any * other methods) until you finish reading the message from the returned * Reader instance. * The NNTP protocol uses the same stream for issuing commands as it does * for returning results. Therefore the returned Reader actually reads * directly from the NNTP connection. After the end of message has been * reached, new commands can be executed and their replies read. If * you do not follow these requirements, your program will not work * properly. * <p> * @param articleId The unique article identifier of the article to * retrieve. If this parameter is null, the currently selected * article is retrieved. * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return A DotTerminatedMessageReader instance from which the article * be read. null if the article does not exist. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public Reader retrieveArticle(String articleId, ArticlePointer pointer) throws IOException { return __retrieve(NNTPCommand.ARTICLE, articleId, pointer); } /*** Same as <code> retrieveArticle(articleId, null) </code> ***/ public Reader retrieveArticle(String articleId) throws IOException { return retrieveArticle(articleId, null); } /*** Same as <code> retrieveArticle(null) </code> ***/ public Reader retrieveArticle() throws IOException { return retrieveArticle(null); } /*** * Retrieves an article from the currently selected newsgroup. The * article is referenced by its article number. * The article number and identifier contained in the server reply * are returned through an ArticlePointer. The <code> articleId </code> * field of the ArticlePointer cannot always be trusted because some * NNTP servers do not correctly follow the RFC 977 reply format. * <p> * A DotTerminatedMessageReader is returned from which the article can * be read. If the article does not exist, null is returned. * <p> * You must not issue any commands to the NNTP server (i.e., call any * other methods) until you finish reading the message from the returned * Reader instance. * The NNTP protocol uses the same stream for issuing commands as it does * for returning results. Therefore the returned Reader actually reads * directly from the NNTP connection. After the end of message has been * reached, new commands can be executed and their replies read. If * you do not follow these requirements, your program will not work * properly. * <p> * @param articleNumber The number of the the article to * retrieve. * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return A DotTerminatedMessageReader instance from which the article * be read. null if the article does not exist. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public Reader retrieveArticle(int articleNumber, ArticlePointer pointer) throws IOException { return __retrieve(NNTPCommand.ARTICLE, articleNumber, pointer); } /*** Same as <code> retrieveArticle(articleNumber, null) </code> ***/ public Reader retrieveArticle(int articleNumber) throws IOException { return retrieveArticle(articleNumber, null); } /*** * Retrieves an article header from the NNTP server. The article is * referenced * by its unique article identifier (including the enclosing &lt and &gt). * The article number and identifier contained in the server reply * are returned through an ArticlePointer. The <code> articleId </code> * field of the ArticlePointer cannot always be trusted because some * NNTP servers do not correctly follow the RFC 977 reply format. * <p> * A DotTerminatedMessageReader is returned from which the article can * be read. If the article does not exist, null is returned. * <p> * You must not issue any commands to the NNTP server (i.e., call any * other methods) until you finish reading the message from the returned * Reader instance. * The NNTP protocol uses the same stream for issuing commands as it does * for returning results. Therefore the returned Reader actually reads * directly from the NNTP connection. After the end of message has been * reached, new commands can be executed and their replies read. If * you do not follow these requirements, your program will not work * properly. * <p> * @param articleId The unique article identifier of the article whose * header is being retrieved. If this parameter is null, the * header of the currently selected article is retrieved. * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return A DotTerminatedMessageReader instance from which the article * header can be read. null if the article does not exist. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public Reader retrieveArticleHeader(String articleId, ArticlePointer pointer) throws IOException { return __retrieve(NNTPCommand.HEAD, articleId, pointer); } /*** Same as <code> retrieveArticleHeader(articleId, null) </code> ***/ public Reader retrieveArticleHeader(String articleId) throws IOException { return retrieveArticleHeader(articleId, null); } /*** Same as <code> retrieveArticleHeader(null) </code> ***/ public Reader retrieveArticleHeader() throws IOException { return retrieveArticleHeader(null); } /*** * Retrieves an article header from the currently selected newsgroup. The * article is referenced by its article number. * The article number and identifier contained in the server reply * are returned through an ArticlePointer. The <code> articleId </code> * field of the ArticlePointer cannot always be trusted because some * NNTP servers do not correctly follow the RFC 977 reply format. * <p> * A DotTerminatedMessageReader is returned from which the article can * be read. If the article does not exist, null is returned. * <p> * You must not issue any commands to the NNTP server (i.e., call any * other methods) until you finish reading the message from the returned * Reader instance. * The NNTP protocol uses the same stream for issuing commands as it does * for returning results. Therefore the returned Reader actually reads * directly from the NNTP connection. After the end of message has been * reached, new commands can be executed and their replies read. If * you do not follow these requirements, your program will not work * properly. * <p> * @param articleNumber The number of the the article whose header is * being retrieved. * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return A DotTerminatedMessageReader instance from which the article * header can be read. null if the article does not exist. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public Reader retrieveArticleHeader(int articleNumber, ArticlePointer pointer) throws IOException { return __retrieve(NNTPCommand.HEAD, articleNumber, pointer); } /*** Same as <code> retrieveArticleHeader(articleNumber, null) </code> ***/ public Reader retrieveArticleHeader(int articleNumber) throws IOException { return retrieveArticleHeader(articleNumber, null); } /*** * Retrieves an article body from the NNTP server. The article is * referenced * by its unique article identifier (including the enclosing &lt and &gt). * The article number and identifier contained in the server reply * are returned through an ArticlePointer. The <code> articleId </code> * field of the ArticlePointer cannot always be trusted because some * NNTP servers do not correctly follow the RFC 977 reply format. * <p> * A DotTerminatedMessageReader is returned from which the article can * be read. If the article does not exist, null is returned. * <p> * You must not issue any commands to the NNTP server (i.e., call any * other methods) until you finish reading the message from the returned * Reader instance. * The NNTP protocol uses the same stream for issuing commands as it does * for returning results. Therefore the returned Reader actually reads * directly from the NNTP connection. After the end of message has been * reached, new commands can be executed and their replies read. If * you do not follow these requirements, your program will not work * properly. * <p> * @param articleId The unique article identifier of the article whose * body is being retrieved. If this parameter is null, the * body of the currently selected article is retrieved. * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return A DotTerminatedMessageReader instance from which the article * body can be read. null if the article does not exist. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public Reader retrieveArticleBody(String articleId, ArticlePointer pointer) throws IOException { return __retrieve(NNTPCommand.BODY, articleId, pointer); } /*** Same as <code> retrieveArticleBody(articleId, null) </code> ***/ public Reader retrieveArticleBody(String articleId) throws IOException { return retrieveArticleBody(articleId, null); } /*** Same as <code> retrieveArticleBody(null) </code> ***/ public Reader retrieveArticleBody() throws IOException { return retrieveArticleBody(null); } /*** * Retrieves an article body from the currently selected newsgroup. The * article is referenced by its article number. * The article number and identifier contained in the server reply * are returned through an ArticlePointer. The <code> articleId </code> * field of the ArticlePointer cannot always be trusted because some * NNTP servers do not correctly follow the RFC 977 reply format. * <p> * A DotTerminatedMessageReader is returned from which the article can * be read. If the article does not exist, null is returned. * <p> * You must not issue any commands to the NNTP server (i.e., call any * other methods) until you finish reading the message from the returned * Reader instance. * The NNTP protocol uses the same stream for issuing commands as it does * for returning results. Therefore the returned Reader actually reads * directly from the NNTP connection. After the end of message has been * reached, new commands can be executed and their replies read. If * you do not follow these requirements, your program will not work * properly. * <p> * @param articleNumber The number of the the article whose body is * being retrieved. * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return A DotTerminatedMessageReader instance from which the article * body can be read. null if the article does not exist. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public Reader retrieveArticleBody(int articleNumber, ArticlePointer pointer) throws IOException { return __retrieve(NNTPCommand.BODY, articleNumber, pointer); } /*** Same as <code> retrieveArticleBody(articleNumber, null) </code> ***/ public Reader retrieveArticleBody(int articleNumber) throws IOException { return retrieveArticleBody(articleNumber, null); } /*** * Select the specified newsgroup to be the target of for future article * retrieval and posting operations. Also return the newsgroup * information contained in the server reply through the info parameter. * <p> * @param newsgroup The newsgroup to select. * @param info A parameter through which the newsgroup information of * the selected newsgroup contained in the server reply is returned. * Set this to null if you do not desire this information. * @return True if the newsgroup exists and was selected, false otherwise. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean selectNewsgroup(String newsgroup, NewsgroupInfo info) throws IOException { if (!NNTPReply.isPositiveCompletion(group(newsgroup))) return false; if (info != null) __parseGroupReply(getReplyString(), info); return true; } /*** Same as <code> selectNewsgroup(newsgroup, null) </code> ***/ public boolean selectNewsgroup(String newsgroup) throws IOException { return selectNewsgroup(newsgroup, null); } /*** * List the command help from the server. * <p> * @return The sever help information. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public String listHelp() throws IOException { StringWriter help; Reader reader; if (!NNTPReply.isInformational(help())) return null; help = new StringWriter(); reader = new DotTerminatedMessageReader(_reader_); Util.copyReader(reader, help); reader.close(); help.close(); return help.toString(); } /** * Send a "LIST OVERVIEW.FMT" command to the server. * * @return the contents of the Overview format, of {@code null} if the command failed * @throws IOException */ public String[] listOverviewFmt() throws IOException { if (!NNTPReply.isPositiveCompletion(sendCommand("LIST", "OVERVIEW.FMT"))){ return null; } BufferedReader reader = new BufferedReader(new DotTerminatedMessageReader(_reader_)); String line; ArrayList<String> list = new ArrayList<String>(); while((line=reader.readLine()) != null) { list.add(line); } reader.close(); return list.toArray(new String[list.size()]); } /*** * Select an article by its unique identifier (including enclosing * &lt and &gt) and return its article number and id through the * pointer parameter. This is achieved through the STAT command. * According to RFC 977, this will NOT set the current article pointer * on the server. To do that, you must reference the article by its * number. * <p> * @param articleId The unique article identifier of the article that * is being selectedd. If this parameter is null, the * body of the current article is selected * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return True if successful, false if not. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean selectArticle(String articleId, ArticlePointer pointer) throws IOException { if (articleId != null) { if (!NNTPReply.isPositiveCompletion(stat(articleId))) return false; } else { if (!NNTPReply.isPositiveCompletion(stat())) return false; } if (pointer != null) __parseArticlePointer(getReplyString(), pointer); return true; } /**** Same as <code> selectArticle(articleId, null) </code> ***/ public boolean selectArticle(String articleId) throws IOException { return selectArticle(articleId, null); } /**** * Same as <code> selectArticle(null, articleId) </code>. Useful * for retrieving the current article number. ***/ public boolean selectArticle(ArticlePointer pointer) throws IOException { return selectArticle(null, pointer); } /*** * Select an article in the currently selected newsgroup by its number. * and return its article number and id through the * pointer parameter. This is achieved through the STAT command. * According to RFC 977, this WILL set the current article pointer * on the server. Use this command to select an article before retrieving * it, or to obtain an article's unique identifier given its number. * <p> * @param articleNumber The number of the article to select from the * currently selected newsgroup. * @param pointer A parameter through which to return the article's * number and unique id. Although the articleId field cannot always * be trusted because of server deviations from RFC 977 reply formats, * we haven't found a server that misformats this information in response * to this particular command. You may set this parameter to null if * you do not desire to retrieve the returned article information. * @return True if successful, false if not. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean selectArticle(long articleNumber, ArticlePointer pointer) throws IOException { if (!NNTPReply.isPositiveCompletion(stat(articleNumber))) return false; if (pointer != null) __parseArticlePointer(getReplyString(), pointer); return true; } /*** Same as <code> selectArticle(articleNumber, null) </code> ***/ public boolean selectArticle(long articleNumber) throws IOException { return selectArticle(articleNumber, null); } /*** * Select the article preceeding the currently selected article in the * currently selected newsgroup and return its number and unique id * through the pointer parameter. Because of deviating server * implementations, the articleId information cannot be trusted. To * obtain the article identifier, issue a * <code> selectArticle(pointer.articleNumber, pointer) </code> immediately * afterward. * <p> * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return True if successful, false if not (e.g., there is no previous * article). * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean selectPreviousArticle(ArticlePointer pointer) throws IOException { if (!NNTPReply.isPositiveCompletion(last())) return false; if (pointer != null) __parseArticlePointer(getReplyString(), pointer); return true; } /*** Same as <code> selectPreviousArticle(null) </code> ***/ public boolean selectPreviousArticle() throws IOException { return selectPreviousArticle(null); } /*** * Select the article following the currently selected article in the * currently selected newsgroup and return its number and unique id * through the pointer parameter. Because of deviating server * implementations, the articleId information cannot be trusted. To * obtain the article identifier, issue a * <code> selectArticle(pointer.articleNumber, pointer) </code> immediately * afterward. * <p> * @param pointer A parameter through which to return the article's * number and unique id. The articleId field cannot always be trusted * because of server deviations from RFC 977 reply formats. You may * set this parameter to null if you do not desire to retrieve the * returned article information. * @return True if successful, false if not (e.g., there is no following * article). * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean selectNextArticle(ArticlePointer pointer) throws IOException { if (!NNTPReply.isPositiveCompletion(next())) return false; if (pointer != null) __parseArticlePointer(getReplyString(), pointer); return true; } /*** Same as <code> selectNextArticle(null) </code> ***/ public boolean selectNextArticle() throws IOException { return selectNextArticle(null); } /*** * List all newsgroups served by the NNTP server. If no newsgroups * are served, a zero length array will be returned. If the command * fails, null will be returned. * <p> * @return An array of NewsgroupInfo instances containing the information * for each newsgroup served by the NNTP server. If no newsgroups * are served, a zero length array will be returned. If the command * fails, null will be returned. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * @see #iterateNewsgroupListing() * @see #iterateNewsgroups() ***/ public NewsgroupInfo[] listNewsgroups() throws IOException { if (!NNTPReply.isPositiveCompletion(list())) return null; return __readNewsgroupListing(); } /** * List all newsgroups served by the NNTP server. If no newsgroups * are served, no entries will be returned. * <p> * @return An iterable of NewsgroupInfo instances containing the information * for each newsgroup served by the NNTP server. If no newsgroups * are served, no entries will be returned. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * @since 3.0 */ public Iterable<String> iterateNewsgroupListing() throws IOException { if (NNTPReply.isPositiveCompletion(list())) { return new ReplyIterator(_reader_); } throw new IOException(getReplyString()); } /** * List all newsgroups served by the NNTP server. If no newsgroups * are served, no entries will be returned. * <p> * @return An iterable of Strings containing the raw information * for each newsgroup served by the NNTP server. If no newsgroups * are served, no entries will be returned. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * @since 3.0 */ public Iterable<NewsgroupInfo> iterateNewsgroups() throws IOException { return new NewsgroupIterator(iterateNewsgroupListing()); } /** * List the newsgroups that match a given pattern. * Uses the LIST ACTIVE command. * <p> * @param wildmat a pseudo-regex pattern (cf. RFC 2980) * @return An array of NewsgroupInfo instances containing the information * for each newsgroup served by the NNTP server corresponding to the * supplied pattern. If no such newsgroups are served, a zero length * array will be returned. If the command fails, null will be returned. * @throws IOException * @see #iterateNewsgroupListing(String) * @see #iterateNewsgroups(String) */ public NewsgroupInfo[] listNewsgroups(String wildmat) throws IOException { if(!NNTPReply.isPositiveCompletion(listActive(wildmat))) return null; return __readNewsgroupListing(); } /** * List the newsgroups that match a given pattern. * Uses the LIST ACTIVE command. * <p> * @param wildmat a pseudo-regex pattern (cf. RFC 2980) * @return An iterable of Strings containing the raw information * for each newsgroup served by the NNTP server corresponding to the * supplied pattern. If no such newsgroups are served, no entries * will be returned. * @throws IOException * @since 3.0 */ public Iterable<String> iterateNewsgroupListing(String wildmat) throws IOException { if(NNTPReply.isPositiveCompletion(listActive(wildmat))) { return new ReplyIterator(_reader_); } throw new IOException(getReplyString()); } /** * List the newsgroups that match a given pattern. * Uses the LIST ACTIVE command. * <p> * @param wildmat a pseudo-regex pattern (cf. RFC 2980) * @return An iterable NewsgroupInfo instances containing the information * for each newsgroup served by the NNTP server corresponding to the * supplied pattern. If no such newsgroups are served, no entries * will be returned. * @throws IOException * @since 3.0 */ public Iterable<NewsgroupInfo> iterateNewsgroups(String wildmat) throws IOException { return new NewsgroupIterator(iterateNewsgroupListing(wildmat)); } /*** * List all new newsgroups added to the NNTP server since a particular * date subject to the conditions of the specified query. If no new * newsgroups were added, a zero length array will be returned. If the * command fails, null will be returned. * <p> * @param query The query restricting how to search for new newsgroups. * @return An array of NewsgroupInfo instances containing the information * for each new newsgroup added to the NNTP server. If no newsgroups * were added, a zero length array will be returned. If the command * fails, null will be returned. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * @see #iterateNewNewsgroups(NewGroupsOrNewsQuery) * @see #iterateNewNewsgroupListing(NewGroupsOrNewsQuery) ***/ public NewsgroupInfo[] listNewNewsgroups(NewGroupsOrNewsQuery query) throws IOException { if (!NNTPReply.isPositiveCompletion(newgroups( query.getDate(), query.getTime(), query.isGMT(), query.getDistributions()))) return null; return __readNewsgroupListing(); } /** * List all new newsgroups added to the NNTP server since a particular * date subject to the conditions of the specified query. If no new * newsgroups were added, no entries will be returned. * <p> * @param query The query restricting how to search for new newsgroups. * @return An iterable of Strings containing the raw information * for each new newsgroup added to the NNTP server. If no newsgroups * were added, no entries will be returned. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * @since 3.0 */ public Iterable<String> iterateNewNewsgroupListing(NewGroupsOrNewsQuery query) throws IOException { if (NNTPReply.isPositiveCompletion(newgroups( query.getDate(), query.getTime(), query.isGMT(), query.getDistributions()))) { return new ReplyIterator(_reader_); } throw new IOException(getReplyString()); } /** * List all new newsgroups added to the NNTP server since a particular * date subject to the conditions of the specified query. If no new * newsgroups were added, no entries will be returned. * <p> * @param query The query restricting how to search for new newsgroups. * @return An iterable of NewsgroupInfo instances containing the information * for each new newsgroup added to the NNTP server. If no newsgroups * were added, no entries will be returned. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * @since 3.0 */ public Iterable<NewsgroupInfo> iterateNewNewsgroups(NewGroupsOrNewsQuery query) throws IOException { return new NewsgroupIterator(iterateNewNewsgroupListing(query)); } /*** * List all new articles added to the NNTP server since a particular * date subject to the conditions of the specified query. If no new * new news is found, a zero length array will be returned. If the * command fails, null will be returned. You must add at least one * newsgroup to the query, else the command will fail. Each String * in the returned array is a unique message identifier including the * enclosing &lt and &gt. * <p> * @param query The query restricting how to search for new news. You * must add at least one newsgroup to the query. * @return An array of String instances containing the unique message * identifiers for each new article added to the NNTP server. If no * new news is found, a zero length array will be returned. If the * command fails, null will be returned. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * * @see #iterateNewNews(NewGroupsOrNewsQuery) ***/ public String[] listNewNews(NewGroupsOrNewsQuery query) throws IOException { int size; String line; Vector<String> list; String[] result; BufferedReader reader; if (!NNTPReply.isPositiveCompletion(newnews( query.getNewsgroups(), query.getDate(), query.getTime(), query.isGMT(), query.getDistributions()))) return null; list = new Vector<String>(); reader = new BufferedReader(new DotTerminatedMessageReader(_reader_)); while ((line = reader.readLine()) != null) list.addElement(line); size = list.size(); if (size < 1) return new String[0]; result = new String[size]; list.copyInto(result); return result; } /** * List all new articles added to the NNTP server since a particular * date subject to the conditions of the specified query. If no new * new news is found, no entries will be returned. * You must add at least one newsgroup to the query, else the command will fail. * Each String which is returned is a unique message identifier including the * enclosing &lt and &gt. * <p> * @param query The query restricting how to search for new news. You * must add at least one newsgroup to the query. * @return An iterator of String instances containing the unique message * identifiers for each new article added to the NNTP server. If no * new news is found, no strings will be returned. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * @since 3.0 */ public Iterable<String> iterateNewNews(NewGroupsOrNewsQuery query) throws IOException { if (NNTPReply.isPositiveCompletion(newnews( query.getNewsgroups(), query.getDate(), query.getTime(), query.isGMT(), query.getDistributions()))) { return new ReplyIterator(_reader_); } throw new IOException(getReplyString()); } /*** * There are a few NNTPClient methods that do not complete the * entire sequence of NNTP commands to complete a transaction. These * commands require some action by the programmer after the reception * of a positive preliminary command. After the programmer's code * completes its actions, it must call this method to receive * the completion reply from the server and verify the success of the * entire transaction. * <p> * For example * <pre> * writer = client.postArticle(); * if(writer == null) // failure * return false; * header = new SimpleNNTPHeader("[email protected]", "Just testing"); * header.addNewsgroup("alt.test"); * writer.write(header.toString()); * writer.write("This is just a test"); * writer.close(); * if(!client.completePendingCommand()) // failure * return false; * </pre> * <p> * @return True if successfully completed, false if not. * @exception NNTPConnectionClosedException * If the NNTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send NNTP reply code 400. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean completePendingCommand() throws IOException { return NNTPReply.isPositiveCompletion(getReply()); } /*** * Post an article to the NNTP server. This method returns a * DotTerminatedMessageWriter instance to which the article can be * written. Null is returned if the posting attempt fails. You * should check {@link NNTP#isAllowedToPost isAllowedToPost() } * before trying to post. However, a posting * attempt can fail due to malformed headers. * <p> * You must not issue any commands to the NNTP server (i.e., call any * (other methods) until you finish writing to the returned Writer * instance and close it. The NNTP protocol uses the same stream for * issuing commands as it does for returning results. Therefore the * returned Writer actually writes directly to the NNTP connection. * After you close the writer, you can execute new commands. If you * do not follow these requirements your program will not work properly. * <p> * Different NNTP servers will require different header formats, but * you can use the provided * {@link org.apache.commons.net.nntp.SimpleNNTPHeader} * class to construct the bare minimum acceptable header for most * news readers. To construct more complicated headers you should * refer to RFC 822. When the Java Mail API is finalized, you will be * able to use it to compose fully compliant Internet text messages. * The DotTerminatedMessageWriter takes care of doubling line-leading * dots and ending the message with a single dot upon closing, so all * you have to worry about is writing the header and the message. * <p> * Upon closing the returned Writer, you need to call * {@link #completePendingCommand completePendingCommand() } * to finalize the posting and verify its success or failure from * the server reply. * <p> * @return A DotTerminatedMessageWriter to which the article (including * header) can be written. Returns null if the command fails. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public Writer postArticle() throws IOException { if (!NNTPReply.isPositiveIntermediate(post())) return null; return new DotTerminatedMessageWriter(_writer_); } public Writer forwardArticle(String articleId) throws IOException { if (!NNTPReply.isPositiveIntermediate(ihave(articleId))) return null; return new DotTerminatedMessageWriter(_writer_); } /*** * Logs out of the news server gracefully by sending the QUIT command. * However, you must still disconnect from the server before you can open * a new connection. * <p> * @return True if successfully completed, false if not. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean logout() throws IOException { return NNTPReply.isPositiveCompletion(quit()); } /** * Log into a news server by sending the AUTHINFO USER/AUTHINFO * PASS command sequence. This is usually sent in response to a * 480 reply code from the NNTP server. * <p> * @param username a valid username * @param password the corresponding password * @return True for successful login, false for a failure * @throws IOException */ public boolean authenticate(String username, String password) throws IOException { int replyCode = authinfoUser(username); if (replyCode == NNTPReply.MORE_AUTH_INFO_REQUIRED) { replyCode = authinfoPass(password); if (replyCode == NNTPReply.AUTHENTICATION_ACCEPTED) { _isAllowedToPost = true; return true; } } return false; } /*** * Private implementation of XOVER functionality. * * See {@link NNTP#xover} * for legal agument formats. Alternatively, read RFC 2980 :-) * <p> * @param articleRange * @return Returns a DotTerminatedMessageReader if successful, null * otherwise * @exception IOException */ private Reader __retrieveArticleInfo(String articleRange) throws IOException { if (!NNTPReply.isPositiveCompletion(xover(articleRange))) return null; return new DotTerminatedMessageReader(_reader_); } /** * Return article headers for a specified post. * <p> * @param articleNumber the article to retrieve headers for * @return a DotTerminatedReader if successful, null otherwise * @throws IOException */ public Reader retrieveArticleInfo(int articleNumber) throws IOException { return __retrieveArticleInfo(Integer.toString(articleNumber)); } /** * Return article headers for all articles between lowArticleNumber * and highArticleNumber, inclusively. * <p> * @param lowArticleNumber * @param highArticleNumber * @return a DotTerminatedReader if successful, null otherwise * @throws IOException */ public Reader retrieveArticleInfo(long lowArticleNumber, long highArticleNumber) throws IOException { return __retrieveArticleInfo(lowArticleNumber + "-" + highArticleNumber); } /** * Return article headers for all articles between lowArticleNumber * and highArticleNumber, inclusively. * <p> * @param lowArticleNumber * @param highArticleNumber * @return an Iterable of Articles * @throws IOException if the command failed * @since 3.0 */ public Iterable<Article> iterateArticleInfo(long lowArticleNumber, long highArticleNumber) throws IOException { Reader info = retrieveArticleInfo(lowArticleNumber,highArticleNumber); if (info == null) { throw new IOException(getReplyString()); } // N.B. info is already DotTerminated, so don't rewrap return new ArticleIterator(new ReplyIterator(info, false)); } /*** * Private implementation of XHDR functionality. * * See {@link NNTP#xhdr} * for legal agument formats. Alternatively, read RFC 1036. * <p> * @param header * @param articleRange * @return Returns a DotTerminatedMessageReader if successful, null * otherwise * @exception IOException */ private Reader __retrieveHeader(String header, String articleRange) throws IOException { if (!NNTPReply.isPositiveCompletion(xhdr(header, articleRange))) return null; return new DotTerminatedMessageReader(_reader_); } /** * Return an article header for a specified post. * <p> * @param header the header to retrieve * @param articleNumber the article to retrieve the header for * @return a DotTerminatedReader if successful, null otherwise * @throws IOException */ public Reader retrieveHeader(String header, long articleNumber) throws IOException { return __retrieveHeader(header, Long.toString(articleNumber)); } /** * Return an article header for all articles between lowArticleNumber * and highArticleNumber, inclusively. * <p> * @param header * @param lowArticleNumber * @param highArticleNumber * @return a DotTerminatedReader if successful, null otherwise * @throws IOException */ public Reader retrieveHeader(String header, int lowArticleNumber, int highArticleNumber) throws IOException { return __retrieveHeader(header,lowArticleNumber + "-" + highArticleNumber); } } /* Emacs configuration * Local variables: ** * mode: java ** * c-basic-offset: 4 ** * indent-tabs-mode: nil ** * End: ** */
Improve the IOException messages git-svn-id: a30623744da1fa54a2e05f6887273b2822fd1c7c@1081620 13f79535-47bb-0310-9956-ffa450edef68
src/main/java/org/apache/commons/net/nntp/NNTPClient.java
Improve the IOException messages
<ide><path>rc/main/java/org/apache/commons/net/nntp/NNTPClient.java <ide> if (NNTPReply.isPositiveCompletion(list())) { <ide> return new ReplyIterator(_reader_); <ide> } <del> throw new IOException(getReplyString()); <add> throw new IOException("LIST command failed: "+getReplyString()); <ide> } <ide> <ide> /** <ide> if(NNTPReply.isPositiveCompletion(listActive(wildmat))) { <ide> return new ReplyIterator(_reader_); <ide> } <del> throw new IOException(getReplyString()); <add> throw new IOException("LIST ACTIVE "+wildmat+" command failed: "+getReplyString()); <ide> } <ide> <ide> /** <ide> query.isGMT(), query.getDistributions()))) { <ide> return new ReplyIterator(_reader_); <ide> } <del> throw new IOException(getReplyString()); <add> throw new IOException("NEWSGROUPS command failed: "+getReplyString()); <ide> } <ide> <ide> /** <ide> * List all new articles added to the NNTP server since a particular <ide> * date subject to the conditions of the specified query. If no new <ide> * new news is found, no entries will be returned. <add> * This uses the "NEWNEWS" command. <ide> * You must add at least one newsgroup to the query, else the command will fail. <ide> * Each String which is returned is a unique message identifier including the <ide> * enclosing &lt and &gt. <ide> query.isGMT(), query.getDistributions()))) { <ide> return new ReplyIterator(_reader_); <ide> } <del> throw new IOException(getReplyString()); <add> throw new IOException("NEWNEWS command failed: "+getReplyString()); <ide> } <ide> <ide> /*** <ide> <ide> /** <ide> * Return article headers for all articles between lowArticleNumber <del> * and highArticleNumber, inclusively. <add> * and highArticleNumber, inclusively. Uses the XOVER command. <ide> * <p> <ide> * @param lowArticleNumber <ide> * @param highArticleNumber <ide> <ide> /** <ide> * Return article headers for all articles between lowArticleNumber <del> * and highArticleNumber, inclusively. <add> * and highArticleNumber, inclusively, using the XOVER command. <ide> * <p> <ide> * @param lowArticleNumber <ide> * @param highArticleNumber <ide> { <ide> Reader info = retrieveArticleInfo(lowArticleNumber,highArticleNumber); <ide> if (info == null) { <del> throw new IOException(getReplyString()); <add> throw new IOException("XOVER command failed: "+getReplyString()); <ide> } <ide> // N.B. info is already DotTerminated, so don't rewrap <ide> return new ArticleIterator(new ReplyIterator(info, false));
Java
apache-2.0
4efd23e30f8bc9f1da976f62a7c041153e5650cf
0
diet4j/diet4j,diet4j/diet4j
// // The rights holder(s) license 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 // // For information about copyright ownership, see the NOTICE // file distributed with this work. // // 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.diet4j.jsvc; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.text.ParseException; import java.util.HashSet; import org.apache.commons.daemon.Daemon; import org.apache.commons.daemon.DaemonContext; import org.apache.commons.daemon.DaemonInitException; import org.diet4j.cmdline.CmdlineParameters; import org.diet4j.core.Module; import org.diet4j.core.ModuleActivationException; import org.diet4j.core.ModuleDeactivationException; import org.diet4j.core.ModuleMeta; import org.diet4j.core.ModuleNotFoundException; import org.diet4j.core.ModuleRegistry; import org.diet4j.core.ModuleRequirement; import org.diet4j.core.ModuleResolutionException; import org.diet4j.core.ModuleRunException; import org.diet4j.core.NoRunMethodException; import org.diet4j.core.ScanningDirectoriesModuleRegistry; /** * An implementation of the jsvc Daemon interface that enables jsvc to * invoke the diet4j framework and start a diet4j module. */ public class Diet4jDaemon implements Daemon { @Override public void init( DaemonContext dc ) throws DaemonInitException { CmdlineParameters parameters = new CmdlineParameters( new CmdlineParameters.Parameter( "directory", 1, true ), new CmdlineParameters.Parameter( "run", 1 ), new CmdlineParameters.Parameter( "method", 1 ) ); String [] remaining = parameters.parse( dc.getArguments() ); if( remaining.length < 1 ) { throw new DaemonInitException( "Must provide the name of one root module" ); } try { theRootModuleRequirement = ModuleRequirement.parse( remaining[0] ); } catch( ParseException ex ) { throw new DaemonInitException( "Failed to parse root module requirement " + remaining[0], ex ); } theRunArguments = new String[ remaining.length-1 ]; System.arraycopy( remaining, 1, theRunArguments, 0, theRunArguments.length ); String [] dirs = parameters.getMany( "directory" ); HashSet<File> fileDirs = new HashSet<>(); if( dirs != null ) { for( String dir : dirs ) { try { if( !fileDirs.add( new File( dir ).getCanonicalFile() )) { throw new DaemonInitException( "Directory (indirectly?) specified more than once in moduledirectory parameter: " + dir ); } } catch( IOException ex ) { throw new DaemonInitException( "Failed to read directory " + dir, ex ); } } } theModuleDirectories = new File[ fileDirs.size() ]; fileDirs.toArray( theModuleDirectories ); theRunClassName = parameters.get( "run" ); theRunMethodName = parameters.get( "method" ); // create ModuleRegistry theModuleRegistry = ScanningDirectoriesModuleRegistry.create( theModuleDirectories ); try { theRootModuleMeta = theModuleRegistry.determineSingleResolutionCandidate( theRootModuleRequirement ); } catch( Throwable ex ) { throw new DaemonInitException( "Cannot find module " + theRootModuleRequirement ); } try { theRootModule = theModuleRegistry.resolve( theRootModuleMeta ); } catch( Throwable ex ) { throw new DaemonInitException( "Cannot resolve module " + theRootModuleMeta.toString() ); } } @Override public void start() throws ModuleResolutionException, ModuleNotFoundException, ModuleActivationException, ClassNotFoundException, ModuleRunException, NoRunMethodException, InvocationTargetException { if( theRootModule != null ) { theRootModule.activateRecursively(); if( theRunClassName != null ) { theRootModule.run( theRunClassName, theRunMethodName, theRunArguments ); } } } @Override public void stop() throws ModuleDeactivationException { if( theRootModule != null ) { theRootModule.deactivateRecursively(); } } @Override public void destroy() { // no op } protected Module theRootModule; protected ModuleMeta theRootModuleMeta; protected ModuleRegistry theModuleRegistry; protected ModuleRequirement theRootModuleRequirement; protected String [] theRunArguments; protected File [] theModuleDirectories; protected String theRunClassName; protected String theRunMethodName; }
diet4j-jsvc/src/main/java/org/diet4j/jsvc/Diet4jDaemon.java
// // The rights holder(s) license 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 // // For information about copyright ownership, see the NOTICE // file distributed with this work. // // 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.diet4j.jsvc; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.text.ParseException; import java.util.HashSet; import org.apache.commons.daemon.Daemon; import org.apache.commons.daemon.DaemonContext; import org.apache.commons.daemon.DaemonInitException; import org.diet4j.cmdline.CmdlineParameters; import org.diet4j.core.Module; import org.diet4j.core.ModuleActivationException; import org.diet4j.core.ModuleDeactivationException; import org.diet4j.core.ModuleMeta; import org.diet4j.core.ModuleNotFoundException; import org.diet4j.core.ModuleRegistry; import org.diet4j.core.ModuleRequirement; import org.diet4j.core.ModuleResolutionException; import org.diet4j.core.ModuleRunException; import org.diet4j.core.NoRunMethodException; import org.diet4j.core.ScanningDirectoriesModuleRegistry; /** * * @author buildmaster */ public class Diet4jDaemon implements Daemon { @Override public void init( DaemonContext dc ) throws DaemonInitException { CmdlineParameters parameters = new CmdlineParameters( new CmdlineParameters.Parameter( "directory", 1, true ), new CmdlineParameters.Parameter( "run", 1 ), new CmdlineParameters.Parameter( "method", 1 ) ); String [] remaining = parameters.parse( dc.getArguments() ); if( remaining.length < 1 ) { throw new DaemonInitException( "Must provide the name of one root module" ); } try { theRootModuleRequirement = ModuleRequirement.parse( remaining[0] ); } catch( ParseException ex ) { throw new DaemonInitException( "Failed to parse root module requirement " + remaining[0], ex ); } theRunArguments = new String[ remaining.length-1 ]; System.arraycopy( remaining, 1, theRunArguments, 0, theRunArguments.length ); String [] dirs = parameters.getMany( "directory" ); HashSet<File> fileDirs = new HashSet<>(); if( dirs != null ) { for( String dir : dirs ) { try { if( !fileDirs.add( new File( dir ).getCanonicalFile() )) { throw new DaemonInitException( "Directory (indirectly?) specified more than once in moduledirectory parameter: " + dir ); } } catch( IOException ex ) { throw new DaemonInitException( "Failed to read directory " + dir, ex ); } } } theModuleDirectories = new File[ fileDirs.size() ]; fileDirs.toArray( theModuleDirectories ); theRunClassName = parameters.get( "run" ); theRunMethodName = parameters.get( "method" ); // create ModuleRegistry theModuleRegistry = ScanningDirectoriesModuleRegistry.create( theModuleDirectories ); try { theRootModuleMeta = theModuleRegistry.determineSingleResolutionCandidate( theRootModuleRequirement ); } catch( Throwable ex ) { throw new DaemonInitException( "Cannot find module " + theRootModuleRequirement ); } try { theRootModule = theModuleRegistry.resolve( theRootModuleMeta ); } catch( Throwable ex ) { throw new DaemonInitException( "Cannot resolve module " + theRootModuleMeta.toString() ); } } @Override public void start() throws ModuleResolutionException, ModuleNotFoundException, ModuleActivationException, ClassNotFoundException, ModuleRunException, NoRunMethodException, InvocationTargetException { if( theRootModule != null ) { theRootModule.activateRecursively(); if( theRunClassName != null ) { theRootModule.run( theRunClassName, theRunMethodName, theRunArguments ); } } } @Override public void stop() throws ModuleDeactivationException { if( theRootModule != null ) { theRootModule.deactivateRecursively(); } } @Override public void destroy() { // no op } protected Module theRootModule; protected ModuleMeta theRootModuleMeta; protected ModuleRegistry theModuleRegistry; protected ModuleRequirement theRootModuleRequirement; protected String [] theRunArguments; protected File [] theModuleDirectories; protected String theRunClassName; protected String theRunMethodName; }
JavaDoc improvement
diet4j-jsvc/src/main/java/org/diet4j/jsvc/Diet4jDaemon.java
JavaDoc improvement
<ide><path>iet4j-jsvc/src/main/java/org/diet4j/jsvc/Diet4jDaemon.java <ide> import org.diet4j.core.ScanningDirectoriesModuleRegistry; <ide> <ide> /** <del> * <del> * @author buildmaster <add> * An implementation of the jsvc Daemon interface that enables jsvc to <add> * invoke the diet4j framework and start a diet4j module. <ide> */ <ide> public class Diet4jDaemon <ide> implements Daemon
Java
mit
892dcbda3fec19a3653cf75439406dee5ebe9114
0
shadowfacts/EnFusion
package net.shadowfacts.enfusion.recipes; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import net.shadowfacts.enfusion.block.EFBlocks; import net.shadowfacts.enfusion.item.EFItems; public class EFRecipes { public static void registerRecipes() { registerBlockRecipes(); registerItemRecipes(); registerFurnaceRecipes(); } private static void registerBlockRecipes() { // Green Zinchorium Light GameRegistry.addShapedRecipe(new ItemStack(EFBlocks.greenZinchoriumLightIdle, 1), "IGI", "GLG", "IGI", 'I', new ItemStack(EFItems.zinchoriumAlloyIngot), 'G', new ItemStack(Blocks.glass), 'L', new ItemStack(EFItems.lightBulb, 1)); // Zinchorium Block GameRegistry.addShapedRecipe(new ItemStack(EFBlocks.blockZinchorium), "ZZZ", "ZZZ", "ZZZ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); // Solar Panel Tier 1 GameRegistry.addShapedRecipe(new ItemStack(EFBlocks.solarPanelTier1), "MMM", "CFC", "CCC", 'M', new ItemStack(EFItems.mirror), 'C', new ItemStack(Blocks.cobblestone), 'F', new ItemStack(EFItems.basicCapacitor)); // Solar Panel Tier 2 GameRegistry.addShapelessRecipe(new ItemStack(EFBlocks.solarPanelTier2), new ItemStack(EFBlocks.solarPanelTier1), new ItemStack(EFItems.enhancedCapacitor), new ItemStack(EFBlocks.solarPanelTier1)); // Solar Panel Tier 3 GameRegistry.addShapelessRecipe(new ItemStack(EFBlocks.solarPanelTier3), new ItemStack(EFBlocks.solarPanelTier2), new ItemStack(EFItems.energeticCapacitor), new ItemStack(EFBlocks.solarPanelTier1)); // Solar Panel Tier 4 GameRegistry.addShapelessRecipe(new ItemStack(EFBlocks.solarPanelTier4), new ItemStack(EFBlocks.solarPanelTier3), new ItemStack(EFItems.hyperEnergeticCapacitor), new ItemStack(EFBlocks.solarPanelTier3)); // Zinchorium Furnace GameRegistry.addShapedRecipe(new ItemStack(EFBlocks.zinchoriumFurnace), "ZZZ", "ZFZ", "ZZZ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'F', new ItemStack(Blocks.furnace)); } private static void registerItemRecipes() { // Light bulb GameRegistry.addShapedRecipe(new ItemStack(EFItems.lightBulb), "GGG", "GOG", "III", 'G', new ItemStack(Blocks.glass), 'O', new ItemStack(Items.gold_ingot), 'I', new ItemStack(Items.iron_ingot)); // Zinchorium Gem Sword GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumSword), " Z ", " Z ", " S ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'S', new ItemStack(Items.stick)); // Zinchorium Gem Pickaxe GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumPickaxe), "ZZZ", " S ", " S ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'S', new ItemStack(Items.stick)); // Zinchorium Gem Axe GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumAxe), "ZZ ", "ZS ", " S ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'S', new ItemStack(Items.stick)); // Zinchorium Gem Shovel GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumShovel), " Z ", " S ", " S ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'S', new ItemStack(Items.stick)); // Zinchorium Gem Hoe GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumHoe), "ZZ ", " S ", " S ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'S', new ItemStack(Items.stick)); // Zinchorium Helmet GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumHelmet), "ZZZ", "Z Z", " ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); // Zinchorium Chestplate GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumChestplate), "Z Z", "ZZZ", "ZZZ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); // Zinchoruim Leggings GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumLeggings), "ZZZ", "Z Z", "Z Z", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); // Zinchorium Boots GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumBoots), "Z Z", "Z Z", " ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumBoots), " ", "Z Z", "Z Z", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); // Zinchorium Block -> Zinchorium Alloy Ingot GameRegistry.addShapelessRecipe(new ItemStack(EFItems.zinchoriumAlloyIngot, 9), new ItemStack(EFBlocks.blockZinchorium)); // Mirror GameRegistry.addShapedRecipe(new ItemStack(EFItems.mirror, 3), "GGG", "III", " ", 'G', new ItemStack(Blocks.glass), 'I', new ItemStack(Items.iron_ingot)); // Basic Capacitor GameRegistry.addShapedRecipe(new ItemStack(EFItems.basicCapacitor), " R", " G ", "R ", 'R', new ItemStack(Items.redstone), 'G', Items.gold_nugget); // Enhanced Capacitor GameRegistry.addShapedRecipe(new ItemStack(EFItems.enhancedCapacitor), " B", " R ", "B ", 'B', EFItems.basicCapacitor, 'R', Items.redstone); // Energetic Capacitor GameRegistry.addShapedRecipe(new ItemStack(EFItems.energeticCapacitor), " E", " Z ", "E ", 'E', EFItems.enhancedCapacitor, 'Z', EFItems.zinchoriumAlloyIngot); // Hyper Energetic Capacitor GameRegistry.addShapedRecipe(new ItemStack(EFItems.hyperEnergeticCapacitor), " GE", "GZG", "EG ", 'G', Items.gold_nugget, 'E', EFItems.energeticCapacitor, 'Z', EFItems.zinchoriumAlloyIngot); // Zinchorium Dust GameRegistry.addShapelessRecipe(new ItemStack(EFItems.dustZinchorium), EFItems.dustIron, EFItems.dustPeridot); } private static void registerFurnaceRecipes() { // Copper ore --> copper ingot GameRegistry.addSmelting(EFBlocks.oreCopper, new ItemStack(EFItems.ingotCopper, 1), 0.3f); // Zinchorium ore --> Zinchorium Alloy Ingot GameRegistry.addSmelting(EFBlocks.oreZinchorium, new ItemStack(EFItems.zinchoriumAlloyIngot), 0.5f); // Zinchorium dust --> Zinchorium Alloy Ingot GameRegistry.addSmelting(EFItems.dustZinchorium, new ItemStack(EFItems.zinchoriumAlloyIngot), 0.4f); // Peridot dust --> Peridot Gem GameRegistry.addSmelting(EFItems.dustPeridot, new ItemStack(EFItems.gemPeridot), 0.1f); } public static void registerOreDictThings() { // Blocks OreDictionary.registerOre("oreCopper", EFBlocks.oreCopper); OreDictionary.registerOre("orePeridot", EFBlocks.orePeridot); // Items // Ingots OreDictionary.registerOre("ingotCopper", EFItems.ingotCopper); // Gems OreDictionary.registerOre("gemPeridot", EFItems.gemPeridot); // Dusts OreDictionary.registerOre("dustIron", EFItems.dustIron); OreDictionary.registerOre("dustGold", EFItems.dustGold); OreDictionary.registerOre("dustCopper", EFItems.dustCopper); OreDictionary.registerOre("dustPeridot", EFItems.dustPeridot); } }
src/main/java/net/shadowfacts/enfusion/recipes/EFRecipes.java
package net.shadowfacts.enfusion.recipes; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import net.shadowfacts.enfusion.block.EFBlocks; import net.shadowfacts.enfusion.item.EFItems; public class EFRecipes { public static void registerRecipes() { registerBlockRecipes(); registerItemRecipes(); registerFurnaceRecipes(); } private static void registerBlockRecipes() { // Green Zinchorium Light GameRegistry.addShapedRecipe(new ItemStack(EFBlocks.greenZinchoriumLightIdle, 1), "IGI", "GLG", "IGI", 'I', new ItemStack(EFItems.zinchoriumAlloyIngot), 'G', new ItemStack(Blocks.glass), 'L', new ItemStack(EFItems.lightBulb, 1)); // Zinchorium Block GameRegistry.addShapedRecipe(new ItemStack(EFBlocks.blockZinchorium), "ZZZ", "ZZZ", "ZZZ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); // Solar Panel Tier 1 GameRegistry.addShapedRecipe(new ItemStack(EFBlocks.solarPanelTier1), "MMM", "CFC", "CCC", 'M', new ItemStack(EFItems.mirror), 'C', new ItemStack(Blocks.cobblestone), 'F', new ItemStack(EFItems.basicCapacitor)); // Solar Panel Tier 2 GameRegistry.addShapelessRecipe(new ItemStack(EFBlocks.solarPanelTier2), new ItemStack(EFBlocks.solarPanelTier1), new ItemStack(EFItems.enhancedCapacitor), new ItemStack(EFBlocks.solarPanelTier1)); // Solar Panel Tier 3 GameRegistry.addShapelessRecipe(new ItemStack(EFBlocks.solarPanelTier3), new ItemStack(EFBlocks.solarPanelTier2), new ItemStack(EFItems.energeticCapacitor), new ItemStack(EFBlocks.solarPanelTier1)); // Solar Panel Tier 4 GameRegistry.addShapelessRecipe(new ItemStack(EFBlocks.solarPanelTier4), new ItemStack(EFBlocks.solarPanelTier3), new ItemStack(EFItems.hyperEnergeticCapacitor), new ItemStack(EFBlocks.solarPanelTier3)); // Zinchorium Furnace GameRegistry.addShapedRecipe(new ItemStack(EFBlocks.zinchoriumFurnace), "ZZZ", "ZFZ", "ZZZ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'F', new ItemStack(Blocks.furnace)); } private static void registerItemRecipes() { // Light bulb GameRegistry.addShapedRecipe(new ItemStack(EFItems.lightBulb), "GGG", "GOG", "III", 'G', new ItemStack(Blocks.glass), 'O', new ItemStack(Items.gold_ingot), 'I', new ItemStack(Items.iron_ingot)); // Zinchorium Gem Sword GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumSword), " Z ", " Z ", " S ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'S', new ItemStack(Items.stick)); // Zinchorium Gem Pickaxe GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumPickaxe), "ZZZ", " S ", " S ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'S', new ItemStack(Items.stick)); // Zinchorium Gem Axe GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumAxe), "ZZ ", "ZS ", " S ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'S', new ItemStack(Items.stick)); // Zinchorium Gem Shovel GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumShovel), " Z ", " S ", " S ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'S', new ItemStack(Items.stick)); // Zinchorium Gem Hoe GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumHoe), "ZZ ", " S ", " S ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'S', new ItemStack(Items.stick)); // Zinchorium Helmet GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumHelmet), "ZZZ", "Z Z", " ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); // Zinchorium Chestplate GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumChestplate), "Z Z", "ZZZ", "ZZZ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); // Zinchoruim Leggings GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumLeggings), "ZZZ", "Z Z", "Z Z", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); // Zinchorium Boots GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumBoots), "Z Z", "Z Z", " ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumBoots), " ", "Z Z", "Z Z", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); // Zinchorium Block -> Zinchorium Alloy Ingot GameRegistry.addShapelessRecipe(new ItemStack(EFItems.zinchoriumAlloyIngot, 9), new ItemStack(EFBlocks.blockZinchorium)); // Mirror GameRegistry.addShapedRecipe(new ItemStack(EFItems.mirror, 3), "GGG", "III", " ", 'G', new ItemStack(Blocks.glass), 'I', new ItemStack(Items.iron_ingot)); // Basic Capacitor GameRegistry.addShapedRecipe(new ItemStack(EFItems.basicCapacitor), " R", " G ", "R ", 'R', new ItemStack(Items.redstone), 'G', Items.gold_nugget); // Enhanced Capacitor GameRegistry.addShapedRecipe(new ItemStack(EFItems.enhancedCapacitor), " B", " R ", "B ", 'B', EFItems.basicCapacitor, 'R', Items.redstone); // Energetic Capacitor GameRegistry.addShapedRecipe(new ItemStack(EFItems.energeticCapacitor), " E", " Z ", "E ", 'E', EFItems.enhancedCapacitor, 'Z', EFItems.zinchoriumAlloyIngot); // Hyper Energetic Capacitor GameRegistry.addShapedRecipe(new ItemStack(EFItems.hyperEnergeticCapacitor), " GE", "GZG", "EG ", 'G', Items.gold_nugget, 'E', EFItems.energeticCapacitor, 'Z', EFItems.zinchoriumAlloyIngot); // Zinchorium Dust GameRegistry.addShapelessRecipe(new ItemStack(EFItems.dustZinchorium), EFItems.dustIron, EFItems.dustPeridot); } private static void registerFurnaceRecipes() { // Copper ore --> copper ingot GameRegistry.addSmelting(EFBlocks.oreCopper, new ItemStack(EFItems.ingotCopper, 1), 0.3f); // Zinchorium ore --> Zinchorium Alloy Ingot GameRegistry.addSmelting(EFBlocks.oreZinchorium, new ItemStack(EFItems.zinchoriumAlloyIngot), 0.5f); // Zinchorium dust --> Zinchorium Alloy Ingot GameRegistry.addSmelting(EFItems.dustZinchorium, new ItemStack(EFItems.zinchoriumAlloyIngot), 0.4f); // Peridot dust --> Peridot Gem GameRegistry.addSmelting(EFItems.dustPeridot, new ItemStack(EFItems.gemPeridot), 0.1f); } public static void registerOreDictThings() { // Blocks OreDictionary.registerOre("oreCopper", EFBlocks.oreCopper); OreDictionary.registerOre("orePeridot", EFBlocks.orePeridot); // Items OreDictionary.registerOre("ingotCopper", EFItems.ingotCopper); OreDictionary.registerOre("gemPeridot", EFItems.gemPeridot); } }
OreDict dusts
src/main/java/net/shadowfacts/enfusion/recipes/EFRecipes.java
OreDict dusts
<ide><path>rc/main/java/net/shadowfacts/enfusion/recipes/EFRecipes.java <ide> OreDictionary.registerOre("orePeridot", EFBlocks.orePeridot); <ide> <ide> // Items <add>// Ingots <ide> OreDictionary.registerOre("ingotCopper", EFItems.ingotCopper); <add> <add>// Gems <ide> OreDictionary.registerOre("gemPeridot", EFItems.gemPeridot); <add> <add>// Dusts <add> OreDictionary.registerOre("dustIron", EFItems.dustIron); <add> OreDictionary.registerOre("dustGold", EFItems.dustGold); <add> OreDictionary.registerOre("dustCopper", EFItems.dustCopper); <add> OreDictionary.registerOre("dustPeridot", EFItems.dustPeridot); <ide> <ide> } <ide>
Java
apache-2.0
d3b4844d07b76fdf8cd2ff7d28a6f6fe21ea0596
0
apache/tomcat,apache/tomcat,apache/tomcat,apache/tomcat,apache/tomcat
/* * 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.catalina.core; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.DispatcherType; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.UnavailableException; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.Globals; import org.apache.catalina.LifecycleException; import org.apache.catalina.connector.ClientAbortException; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.catalina.valves.ValveBase; import org.apache.coyote.CloseNowException; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.log.SystemLogHandler; import org.apache.tomcat.util.res.StringManager; /** * Valve that implements the default basic behavior for the * <code>StandardWrapper</code> container implementation. * * @author Craig R. McClanahan */ final class StandardWrapperValve extends ValveBase { //------------------------------------------------------ Constructor public StandardWrapperValve() { super(true); } // ----------------------------------------------------- Instance Variables // Some JMX statistics. This valve is associated with a StandardWrapper. // We expose the StandardWrapper as JMX ( j2eeType=Servlet ). The fields // are here for performance. private volatile long processingTime; private volatile long maxTime; private volatile long minTime = Long.MAX_VALUE; private final AtomicInteger requestCount = new AtomicInteger(0); private final AtomicInteger errorCount = new AtomicInteger(0); /** * The string manager for this package. */ private static final StringManager sm = StringManager.getManager(Constants.Package); // --------------------------------------------------------- Public Methods /** * Invoke the servlet we are managing, respecting the rules regarding * servlet lifecycle and SingleThreadModel support. * * @param request Request to be processed * @param response Response to be produced * * @exception IOException if an input/output error occurred * @exception ServletException if a servlet error occurred */ @Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Initialize local variables we may need boolean unavailable = false; Throwable throwable = null; // This should be a Request attribute... long t1=System.currentTimeMillis(); requestCount.incrementAndGet(); StandardWrapper wrapper = (StandardWrapper) getContainer(); Servlet servlet = null; Context context = (Context) wrapper.getParent(); // Check for the application being marked unavailable if (!context.getState().isAvailable()) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardContext.isUnavailable")); unavailable = true; } // Check for the servlet being marked unavailable if (!unavailable && wrapper.isUnavailable()) { container.getLogger().info(sm.getString("standardWrapper.isUnavailable", wrapper.getName())); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } unavailable = true; } // Allocate a servlet instance to process this request try { if (!unavailable) { servlet = wrapper.allocate(); } } catch (UnavailableException e) { container.getLogger().error( sm.getString("standardWrapper.allocateException", wrapper.getName()), e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } } catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; } MessageBytes requestPathMB = request.getRequestPathMB(); DispatcherType dispatcherType = DispatcherType.REQUEST; if (request.getDispatcherType()==DispatcherType.ASYNC) dispatcherType = DispatcherType.ASYNC; request.setAttribute(Globals.DISPATCHER_TYPE_ATTR,dispatcherType); request.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, requestPathMB); // Create the filter chain for this request ApplicationFilterChain filterChain = ApplicationFilterFactory.createFilterChain(request, wrapper, servlet); // Call the filter chain for this request // NOTE: This also calls the servlet's service() method Container container = this.container; try { if ((servlet != null) && (filterChain != null)) { // Swallow output if needed if (context.getSwallowOutput()) { try { SystemLogHandler.startCapture(); if (request.isAsyncDispatching()) { request.getAsyncContextInternal().doInternalDispatch(); } else { filterChain.doFilter(request.getRequest(), response.getResponse()); } } finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } } } else { if (request.isAsyncDispatching()) { request.getAsyncContextInternal().doInternalDispatch(); } else { filterChain.doFilter (request.getRequest(), response.getResponse()); } } } } catch (ClientAbortException | CloseNowException e) { if (container.getLogger().isDebugEnabled()) { container.getLogger().debug(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); } throwable = e; exception(request, response, e); } catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing } catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } finally { // Release the filter chain (if any) for this request if (filterChain != null) { filterChain.release(); } // Deallocate the allocated servlet instance try { if (servlet != null) { wrapper.deallocate(servlet); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } // If this servlet has been marked permanently unavailable, // unload it and release this instance try { if ((servlet != null) && (wrapper.getAvailable() == Long.MAX_VALUE)) { wrapper.unload(); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { exception(request, response, e); } } long t2=System.currentTimeMillis(); long time=t2-t1; processingTime += time; if( time > maxTime) maxTime=time; if( time < minTime) minTime=time; } } // -------------------------------------------------------- Private Methods /** * Handle the specified ServletException encountered while processing * the specified Request to produce the specified Response. Any * exceptions that occur during generation of the exception report are * logged and swallowed. * * @param request The request being processed * @param response The response being generated * @param exception The exception that occurred (which possibly wraps * a root cause exception */ private void exception(Request request, Response response, Throwable exception) { request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, exception); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setError(); } public long getProcessingTime() { return processingTime; } public long getMaxTime() { return maxTime; } public long getMinTime() { return minTime; } public int getRequestCount() { return requestCount.get(); } public int getErrorCount() { return errorCount.get(); } public void incrementErrorCount() { errorCount.incrementAndGet(); } @Override protected void initInternal() throws LifecycleException { // NOOP - Don't register this Valve in JMX } }
java/org/apache/catalina/core/StandardWrapperValve.java
/* * 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.catalina.core; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.DispatcherType; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.UnavailableException; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.Globals; import org.apache.catalina.LifecycleException; import org.apache.catalina.connector.ClientAbortException; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.catalina.valves.ValveBase; import org.apache.coyote.CloseNowException; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.log.SystemLogHandler; import org.apache.tomcat.util.res.StringManager; /** * Valve that implements the default basic behavior for the * <code>StandardWrapper</code> container implementation. * * @author Craig R. McClanahan */ final class StandardWrapperValve extends ValveBase { //------------------------------------------------------ Constructor public StandardWrapperValve() { super(true); } // ----------------------------------------------------- Instance Variables // Some JMX statistics. This valve is associated with a StandardWrapper. // We expose the StandardWrapper as JMX ( j2eeType=Servlet ). The fields // are here for performance. private volatile long processingTime; private volatile long maxTime; private volatile long minTime = Long.MAX_VALUE; private final AtomicInteger requestCount = new AtomicInteger(0); private final AtomicInteger errorCount = new AtomicInteger(0); /** * The string manager for this package. */ private static final StringManager sm = StringManager.getManager(Constants.Package); // --------------------------------------------------------- Public Methods /** * Invoke the servlet we are managing, respecting the rules regarding * servlet lifecycle and SingleThreadModel support. * * @param request Request to be processed * @param response Response to be produced * * @exception IOException if an input/output error occurred * @exception ServletException if a servlet error occurred */ @Override public final void invoke(Request request, Response response) throws IOException, ServletException { // Initialize local variables we may need boolean unavailable = false; Throwable throwable = null; // This should be a Request attribute... long t1=System.currentTimeMillis(); requestCount.incrementAndGet(); StandardWrapper wrapper = (StandardWrapper) getContainer(); Servlet servlet = null; Context context = (Context) wrapper.getParent(); // Check for the application being marked unavailable if (!context.getState().isAvailable()) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardContext.isUnavailable")); unavailable = true; } // Check for the servlet being marked unavailable if (!unavailable && wrapper.isUnavailable()) { container.getLogger().info(sm.getString("standardWrapper.isUnavailable", wrapper.getName())); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } unavailable = true; } // Allocate a servlet instance to process this request try { if (!unavailable) { servlet = wrapper.allocate(); } } catch (UnavailableException e) { container.getLogger().error( sm.getString("standardWrapper.allocateException", wrapper.getName()), e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } } catch (ServletException e) { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e)); throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; } MessageBytes requestPathMB = request.getRequestPathMB(); DispatcherType dispatcherType = DispatcherType.REQUEST; if (request.getDispatcherType()==DispatcherType.ASYNC) dispatcherType = DispatcherType.ASYNC; request.setAttribute(Globals.DISPATCHER_TYPE_ATTR,dispatcherType); request.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, requestPathMB); // Create the filter chain for this request ApplicationFilterChain filterChain = ApplicationFilterFactory.createFilterChain(request, wrapper, servlet); // Call the filter chain for this request // NOTE: This also calls the servlet's service() method Container container = this.container; try { if ((servlet != null) && (filterChain != null)) { // Swallow output if needed if (context.getSwallowOutput()) { try { SystemLogHandler.startCapture(); if (request.isAsyncDispatching()) { request.getAsyncContextInternal().doInternalDispatch(); } else { filterChain.doFilter(request.getRequest(), response.getResponse()); } } finally { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { context.getLogger().info(log); } } } else { if (request.isAsyncDispatching()) { request.getAsyncContextInternal().doInternalDispatch(); } else { filterChain.doFilter (request.getRequest(), response.getResponse()); } } } } catch (ClientAbortException | CloseNowException e) { if (container.getLogger().isDebugEnabled()) { container.getLogger().debug(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); } throwable = e; exception(request, response, e); } catch (IOException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } catch (UnavailableException e) { container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { response.setDateHeader("Retry-After", available); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing } catch (ServletException e) { Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { container.getLogger().error(sm.getString( "standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause); } throwable = e; exception(request, response, e); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString( "standardWrapper.serviceException", wrapper.getName(), context.getName()), e); throwable = e; exception(request, response, e); } finally { // Release the filter chain (if any) for this request if (filterChain != null) { filterChain.release(); } // Deallocate the allocated servlet instance try { if (servlet != null) { wrapper.deallocate(servlet); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } // If this servlet has been marked permanently unavailable, // unload it and release this instance try { if ((servlet != null) && (wrapper.getAvailable() == Long.MAX_VALUE)) { wrapper.unload(); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } long t2=System.currentTimeMillis(); long time=t2-t1; processingTime += time; if( time > maxTime) maxTime=time; if( time < minTime) minTime=time; } } // -------------------------------------------------------- Private Methods /** * Handle the specified ServletException encountered while processing * the specified Request to produce the specified Response. Any * exceptions that occur during generation of the exception report are * logged and swallowed. * * @param request The request being processed * @param response The response being generated * @param exception The exception that occurred (which possibly wraps * a root cause exception */ private void exception(Request request, Response response, Throwable exception) { request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, exception); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setError(); } public long getProcessingTime() { return processingTime; } public long getMaxTime() { return maxTime; } public long getMinTime() { return minTime; } public int getRequestCount() { return requestCount.get(); } public int getErrorCount() { return errorCount.get(); } public void incrementErrorCount() { errorCount.incrementAndGet(); } @Override protected void initInternal() throws LifecycleException { // NOOP - Don't register this Valve in JMX } }
Remove redundant method for clean
java/org/apache/catalina/core/StandardWrapperValve.java
Remove redundant method for clean
<ide><path>ava/org/apache/catalina/core/StandardWrapperValve.java <ide> container.getLogger().error(sm.getString("standardWrapper.unloadException", <ide> wrapper.getName()), e); <ide> if (throwable == null) { <del> throwable = e; <ide> exception(request, response, e); <ide> } <ide> }
Java
mit
4b5c6558ed81c9005a7289124599377e4d6714f8
0
yarenty/rootbeer1,yarenty/rootbeer1,yarenty/rootbeer1,yarenty/rootbeer1,Lexine/rootbeer1,Lexine/rootbeer1,Lexine/rootbeer1,Lexine/rootbeer1,yarenty/rootbeer1
package org.trifort.rootbeer.testcases.rootbeertest.kerneltemplate; import org.trifort.rootbeer.runtime.Kernel; import org.trifort.rootbeer.runtime.RootbeerGpu; public class SharedMemoryArraysRunOnGpu implements Kernel { private int[][][] inputArray; private int[][][] outputArray; private int subArrayLength; public SharedMemoryArraysRunOnGpu(int[][][] inputArray, int[][][] outputArray, int subArrayLength){ this.inputArray = inputArray; this.outputArray = outputArray; this.subArrayLength = subArrayLength; } @Override public void gpuMethod() { int blockIdxx = RootbeerGpu.getBlockIdxx(); int threadIdxx = RootbeerGpu.getThreadIdxx(); int[] localInputArray = inputArray[blockIdxx][threadIdxx]; int[] localOutputArray = outputArray[blockIdxx][threadIdxx]; //RootbeerGpu.createSharedIntArray(threadIdxx, subArrayLength); //RootbeerGpu.syncthreads(); /* * * / Allocate an array for this thread RootbeerGpu.createSharedIntArray(threadIdx, subArrayLength); RootbeerGpu.syncthreads(); // Use all threads of the thread group to fetch data from global memory // into each of the shared memory arrays. // Each thread contributes to filling the shared array of all threads in the // current thread group for (int i = threadIdx; i < blkDim * subArrayLength; i += blkDim) { int sharedArrayIndex = i / subArrayLength; int[] sharedArray = RootbeerGpu.getSharedIntArray(sharedArrayIndex); int globalIdx = RootbeerGpu.getBlockIdxx() * blkDim + threadIdx + i; sharedArray[i % blkDim] = data[globalIdx]; } RootbeerGpu.syncthreads(); int[] threadArray = RootbeerGpu.getSharedIntArray(threadIdx); // Do something with threadArray locally RootbeerGpu.syncthreads(); // Copy the data back into global memory. // Again, each thread contributes to copying the shared array of all threads in the // current thread group for (int i = threadIdx; i < blkDim * subArrayLength; i += blkDim) { int sharedArrayIndex = i / subArrayLength; int[] sharedArray = RootbeerGpu.getSharedIntArray(sharedArrayIndex); int globalIdx = RootbeerGpu.getBlockIdxx() * blkDim + threadIdx + i; data[globalIdx] = sharedArray[i % blkDim]; } */ } public boolean compare(SharedMemoryArraysRunOnGpu rhs) { for(int i = 0; i < outputArray.length; ++i){ int[][] innerArray1a = outputArray[i]; int[][] innerArray1b = rhs.outputArray[i]; for(int j = 0; j < innerArray1a.length; ++j){ int[] innerArray2a = innerArray1a[j]; int[] innerArray2b = innerArray1b[j]; for(int k = 0; k < innerArray2a.length; ++k){ int value1 = innerArray2a[k]; int value2 = innerArray2b[k]; if(value1 != value2){ System.out.println("i: "+i+" j: "+j+" k: "+k); System.out.println("value1: "+value1); System.out.println("value2: "+value2); return false; } } } } return true; } }
src/org/trifort/rootbeer/testcases/rootbeertest/kerneltemplate/SharedMemoryArraysRunOnGpu.java
package org.trifort.rootbeer.testcases.rootbeertest.kerneltemplate; import org.trifort.rootbeer.runtime.Kernel; import org.trifort.rootbeer.runtime.RootbeerGpu; public class SharedMemoryArraysRunOnGpu implements Kernel { private int[][][] inputArray; private int[][][] outputArray; private int subArrayLength; public SharedMemoryArraysRunOnGpu(int[][][] inputArray, int[][][] outputArray, int subArrayLength){ this.inputArray = inputArray; this.outputArray = outputArray; this.subArrayLength = subArrayLength; } @Override public void gpuMethod() { int blockIdxx = RootbeerGpu.getBlockIdxx(); int threadIdxx = RootbeerGpu.getThreadIdxx(); int[] localInputArray = inputArray[blockIdxx][threadIdxx]; int[] localOutputArray = outputArray[blockIdxx][threadIdxx]; RootbeerGpu.createSharedIntArray(threadIdxx, subArrayLength); RootbeerGpu.syncthreads(); /* * * / Allocate an array for this thread RootbeerGpu.createSharedIntArray(threadIdx, subArrayLength); RootbeerGpu.syncthreads(); // Use all threads of the thread group to fetch data from global memory // into each of the shared memory arrays. // Each thread contributes to filling the shared array of all threads in the // current thread group for (int i = threadIdx; i < blkDim * subArrayLength; i += blkDim) { int sharedArrayIndex = i / subArrayLength; int[] sharedArray = RootbeerGpu.getSharedIntArray(sharedArrayIndex); int globalIdx = RootbeerGpu.getBlockIdxx() * blkDim + threadIdx + i; sharedArray[i % blkDim] = data[globalIdx]; } RootbeerGpu.syncthreads(); int[] threadArray = RootbeerGpu.getSharedIntArray(threadIdx); // Do something with threadArray locally RootbeerGpu.syncthreads(); // Copy the data back into global memory. // Again, each thread contributes to copying the shared array of all threads in the // current thread group for (int i = threadIdx; i < blkDim * subArrayLength; i += blkDim) { int sharedArrayIndex = i / subArrayLength; int[] sharedArray = RootbeerGpu.getSharedIntArray(sharedArrayIndex); int globalIdx = RootbeerGpu.getBlockIdxx() * blkDim + threadIdx + i; data[globalIdx] = sharedArray[i % blkDim]; } */ } public boolean compare(SharedMemoryArraysRunOnGpu rhs) { for(int i = 0; i < outputArray.length; ++i){ int[][] innerArray1a = outputArray[i]; int[][] innerArray1b = rhs.outputArray[i]; for(int j = 0; j < innerArray1a.length; ++j){ int[] innerArray2a = innerArray1a[j]; int[] innerArray2b = innerArray1b[j]; for(int k = 0; k < innerArray2a.length; ++k){ int value1 = innerArray2a[k]; int value2 = innerArray2b[k]; if(value1 != value2){ System.out.println("i: "+i+" j: "+j+" k: "+k); System.out.println("value1: "+value1); System.out.println("value2: "+value2); return false; } } } } return true; } }
temporarily removing prototype of shared memory arrays. (2)
src/org/trifort/rootbeer/testcases/rootbeertest/kerneltemplate/SharedMemoryArraysRunOnGpu.java
temporarily removing prototype of shared memory arrays. (2)
<ide><path>rc/org/trifort/rootbeer/testcases/rootbeertest/kerneltemplate/SharedMemoryArraysRunOnGpu.java <ide> int[] localInputArray = inputArray[blockIdxx][threadIdxx]; <ide> int[] localOutputArray = outputArray[blockIdxx][threadIdxx]; <ide> <del> RootbeerGpu.createSharedIntArray(threadIdxx, subArrayLength); <del> RootbeerGpu.syncthreads(); <add> //RootbeerGpu.createSharedIntArray(threadIdxx, subArrayLength); <add> //RootbeerGpu.syncthreads(); <ide> <ide> /* <ide> *
Java
apache-2.0
ec3a729d479b199b3ebe2e21aaa94788703a6b76
0
MovingBlocks/DestinationSol,MovingBlocks/DestinationSol
/* * Copyright 2019 MovingBlocks * * 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.destinationsol.game.screens; import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import org.destinationsol.SolApplication; import org.destinationsol.assets.Assets; import org.destinationsol.common.SolColor; import org.destinationsol.game.SolGame; import org.destinationsol.game.console.Console; import org.destinationsol.game.console.ConsoleImpl; import org.destinationsol.game.console.ConsoleSubscriber; import org.destinationsol.game.console.CoreMessageType; import org.destinationsol.game.console.CyclingTabCompletionEngine; import org.destinationsol.game.console.Message; import org.destinationsol.game.console.TabCompletionEngine; import org.destinationsol.game.context.Context; import org.destinationsol.modules.ModuleManager; import org.destinationsol.ui.SolInputManager; import org.destinationsol.ui.SolUiControl; import org.destinationsol.ui.SolUiScreen; import org.destinationsol.ui.UiDrawer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; public class ConsoleScreen implements SolUiScreen, ConsoleSubscriber { private static final Logger logger = LoggerFactory.getLogger(ConsoleScreen.class); /** * Magic happens here. * <p> * Sets the maximum width a line of text can have to fit into the console, in some sort of magical units. If you * change {@link #TOP_LEFT}, {@link #BOTTOM_RIGHT} or {@link #FRAME_WIDTH}, be sure to change this number too. The * only way known to me how to figure out the expected value of this field, is to randomly change it until the text * fits into the console nicely. Be sure to uncomment the block of code in {@link #drawBackground(UiDrawer, SolApplication)} * to clearly see the expected width of the text. */ /** * Position of top left corner of the outermost frame of the console. */ private static final Vector2 TOP_LEFT = new Vector2(0.03f, 0.03f); /** * Position of bottom right corner of the outermost frame of the console. */ private static final Vector2 BOTTOM_RIGHT = new Vector2(0.8f, 0.5f); /** * Width of the gap between outer, inner and text area frames. */ private static final float FRAME_WIDTH = 0.02f; /** * "Line number" of the input line. */ private static final float INPUT_LINE_Y = 20.666f; /** * "Line number" of the input line separator. */ private static final float INPUT_LINE_SEPARATOR_Y = 20.333f; private Console console; private static ConsoleScreen instance; private boolean welcomePrinted; private boolean isActive; public final BitmapFont font; private final SolUiControl exitControl; private final SolUiControl commandHistoryUpControl; private final SolUiControl commandHistoryDownControl; private final List<SolUiControl> controls; private int commandHistoryIndex; private TabCompletionEngine completionEngine; private StringBuilder inputLine; public ConsoleScreen(Context context) { font = Assets.getFont("engine:main").getBitmapFont(); this.console = new ConsoleImpl(font, context); exitControl = new SolUiControl(null, true, Input.Keys.ESCAPE); commandHistoryUpControl = new SolUiControl(null, true, Input.Keys.UP); commandHistoryDownControl = new SolUiControl(null, true, Input.Keys.DOWN); controls = new ArrayList<>(); controls.add(exitControl); controls.add(commandHistoryUpControl); controls.add(commandHistoryDownControl); inputLine = new StringBuilder(); instance = this; completionEngine = new CyclingTabCompletionEngine(console); commandHistoryIndex = console.getPreviousCommands().size(); welcomePrinted = false; } public void init(SolGame game) { console.init(game); } public static Optional<ConsoleScreen> getInstance() { if (instance == null) { return Optional.empty(); } else { return Optional.of(instance); } } @Override public List<SolUiControl> getControls() { return controls; } @Override public void onAdd(SolApplication solApplication) { isActive = true; if (!welcomePrinted) { console.addMessage("Welcome to the world of Destination Sol! Your journey begins!" + Console.NEW_LINE + "Type 'help' to see a list with available commands or 'help <commandName>' for command details." + Console.NEW_LINE + "Text parameters do not need quotes, unless containing spaces. No commas between parameters." + Console.NEW_LINE + "You can use auto-completion by typing a partial command then hitting [tab] - examples:" + Console.NEW_LINE + Console.NEW_LINE + "gh + [tab] => 'ghost'" + Console.NEW_LINE + "help gh + [tab] => 'help ghost' (can auto complete commands fed to help)" + Console.NEW_LINE + "giv + [tab] => 'give givePermission' (use [tab] again to cycle between choices)" + Console.NEW_LINE + "lS + [tab] => 'listShapes' (camel casing abbreviated commands)" + Console.NEW_LINE); welcomePrinted = true; } } @Override public void updateCustom(SolApplication solApplication, SolInputManager.InputPointer[] inputPointers, boolean clickedOutside) { if (exitControl.isJustOff()) { solApplication.getInputManager().setScreen(solApplication, solApplication.getGame().getScreens().mainGameScreen); } if (commandHistoryUpControl.isJustOff()) { if (commandHistoryIndex > 0) { commandHistoryIndex--; this.inputLine = new StringBuilder(); this.inputLine.append(console.getPreviousCommands().get(commandHistoryIndex)); } } else if (commandHistoryDownControl.isJustOff()) { if (commandHistoryIndex < console.getPreviousCommands().size()) { commandHistoryIndex++; if (commandHistoryIndex == console.getPreviousCommands().size()) { this.inputLine = new StringBuilder(); } else { this.inputLine = new StringBuilder(); this.inputLine.append(console.getPreviousCommands().get(commandHistoryIndex)); } } } } @Override public boolean isCursorOnBackground(SolInputManager.InputPointer inputPointer) { return false; } @Override public void blurCustom(SolApplication solApplication) { isActive = false; } @Override public void drawBackground(UiDrawer uiDrawer, SolApplication solApplication) { drawFrame(uiDrawer); drawTextEntrySeparator(uiDrawer); } private void drawFrame(UiDrawer uiDrawer) { uiDrawer.draw(new Rectangle(TOP_LEFT.x, TOP_LEFT.y, (BOTTOM_RIGHT.x - TOP_LEFT.x), BOTTOM_RIGHT.y - TOP_LEFT.y), SolColor.UI_LIGHT); uiDrawer.draw(new Rectangle(TOP_LEFT.x + FRAME_WIDTH, TOP_LEFT.y + FRAME_WIDTH, (BOTTOM_RIGHT.x - TOP_LEFT.x) - 2 * FRAME_WIDTH, BOTTOM_RIGHT.y - TOP_LEFT.y - 2 * FRAME_WIDTH), SolColor.UI_BG_LIGHT); } private void drawTextEntrySeparator(UiDrawer uiDrawer) { // 20.333f - magic constant, change is console is ever resized uiDrawer.drawLine(TOP_LEFT.x + 2 * FRAME_WIDTH, getLineY(INPUT_LINE_SEPARATOR_Y), 0, (BOTTOM_RIGHT.x - TOP_LEFT.x) - 4 * FRAME_WIDTH, Color.WHITE); } @Override public void drawText(UiDrawer uiDrawer, SolApplication solApplication) { final float textX = TOP_LEFT.x + 2 * FRAME_WIDTH; // X position of all text Iterator<Message> iterator = console.getMessages().iterator(); int lineNumber = 0; while (iterator.hasNext() && lineNumber < ConsoleImpl.MAX_MESSAGE_HISTORY) { Message message = iterator.next(); uiDrawer.drawString(message.getMessage(), textX, getLineY(lineNumber), 0.5f, UiDrawer.TextAlignment.LEFT, false, message.getType().getColor()); lineNumber++; } drawInputLine(uiDrawer, textX); } private void drawInputLine(UiDrawer uiDrawer, float textX) { StringBuilder stringBuilder = new StringBuilder(); if (System.currentTimeMillis() % 2000 > 1000) { stringBuilder.append('_'); } int width = font.getData().getGlyph('_').width; for (char c : inputLine.reverse().toString().toCharArray()) { final BitmapFont.Glyph glyph = font.getData().getGlyph(c); if (glyph != null) { width += glyph.width < 10 ? 10 : glyph.width; if (width > ConsoleImpl.MAX_WIDTH_OF_LINE) { break; } stringBuilder.append(c); } else { inputLine.deleteCharAt(0); } } // 20.666f - magic constant, change if console is ever resized. uiDrawer.drawString(stringBuilder.reverse().toString(), textX, getLineY(INPUT_LINE_Y), 0.5f, UiDrawer.TextAlignment.LEFT, false, Color.WHITE); inputLine.reverse(); } @Override public void onNewConsoleMessage(Message message) { } public void onCharEntered (char character) { if (isActive) { logger.info(character + " CHAR"); if (character == '\t' && this.inputLine.length() > 0) { this.inputLine = new StringBuilder(this.completionEngine.complete(inputLine.toString())); } else if (character != '\t') { this.completionEngine.reset(); } if (character == '\r' || character == '\n') { console.addMessage("> " + inputLine.toString(), CoreMessageType.WARN); console.execute(inputLine.toString()); inputLine = new StringBuilder(); commandHistoryIndex = console.getPreviousCommands().size(); return; } if (character == '\b') { if (inputLine.length() != 0) { inputLine.deleteCharAt(inputLine.length() - 1); } return; } inputLine.append(character); } } private float getLineY(float line) { return TOP_LEFT.y + 2 * FRAME_WIDTH + line * UiDrawer.FONT_SIZE * 0.5f * 1.8f; } }
engine/src/main/java/org/destinationsol/game/screens/ConsoleScreen.java
/* * Copyright 2019 MovingBlocks * * 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.destinationsol.game.screens; import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import org.destinationsol.SolApplication; import org.destinationsol.assets.Assets; import org.destinationsol.common.SolColor; import org.destinationsol.game.SolGame; import org.destinationsol.game.console.Console; import org.destinationsol.game.console.ConsoleImpl; import org.destinationsol.game.console.ConsoleSubscriber; import org.destinationsol.game.console.CoreMessageType; import org.destinationsol.game.console.CyclingTabCompletionEngine; import org.destinationsol.game.console.Message; import org.destinationsol.game.console.TabCompletionEngine; import org.destinationsol.game.context.Context; import org.destinationsol.modules.ModuleManager; import org.destinationsol.ui.SolInputManager; import org.destinationsol.ui.SolUiControl; import org.destinationsol.ui.SolUiScreen; import org.destinationsol.ui.UiDrawer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; public class ConsoleScreen implements SolUiScreen, ConsoleSubscriber { private static final Logger logger = LoggerFactory.getLogger(ConsoleScreen.class); /** * Magic happens here. * <p> * Sets the maximum width a line of text can have to fit into the console, in some sort of magical units. If you * change {@link #TOP_LEFT}, {@link #BOTTOM_RIGHT} or {@link #FRAME_WIDTH}, be sure to change this number too. The * only way known to me how to figure out the expected value of this field, is to randomly change it until the text * fits into the console nicely. Be sure to uncomment the block of code in {@link #drawBackground(UiDrawer, SolApplication)} * to clearly see the expected width of the text. */ /** * Position of top left corner of the outermost frame of the console. */ private static final Vector2 TOP_LEFT = new Vector2(0.03f, 0.03f); /** * Position of bottom right corner of the outermost frame of the console. */ private static final Vector2 BOTTOM_RIGHT = new Vector2(0.8f, 0.5f); /** * Width of the gap between outer, inner and text area frames. */ private static final float FRAME_WIDTH = 0.02f; /** * "Line number" of the input line. */ private static final float INPUT_LINE_Y = 20.666f; /** * "Line number" of the input line separator. */ private static final float INPUT_LINE_SEPARATOR_Y = 20.333f; private Console console; private static ConsoleScreen instance; private boolean welcomePrinted; private boolean isActive; public final BitmapFont font; private final SolUiControl exitControl; private final SolUiControl commandHistoryUpControl; private final SolUiControl commandHistoryDownControl; private final List<SolUiControl> controls; private int commandHistoryIndex; private TabCompletionEngine completionEngine; private StringBuilder inputLine; public ConsoleScreen(Context context) { font = Assets.getFont("engine:main").getBitmapFont(); this.console = new ConsoleImpl(font, context); exitControl = new SolUiControl(null, true, Input.Keys.ESCAPE); commandHistoryUpControl = new SolUiControl(null, true, Input.Keys.UP); commandHistoryDownControl = new SolUiControl(null, true, Input.Keys.DOWN); controls = new ArrayList<>(); controls.add(exitControl); controls.add(commandHistoryUpControl); controls.add(commandHistoryDownControl); inputLine = new StringBuilder(); console.addMessage("Welcome to the world of Destination Sol! Your journey begins!"); instance = this; completionEngine = new CyclingTabCompletionEngine(console); commandHistoryIndex = console.getPreviousCommands().size(); welcomePrinted = false; } public void init(SolGame game) { console.init(game); } public static Optional<ConsoleScreen> getInstance() { if (instance == null) { return Optional.empty(); } else { return Optional.of(instance); } } @Override public List<SolUiControl> getControls() { return controls; } @Override public void onAdd(SolApplication solApplication) { isActive = true; if (!welcomePrinted) { console.addMessage("Welcome to the wonderful world of Terasology!" + Console.NEW_LINE + Console.NEW_LINE + "Type 'help' to see a list with available commands or 'help <commandName>' for command details." + Console.NEW_LINE + "Text parameters do not need quotes, unless containing spaces. No commas between parameters." + Console.NEW_LINE + "You can use auto-completion by typing a partial command then hitting [tab] - examples:" + Console.NEW_LINE + Console.NEW_LINE + "gh + [tab] => 'ghost'" + Console.NEW_LINE + "help gh + [tab] => 'help ghost' (can auto complete commands fed to help)" + Console.NEW_LINE + "giv + [tab] => 'give givePermission' (use [tab] again to cycle between choices)" + Console.NEW_LINE + "lS + [tab] => 'listShapes' (camel casing abbreviated commands)" + Console.NEW_LINE); welcomePrinted = true; } } @Override public void updateCustom(SolApplication solApplication, SolInputManager.InputPointer[] inputPointers, boolean clickedOutside) { if (exitControl.isJustOff()) { solApplication.getInputManager().setScreen(solApplication, solApplication.getGame().getScreens().mainGameScreen); } if (commandHistoryUpControl.isJustOff()) { if (commandHistoryIndex > 0) { commandHistoryIndex--; this.inputLine = new StringBuilder(); this.inputLine.append(console.getPreviousCommands().get(commandHistoryIndex)); } } else if (commandHistoryDownControl.isJustOff()) { if (commandHistoryIndex < console.getPreviousCommands().size()) { commandHistoryIndex++; if (commandHistoryIndex == console.getPreviousCommands().size()) { this.inputLine = new StringBuilder(); } else { this.inputLine = new StringBuilder(); this.inputLine.append(console.getPreviousCommands().get(commandHistoryIndex)); } } } } @Override public boolean isCursorOnBackground(SolInputManager.InputPointer inputPointer) { return false; } @Override public void blurCustom(SolApplication solApplication) { isActive = false; } @Override public void drawBackground(UiDrawer uiDrawer, SolApplication solApplication) { drawFrame(uiDrawer); drawTextEntrySeparator(uiDrawer); } private void drawFrame(UiDrawer uiDrawer) { uiDrawer.draw(new Rectangle(TOP_LEFT.x, TOP_LEFT.y, (BOTTOM_RIGHT.x - TOP_LEFT.x), BOTTOM_RIGHT.y - TOP_LEFT.y), SolColor.UI_LIGHT); uiDrawer.draw(new Rectangle(TOP_LEFT.x + FRAME_WIDTH, TOP_LEFT.y + FRAME_WIDTH, (BOTTOM_RIGHT.x - TOP_LEFT.x) - 2 * FRAME_WIDTH, BOTTOM_RIGHT.y - TOP_LEFT.y - 2 * FRAME_WIDTH), SolColor.UI_BG_LIGHT); } private void drawTextEntrySeparator(UiDrawer uiDrawer) { // 20.333f - magic constant, change is console is ever resized uiDrawer.drawLine(TOP_LEFT.x + 2 * FRAME_WIDTH, getLineY(INPUT_LINE_SEPARATOR_Y), 0, (BOTTOM_RIGHT.x - TOP_LEFT.x) - 4 * FRAME_WIDTH, Color.WHITE); } @Override public void drawText(UiDrawer uiDrawer, SolApplication solApplication) { final float textX = TOP_LEFT.x + 2 * FRAME_WIDTH; // X position of all text Iterator<Message> iterator = console.getMessages().iterator(); int lineNumber = 0; while (iterator.hasNext() && lineNumber < ConsoleImpl.MAX_MESSAGE_HISTORY) { Message message = iterator.next(); uiDrawer.drawString(message.getMessage(), textX, getLineY(lineNumber), 0.5f, UiDrawer.TextAlignment.LEFT, false, message.getType().getColor()); lineNumber++; } drawInputLine(uiDrawer, textX); } private void drawInputLine(UiDrawer uiDrawer, float textX) { StringBuilder stringBuilder = new StringBuilder(); if (System.currentTimeMillis() % 2000 > 1000) { stringBuilder.append('_'); } int width = font.getData().getGlyph('_').width; for (char c : inputLine.reverse().toString().toCharArray()) { final BitmapFont.Glyph glyph = font.getData().getGlyph(c); if (glyph != null) { width += glyph.width < 10 ? 10 : glyph.width; if (width > ConsoleImpl.MAX_WIDTH_OF_LINE) { break; } stringBuilder.append(c); } else { inputLine.deleteCharAt(0); } } // 20.666f - magic constant, change if console is ever resized. uiDrawer.drawString(stringBuilder.reverse().toString(), textX, getLineY(INPUT_LINE_Y), 0.5f, UiDrawer.TextAlignment.LEFT, false, Color.WHITE); inputLine.reverse(); } @Override public void onNewConsoleMessage(Message message) { } public void onCharEntered (char character) { if (isActive) { logger.info(character + " CHAR"); if (character == '\t' && this.inputLine.length() > 0) { this.inputLine = new StringBuilder(this.completionEngine.complete(inputLine.toString())); } else if (character != '\t') { this.completionEngine.reset(); } if (character == '\r' || character == '\n') { console.addMessage("> " + inputLine.toString(), CoreMessageType.WARN); console.execute(inputLine.toString()); inputLine = new StringBuilder(); commandHistoryIndex = console.getPreviousCommands().size(); return; } if (character == '\b') { if (inputLine.length() != 0) { inputLine.deleteCharAt(inputLine.length() - 1); } return; } inputLine.append(character); } } private float getLineY(float line) { return TOP_LEFT.y + 2 * FRAME_WIDTH + line * UiDrawer.FONT_SIZE * 0.5f * 1.8f; } }
Welcome text fix
engine/src/main/java/org/destinationsol/game/screens/ConsoleScreen.java
Welcome text fix
<ide><path>ngine/src/main/java/org/destinationsol/game/screens/ConsoleScreen.java <ide> controls.add(commandHistoryUpControl); <ide> controls.add(commandHistoryDownControl); <ide> inputLine = new StringBuilder(); <del> console.addMessage("Welcome to the world of Destination Sol! Your journey begins!"); <ide> instance = this; <ide> completionEngine = new CyclingTabCompletionEngine(console); <ide> <ide> public void onAdd(SolApplication solApplication) { <ide> isActive = true; <ide> if (!welcomePrinted) { <del> console.addMessage("Welcome to the wonderful world of Terasology!" + Console.NEW_LINE + <del> Console.NEW_LINE + <add> console.addMessage("Welcome to the world of Destination Sol! Your journey begins!" + Console.NEW_LINE + <ide> "Type 'help' to see a list with available commands or 'help <commandName>' for command details." + Console.NEW_LINE + <ide> "Text parameters do not need quotes, unless containing spaces. No commas between parameters." + Console.NEW_LINE + <ide> "You can use auto-completion by typing a partial command then hitting [tab] - examples:" + Console.NEW_LINE + Console.NEW_LINE +
JavaScript
mit
0b71f74a7e275db11b389da9aba9f551b7212413
0
Eiskis/layers-css,Eiskis/layers-css,Eiskis/layers-css
/** * Custom behavior */ // Scrolling behavior var scrollWindow = function (element, waypoint, duration) { if (duration < 1) return; var target = menuWaypoints[waypoint]+1; var difference = target - element.scrollTop; var perTick = difference / duration * 10; element.scrollTop = element.scrollTop + perTick; setTimeout(function() { scrollWindow(element, waypoint, duration - 5); }, 5); }; // Calculate waypoints for toggling the menu items var findWaypoints = function () { var results = []; // Menu position results.push(menuPrev.offsetTop + menuPrev.offsetHeight + getCss(menuPrev, 'margin-bottom')); // Sections for (var i = 0; i < menuLinks.length; i++) { var target = document.getElementById(menuLinks[i].getAttribute('href').substring(1)); results.push(target.offsetTop - menu.offsetHeight + getCss(target, 'border-top-width')); } return results; }; // Update menu and other elements as the user scrolls var watchWaypoints = function () { var i; var scrollPosition = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop; // Toggle fixed menu, we're in sections if (scrollPosition > menuWaypoints[0]) { addClass(menu, 'fixed'); var newWaypoint = 0; // Going up if (scrollPosition < menuWaypoints[currentWaypoint]) { newWaypoint = currentWaypoint - 1; // Going down, but not past end } else if (currentWaypoint < (menuWaypoints.length-1) && scrollPosition > menuWaypoints[currentWaypoint+1]) { newWaypoint = currentWaypoint + 1; } // We changed sections if (newWaypoint > 0) { currentWaypoint = newWaypoint; // Choose correct menu item for (i = 0; i < menuLinks.length; i++) { if (i === currentWaypoint-1) { addClass(menuLinks[i], 'selected'); menuLinks[i].focus(); } else { removeClass(menuLinks[i], 'selected'); // menuLinks[i].blur(); } } } // We're up in the intro of Timo } else { removeClass(menu, 'fixed'); currentWaypoint = 0; for (i = 0; i < menuLinks.length; i++) { menuLinks[i].blur(); removeClass(menuLinks[i], 'selected'); } } }; /** * Helpers */ // Helper to read numerical CSS values var getCss = function (target, property) { return parseInt(window.getComputedStyle(target).getPropertyValue(property), 10); }; // Class toggling var toggleClass = function (element, className) { if (hasClass(element, className)) { removeClass(element, className); } else { addClass(element, className); } }; var addClass = function (element, className) { if (!hasClass(element, className)) { element.className = element.className + ' ' + className; } }; var removeClass = function (element, className) { if (hasClass(element, className)) { element.className = (' ' + element.className.replace(' ' + className, '')).substring(1); } }; var hasClass = function (element, className) { return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1; }; /** * Document skeleton & configs */ var downloadLink = document.getElementsByClassName('download')[0]; var firstSection = document.getElementById('grid'); var intro = document.getElementsByClassName('row-intro')[0]; var menu = document.getElementById('menu'); var menuLinks = menu.getElementsByTagName('a'); var menuPrev = document.getElementsByClassName('display')[0]; var sourceContainers = document.getElementsByClassName('source'); var tabGuard = document.getElementsByClassName('tabGuard')[0]; var menuWaypoints = []; var currentWaypoint = 0; var highlightDownload = function () { addClass(intro, 'highlightDownload'); }; var removeHighlightDownload = function () { removeClass(intro, 'highlightDownload'); }; /** * App launch & bindings */ window.onload = function () { var i; // Highlight download link downloadLink.onmouseover = highlightDownload; downloadLink.onfocus = highlightDownload; downloadLink.onmouseout = removeHighlightDownload; downloadLink.onblur = removeHighlightDownload; // Cycle tabindex tabGuard.onfocus = function () { downloadLink.focus(); }; // Bind menu links to scrolling for (i = 0; i < menuLinks.length; i++) { (function () { var j = i; var links = menuLinks; links[j].onclick = function (event) { event.preventDefault(); scrollWindow(document.body, j+1, 300); scrollWindow(document.documentElement, j+1, 300); }; })(); } // Keep menu waypoints accurate menuWaypoints = findWaypoints(); window.onresize = function (event) { menuWaypoints = findWaypoints(); }; // Watch waypoints when scrolling watchWaypoints(); window.onscroll = watchWaypoints; // Source code previews for (i = 0; i < sourceContainers.length; i++) { (function () { var parent = sourceContainers[i]; parent.getElementsByClassName('trigger')[0].onclick = function (event) { event.preventDefault(); toggleClass(parent, 'collapsed'); // Recalculate waypoints (hacky) setTimeout(function () { menuWaypoints = findWaypoints(); }, 300); }; })(); } };
index/index.js
/** * Custom behavior */ // Scrolling behavior var scrollWindow = function (element, waypoint, duration) { if (duration < 1) return; var target = menuWaypoints[waypoint]+1; var difference = target - element.scrollTop; var perTick = difference / duration * 10; element.scrollTop = element.scrollTop + perTick; setTimeout(function() { scrollWindow(element, waypoint, duration - 5); }, 5); }; // Calculate waypoints for toggling the menu items var findWaypoints = function () { var results = []; // Menu position results.push(menuPrev.offsetTop + menuPrev.offsetHeight + getCss(menuPrev, 'margin-bottom')); // Sections for (var i = 0; i < menuLinks.length; i++) { var target = document.getElementById(menuLinks[i].getAttribute('href').substring(1)); results.push(target.offsetTop - menu.offsetHeight + getCss(target, 'border-top-width')); } return results; }; // Update menu and other elements as the user scrolls var watchWaypoints = function () { var i; var scrollPosition = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop; // Toggle fixed menu, we're in sections if (scrollPosition > menuWaypoints[0]) { addClass(menu, 'fixed'); var newWaypoint = 0; // Going up if (scrollPosition < menuWaypoints[currentWaypoint]) { newWaypoint = currentWaypoint - 1; // Going down, but not past end } else if (currentWaypoint < (menuWaypoints.length-1) && scrollPosition > menuWaypoints[currentWaypoint+1]) { newWaypoint = currentWaypoint + 1; } // We changed sections if (newWaypoint > 0) { currentWaypoint = newWaypoint; // Choose correct menu item for (i = 0; i < menuLinks.length; i++) { if (i === currentWaypoint-1) { addClass(menuLinks[i], 'selected'); menuLinks[i].focus(); } else { removeClass(menuLinks[i], 'selected'); // menuLinks[i].blur(); } } } // Switch selected item } else { removeClass(menu, 'fixed'); currentWaypoint = 0; for (i = 0; i < menuLinks.length; i++) { removeClass(menuLinks[i], 'selected'); } } }; /** * Helpers */ // Helper to read numerical CSS values var getCss = function (target, property) { return parseInt(window.getComputedStyle(target).getPropertyValue(property), 10); }; // Class toggling var toggleClass = function (element, className) { if (hasClass(element, className)) { removeClass(element, className); } else { addClass(element, className); } }; var addClass = function (element, className) { if (!hasClass(element, className)) { element.className = element.className + ' ' + className; } }; var removeClass = function (element, className) { if (hasClass(element, className)) { element.className = (' ' + element.className.replace(' ' + className, '')).substring(1); } }; var hasClass = function (element, className) { return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1; }; /** * Document skeleton & configs */ var downloadLink = document.getElementsByClassName('download')[0]; var firstSection = document.getElementById('grid'); var intro = document.getElementsByClassName('row-intro')[0]; var menu = document.getElementById('menu'); var menuLinks = menu.getElementsByTagName('a'); var menuPrev = document.getElementsByClassName('display')[0]; var sourceContainers = document.getElementsByClassName('source'); var tabGuard = document.getElementsByClassName('tabGuard')[0]; var menuWaypoints = []; var currentWaypoint = 0; var highlightDownload = function () { addClass(intro, 'highlightDownload'); }; var removeHighlightDownload = function () { removeClass(intro, 'highlightDownload'); }; /** * App launch & bindings */ window.onload = function () { var i; // Highlight download link downloadLink.onmouseover = highlightDownload; downloadLink.onfocus = highlightDownload; downloadLink.onmouseout = removeHighlightDownload; downloadLink.onblur = removeHighlightDownload; // Cycle tabindex tabGuard.onfocus = function () { downloadLink.focus(); }; // Bind menu links to scrolling for (i = 0; i < menuLinks.length; i++) { (function () { var j = i; var links = menuLinks; links[j].onclick = function (event) { event.preventDefault(); scrollWindow(document.body, j+1, 300); scrollWindow(document.documentElement, j+1, 300); }; })(); } // Keep menu waypoints accurate menuWaypoints = findWaypoints(); window.onresize = function (event) { menuWaypoints = findWaypoints(); }; // Watch waypoints when scrolling watchWaypoints(); window.onscroll = watchWaypoints; // Source code previews for (i = 0; i < sourceContainers.length; i++) { (function () { var parent = sourceContainers[i]; parent.getElementsByClassName('trigger')[0].onclick = function (event) { event.preventDefault(); toggleClass(parent, 'collapsed'); // Recalculate waypoints (hacky) setTimeout(function () { menuWaypoints = findWaypoints(); }, 300); }; })(); } };
Unfocusing menu items when ucrolling up
index/index.js
Unfocusing menu items when ucrolling up
<ide><path>ndex/index.js <ide> } <ide> <ide> <del> // Switch selected item <add> // We're up in the intro of Timo <ide> } else { <ide> removeClass(menu, 'fixed'); <ide> currentWaypoint = 0; <ide> for (i = 0; i < menuLinks.length; i++) { <add> menuLinks[i].blur(); <ide> removeClass(menuLinks[i], 'selected'); <ide> } <ide> }
Java
lgpl-2.1
dc30c00fae757f40c238312344a138e23a648d25
0
roidelapluie/mariadb-connector-j-travis,Mikelarg/mariadb-connector-j,roidelapluie/mariadb-connector-j,roidelapluie/mariadb-connector-j-travis,MariaDB/mariadb-connector-j,Mikelarg/mariadb-connector-j,roidelapluie/mariadb-connector-j,MariaDB/mariadb-connector-j
/* MariaDB Client for Java Copyright (c) 2012 Monty Program Ab. 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 Monty Program Ab [email protected]. This particular MariaDB Client for Java file is work derived from a Drizzle-JDBC. Drizzle-JDBC file which is covered by subject to the following copyright and notice provisions: Copyright (c) 2009-2011, Marcus Eriksson Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the driver nor the names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.mariadb.jdbc; import org.mariadb.jdbc.internal.SQLExceptionMapper; import org.mariadb.jdbc.internal.common.Protocol; import org.mariadb.jdbc.internal.common.QueryException; import org.mariadb.jdbc.internal.common.Utils; import org.mariadb.jdbc.internal.common.query.Query; import org.mariadb.jdbc.internal.common.query.QueryFactory; import org.mariadb.jdbc.internal.common.queryresults.ModifyQueryResult; import org.mariadb.jdbc.internal.common.queryresults.QueryResult; import org.mariadb.jdbc.internal.common.queryresults.ResultSetType; import org.mariadb.jdbc.internal.mysql.MySQLProtocol; import java.io.IOException; import java.sql.*; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Timer; import java.util.TimerTask; public class MySQLStatement implements Statement { /** * the protocol used to talk to the server. */ private final MySQLProtocol protocol; /** * the Connection object. */ protected MySQLConnection connection; /** * The actual query result. */ private QueryResult queryResult; /** * are warnings cleared? */ private boolean warningsCleared; /** * creates queries. */ private final QueryFactory queryFactory; private int queryTimeout; private boolean escapeProcessing; private int fetchSize; private int maxRows; boolean isClosed; private static volatile Timer timer; private TimerTask timerTask; private boolean isTimedout; Queue<Object> cachedResultSets; public boolean isStreaming() { return fetchSize == Integer.MIN_VALUE; } /** * Creates a new Statement. * * @param protocol the protocol to use. * @param connection the connection to return in getConnection. * @param queryFactory the query factory to produce internal queries. */ public MySQLStatement(final MySQLProtocol protocol, final MySQLConnection connection, final QueryFactory queryFactory) { this.protocol = protocol; this.connection = connection; this.queryFactory = queryFactory; this.escapeProcessing = true; cachedResultSets = new LinkedList<Object>(); } /** * returns the protocol. * * @return the protocol used. */ public Protocol getProtocol() { return protocol; } private static Timer getTimer() { Timer result = timer; if (result == null) { synchronized(MySQLStatement.class) { result = timer; if (result == null) { timer = result = new Timer(); } } } return result; } // Part of query prolog - setup timeout timer private void setTimerTask() { assert(timerTask == null); timerTask = new TimerTask() { @Override public void run() { try { isTimedout = true; protocol.cancelCurrentQuery(); } catch (Throwable e) { } } }; getTimer().schedule(timerTask, queryTimeout*1000); } // Part of query prolog - check if connection is broken and reconnect private void checkReconnect() throws SQLException { if (protocol.shouldReconnect()) { try { protocol.connect(); } catch (QueryException qe) { SQLExceptionMapper.throwException(qe, connection, this); } } else if (protocol.shouldTryFailback()) { try { protocol.reconnectToMaster(); } catch (Exception e) { // Do nothing } } } void executeQueryProlog() throws SQLException{ checkReconnect(); if (protocol.hasUnreadData()) { throw new SQLException("There is an open result set on the current connection, "+ "which must be closed prior to executing a query"); } if (protocol.hasMoreResults()) { // Skip remaining result sets. CallableStatement might return many of them - // not only the "select" result sets, but also the "update" results while(getMoreResults(true)) { } } cachedResultSets.clear(); MySQLConnection conn = (MySQLConnection)getConnection(); conn.reenableWarnings(); try { protocol.setMaxRows(maxRows); } catch(QueryException qe) { SQLExceptionMapper.throwException(qe, connection, this); } if (queryTimeout != 0) { setTimerTask(); } } private void cacheMoreResults() { if (isStreaming()) return; QueryResult saveResult = queryResult; for(;;) { try { if (getMoreResults(false)) { cachedResultSets.add(queryResult); } else { break; } } catch(SQLException e) { cachedResultSets.add(e); break; } } queryResult = saveResult; } /* Reset timeout after query, re-throw correct SQL exception */ private void executeQueryEpilog(QueryException e, Query query) throws SQLException{ if (timerTask != null) { timerTask.cancel(); timerTask = null; } if (isTimedout) { isTimedout = false; e = new QueryException("Query timed out", 1317, "JZ0002", e); } if (e == null) return; if (protocol.getInfo().getProperty("dumpQueriesOnException", "false").equalsIgnoreCase("true")) { e.setMessage(e.getMessage()+ "\nQuery is : " + query); } SQLExceptionMapper.throwException(e, connection, this); } /** * executes a query. * * @param query the query * @return true if there was a result set, false otherwise. * @throws SQLException */ protected boolean execute(Query query) throws SQLException { synchronized (protocol) { if (isClosed()) { throw new SQLException("execute() is called on closed statement"); } QueryException exception = null; executeQueryProlog(); try { queryResult = protocol.executeQuery(query, isStreaming()); cacheMoreResults(); return (queryResult.getResultSetType() == ResultSetType.SELECT); } catch (QueryException e) { exception = e; return false; } finally { executeQueryEpilog(exception, query); } } } /** * executes a select query. * * @param query the query to send to the server * @return a result set * @throws SQLException if something went wrong */ protected ResultSet executeQuery(Query query) throws SQLException { if (execute(query)) { return new MySQLResultSet(queryResult, this, protocol); } //throw new SQLException("executeQuery() with query '" + query +"' did not return a result set"); return MySQLResultSet.EMPTY; } /** * Executes an update. * * @param query the update query. * @return update count * @throws SQLException if the query could not be sent to server. */ protected int executeUpdate(Query query) throws SQLException { if (execute(query)) return 0; return getUpdateCount(); } private Query stringToQuery(String queryString) throws SQLException { if (escapeProcessing) { queryString = Utils.nativeSQL(queryString,connection.noBackslashEscapes); } return queryFactory.createQuery(queryString); } /** * executes a query. * * @param queryString the query * @return true if there was a result set, false otherwise. * @throws SQLException */ public boolean execute(String queryString) throws SQLException { return execute(stringToQuery(queryString)); } /** * Executes an update. * * @param queryString the update query. * @return update count * @throws SQLException if the query could not be sent to server. */ public int executeUpdate(String queryString) throws SQLException { return executeUpdate(stringToQuery(queryString)); } /** * executes a select query. * * @param queryString the query to send to the server * @return a result set * @throws SQLException if something went wrong */ public ResultSet executeQuery(String queryString) throws SQLException { return executeQuery(stringToQuery(queryString)); } public QueryFactory getQueryFactory() { return queryFactory; } /** * Releases this <code>Statement</code> object's database and JDBC resources immediately instead of waiting for this * to happen when it is automatically closed. It is generally good practice to release resources as soon as you are * finished with them to avoid tying up database resources. * <p/> * Calling the method <code>close</code> on a <code>Statement</code> object that is already closed has no effect. * <p/> * <B>Note:</B>When a <code>Statement</code> object is closed, its current <code>ResultSet</code> object, if one * exists, is also closed. * * @throws java.sql.SQLException if a database access error occurs */ public void close() throws SQLException { if (queryResult != null) { queryResult.close(); queryResult = null; } // No possible future use for the cached results, so these can be cleared // This makes the cache eligible for garbage collection earlier if the statement is not // immediately garbage collected cachedResultSets.clear(); if (isStreaming()) { synchronized (protocol) { // Skip all outstanding result sets while(getMoreResults(true)) { } } } isClosed = true; } /** * Retrieves the maximum number of bytes that can be returned for character and binary column values in a * <code>ResultSet</code> object produced by this <code>Statement</code> object. This limit applies only to * <code>BINARY</code>, <code>VARBINARY</code>, <code>LONGVARBINARY</code>, <code>CHAR</code>, <code>VARCHAR</code>, * <code>NCHAR</code>, <code>NVARCHAR</code>, <code>LONGNVARCHAR</code> and <code>LONGVARCHAR</code> columns. If * the limit is exceeded, the excess data is silently discarded. * * @return the current column size limit for columns storing character and binary values; zero means there is no * limit * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @see #setMaxFieldSize */ public int getMaxFieldSize() throws SQLException { return 0; } /** * Sets the limit for the maximum number of bytes that can be returned for character and binary column values in a * <code>ResultSet</code> object produced by this <code>Statement</code> object. * <p/> * This limit applies only to <code>BINARY</code>, <code>VARBINARY</code>, <code>LONGVARBINARY</code>, * <code>CHAR</code>, <code>VARCHAR</code>, <code>NCHAR</code>, <code>NVARCHAR</code>, <code>LONGNVARCHAR</code> and * <code>LONGVARCHAR</code> fields. If the limit is exceeded, the excess data is silently discarded. For maximum * portability, use values greater than 256. * * @param max the new column size limit in bytes; zero means there is no limit * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the condition max >= 0 is not satisfied * @see #getMaxFieldSize */ public void setMaxFieldSize(final int max) throws SQLException { //we dont support max field sizes } /** * Retrieves the maximum number of rows that a <code>ResultSet</code> object produced by this <code>Statement</code> * object can contain. If this limit is exceeded, the excess rows are silently dropped. * * @return the current maximum number of rows for a <code>ResultSet</code> object produced by this * <code>Statement</code> object; zero means there is no limit * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @see #setMaxRows */ public int getMaxRows() throws SQLException { return maxRows; } /** * Sets the limit for the maximum number of rows that any <code>ResultSet</code> object generated by this * <code>Statement</code> object can contain to the given number. If the limit is exceeded, the excess rows are * silently dropped. * * @param max the new max rows limit; zero means there is no limit * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the condition max >= 0 is not satisfied * @see #getMaxRows */ public void setMaxRows(final int max) throws SQLException { if (max < 0) { throw new SQLException("max rows is negative"); } maxRows = max; } /** * Sets escape processing on or off. If escape scanning is on (the default), the driver will do escape substitution * before sending the SQL statement to the database. * <p/> * Note: Since prepared statements have usually been parsed prior to making this call, disabling escape processing * for <code>PreparedStatements</code> objects will have no effect. * * @param enable <code>true</code> to enable escape processing; <code>false</code> to disable it * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> */ public void setEscapeProcessing(final boolean enable) throws SQLException { escapeProcessing = enable; } /** * Retrieves the number of seconds the driver will wait for a <code>Statement</code> object to execute. If the limit * is exceeded, a <code>SQLException</code> is thrown. * * @return the current query timeout limit in seconds; zero means there is no limit * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @see #setQueryTimeout */ public int getQueryTimeout() throws SQLException { return queryTimeout; } /** * Sets the number of seconds the driver will wait for a <code>Statement</code> object to execute to the given * number of seconds. If the limit is exceeded, an <code>SQLException</code> is thrown. A JDBC driver must apply * this limit to the <code>execute</code>, <code>executeQuery</code> and <code>executeUpdate</code> methods. JDBC * driver implementations may also apply this limit to <code>ResultSet</code> methods (consult your driver vendor * documentation for details). * * @param seconds the new query timeout limit in seconds; zero means there is no limit * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the condition seconds >= 0 is not satisfied * @see #getQueryTimeout */ public void setQueryTimeout(final int seconds) throws SQLException { this.queryTimeout = seconds; } /** * Cancels this <code>Statement</code> object if both the DBMS and driver support aborting an SQL statement. This * method can be used by one thread to cancel a statement that is being executed by another thread. * * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method */ public void cancel() throws SQLException { try { protocol.cancelCurrentQuery(); } catch (QueryException e) { SQLExceptionMapper.throwException(e, connection, this); } catch (IOException e) { // connection gone, query is definitely canceled } } /** * Retrieves the first warning reported by calls on this <code>Statement</code> object. Subsequent * <code>Statement</code> object warnings will be chained to this <code>SQLWarning</code> object. * <p/> * <p>The warning chain is automatically cleared each time a statement is (re)executed. This method may not be * called on a closed <code>Statement</code> object; doing so will cause an <code>SQLException</code> to be thrown. * <p/> * <P><B>Note:</B> If you are processing a <code>ResultSet</code> object, any warnings associated with reads on that * <code>ResultSet</code> object will be chained on it rather than on the <code>Statement</code> object that * produced it. * * @return the first <code>SQLWarning</code> object or <code>null</code> if there are no warnings * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> */ public SQLWarning getWarnings() throws SQLException { if (!warningsCleared) { return this.connection.getWarnings(); } return null; } /** * Clears all the warnings reported on this <code>Statement</code> object. After a call to this method, the method * <code>getWarnings</code> will return <code>null</code> until a new warning is reported for this * <code>Statement</code> object. * * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> */ public void clearWarnings() throws SQLException { warningsCleared = true; } /** * Sets the SQL cursor name to the given <code>String</code>, which will be used by subsequent * <code>Statement</code> object <code>execute</code> methods. This name can then be used in SQL positioned update * or delete statements to identify the current row in the <code>ResultSet</code> object generated by this * statement. If the database does not support positioned update/delete, this method is a noop. To insure that a * cursor has the proper isolation level to support updates, the cursor's <code>SELECT</code> statement should have * the form <code>SELECT FOR UPDATE</code>. If <code>FOR UPDATE</code> is not present, positioned updates may * fail. * <p/> * <P><B>Note:</B> By definition, the execution of positioned updates and deletes must be done by a different * <code>Statement</code> object than the one that generated the <code>ResultSet</code> object being used for * positioning. Also, cursor names must be unique within a connection. * * @param name the new cursor name, which must be unique within a connection * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method */ public void setCursorName(final String name) throws SQLException { throw SQLExceptionMapper.getFeatureNotSupportedException("Cursors are not supported"); } /** * gets the connection that created this statement * * @return the connection * @throws SQLException */ public Connection getConnection() throws SQLException { return this.connection; } /** * Moves to this <code>Statement</code> object's next result, deals with any current <code>ResultSet</code> * object(s) according to the instructions specified by the given flag, and returns <code>true</code> if the next * result is a <code>ResultSet</code> object. * <p/> * <P>There are no more results when the following is true: <PRE> // stmt is a Statement object * ((stmt.getMoreResults(current) == false) && (stmt.getUpdateCount() == -1)) </PRE> * * @param current one of the following <code>Statement</code> constants indicating what should happen to current * <code>ResultSet</code> objects obtained using the method <code>getResultSet</code>: * <code>Statement.CLOSE_CURRENT_RESULT</code>, <code>Statement.KEEP_CURRENT_RESULT</code>, or * <code>Statement.CLOSE_ALL_RESULTS</code> * @return <code>true</code> if the next result is a <code>ResultSet</code> object; <code>false</code> if it is an * update count or there are no more results * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the argument supplied is not one of the following: * <code>Statement.CLOSE_CURRENT_RESULT</code>, <code>Statement.KEEP_CURRENT_RESULT</code> * or <code>Statement.CLOSE_ALL_RESULTS</code> * @throws java.sql.SQLFeatureNotSupportedException * if <code>DatabaseMetaData.supportsMultipleOpenResults</code> returns * <code>false</code> and either <code>Statement.KEEP_CURRENT_RESULT</code> or * <code>Statement.CLOSE_ALL_RESULTS</code> are supplied as the argument. * @see #execute * @since 1.4 */ public boolean getMoreResults(final int current) throws SQLException { return getMoreResults(); } /** * Retrieves any auto-generated keys created as a result of executing this <code>Statement</code> object. If this * <code>Statement</code> object did not generate any keys, an empty <code>ResultSet</code> object is returned. * <p/> * <p><B>Note:</B>If the columns which represent the auto-generated keys were not specified, the JDBC driver * implementation will determine the columns which best represent the auto-generated keys. * * @return a <code>ResultSet</code> object containing the auto-generated key(s) generated by the execution of this * <code>Statement</code> object * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method * @since 1.4 */ public ResultSet getGeneratedKeys() throws SQLException { if (queryResult != null && queryResult.getResultSetType() == ResultSetType.MODIFY) { final QueryResult genRes = ((ModifyQueryResult) queryResult).getGeneratedKeysResult(); return new MySQLGeneratedKeysResultSet(genRes, this, protocol); } return MySQLResultSet.EMPTY; } /** * Executes the given SQL statement and signals the driver with the given flag about whether the auto-generated keys * produced by this <code>Statement</code> object should be made available for retrieval. The driver will ignore * the flag if the SQL statement is not an <code>INSERT</code> statement, or an SQL statement able to return * auto-generated keys (the list of such statements is vendor-specific). * * @param sql an SQL Data Manipulation Language (DML) statement, such as <code>INSERT</code>, * <code>UPDATE</code> or <code>DELETE</code>; or an SQL statement that returns nothing, * such as a DDL statement. * @param autoGeneratedKeys a flag indicating whether auto-generated keys should be made available for retrieval; * one of the following constants: <code>Statement.RETURN_GENERATED_KEYS</code> * <code>Statement.NO_GENERATED_KEYS</code> * @return either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements * that return nothing * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code>, the given SQL statement returns a <code>ResultSet</code> * object, or the given constant is not one of those allowed * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method with a constant of * Statement.RETURN_GENERATED_KEYS * @since 1.4 */ public int executeUpdate(final String sql, final int autoGeneratedKeys) throws SQLException { return executeUpdate(sql); } /** * Executes the given SQL statement and signals the driver that the auto-generated keys indicated in the given array * should be made available for retrieval. This array contains the indexes of the columns in the target table that * contain the auto-generated keys that should be made available. The driver will ignore the array if the SQL * statement is not an <code>INSERT</code> statement, or an SQL statement able to return auto-generated keys (the * list of such statements is vendor-specific). * * @param sql an SQL Data Manipulation Language (DML) statement, such as <code>INSERT</code>, * <code>UPDATE</code> or <code>DELETE</code>; or an SQL statement that returns nothing, such * as a DDL statement. * @param columnIndexes an array of column indexes indicating the columns that should be returned from the inserted * row * @return either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements * that return nothing * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code>, the SQL statement returns a <code>ResultSet</code> object, * or the second argument supplied to this method is not an <code>int</code> array * whose elements are valid column indexes * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method * @since 1.4 */ public int executeUpdate(final String sql, final int[] columnIndexes) throws SQLException { return executeUpdate(sql); } /** * Executes the given SQL statement and signals the driver that the auto-generated keys indicated in the given array * should be made available for retrieval. This array contains the names of the columns in the target table that * contain the auto-generated keys that should be made available. The driver will ignore the array if the SQL * statement is not an <code>INSERT</code> statement, or an SQL statement able to return auto-generated keys (the * list of such statements is vendor-specific). * * @param sql an SQL Data Manipulation Language (DML) statement, such as <code>INSERT</code>, * <code>UPDATE</code> or <code>DELETE</code>; or an SQL statement that returns nothing, such as * a DDL statement. * @param columnNames an array of the names of the columns that should be returned from the inserted row * @return either the row count for <code>INSERT</code>, <code>UPDATE</code>, or <code>DELETE</code> statements, or * 0 for SQL statements that return nothing * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code>, the SQL statement returns a <code>ResultSet</code> object, * or the second argument supplied to this method is not a <code>String</code> array * whose elements are valid column names * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method * @since 1.4 */ public int executeUpdate(final String sql, final String[] columnNames) throws SQLException { return executeUpdate(sql); } /** * Executes the given SQL statement, which may return multiple results, and signals the driver that any * auto-generated keys should be made available for retrieval. The driver will ignore this signal if the SQL * statement is not an <code>INSERT</code> statement, or an SQL statement able to return auto-generated keys (the * list of such statements is vendor-specific). * <p/> * In some (uncommon) situations, a single SQL statement may return multiple result sets and/or update counts. * Normally you can ignore this unless you are (1) executing a stored procedure that you know may return multiple * results or (2) you are dynamically executing an unknown SQL string. * <p/> * The <code>execute</code> method executes an SQL statement and indicates the form of the first result. You must * then use the methods <code>getResultSet</code> or <code>getUpdateCount</code> to retrieve the result, and * <code>getMoreResults</code> to move to any subsequent result(s). * * @param sql any SQL statement * @param autoGeneratedKeys a constant indicating whether auto-generated keys should be made available for retrieval * using the method <code>getGeneratedKeys</code>; one of the following constants: * <code>Statement.RETURN_GENERATED_KEYS</code> or <code>Statement.NO_GENERATED_KEYS</code> * @return <code>true</code> if the first result is a <code>ResultSet</code> object; <code>false</code> if it is an * update count or there are no results * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the second parameter supplied to this method is not * <code>Statement.RETURN_GENERATED_KEYS</code> or <code>Statement.NO_GENERATED_KEYS</code>. * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method with a constant of * Statement.RETURN_GENERATED_KEYS * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults * @see #getGeneratedKeys * @since 1.4 */ public boolean execute(final String sql, final int autoGeneratedKeys) throws SQLException { return execute(sql); // auto generated keys are always available } /** * Executes the given SQL statement, which may return multiple results, and signals the driver that the * auto-generated keys indicated in the given array should be made available for retrieval. This array contains the * indexes of the columns in the target table that contain the auto-generated keys that should be made available. * The driver will ignore the array if the SQL statement is not an <code>INSERT</code> statement, or an SQL * statement able to return auto-generated keys (the list of such statements is vendor-specific). * <p/> * Under some (uncommon) situations, a single SQL statement may return multiple result sets and/or update counts. * Normally you can ignore this unless you are (1) executing a stored procedure that you know may return multiple * results or (2) you are dynamically executing an unknown SQL string. * <p/> * The <code>execute</code> method executes an SQL statement and indicates the form of the first result. You must * then use the methods <code>getResultSet</code> or <code>getUpdateCount</code> to retrieve the result, and * <code>getMoreResults</code> to move to any subsequent result(s). * * @param sql any SQL statement * @param columnIndexes an array of the indexes of the columns in the inserted row that should be made available * for retrieval by a call to the method <code>getGeneratedKeys</code> * @return <code>true</code> if the first result is a <code>ResultSet</code> object; <code>false</code> if it is an * update count or there are no results * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the elements in the <code>int</code> array passed to this * method are not valid column indexes * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults * @since 1.4 */ public boolean execute(final String sql, final int[] columnIndexes) throws SQLException { return execute(sql); } /** * Executes the given SQL statement, which may return multiple results, and signals the driver that the * auto-generated keys indicated in the given array should be made available for retrieval. This array contains the * names of the columns in the target table that contain the auto-generated keys that should be made available. The * driver will ignore the array if the SQL statement is not an <code>INSERT</code> statement, or an SQL statement * able to return auto-generated keys (the list of such statements is vendor-specific). * <p/> * In some (uncommon) situations, a single SQL statement may return multiple result sets and/or update counts. * Normally you can ignore this unless you are (1) executing a stored procedure that you know may return multiple * results or (2) you are dynamically executing an unknown SQL string. * <p/> * The <code>execute</code> method executes an SQL statement and indicates the form of the first result. You must * then use the methods <code>getResultSet</code> or <code>getUpdateCount</code> to retrieve the result, and * <code>getMoreResults</code> to move to any subsequent result(s). * * @param sql any SQL statement * @param columnNames an array of the names of the columns in the inserted row that should be made available for * retrieval by a call to the method <code>getGeneratedKeys</code> * @return <code>true</code> if the next result is a <code>ResultSet</code> object; <code>false</code> if it is an * update count or there are no more results * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the elements of the <code>String</code> array passed to * this method are not valid column names * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults * @see #getGeneratedKeys * @since 1.4 */ public boolean execute(final String sql, final String[] columnNames) throws SQLException { return execute(sql); } /** * Retrieves the result set holdability for <code>ResultSet</code> objects generated by this <code>Statement</code> * object. * * @return either <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code> * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @since 1.4 */ public int getResultSetHoldability() throws SQLException { return ResultSet.HOLD_CURSORS_OVER_COMMIT; } /** * Retrieves whether this <code>Statement</code> object has been closed. A <code>Statement</code> is closed if the * method close has been called on it, or if it is automatically closed. * * @return true if this <code>Statement</code> object is closed; false if it is still open * @throws java.sql.SQLException if a database access error occurs * @since 1.6 */ public boolean isClosed() throws SQLException { return isClosed; } /** * Requests that a <code>Statement</code> be pooled or not pooled. The value specified is a hint to the statement * pool implementation indicating whether the applicaiton wants the statement to be pooled. It is up to the * statement pool manager as to whether the hint is used. * <p/> * The poolable value of a statement is applicable to both internal statement caches implemented by the driver and * external statement caches implemented by application servers and other applications. * <p/> * By default, a <code>Statement</code> is not poolable when created, and a <code>PreparedStatement</code> and * <code>CallableStatement</code> are poolable when created. * <p/> * * @param poolable requests that the statement be pooled if true and that the statement not be pooled if false * <p/> * @throws java.sql.SQLException if this method is called on a closed <code>Statement</code> * <p/> * @since 1.6 */ public void setPoolable(final boolean poolable) throws SQLException { } /** * Returns a value indicating whether the <code>Statement</code> is poolable or not. * <p/> * * @return <code>true</code> if the <code>Statement</code> is poolable; <code>false</code> otherwise * <p/> * @throws java.sql.SQLException if this method is called on a closed <code>Statement</code> * <p/> * @see java.sql.Statement#setPoolable(boolean) setPoolable(boolean) * @since 1.6 * <p/> */ public boolean isPoolable() throws SQLException { return false; } public ResultSet getResultSet() throws SQLException { return new MySQLResultSet(queryResult,this,protocol); } public int getUpdateCount() throws SQLException { if(queryResult.getResultSetType() == ResultSetType.SELECT) { return -1; } return (int) ((ModifyQueryResult) queryResult).getUpdateCount(); } private boolean getMoreResults(boolean streaming) throws SQLException { try { synchronized(protocol) { if (queryResult != null) { queryResult.close(); } queryResult = protocol.getMoreResults(streaming); if(queryResult == null) return false; warningsCleared = false; connection.reenableWarnings(); return true; } } catch (QueryException e) { SQLExceptionMapper.throwException(e, connection, this); return false; } } /** * Moves to this <code>Statement</code> object's next result, returns <code>true</code> if it is a * <code>ResultSet</code> object, and implicitly closes any current <code>ResultSet</code> object(s) obtained with * the method <code>getResultSet</code>. * <p/> * <P>There are no more results when the following is true: <PRE> // stmt is a Statement object * ((stmt.getMoreResults() == false) && (stmt.getUpdateCount() == -1)) </PRE> * * @return <code>true</code> if the next result is a <code>ResultSet</code> object; <code>false</code> if it is an * update count or there are no more results * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @see #execute */ public boolean getMoreResults() throws SQLException { if (!isStreaming()) { /* return pre-cached result set, if available */ if(cachedResultSets.isEmpty()) return false; Object o = cachedResultSets.remove(); if (o instanceof SQLException) throw (SQLException)o; queryResult = (QueryResult)o; return true; } return getMoreResults(false); } /** * Gives the driver a hint as to the direction in which rows will be processed in <code>ResultSet</code> objects * created using this <code>Statement</code> object. The default value is <code>ResultSet.FETCH_FORWARD</code>. * <p/> * Note that this method sets the default fetch direction for result sets generated by this <code>Statement</code> * object. Each result set has its own methods for getting and setting its own fetch direction. * * @param direction the initial direction for processing rows * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the given direction is not one of * <code>ResultSet.FETCH_FORWARD</code>, <code>ResultSet.FETCH_REVERSE</code>, or * <code>ResultSet.FETCH_UNKNOWN</code> * @see #getFetchDirection * @since 1.2 */ public void setFetchDirection(final int direction) throws SQLException { } /** * Retrieves the direction for fetching rows from database tables that is the default for result sets generated from * this <code>Statement</code> object. If this <code>Statement</code> object has not set a fetch direction by * calling the method <code>setFetchDirection</code>, the return value is implementation-specific. * * @return the default fetch direction for result sets generated from this <code>Statement</code> object * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @see #setFetchDirection * @since 1.2 */ public int getFetchDirection() throws SQLException { return ResultSet.FETCH_FORWARD; } /** * Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are * needed for <code>ResultSet</code> objects genrated by this <code>Statement</code>. If the value specified is * zero, then the hint is ignored. The default value is zero. * * @param rows the number of rows to fetch * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the condition <code>rows >= 0</code> is not satisfied. * @see #getFetchSize * @since 1.2 */ public void setFetchSize(final int rows) throws SQLException { if (rows < 0 && rows != Integer.MIN_VALUE) throw new SQLException("invalid fetch size"); this.fetchSize = rows; } /** * Retrieves the number of result set rows that is the default fetch size for <code>ResultSet</code> objects * generated from this <code>Statement</code> object. If this <code>Statement</code> object has not set a fetch size * by calling the method <code>setFetchSize</code>, the return value is implementation-specific. * * @return the default fetch size for result sets generated from this <code>Statement</code> object * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @see #setFetchSize * @since 1.2 */ public int getFetchSize() throws SQLException { return this.fetchSize; } /** * Retrieves the result set concurrency for <code>ResultSet</code> objects generated by this <code>Statement</code> * object. * * @return either <code>ResultSet.CONCUR_READ_ONLY</code> or <code>ResultSet.CONCUR_UPDATABLE</code> * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @since 1.2 */ public int getResultSetConcurrency() throws SQLException { return ResultSet.CONCUR_READ_ONLY; } /** * Retrieves the result set type for <code>ResultSet</code> objects generated by this <code>Statement</code> * object. * * @return one of <code>ResultSet.TYPE_FORWARD_ONLY</code>, <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or * <code>ResultSet.TYPE_SCROLL_SENSITIVE</code> * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @since 1.2 */ public int getResultSetType() throws SQLException { // TODO: this will change when the async protocol is implemented return ResultSet.TYPE_SCROLL_INSENSITIVE; } /** * Adds the given SQL command to the current list of commmands for this <code>Statement</code> object. The commands * in this list can be executed as a batch by calling the method <code>executeBatch</code>. * <p/> * * @param sql typically this is a SQL <code>INSERT</code> or <code>UPDATE</code> statement * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the driver does not support batch updates * @see #executeBatch * @see java.sql.DatabaseMetaData#supportsBatchUpdates * @since 1.2 */ public void addBatch(final String sql) throws SQLException { this.protocol.addToBatch(queryFactory.createQuery(sql)); } public void addBatch(final byte[] sql) throws SQLException { this.protocol.addToBatch(queryFactory.createQuery(sql)); } /** * Empties this <code>Statement</code> object's current list of SQL commands. * <p/> * * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the driver does not support batch updates * @see #addBatch * @see java.sql.DatabaseMetaData#supportsBatchUpdates * @since 1.2 */ public void clearBatch() throws SQLException { this.protocol.clearBatch(); } /** * Submits a batch of commands to the database for execution and if all commands execute successfully, returns an * array of update counts. The <code>int</code> elements of the array that is returned are ordered to correspond to * the commands in the batch, which are ordered according to the order in which they were added to the batch. The * elements in the array returned by the method <code>executeBatch</code> may be one of the following: <OL> <LI>A * number greater than or equal to zero -- indicates that the command was processed successfully and is an update * count giving the number of rows in the database that were affected by the command's execution <LI>A value of * <code>SUCCESS_NO_INFO</code> -- indicates that the command was processed successfully but that the number of rows * affected is unknown * <p/> * If one of the commands in a batch update fails to execute properly, this method throws a * <code>BatchUpdateException</code>, and a JDBC driver may or may not continue to process the remaining commands in * the batch. However, the driver's behavior must be consistent with a particular DBMS, either always continuing to * process commands or never continuing to process commands. If the driver continues processing after a failure, * the array returned by the method <code>BatchUpdateException.getUpdateCounts</code> will contain as many elements * as there are commands in the batch, and at least one of the elements will be the following: * <p/> * <LI>A value of <code>EXECUTE_FAILED</code> -- indicates that the command failed to execute successfully and * occurs only if a driver continues to process commands after a command fails </OL> * <p/> * The possible implementations and return values have been modified in the Java 2 SDK, Standard Edition, version * 1.3 to accommodate the option of continuing to proccess commands in a batch update after a * <code>BatchUpdateException</code> obejct has been thrown. * * @return an array of update counts containing one element for each command in the batch. The elements of the * array are ordered according to the order in which commands were added to the batch. * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the driver does not support batch statements. Throws * {@link java.sql.BatchUpdateException} (a subclass of <code>SQLException</code>) if * one of the commands sent to the database fails to execute properly or attempts to * return a result set. * @see #addBatch * @see java.sql.DatabaseMetaData#supportsBatchUpdates * @since 1.3 */ public int[] executeBatch() throws SQLException { try { final List<QueryResult> queryRes = protocol.executeBatch(); final int[] retVals = new int[queryRes.size()]; int i = 0; for (final QueryResult qr : queryRes) { if (qr.getResultSetType() == ResultSetType.MODIFY) { retVals[i++] = (int) ((ModifyQueryResult) qr).getUpdateCount(); //TODO: this needs to be handled according to javadoc } else { retVals[i++] = SUCCESS_NO_INFO; } } return retVals; } catch (QueryException e) { SQLExceptionMapper.throwException(e, connection, this); return null; } } /** * Returns an object that implements the given interface to allow access to non-standard methods, or standard * methods not exposed by the proxy. * <p/> * If the receiver implements the interface then the result is the receiver or a proxy for the receiver. If the * receiver is a wrapper and the wrapped object implements the interface then the result is the wrapped object or a * proxy for the wrapped object. Otherwise return the the result of calling <code>unwrap</code> recursively on the * wrapped object or a proxy for that result. If the receiver is not a wrapper and does not implement the interface, * then an <code>SQLException</code> is thrown. * * @param iface A Class defining an interface that the result must implement. * @return an object that implements the interface. May be a proxy for the actual implementing object. * @throws java.sql.SQLException If no object found that implements the interface * @since 1.6 */ public <T> T unwrap(final Class<T> iface) throws SQLException { return null; } /** * Returns true if this either implements the interface argument or is directly or indirectly a wrapper for an * object that does. Returns false otherwise. If this implements the interface then return true, else if this is a * wrapper then return the result of recursively calling <code>isWrapperFor</code> on the wrapped object. If this * does not implement the interface and is not a wrapper, return false. This method should be implemented as a * low-cost operation compared to <code>unwrap</code> so that callers can use this method to avoid expensive * <code>unwrap</code> calls that may fail. If this method returns true then calling <code>unwrap</code> with the * same argument should succeed. * * @param iface a Class defining an interface. * @return true if this implements the interface or directly or indirectly wraps an object that does. * @throws java.sql.SQLException if an error occurs while determining whether this is a wrapper for an object with * the given interface. * @since 1.6 */ public boolean isWrapperFor(final Class<?> iface) throws SQLException { return false; } /** * returns the query result. * * @return the queryresult */ protected QueryResult getQueryResult() { return queryResult; } /** * sets the current query result * * @param result */ protected void setQueryResult(final QueryResult result) { this.queryResult = result; } public void closeOnCompletion() throws SQLException { // TODO Auto-generated method stub } public boolean isCloseOnCompletion() throws SQLException { // TODO Auto-generated method stub return false; } }
src/main/java/org/mariadb/jdbc/MySQLStatement.java
/* MariaDB Client for Java Copyright (c) 2012 Monty Program Ab. 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 Monty Program Ab [email protected]. This particular MariaDB Client for Java file is work derived from a Drizzle-JDBC. Drizzle-JDBC file which is covered by subject to the following copyright and notice provisions: Copyright (c) 2009-2011, Marcus Eriksson Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the driver nor the names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.mariadb.jdbc; import org.mariadb.jdbc.internal.SQLExceptionMapper; import org.mariadb.jdbc.internal.common.Protocol; import org.mariadb.jdbc.internal.common.QueryException; import org.mariadb.jdbc.internal.common.Utils; import org.mariadb.jdbc.internal.common.query.Query; import org.mariadb.jdbc.internal.common.query.QueryFactory; import org.mariadb.jdbc.internal.common.queryresults.ModifyQueryResult; import org.mariadb.jdbc.internal.common.queryresults.QueryResult; import org.mariadb.jdbc.internal.common.queryresults.ResultSetType; import org.mariadb.jdbc.internal.mysql.MySQLProtocol; import java.io.IOException; import java.sql.*; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Timer; import java.util.TimerTask; public class MySQLStatement implements Statement { /** * the protocol used to talk to the server. */ private final MySQLProtocol protocol; /** * the Connection object. */ protected MySQLConnection connection; /** * The actual query result. */ private QueryResult queryResult; /** * are warnings cleared? */ private boolean warningsCleared; /** * creates queries. */ private final QueryFactory queryFactory; private int queryTimeout; private boolean escapeProcessing; private int fetchSize; private int maxRows; boolean isClosed; Timer timer; private boolean isTimedout; Queue<Object> cachedResultSets; public boolean isStreaming() { return fetchSize == Integer.MIN_VALUE; } /** * Creates a new Statement. * * @param protocol the protocol to use. * @param connection the connection to return in getConnection. * @param queryFactory the query factory to produce internal queries. */ public MySQLStatement(final MySQLProtocol protocol, final MySQLConnection connection, final QueryFactory queryFactory) { this.protocol = protocol; this.connection = connection; this.queryFactory = queryFactory; this.escapeProcessing = true; cachedResultSets = new LinkedList<Object>(); timer = new Timer(); } /** * returns the protocol. * * @return the protocol used. */ public Protocol getProtocol() { return protocol; } // Part of query prolog - setup timeout timer private void setTimer() { TimerTask task = new TimerTask() { @Override public void run() { try { isTimedout = true; protocol.cancelCurrentQuery(); } catch (Throwable e) { } } }; timer.schedule(task, queryTimeout*1000); } // Part of query prolog - check if connection is broken and reconnect private void checkReconnect() throws SQLException { if (protocol.shouldReconnect()) { try { protocol.connect(); } catch (QueryException qe) { SQLExceptionMapper.throwException(qe, connection, this); } } else if (protocol.shouldTryFailback()) { try { protocol.reconnectToMaster(); } catch (Exception e) { // Do nothing } } } void executeQueryProlog() throws SQLException{ checkReconnect(); if (protocol.hasUnreadData()) { throw new SQLException("There is an open result set on the current connection, "+ "which must be closed prior to executing a query"); } if (protocol.hasMoreResults()) { // Skip remaining result sets. CallableStatement might return many of them - // not only the "select" result sets, but also the "update" results while(getMoreResults(true)) { } } cachedResultSets.clear(); MySQLConnection conn = (MySQLConnection)getConnection(); conn.reenableWarnings(); try { protocol.setMaxRows(maxRows); } catch(QueryException qe) { SQLExceptionMapper.throwException(qe, connection, this); } if (queryTimeout != 0) { setTimer(); } } private void cacheMoreResults() { if (isStreaming()) return; QueryResult saveResult = queryResult; for(;;) { try { if (getMoreResults(false)) { cachedResultSets.add(queryResult); } else { break; } } catch(SQLException e) { cachedResultSets.add(e); break; } } queryResult = saveResult; } /* Reset timeout after query, re-throw correct SQL exception */ private void executeQueryEpilog(QueryException e, Query query) throws SQLException{ if (queryTimeout > 0) { timer.cancel(); } if (isTimedout) { isTimedout = false; e = new QueryException("Query timed out", 1317, "JZ0002", e); } if (e == null) return; if (protocol.getInfo().getProperty("dumpQueriesOnException", "false").equalsIgnoreCase("true")) { e.setMessage(e.getMessage()+ "\nQuery is : " + query); } SQLExceptionMapper.throwException(e, connection, this); } /** * executes a query. * * @param query the query * @return true if there was a result set, false otherwise. * @throws SQLException */ protected boolean execute(Query query) throws SQLException { synchronized (protocol) { if (isClosed()) { throw new SQLException("execute() is called on closed statement"); } QueryException exception = null; executeQueryProlog(); try { queryResult = protocol.executeQuery(query, isStreaming()); cacheMoreResults(); return (queryResult.getResultSetType() == ResultSetType.SELECT); } catch (QueryException e) { exception = e; return false; } finally { executeQueryEpilog(exception, query); } } } /** * executes a select query. * * @param query the query to send to the server * @return a result set * @throws SQLException if something went wrong */ protected ResultSet executeQuery(Query query) throws SQLException { if (execute(query)) { return new MySQLResultSet(queryResult, this, protocol); } //throw new SQLException("executeQuery() with query '" + query +"' did not return a result set"); return MySQLResultSet.EMPTY; } /** * Executes an update. * * @param query the update query. * @return update count * @throws SQLException if the query could not be sent to server. */ protected int executeUpdate(Query query) throws SQLException { if (execute(query)) return 0; return getUpdateCount(); } private Query stringToQuery(String queryString) throws SQLException { if (escapeProcessing) { queryString = Utils.nativeSQL(queryString,connection.noBackslashEscapes); } return queryFactory.createQuery(queryString); } /** * executes a query. * * @param queryString the query * @return true if there was a result set, false otherwise. * @throws SQLException */ public boolean execute(String queryString) throws SQLException { return execute(stringToQuery(queryString)); } /** * Executes an update. * * @param queryString the update query. * @return update count * @throws SQLException if the query could not be sent to server. */ public int executeUpdate(String queryString) throws SQLException { return executeUpdate(stringToQuery(queryString)); } /** * executes a select query. * * @param queryString the query to send to the server * @return a result set * @throws SQLException if something went wrong */ public ResultSet executeQuery(String queryString) throws SQLException { return executeQuery(stringToQuery(queryString)); } public QueryFactory getQueryFactory() { return queryFactory; } /** * Releases this <code>Statement</code> object's database and JDBC resources immediately instead of waiting for this * to happen when it is automatically closed. It is generally good practice to release resources as soon as you are * finished with them to avoid tying up database resources. * <p/> * Calling the method <code>close</code> on a <code>Statement</code> object that is already closed has no effect. * <p/> * <B>Note:</B>When a <code>Statement</code> object is closed, its current <code>ResultSet</code> object, if one * exists, is also closed. * * @throws java.sql.SQLException if a database access error occurs */ public void close() throws SQLException { if (queryResult != null) { queryResult.close(); queryResult = null; } // No possible future use for the cached results, so these can be cleared // This makes the cache eligible for garbage collection earlier if the statement is not // immediately garbage collected cachedResultSets.clear(); if (isStreaming()) { synchronized (protocol) { // Skip all outstanding result sets while(getMoreResults(true)) { } } } isClosed = true; } /** * Retrieves the maximum number of bytes that can be returned for character and binary column values in a * <code>ResultSet</code> object produced by this <code>Statement</code> object. This limit applies only to * <code>BINARY</code>, <code>VARBINARY</code>, <code>LONGVARBINARY</code>, <code>CHAR</code>, <code>VARCHAR</code>, * <code>NCHAR</code>, <code>NVARCHAR</code>, <code>LONGNVARCHAR</code> and <code>LONGVARCHAR</code> columns. If * the limit is exceeded, the excess data is silently discarded. * * @return the current column size limit for columns storing character and binary values; zero means there is no * limit * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @see #setMaxFieldSize */ public int getMaxFieldSize() throws SQLException { return 0; } /** * Sets the limit for the maximum number of bytes that can be returned for character and binary column values in a * <code>ResultSet</code> object produced by this <code>Statement</code> object. * <p/> * This limit applies only to <code>BINARY</code>, <code>VARBINARY</code>, <code>LONGVARBINARY</code>, * <code>CHAR</code>, <code>VARCHAR</code>, <code>NCHAR</code>, <code>NVARCHAR</code>, <code>LONGNVARCHAR</code> and * <code>LONGVARCHAR</code> fields. If the limit is exceeded, the excess data is silently discarded. For maximum * portability, use values greater than 256. * * @param max the new column size limit in bytes; zero means there is no limit * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the condition max >= 0 is not satisfied * @see #getMaxFieldSize */ public void setMaxFieldSize(final int max) throws SQLException { //we dont support max field sizes } /** * Retrieves the maximum number of rows that a <code>ResultSet</code> object produced by this <code>Statement</code> * object can contain. If this limit is exceeded, the excess rows are silently dropped. * * @return the current maximum number of rows for a <code>ResultSet</code> object produced by this * <code>Statement</code> object; zero means there is no limit * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @see #setMaxRows */ public int getMaxRows() throws SQLException { return maxRows; } /** * Sets the limit for the maximum number of rows that any <code>ResultSet</code> object generated by this * <code>Statement</code> object can contain to the given number. If the limit is exceeded, the excess rows are * silently dropped. * * @param max the new max rows limit; zero means there is no limit * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the condition max >= 0 is not satisfied * @see #getMaxRows */ public void setMaxRows(final int max) throws SQLException { if (max < 0) { throw new SQLException("max rows is negative"); } maxRows = max; } /** * Sets escape processing on or off. If escape scanning is on (the default), the driver will do escape substitution * before sending the SQL statement to the database. * <p/> * Note: Since prepared statements have usually been parsed prior to making this call, disabling escape processing * for <code>PreparedStatements</code> objects will have no effect. * * @param enable <code>true</code> to enable escape processing; <code>false</code> to disable it * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> */ public void setEscapeProcessing(final boolean enable) throws SQLException { escapeProcessing = enable; } /** * Retrieves the number of seconds the driver will wait for a <code>Statement</code> object to execute. If the limit * is exceeded, a <code>SQLException</code> is thrown. * * @return the current query timeout limit in seconds; zero means there is no limit * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @see #setQueryTimeout */ public int getQueryTimeout() throws SQLException { return queryTimeout; } /** * Sets the number of seconds the driver will wait for a <code>Statement</code> object to execute to the given * number of seconds. If the limit is exceeded, an <code>SQLException</code> is thrown. A JDBC driver must apply * this limit to the <code>execute</code>, <code>executeQuery</code> and <code>executeUpdate</code> methods. JDBC * driver implementations may also apply this limit to <code>ResultSet</code> methods (consult your driver vendor * documentation for details). * * @param seconds the new query timeout limit in seconds; zero means there is no limit * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the condition seconds >= 0 is not satisfied * @see #getQueryTimeout */ public void setQueryTimeout(final int seconds) throws SQLException { this.queryTimeout = seconds; } /** * Cancels this <code>Statement</code> object if both the DBMS and driver support aborting an SQL statement. This * method can be used by one thread to cancel a statement that is being executed by another thread. * * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method */ public void cancel() throws SQLException { try { protocol.cancelCurrentQuery(); } catch (QueryException e) { SQLExceptionMapper.throwException(e, connection, this); } catch (IOException e) { // connection gone, query is definitely canceled } } /** * Retrieves the first warning reported by calls on this <code>Statement</code> object. Subsequent * <code>Statement</code> object warnings will be chained to this <code>SQLWarning</code> object. * <p/> * <p>The warning chain is automatically cleared each time a statement is (re)executed. This method may not be * called on a closed <code>Statement</code> object; doing so will cause an <code>SQLException</code> to be thrown. * <p/> * <P><B>Note:</B> If you are processing a <code>ResultSet</code> object, any warnings associated with reads on that * <code>ResultSet</code> object will be chained on it rather than on the <code>Statement</code> object that * produced it. * * @return the first <code>SQLWarning</code> object or <code>null</code> if there are no warnings * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> */ public SQLWarning getWarnings() throws SQLException { if (!warningsCleared) { return this.connection.getWarnings(); } return null; } /** * Clears all the warnings reported on this <code>Statement</code> object. After a call to this method, the method * <code>getWarnings</code> will return <code>null</code> until a new warning is reported for this * <code>Statement</code> object. * * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> */ public void clearWarnings() throws SQLException { warningsCleared = true; } /** * Sets the SQL cursor name to the given <code>String</code>, which will be used by subsequent * <code>Statement</code> object <code>execute</code> methods. This name can then be used in SQL positioned update * or delete statements to identify the current row in the <code>ResultSet</code> object generated by this * statement. If the database does not support positioned update/delete, this method is a noop. To insure that a * cursor has the proper isolation level to support updates, the cursor's <code>SELECT</code> statement should have * the form <code>SELECT FOR UPDATE</code>. If <code>FOR UPDATE</code> is not present, positioned updates may * fail. * <p/> * <P><B>Note:</B> By definition, the execution of positioned updates and deletes must be done by a different * <code>Statement</code> object than the one that generated the <code>ResultSet</code> object being used for * positioning. Also, cursor names must be unique within a connection. * * @param name the new cursor name, which must be unique within a connection * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method */ public void setCursorName(final String name) throws SQLException { throw SQLExceptionMapper.getFeatureNotSupportedException("Cursors are not supported"); } /** * gets the connection that created this statement * * @return the connection * @throws SQLException */ public Connection getConnection() throws SQLException { return this.connection; } /** * Moves to this <code>Statement</code> object's next result, deals with any current <code>ResultSet</code> * object(s) according to the instructions specified by the given flag, and returns <code>true</code> if the next * result is a <code>ResultSet</code> object. * <p/> * <P>There are no more results when the following is true: <PRE> // stmt is a Statement object * ((stmt.getMoreResults(current) == false) && (stmt.getUpdateCount() == -1)) </PRE> * * @param current one of the following <code>Statement</code> constants indicating what should happen to current * <code>ResultSet</code> objects obtained using the method <code>getResultSet</code>: * <code>Statement.CLOSE_CURRENT_RESULT</code>, <code>Statement.KEEP_CURRENT_RESULT</code>, or * <code>Statement.CLOSE_ALL_RESULTS</code> * @return <code>true</code> if the next result is a <code>ResultSet</code> object; <code>false</code> if it is an * update count or there are no more results * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the argument supplied is not one of the following: * <code>Statement.CLOSE_CURRENT_RESULT</code>, <code>Statement.KEEP_CURRENT_RESULT</code> * or <code>Statement.CLOSE_ALL_RESULTS</code> * @throws java.sql.SQLFeatureNotSupportedException * if <code>DatabaseMetaData.supportsMultipleOpenResults</code> returns * <code>false</code> and either <code>Statement.KEEP_CURRENT_RESULT</code> or * <code>Statement.CLOSE_ALL_RESULTS</code> are supplied as the argument. * @see #execute * @since 1.4 */ public boolean getMoreResults(final int current) throws SQLException { return getMoreResults(); } /** * Retrieves any auto-generated keys created as a result of executing this <code>Statement</code> object. If this * <code>Statement</code> object did not generate any keys, an empty <code>ResultSet</code> object is returned. * <p/> * <p><B>Note:</B>If the columns which represent the auto-generated keys were not specified, the JDBC driver * implementation will determine the columns which best represent the auto-generated keys. * * @return a <code>ResultSet</code> object containing the auto-generated key(s) generated by the execution of this * <code>Statement</code> object * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method * @since 1.4 */ public ResultSet getGeneratedKeys() throws SQLException { if (queryResult != null && queryResult.getResultSetType() == ResultSetType.MODIFY) { final QueryResult genRes = ((ModifyQueryResult) queryResult).getGeneratedKeysResult(); return new MySQLGeneratedKeysResultSet(genRes, this, protocol); } return MySQLResultSet.EMPTY; } /** * Executes the given SQL statement and signals the driver with the given flag about whether the auto-generated keys * produced by this <code>Statement</code> object should be made available for retrieval. The driver will ignore * the flag if the SQL statement is not an <code>INSERT</code> statement, or an SQL statement able to return * auto-generated keys (the list of such statements is vendor-specific). * * @param sql an SQL Data Manipulation Language (DML) statement, such as <code>INSERT</code>, * <code>UPDATE</code> or <code>DELETE</code>; or an SQL statement that returns nothing, * such as a DDL statement. * @param autoGeneratedKeys a flag indicating whether auto-generated keys should be made available for retrieval; * one of the following constants: <code>Statement.RETURN_GENERATED_KEYS</code> * <code>Statement.NO_GENERATED_KEYS</code> * @return either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements * that return nothing * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code>, the given SQL statement returns a <code>ResultSet</code> * object, or the given constant is not one of those allowed * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method with a constant of * Statement.RETURN_GENERATED_KEYS * @since 1.4 */ public int executeUpdate(final String sql, final int autoGeneratedKeys) throws SQLException { return executeUpdate(sql); } /** * Executes the given SQL statement and signals the driver that the auto-generated keys indicated in the given array * should be made available for retrieval. This array contains the indexes of the columns in the target table that * contain the auto-generated keys that should be made available. The driver will ignore the array if the SQL * statement is not an <code>INSERT</code> statement, or an SQL statement able to return auto-generated keys (the * list of such statements is vendor-specific). * * @param sql an SQL Data Manipulation Language (DML) statement, such as <code>INSERT</code>, * <code>UPDATE</code> or <code>DELETE</code>; or an SQL statement that returns nothing, such * as a DDL statement. * @param columnIndexes an array of column indexes indicating the columns that should be returned from the inserted * row * @return either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements * that return nothing * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code>, the SQL statement returns a <code>ResultSet</code> object, * or the second argument supplied to this method is not an <code>int</code> array * whose elements are valid column indexes * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method * @since 1.4 */ public int executeUpdate(final String sql, final int[] columnIndexes) throws SQLException { return executeUpdate(sql); } /** * Executes the given SQL statement and signals the driver that the auto-generated keys indicated in the given array * should be made available for retrieval. This array contains the names of the columns in the target table that * contain the auto-generated keys that should be made available. The driver will ignore the array if the SQL * statement is not an <code>INSERT</code> statement, or an SQL statement able to return auto-generated keys (the * list of such statements is vendor-specific). * * @param sql an SQL Data Manipulation Language (DML) statement, such as <code>INSERT</code>, * <code>UPDATE</code> or <code>DELETE</code>; or an SQL statement that returns nothing, such as * a DDL statement. * @param columnNames an array of the names of the columns that should be returned from the inserted row * @return either the row count for <code>INSERT</code>, <code>UPDATE</code>, or <code>DELETE</code> statements, or * 0 for SQL statements that return nothing * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code>, the SQL statement returns a <code>ResultSet</code> object, * or the second argument supplied to this method is not a <code>String</code> array * whose elements are valid column names * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method * @since 1.4 */ public int executeUpdate(final String sql, final String[] columnNames) throws SQLException { return executeUpdate(sql); } /** * Executes the given SQL statement, which may return multiple results, and signals the driver that any * auto-generated keys should be made available for retrieval. The driver will ignore this signal if the SQL * statement is not an <code>INSERT</code> statement, or an SQL statement able to return auto-generated keys (the * list of such statements is vendor-specific). * <p/> * In some (uncommon) situations, a single SQL statement may return multiple result sets and/or update counts. * Normally you can ignore this unless you are (1) executing a stored procedure that you know may return multiple * results or (2) you are dynamically executing an unknown SQL string. * <p/> * The <code>execute</code> method executes an SQL statement and indicates the form of the first result. You must * then use the methods <code>getResultSet</code> or <code>getUpdateCount</code> to retrieve the result, and * <code>getMoreResults</code> to move to any subsequent result(s). * * @param sql any SQL statement * @param autoGeneratedKeys a constant indicating whether auto-generated keys should be made available for retrieval * using the method <code>getGeneratedKeys</code>; one of the following constants: * <code>Statement.RETURN_GENERATED_KEYS</code> or <code>Statement.NO_GENERATED_KEYS</code> * @return <code>true</code> if the first result is a <code>ResultSet</code> object; <code>false</code> if it is an * update count or there are no results * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the second parameter supplied to this method is not * <code>Statement.RETURN_GENERATED_KEYS</code> or <code>Statement.NO_GENERATED_KEYS</code>. * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method with a constant of * Statement.RETURN_GENERATED_KEYS * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults * @see #getGeneratedKeys * @since 1.4 */ public boolean execute(final String sql, final int autoGeneratedKeys) throws SQLException { return execute(sql); // auto generated keys are always available } /** * Executes the given SQL statement, which may return multiple results, and signals the driver that the * auto-generated keys indicated in the given array should be made available for retrieval. This array contains the * indexes of the columns in the target table that contain the auto-generated keys that should be made available. * The driver will ignore the array if the SQL statement is not an <code>INSERT</code> statement, or an SQL * statement able to return auto-generated keys (the list of such statements is vendor-specific). * <p/> * Under some (uncommon) situations, a single SQL statement may return multiple result sets and/or update counts. * Normally you can ignore this unless you are (1) executing a stored procedure that you know may return multiple * results or (2) you are dynamically executing an unknown SQL string. * <p/> * The <code>execute</code> method executes an SQL statement and indicates the form of the first result. You must * then use the methods <code>getResultSet</code> or <code>getUpdateCount</code> to retrieve the result, and * <code>getMoreResults</code> to move to any subsequent result(s). * * @param sql any SQL statement * @param columnIndexes an array of the indexes of the columns in the inserted row that should be made available * for retrieval by a call to the method <code>getGeneratedKeys</code> * @return <code>true</code> if the first result is a <code>ResultSet</code> object; <code>false</code> if it is an * update count or there are no results * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the elements in the <code>int</code> array passed to this * method are not valid column indexes * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults * @since 1.4 */ public boolean execute(final String sql, final int[] columnIndexes) throws SQLException { return execute(sql); } /** * Executes the given SQL statement, which may return multiple results, and signals the driver that the * auto-generated keys indicated in the given array should be made available for retrieval. This array contains the * names of the columns in the target table that contain the auto-generated keys that should be made available. The * driver will ignore the array if the SQL statement is not an <code>INSERT</code> statement, or an SQL statement * able to return auto-generated keys (the list of such statements is vendor-specific). * <p/> * In some (uncommon) situations, a single SQL statement may return multiple result sets and/or update counts. * Normally you can ignore this unless you are (1) executing a stored procedure that you know may return multiple * results or (2) you are dynamically executing an unknown SQL string. * <p/> * The <code>execute</code> method executes an SQL statement and indicates the form of the first result. You must * then use the methods <code>getResultSet</code> or <code>getUpdateCount</code> to retrieve the result, and * <code>getMoreResults</code> to move to any subsequent result(s). * * @param sql any SQL statement * @param columnNames an array of the names of the columns in the inserted row that should be made available for * retrieval by a call to the method <code>getGeneratedKeys</code> * @return <code>true</code> if the next result is a <code>ResultSet</code> object; <code>false</code> if it is an * update count or there are no more results * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the elements of the <code>String</code> array passed to * this method are not valid column names * @throws java.sql.SQLFeatureNotSupportedException * if the JDBC driver does not support this method * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults * @see #getGeneratedKeys * @since 1.4 */ public boolean execute(final String sql, final String[] columnNames) throws SQLException { return execute(sql); } /** * Retrieves the result set holdability for <code>ResultSet</code> objects generated by this <code>Statement</code> * object. * * @return either <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code> * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @since 1.4 */ public int getResultSetHoldability() throws SQLException { return ResultSet.HOLD_CURSORS_OVER_COMMIT; } /** * Retrieves whether this <code>Statement</code> object has been closed. A <code>Statement</code> is closed if the * method close has been called on it, or if it is automatically closed. * * @return true if this <code>Statement</code> object is closed; false if it is still open * @throws java.sql.SQLException if a database access error occurs * @since 1.6 */ public boolean isClosed() throws SQLException { return isClosed; } /** * Requests that a <code>Statement</code> be pooled or not pooled. The value specified is a hint to the statement * pool implementation indicating whether the applicaiton wants the statement to be pooled. It is up to the * statement pool manager as to whether the hint is used. * <p/> * The poolable value of a statement is applicable to both internal statement caches implemented by the driver and * external statement caches implemented by application servers and other applications. * <p/> * By default, a <code>Statement</code> is not poolable when created, and a <code>PreparedStatement</code> and * <code>CallableStatement</code> are poolable when created. * <p/> * * @param poolable requests that the statement be pooled if true and that the statement not be pooled if false * <p/> * @throws java.sql.SQLException if this method is called on a closed <code>Statement</code> * <p/> * @since 1.6 */ public void setPoolable(final boolean poolable) throws SQLException { } /** * Returns a value indicating whether the <code>Statement</code> is poolable or not. * <p/> * * @return <code>true</code> if the <code>Statement</code> is poolable; <code>false</code> otherwise * <p/> * @throws java.sql.SQLException if this method is called on a closed <code>Statement</code> * <p/> * @see java.sql.Statement#setPoolable(boolean) setPoolable(boolean) * @since 1.6 * <p/> */ public boolean isPoolable() throws SQLException { return false; } public ResultSet getResultSet() throws SQLException { return new MySQLResultSet(queryResult,this,protocol); } public int getUpdateCount() throws SQLException { if(queryResult.getResultSetType() == ResultSetType.SELECT) { return -1; } return (int) ((ModifyQueryResult) queryResult).getUpdateCount(); } private boolean getMoreResults(boolean streaming) throws SQLException { try { synchronized(protocol) { if (queryResult != null) { queryResult.close(); } queryResult = protocol.getMoreResults(streaming); if(queryResult == null) return false; warningsCleared = false; connection.reenableWarnings(); return true; } } catch (QueryException e) { SQLExceptionMapper.throwException(e, connection, this); return false; } } /** * Moves to this <code>Statement</code> object's next result, returns <code>true</code> if it is a * <code>ResultSet</code> object, and implicitly closes any current <code>ResultSet</code> object(s) obtained with * the method <code>getResultSet</code>. * <p/> * <P>There are no more results when the following is true: <PRE> // stmt is a Statement object * ((stmt.getMoreResults() == false) && (stmt.getUpdateCount() == -1)) </PRE> * * @return <code>true</code> if the next result is a <code>ResultSet</code> object; <code>false</code> if it is an * update count or there are no more results * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @see #execute */ public boolean getMoreResults() throws SQLException { if (!isStreaming()) { /* return pre-cached result set, if available */ if(cachedResultSets.isEmpty()) return false; Object o = cachedResultSets.remove(); if (o instanceof SQLException) throw (SQLException)o; queryResult = (QueryResult)o; return true; } return getMoreResults(false); } /** * Gives the driver a hint as to the direction in which rows will be processed in <code>ResultSet</code> objects * created using this <code>Statement</code> object. The default value is <code>ResultSet.FETCH_FORWARD</code>. * <p/> * Note that this method sets the default fetch direction for result sets generated by this <code>Statement</code> * object. Each result set has its own methods for getting and setting its own fetch direction. * * @param direction the initial direction for processing rows * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the given direction is not one of * <code>ResultSet.FETCH_FORWARD</code>, <code>ResultSet.FETCH_REVERSE</code>, or * <code>ResultSet.FETCH_UNKNOWN</code> * @see #getFetchDirection * @since 1.2 */ public void setFetchDirection(final int direction) throws SQLException { } /** * Retrieves the direction for fetching rows from database tables that is the default for result sets generated from * this <code>Statement</code> object. If this <code>Statement</code> object has not set a fetch direction by * calling the method <code>setFetchDirection</code>, the return value is implementation-specific. * * @return the default fetch direction for result sets generated from this <code>Statement</code> object * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @see #setFetchDirection * @since 1.2 */ public int getFetchDirection() throws SQLException { return ResultSet.FETCH_FORWARD; } /** * Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are * needed for <code>ResultSet</code> objects genrated by this <code>Statement</code>. If the value specified is * zero, then the hint is ignored. The default value is zero. * * @param rows the number of rows to fetch * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the condition <code>rows >= 0</code> is not satisfied. * @see #getFetchSize * @since 1.2 */ public void setFetchSize(final int rows) throws SQLException { if (rows < 0 && rows != Integer.MIN_VALUE) throw new SQLException("invalid fetch size"); this.fetchSize = rows; } /** * Retrieves the number of result set rows that is the default fetch size for <code>ResultSet</code> objects * generated from this <code>Statement</code> object. If this <code>Statement</code> object has not set a fetch size * by calling the method <code>setFetchSize</code>, the return value is implementation-specific. * * @return the default fetch size for result sets generated from this <code>Statement</code> object * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @see #setFetchSize * @since 1.2 */ public int getFetchSize() throws SQLException { return this.fetchSize; } /** * Retrieves the result set concurrency for <code>ResultSet</code> objects generated by this <code>Statement</code> * object. * * @return either <code>ResultSet.CONCUR_READ_ONLY</code> or <code>ResultSet.CONCUR_UPDATABLE</code> * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @since 1.2 */ public int getResultSetConcurrency() throws SQLException { return ResultSet.CONCUR_READ_ONLY; } /** * Retrieves the result set type for <code>ResultSet</code> objects generated by this <code>Statement</code> * object. * * @return one of <code>ResultSet.TYPE_FORWARD_ONLY</code>, <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or * <code>ResultSet.TYPE_SCROLL_SENSITIVE</code> * @throws java.sql.SQLException if a database access error occurs or this method is called on a closed * <code>Statement</code> * @since 1.2 */ public int getResultSetType() throws SQLException { // TODO: this will change when the async protocol is implemented return ResultSet.TYPE_SCROLL_INSENSITIVE; } /** * Adds the given SQL command to the current list of commmands for this <code>Statement</code> object. The commands * in this list can be executed as a batch by calling the method <code>executeBatch</code>. * <p/> * * @param sql typically this is a SQL <code>INSERT</code> or <code>UPDATE</code> statement * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the driver does not support batch updates * @see #executeBatch * @see java.sql.DatabaseMetaData#supportsBatchUpdates * @since 1.2 */ public void addBatch(final String sql) throws SQLException { this.protocol.addToBatch(queryFactory.createQuery(sql)); } public void addBatch(final byte[] sql) throws SQLException { this.protocol.addToBatch(queryFactory.createQuery(sql)); } /** * Empties this <code>Statement</code> object's current list of SQL commands. * <p/> * * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the driver does not support batch updates * @see #addBatch * @see java.sql.DatabaseMetaData#supportsBatchUpdates * @since 1.2 */ public void clearBatch() throws SQLException { this.protocol.clearBatch(); } /** * Submits a batch of commands to the database for execution and if all commands execute successfully, returns an * array of update counts. The <code>int</code> elements of the array that is returned are ordered to correspond to * the commands in the batch, which are ordered according to the order in which they were added to the batch. The * elements in the array returned by the method <code>executeBatch</code> may be one of the following: <OL> <LI>A * number greater than or equal to zero -- indicates that the command was processed successfully and is an update * count giving the number of rows in the database that were affected by the command's execution <LI>A value of * <code>SUCCESS_NO_INFO</code> -- indicates that the command was processed successfully but that the number of rows * affected is unknown * <p/> * If one of the commands in a batch update fails to execute properly, this method throws a * <code>BatchUpdateException</code>, and a JDBC driver may or may not continue to process the remaining commands in * the batch. However, the driver's behavior must be consistent with a particular DBMS, either always continuing to * process commands or never continuing to process commands. If the driver continues processing after a failure, * the array returned by the method <code>BatchUpdateException.getUpdateCounts</code> will contain as many elements * as there are commands in the batch, and at least one of the elements will be the following: * <p/> * <LI>A value of <code>EXECUTE_FAILED</code> -- indicates that the command failed to execute successfully and * occurs only if a driver continues to process commands after a command fails </OL> * <p/> * The possible implementations and return values have been modified in the Java 2 SDK, Standard Edition, version * 1.3 to accommodate the option of continuing to proccess commands in a batch update after a * <code>BatchUpdateException</code> obejct has been thrown. * * @return an array of update counts containing one element for each command in the batch. The elements of the * array are ordered according to the order in which commands were added to the batch. * @throws java.sql.SQLException if a database access error occurs, this method is called on a closed * <code>Statement</code> or the driver does not support batch statements. Throws * {@link java.sql.BatchUpdateException} (a subclass of <code>SQLException</code>) if * one of the commands sent to the database fails to execute properly or attempts to * return a result set. * @see #addBatch * @see java.sql.DatabaseMetaData#supportsBatchUpdates * @since 1.3 */ public int[] executeBatch() throws SQLException { try { final List<QueryResult> queryRes = protocol.executeBatch(); final int[] retVals = new int[queryRes.size()]; int i = 0; for (final QueryResult qr : queryRes) { if (qr.getResultSetType() == ResultSetType.MODIFY) { retVals[i++] = (int) ((ModifyQueryResult) qr).getUpdateCount(); //TODO: this needs to be handled according to javadoc } else { retVals[i++] = SUCCESS_NO_INFO; } } return retVals; } catch (QueryException e) { SQLExceptionMapper.throwException(e, connection, this); return null; } } /** * Returns an object that implements the given interface to allow access to non-standard methods, or standard * methods not exposed by the proxy. * <p/> * If the receiver implements the interface then the result is the receiver or a proxy for the receiver. If the * receiver is a wrapper and the wrapped object implements the interface then the result is the wrapped object or a * proxy for the wrapped object. Otherwise return the the result of calling <code>unwrap</code> recursively on the * wrapped object or a proxy for that result. If the receiver is not a wrapper and does not implement the interface, * then an <code>SQLException</code> is thrown. * * @param iface A Class defining an interface that the result must implement. * @return an object that implements the interface. May be a proxy for the actual implementing object. * @throws java.sql.SQLException If no object found that implements the interface * @since 1.6 */ public <T> T unwrap(final Class<T> iface) throws SQLException { return null; } /** * Returns true if this either implements the interface argument or is directly or indirectly a wrapper for an * object that does. Returns false otherwise. If this implements the interface then return true, else if this is a * wrapper then return the result of recursively calling <code>isWrapperFor</code> on the wrapped object. If this * does not implement the interface and is not a wrapper, return false. This method should be implemented as a * low-cost operation compared to <code>unwrap</code> so that callers can use this method to avoid expensive * <code>unwrap</code> calls that may fail. If this method returns true then calling <code>unwrap</code> with the * same argument should succeed. * * @param iface a Class defining an interface. * @return true if this implements the interface or directly or indirectly wraps an object that does. * @throws java.sql.SQLException if an error occurs while determining whether this is a wrapper for an object with * the given interface. * @since 1.6 */ public boolean isWrapperFor(final Class<?> iface) throws SQLException { return false; } /** * returns the query result. * * @return the queryresult */ protected QueryResult getQueryResult() { return queryResult; } /** * sets the current query result * * @param result */ protected void setQueryResult(final QueryResult result) { this.queryResult = result; } public void closeOnCompletion() throws SQLException { // TODO Auto-generated method stub } public boolean isCloseOnCompletion() throws SQLException { // TODO Auto-generated method stub return false; } }
CONJ-1 : use a single (static) java.util.Timer and multiple TimerTasks to implement timeouts, rather than multiple Timers, since every java.util.Timer has a background thread attached to it.
src/main/java/org/mariadb/jdbc/MySQLStatement.java
CONJ-1 : use a single (static) java.util.Timer and multiple TimerTasks to implement timeouts, rather than multiple Timers, since every java.util.Timer has a background thread attached to it.
<ide><path>rc/main/java/org/mariadb/jdbc/MySQLStatement.java <ide> private int fetchSize; <ide> private int maxRows; <ide> boolean isClosed; <del> Timer timer; <add> private static volatile Timer timer; <add> private TimerTask timerTask; <add> <ide> private boolean isTimedout; <ide> <ide> Queue<Object> cachedResultSets; <ide> this.queryFactory = queryFactory; <ide> this.escapeProcessing = true; <ide> cachedResultSets = new LinkedList<Object>(); <del> timer = new Timer(); <add> <ide> } <ide> <ide> /** <ide> return protocol; <ide> } <ide> <add> private static Timer getTimer() { <add> Timer result = timer; <add> if (result == null) { <add> synchronized(MySQLStatement.class) { <add> result = timer; <add> if (result == null) { <add> timer = result = new Timer(); <add> } <add> } <add> } <add> return result; <add> } <add> <ide> // Part of query prolog - setup timeout timer <del> private void setTimer() { <del> TimerTask task = new TimerTask() { <add> private void setTimerTask() { <add> assert(timerTask == null); <add> timerTask = new TimerTask() { <ide> @Override <ide> public void run() { <ide> try { <ide> } catch (Throwable e) { <ide> } <ide> } <del> <ide> }; <del> timer.schedule(task, queryTimeout*1000); <add> getTimer().schedule(timerTask, queryTimeout*1000); <ide> } <ide> <ide> // Part of query prolog - check if connection is broken and reconnect <ide> } <ide> <ide> if (queryTimeout != 0) { <del> setTimer(); <add> setTimerTask(); <ide> } <ide> } <ide> <ide> */ <ide> private void executeQueryEpilog(QueryException e, Query query) throws SQLException{ <ide> <del> if (queryTimeout > 0) { <del> timer.cancel(); <add> if (timerTask != null) { <add> timerTask.cancel(); <add> timerTask = null; <ide> } <ide> <ide> if (isTimedout) {
JavaScript
mit
23e4973e4d285e87da7904e58c57f7e69d5ecd10
0
omriBernstein/qromp
/* * visualizer.js * Created by: knod * Date created: 04/20/14 * Uses d3 to visualize entanglement. * * Sources: * (1) http://bl.ocks.org/mbostock/4062006 * (2) http://fleetinbeing.net/d3e/chord.html * (3) http://stackoverflow.com/questions/21813723/change-and-transition-dataset-in-chord-diagram-with-d3 * * Currently just creates a chord diagram with arbitrary * values with one alteration - the chords that go back * to the parent are hidden (opacity 0). It is animated, * but doesn't show partial potential for entanglement. * * Arcs don't look pixelated when large, unlike last attempt */ var entang = { firstOuterRadius: null , animTime: null , arcForGroups: null , pathForChords: null , fullEntangElem: null , partEntangElem: null , oldFullLayout: null , oldPartLayout: null // Just for testing /* (int, int) -> array of ints Create one row of the matrix for the qubit */ , createRow: function (indx, numQubits) { // Make one array for reach qubit with the right number of 0's var newRow = []; for (var indx2 = 0; indx2 < numQubits; indx2++) { newRow.push(0); } // Give it some starting value for itself newRow[indx] = 100; return newRow; } /* (int) -> Array of Arrays of ints Creates a matrix of numQubits size with no pair-wise paths */ , newFullEntangMatrix: function (numQubits) { var newMatrix = [], newRow = []; // Every row is the same, filled with the right number of 1's for (var indx = 0; indx < numQubits; indx++) {newRow.push(1);} // Fill the matrix with the right number of those rows for (var indx = 0; indx < numQubits; indx++) {newMatrix.push(newRow);} return newMatrix; } /* (str) -> d3 element? Adds a chord to the svg element. This is very specific to the current setup, not very general */ , attachChord: function (classNames, center, rotation) { return d3.select("#qubit-svg") .append("g") // Unique class for scaling the size of the whole thing .attr("class", classNames) .attr("transform", "translate(" + center + ") rotate(" + rotation //To help pixelation when big + ")" // + " scale(0.5)" ) ; } // !!! This only takes care of entanglement that shows that things // when they can be fully entangled. !!! // Should there be separate functions for updating outer sections and // connecting paths? /* (str, num, Array of Array of ints, int) -> None Creates a placeholder for the chord diagram centered at center ("num, num") with an outer radius of firstOuterRadius, matrix values of entangMatrix and assigns the animation time animTime passed to it. It gives values to a lot of the entang properties. It will start things off with a scale of 1 and adjustments will be made from using outerRadius to calculate the new scale. */ , initChord: function (center, firstOuterRadius, entangMatrix, animTime) { // --- SETUP --- \\ // *** All this stuff will only be calculated once // * Establishing object variables // This will be used to get the scale in future when there // are new outer radii entang.firstOuterRadius = firstOuterRadius; entang.animTime = animTime; // * This is used to establish the next object variable var innerRadius = firstOuterRadius/1.1; // *** These initial values will only be calculated once, // but later on the function will be used. // Why make a function not look like a function? I don't know. // * Still establishing object variables // It's a pain that this doesn't look like a function, but later // looks like a function later, but I think it's just changing // values. // Sources (3): create the arc path data generator for the groups // What are the groups? There are lots of groups! Are these groups // of bridges? Or sections around the circle? What? entang.arcForGroups = d3.svg.arc() .innerRadius(innerRadius) .outerRadius(firstOuterRadius); // Sources (3): create the chord path data generator for the chords // What are we calling chords? Seen chord used for different things entang.pathForChords = d3.svg.chord() .radius(innerRadius) ; // This is just for testing purposes var entangMatrix = entangMatrix || [ [100, 20, 30], [20, 130, 0], [30, 0, 120], ] ; // Rotate the diagram to line it up with the qubits var rotation = -(360/entangMatrix.length)/2; ; // *** PARTIAL ENTANGLEMENT (this one has paths) *** \\ // Place the element that will have the diagram entang.partEntangElem = entang.attachChord("entang part-entang", center, rotation); // *** FULL ENTANGLEMENT OUTLINE (no paths) *** \\ // Place the element that will have the diagram entang.fullEntangElem = entang.attachChord("entang full-entang", center, rotation); // Call the function that will animate the diagram's appearance entang.updateChord(center, firstOuterRadius, entangMatrix); } // end initChord() /* (str, num, Array of Arrays of ints) -> None Handles animating the creation of and changes to the chord diagram. Uses newCenter ("num, num") to animate the move to the new centerpoint (I hope), newRadius (and entang.firstOuterRadius) to get the new scale of the object, and newEntangMatrix to move the various paths to correct locations. */ , updateChord: function (newCenter, newRadius, newEntangMatrix) { // *** SETUP *** \\ // Temp for testing var newEntangMatrix = newEntangMatrix || [ [100, 20, 30], [20, 130, 0], [30, 0, 120], ] ; center = newCenter radius = newRadius /* To put in inspector once chord dia. is visible (test) matrix = [[100, 0, 10, 30], [0, 100, 30, 10], [10, 30, 100, 0], [0, 10, 30, 100],] entang.updateChord(center, radius, matrix)*/ // end testing // To rotate the diagram to line it up with the qubits var rotation = -(360/newEntangMatrix.length)/2 , scale = newRadius/entang.firstOuterRadius ; // Bring some things (that will be used repeatedly) into scope var animTime = entang.animTime , arcForGroups = entang.arcForGroups , pathForChords = entang.pathForChords , fullEntangElem = entang.fullEntangElem , partEntangElem = entang.partEntangElem , oldFullLayout = entang.oldFullLayout , oldPartLayout = entang.oldPartLayout ; // Color for potential var partArcColor = "#9986b3"; // Just an array of colors now var bridgeColors = ["#9986b3", "red", "green", "blue"]; // // I'm not sure why this isn't just an array, but afraid to change // var bridgeColors = d3.scale.ordinal() // .domain(d3.range(4)) // .range(["#9986b3", "red", "green", "blue"]) // ; // --- ARCS --- \\ // *** Functions *** \\ /* (?, str, layout.chord()?) -> d3 collection of objects? Creates new arcs (those outside sections) for chord diagram. Can this be outside of update? */ function createArcs (thisDiv, thisSelector, thisLayout) { // Maybe we can do d3.selectAll() instead of thisDiv.selectAll() var groupOfArcs = thisDiv.selectAll(thisSelector) .data(thisLayout.groups(), function (d) { return d.index; //use a key function in case the //groups are sorted differently between updates }); return groupOfArcs; } /* (d3 collection?) -> None Update (and animate?) arcs that are removed. Can this be outside of update? */ function removeArcs (groupOfArcs) { groupOfArcs.exit() .transition() .duration(animTime) .attr("opacity", 0) .remove(); //remove after transitions are complete } /* (d3 collection?, str) -> d3 collection? Updates arcs that are added. Can this be outside of update? */ function addArcs (groupOfArcs, selector) { // Add a new element to the DOM var newGroups = groupOfArcs.enter().append("g") .attr("class", "group"); //create the arc paths and set the constant attributes //(those based on the group index, not on the value) // ~~ id's and colors newGroups.append("path") .attr("id", function (dat) { return selector + dat.index; //using dat.index and not i to maintain consistency //even if groups are sorted (knod: huh?) }) // ~~~ qromp color versions .style("fill", function (dat) { // Color for arcs indicating entanglement potential if (selector == "part-group") {return partArcColor; } // Color for showing full entanglement else {return "none";} }) .style("stroke", function (dat) { // Same if (selector == "part-group") {return partArcColor;} else {return "black";} }) ; return newGroups; } // end addArcs() /* (d3 collection?, layout.chord?) -> None I think this only takes care of the animation for arcs that have been added, I think removal of arcs anims itself. */ function animAddedArcs (groupOfArcs, thisLayout) { groupOfArcs.select("path") .transition() .duration(animTime) .attrTween("d", entang.arcTween( thisLayout )) ; } updateFull(); // *** FULL ENTANGLEMENT *** \\ function updateFull () { var newFullMatrix = entang.newFullEntangMatrix(newEntangMatrix.length); var newFullEntangLayout = entang.newChord(newFullMatrix); } // end updateFull() // *** PARTIAL ENTANGLEMENT *** \\ // Make and store a new layout.chord() with the new matrix that // we'll transition to (from oldPartLayout) var newLayoutChord = entang.newChord(newEntangMatrix, 0.5); // --- SOURCES (3) --- \\ // *** GROUPS(?), creation *** \\ // I don't really understand this. And what's considered a group? // ~~~ Changed some names among other things /* Create/update "group" elements */ var groupG = createArcs(partEntangElem, ".part-entang .group", newLayoutChord); updatePart(); function updatePart () { // *** GROUPS(?), exit (removal), entrance (added), animation *** \\ // ~~~ When groupG is destroyed? Or perhaps when data of groupG // is taken out? Also animates that? Transition to fewer arcs removeArcs(groupG); //the enter() selection is stored in a variable so we can //enter the <path>, <text>, and <title> elements as well // ~~~ (qromp skips this part, wouldn't work as our labels) var newGroups = addArcs(groupG, "part-group"); // Animate the added paths? Tween to new layout animAddedArcs(groupG, oldPartLayout); // *** CHORD PATHS, creation, entrance, exit, animation *** \\ // *** Also event handler for fading *** \\ /* Create/update the chord paths */ var chordPaths = partEntangElem.selectAll("path.chord") // ~~~ I don't understand what this does .data(newLayoutChord.chords(), entang.chordKey ); //specify a key function to match chords //between updates //create the new chord paths var newChords = chordPaths.enter() .append("path") .attr("class", "chord"); //handle exiting paths: chordPaths.exit().transition() .duration(animTime) .attr("opacity", 0) .remove(); // Can't get this function to work. Wanted to remove repetition. // chordPaths.exit().call(removeElements(this)); // function removeElements (thisElement) { // console.log(thisElement); // thisElement.transition() // // Uncaught TypeError: undefined is not a function // .duration(animTime) // .attr("opacity", 0) // .remove(); //remove after transitions are complete // } // ~~~ Hide stuff here instead? Need to test. entang.hideOwn(); // ~~~ !!! This is what's causing the black in the transition somehow !!! //update the path shape chordPaths.transition() .duration(animTime) // ~~~ Changing the colors here doesn't fix the black .style("fill", function(d) { return bridgeColors[d.source.index]; }) .style("stroke", function(d) { return bridgeColors[d.source.index]; }) .attrTween("d", entang.chordTween( oldPartLayout )) ; } // end updatePart() // *** EVENT HANDLERS *** \\ // ~~~ !!! Make this not in a function in future !!! //add the mouseover/fade out behaviour to the groups //this is reset on every update, so it will use the latest //chordPaths selection // ~~~ Our own version of fade, theirs was too complex // ~~~ Could possibly do the whole thing in CSS? groupG.on("mouseover", entang.fade(.1)) .on("mouseout", entang.fade(1)) ; // ~~~ At the very end, since I don't know where else to put it that // ~~~ it won't get overriden, animate the size and pos change d3.selectAll(".entang") .transition() .duration(animTime) .attr("transform", "translate(" + newCenter + ") rotate(" + rotation + ") scale(" + scale + ")") ; entang.oldPartLayout = newLayoutChord; //save for next update // --- END SOURCES (3) --- \\ // For hide, maybe on the fill function use a filter to hide stuff then? } // end updateChord() /* (Array of Arrays of ints) -> None Creates a new chord layout with matrix as it's matrix. Just breaking things up in to smaller chunks */ , newChord: function (matrix, arcPadding) { var arcPadding = arcPadding || 0.03; return d3.layout.chord() // padding between sections .padding(arcPadding) .sortSubgroups(d3.descending) .sortChords(d3.ascending) .matrix(matrix) ; } // ~~~ Sources (3) , arcTween: function (oldLayout) { //this function will be called once per update cycle //Create a key:value version of the old layout's groups array //so we can easily find the matching group //even if the group index values don't match the array index //(because of sorting) var oldGroups = {}; if (oldLayout) { oldLayout.groups().forEach( function(groupData) { oldGroups[ groupData.index ] = groupData; }); } return function (d, i) { var tween; var old = oldGroups[d.index]; if (old) { //there's a matching old group tween = d3.interpolate(old, d); } else { //create a zero-width arc object var emptyArc = {startAngle:d.startAngle, endAngle:d.startAngle}; tween = d3.interpolate(emptyArc, d); } return function (t) { return entang.arcForGroups( tween(t) ); }; }; } // end arcTween() , chordKey: function (data) { return (data.source.index < data.target.index) ? data.source.index + "-" + data.target.index: data.target.index + "-" + data.source.index; //create a key that will represent the relationship //between these two groups *regardless* //of which group is called 'source' and which 'target' } , chordTween: function (oldLayout) { //this function will be called once per update cycle //Create a key:value version of the old layout's chords array //so we can easily find the matching chord //(which may not have a matching index) var oldChords = {}; if (oldLayout) { oldLayout.chords().forEach( function(chordData) { oldChords[ entang.chordKey(chordData) ] = chordData; }); } return function (d, i) { //this function will be called for each active chord var tween; var old = oldChords[ entang.chordKey(d) ]; if (old) { //old is not undefined, i.e. //there is a matching old chord value //check whether source and target have been switched: if (d.source.index != old.source.index ){ //swap source and target to match the new data old = { source: old.target, target: old.source }; } tween = d3.interpolate(old, d); } else { //create a zero-width chord object var emptyChord = { source: { startAngle: d.source.startAngle, endAngle: d.source.startAngle}, target: { startAngle: d.target.startAngle, endAngle: d.target.startAngle} }; tween = d3.interpolate( emptyChord, d ); } return function (t) { //this function calculates the intermediary shapes return entang.pathForChords(tween(t)); }; }; } // end chordTween() // ~~~ end Sources (3) /* (num) -> No idea Uses a number between 0 and 1 (opacity) to animate the fading out (or in) the filtered paths. I don't know what kind of thing it returns. Sources (1) (I think says "Returns an event handler for fading a given chord group.") */ , fade: function (opacity) { return function(g, indx) { d3.selectAll(".chord") .filter(function(dat) { return dat.source.index != indx && dat.target.index != indx // Added by knod to keep own chords hidden (for qromp) && dat.target.index != dat.target.subindex; }) .transition() .style("opacity", opacity); }; } /* Custom code for qromp */ /* (None) -> None Hides non-pairwise paths - paths that don't make a bridge between one section or another. I'm not sure how else to do this, so I've just decided to put a barnacle on this ship. */ , hideOwn: function () { // Unless the path crosses to somewhere, it's opacity will be 0 d3.selectAll(".chord") // Get the paths whose index and subindex match // (the path is refering to its own section) .filter(function (dat) { return dat.target.index == dat.target.subindex; }) .style("opacity", 0); } } // /* (int, int) -> array of ints // Create one row of the matrix for the qubit // */ // createRow: function (indx, numQubits) { // // Make one array for reach qubit with the right number of 0's // var newRow = []; // for (var indx2 = 0; indx2 < numQubits; indx2++) { // newRow.push(0); // } // // Give it some starting value for itself // newRow[indx] = 100; // return newRow; // }, // /* // Create the initial matrix for the qubits // */ // /* (Array of arrays of ints, num, str) -> None // In future matrix should be passed in. // Creates a chord diagram with the number of sections and // chords provided in matrix. Chords that refer to their own // section are given an opacity of 0. // */ // createChord: function (matrix, outerRadius, center) { // // From http://bl.ocks.org/mbostock/4062006 // // From http://mkweb.bcgsc.ca/circos/guide/tables/ // var matrix = matrix || [ // [100, 20, 0, 0], // [0, 100, 0, 0], // [0, 0, 100, 0], // [0, 0, 0, 100] // ]; // var rotation = -(360/matrix.length)/2; // var chord = d3.layout.chord() // .padding(.05) // .sortSubgroups(d3.descending) // .matrix(matrix); // // var width = 960, // // height = 500, // // innerRadius = Math.min(width, height) * .41, // // outerRadius = innerRadius * 1.1; // var innerRadius = outerRadius/1.1; // var fill = d3.scale.ordinal() // .domain(d3.range(4)) // // .range(["#000000", "#FFDD89", "#957244", "#F26223"]); // .range(["#9986b3", "red", "green", "blue"]); // svg = d3.select("#qubit-svg") // .append("g") // .attr("class", "entang") // .attr("transform", "translate(" + center + ") rotate(" + rotation + ")"); // svg.append("g").selectAll("path") // .data(chord.groups) // .enter().append("path") // .style("fill", function(d) { return fill(d.index); }) // .style("stroke", function(d) { return fill(d.index); }) // .attr("d", d3.svg.arc().innerRadius(innerRadius).outerRadius(outerRadius)) // .on("mouseover", fade(.1)) // .on("mouseout", fade(1)); // // var ticks = svg.append("g").selectAll("g") // // .data(chord.groups) // // .enter().append("g").selectAll("g") // // .data(groupTicks) // // .enter().append("g") // // .attr("transform", function(d) { // // return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")" // // + "translate(" + outerRadius + ",0)"; // // }); // // ticks.append("line") // // .attr("x1", 1) // // .attr("y1", 0) // // .attr("x2", 5) // // .attr("y2", 0) // // .style("stroke", "#000"); // // ticks.append("text") // // .attr("x", 8) // // .attr("dy", ".35em") // // .attr("transform", function(d) { // // return d.angle > Math.PI ? "rotate(180)translate(-16)" : null; // // }) // // .style("text-anchor", function(d) { return d.angle > Math.PI ? "end" : null; }) // // .text(function(d) { return d.label; }); // svg.append("g") // .attr("class", "chord") // .selectAll("path") // .data(chord.chords) // .enter().append("path") // .attr("d", d3.svg.chord().radius(innerRadius)) // .style("fill", function(d) { return fill(d.target.index); }) // .style("opacity", 1); // // // Returns an array of tick angles and labels, given a group. // // function groupTicks(d) { // // var k = (d.endAngle - d.startAngle) / d.value; // // return d3.range(0, d.value, 1000).map(function(v, i) { // // return { // // angle: v * k + d.startAngle, // // label: i % 5 ? null : v / 1000 + "k" // // }; // // }); // // } // // Returns an event handler for fading a given chord group. // function fade(opacity) { // return function(g, indx) { // svg.selectAll(".chord path") // .filter(function(dat) { return dat.source.index != indx && dat.target.index != indx // // Added by knod to keep own chords hidden (for qromp) // && dat.target.index != dat.target.subindex; }) // .transition() // .style("opacity", opacity); // }; // } // // /* Custom code for qromp */ // function hideOwn() { // // Unless the path crosses to somewhere, it's opacity will be 0 // svg.selectAll(".chord path") // // Get the paths whose index and subindex match // // (the path is refering to its own section) // .filter(function (dat) { // return dat.target.index == dat.target.subindex; // }) // .style("opacity", 0); // } // }, // /* (?) -> None // Shoud handle the animation from one chord state to // another, not sure how yet. // */ // transChord: function () { // }, // }
static/entang.js
/* * visualizer.js * Created by: knod * Date created: 04/20/14 * Uses d3 to visualize entanglement. * * Sources: * (1) http://bl.ocks.org/mbostock/4062006 * (2) http://fleetinbeing.net/d3e/chord.html * (3) http://stackoverflow.com/questions/21813723/change-and-transition-dataset-in-chord-diagram-with-d3 * * Currently just creates a chord diagram with arbitrary * values with one alteration - the chords that go back * to the parent are hidden (opacity 0). It is animated, * but doesn't show partial potential for entanglement. * * Arcs don't look pixelated when large, unlike last attempt */ var entang = { firstOuterRadius: null , animTime: null , arcForGroups: null , pathForChords: null , fullEntangElem: null , partEntangElem: null , oldFullLayout: null , oldPartLayout: null // Just for testing /* (int, int) -> array of ints Create one row of the matrix for the qubit */ , createRow: function (indx, numQubits) { // Make one array for reach qubit with the right number of 0's var newRow = []; for (var indx2 = 0; indx2 < numQubits; indx2++) { newRow.push(0); } // Give it some starting value for itself newRow[indx] = 100; return newRow; } /* (int) -> Array of Arrays of ints Creates a matrix of numQubits size with no pair-wise paths */ , newFullEntangMatrix: function (numQubits) { var newMatrix = [], newRow = []; // Every row is the same, filled with the right number of 1's for (var indx = 0; indx < numQubits; indx++) {newRow.push(1);} // Fill the matrix with the right number of those rows for (var indx = 0; indx < numQubits; indx++) {newMatrix.push(newRow);} return newMatrix; } /* (str) -> d3 element? Adds a chord to the svg element. This is very specific to the current setup, not very general */ , attachChord: function (classNames, center, rotation) { return d3.select("#qubit-svg") .append("g") // Unique class for scaling the size of the whole thing .attr("class", classNames) .attr("transform", "translate(" + center + ") rotate(" + rotation //To help pixelation when big + ")" // + " scale(0.5)" ) ; } // !!! This only takes care of entanglement that shows that things // when they can be fully entangled. !!! // Should there be separate functions for updating outer sections and // connecting paths? /* (str, num, Array of Array of ints, int) -> None Creates a placeholder for the chord diagram centered at center ("num, num") with an outer radius of firstOuterRadius, matrix values of entangMatrix and assigns the animation time animTime passed to it. It gives values to a lot of the entang properties. It will start things off with a scale of 1 and adjustments will be made from using outerRadius to calculate the new scale. */ , initChord: function (center, firstOuterRadius, entangMatrix, animTime) { // --- SETUP --- \\ // *** All this stuff will only be calculated once // * Establishing object variables // This will be used to get the scale in future when there // are new outer radii entang.firstOuterRadius = firstOuterRadius; entang.animTime = animTime; // * This is used to establish the next object variable var innerRadius = firstOuterRadius/1.1; // *** These initial values will only be calculated once, // but later on the function will be used. // Why make a function not look like a function? I don't know. // * Still establishing object variables // It's a pain that this doesn't look like a function, but later // looks like a function later, but I think it's just changing // values. // Sources (3): create the arc path data generator for the groups // What are the groups? There are lots of groups! Are these groups // of bridges? Or sections around the circle? What? entang.arcForGroups = d3.svg.arc() .innerRadius(innerRadius) .outerRadius(firstOuterRadius); // Sources (3): create the chord path data generator for the chords // What are we calling chords? Seen chord used for different things entang.pathForChords = d3.svg.chord() .radius(innerRadius) ; // This is just for testing purposes var entangMatrix = entangMatrix || [ [100, 20, 30], [20, 130, 0], [30, 0, 120], ] ; // Rotate the diagram to line it up with the qubits var rotation = -(360/entangMatrix.length)/2; ; // *** PARTIAL ENTANGLEMENT (this one has paths) *** \\ // Place the element that will have the diagram entang.partEntangElem = entang.attachChord("entang part-entang", center, rotation); // *** FULL ENTANGLEMENT OUTLINE (no paths) *** \\ // Place the element that will have the diagram entang.fullEntangElem = entang.attachChord("entang full-entang", center, rotation); // Call the function that will animate the diagram's appearance entang.updateChord(center, firstOuterRadius, entangMatrix); } /* (str, num, Array of Arrays of ints) -> None Handles animating the creation of and changes to the chord diagram. Uses newCenter ("num, num") to animate the move to the new centerpoint (I hope), newRadius (and entang.firstOuterRadius) to get the new scale of the object, and newEntangMatrix to move the various paths to correct locations. */ , updateChord: function (newCenter, newRadius, newEntangMatrix) { // *** SETUP *** \\ // Temp for testing var newEntangMatrix = newEntangMatrix || [ [100, 20, 30], [20, 130, 0], [30, 0, 120], ] ; center = newCenter radius = newRadius /* To put in inspector once chord dia. is visible (test) matrix = [[100, 0, 10, 30], [0, 100, 30, 10], [10, 30, 100, 0], [0, 10, 30, 100],] entang.updateChord(center, radius, matrix)*/ // end testing // To rotate the diagram to line it up with the qubits var rotation = -(360/newEntangMatrix.length)/2 , scale = newRadius/entang.firstOuterRadius ; // Bring some things (that will be used repeatedly) into scope var animTime = entang.animTime , arcForGroups = entang.arcForGroups , pathForChords = entang.pathForChords , fullEntangElem = entang.fullEntangElem , partEntangElem = entang.partEntangElem , oldFullLayout = entang.oldFullLayout , oldPartLayout = entang.oldPartLayout ; // Color for potential var partArcColor = "#9986b3"; // Just an array of colors now var bridgeColors = ["#9986b3", "red", "green", "blue"]; // // I'm not sure why this isn't just an array, but afraid to change // var bridgeColors = d3.scale.ordinal() // .domain(d3.range(4)) // .range(["#9986b3", "red", "green", "blue"]) // ; // --- ARCS --- \\ // *** Functions *** \\ /* (?, str, layout.chord()?) -> d3 collection of objects? Creates new arcs (those outside sections) for chord diagram. Can this be outside of update? */ function createArcs (thisDiv, thisSelector, thisLayout) { // Maybe we can do d3.selectAll() instead of thisDiv.selectAll() var groupOfArcs = thisDiv.selectAll(thisSelector) .data(thisLayout.groups(), function (d) { return d.index; //use a key function in case the //groups are sorted differently between updates }); return groupOfArcs; }; /* (d3 collection?) -> None Update (and animate?) arcs that are removed. Can this be outside of update? */ function removeArcs (groupOfArcs) { groupOfArcs.exit() .transition() .duration(animTime) .attr("opacity", 0) .remove(); //remove after transitions are complete }; /* (d3 collection?, str) -> d3 collection? Updates arcs that are added. Can this be outside of update? */ function addArcs (groupOfArcs, selector) { // Add a new element to the DOM var newGroups = groupOfArcs.enter().append("g") .attr("class", "group"); //create the arc paths and set the constant attributes //(those based on the group index, not on the value) // ~~ id's and colors newGroups.append("path") .attr("id", function (dat) { return selector + dat.index; //using dat.index and not i to maintain consistency //even if groups are sorted (knod: huh?) }) // ~~~ qromp color versions .style("fill", function (dat) { // Color for arcs indicating entanglement potential if (selector == "part-group") {return partArcColor; } // Color for showing full entanglement else {return "none";} }) .style("stroke", function (dat) { // Same if (selector == "part-group") {return partArcColor;} else {return "black";} }) ; return newGroups; }; /* (d3 collection?, layout.chord?) -> None I think this only takes care of the animation for arcs that have been added, I think removal of arcs anims itself. */ function animAddedArcs (groupOfArcs, thisLayout) { groupOfArcs.select("path") .transition() .duration(animTime) .attrTween("d", entang.arcTween( thisLayout )) ; }; updateFull(); // *** FULL ENTANGLEMENT *** \\ function updateFull () { var newFullMatrix = entang.newFullEntangMatrix(newEntangMatrix.length); var newFullEntangLayout = entang.newChord(newFullMatrix); }; // end updateFull() // *** PARTIAL ENTANGLEMENT *** \\ // Make and store a new layout.chord() with the new matrix that // we'll transition to (from oldPartLayout) var newLayoutChord = entang.newChord(newEntangMatrix, 0.5); // --- SOURCES (3) --- \\ // *** GROUPS(?), creation *** \\ // I don't really understand this. And what's considered a group? // ~~~ Changed some names among other things /* Create/update "group" elements */ var groupG = createArcs(partEntangElem, ".part-entang .group", newLayoutChord); updatePart(); function updatePart () { // *** GROUPS(?), exit (removal), entrance (added), animation *** \\ // ~~~ When groupG is destroyed? Or perhaps when data of groupG // is taken out? Also animates that? Transition to fewer arcs removeArcs(groupG); //the enter() selection is stored in a variable so we can //enter the <path>, <text>, and <title> elements as well // ~~~ (qromp skips this part, wouldn't work as our labels) var newGroups = addArcs(groupG, "part-group"); // Animate the added paths? Tween to new layout animAddedArcs(groupG, oldPartLayout); // *** CHORD PATHS, creation, entrance, exit, animation *** \\ // *** Also event handler for fading *** \\ /* Create/update the chord paths */ var chordPaths = partEntangElem.selectAll("path.chord") // ~~~ I don't understand what this does .data(newLayoutChord.chords(), entang.chordKey ); //specify a key function to match chords //between updates //create the new chord paths var newChords = chordPaths.enter() .append("path") .attr("class", "chord"); //handle exiting paths: chordPaths.exit().transition() .duration(animTime) .attr("opacity", 0) .remove(); // Can't get this function to work. Wanted to remove repetition. // chordPaths.exit().call(removeElements(this)); // function removeElements (thisElement) { // console.log(thisElement); // thisElement.transition() // // Uncaught TypeError: undefined is not a function // .duration(animTime) // .attr("opacity", 0) // .remove(); //remove after transitions are complete // } // ~~~ Hide stuff here instead? Need to test. entang.hideOwn(); // ~~~ !!! This is what's causing the black in the transition somehow !!! //update the path shape chordPaths.transition() .duration(animTime) // ~~~ Changing the colors here doesn't fix the black .style("fill", function(d) { return bridgeColors[d.source.index]; }) .style("stroke", function(d) { return bridgeColors[d.source.index]; }) .attrTween("d", entang.chordTween( oldPartLayout )) ; }; // end updatePart() // *** EVENT HANDLERS *** \\ // ~~~ !!! Make this not in a function in future !!! //add the mouseover/fade out behaviour to the groups //this is reset on every update, so it will use the latest //chordPaths selection // ~~~ Our own version of fade, theirs was too complex // ~~~ Could possibly do the whole thing in CSS? groupG.on("mouseover", entang.fade(.1)) .on("mouseout", entang.fade(1)) ; // ~~~ At the very end, since I don't know where else to put it that // ~~~ it won't get overriden, animate the size and pos change d3.selectAll(".entang") .transition() .duration(animTime) .attr("transform", "translate(" + newCenter + ") rotate(" + rotation + ") scale(" + scale + ")") ; entang.oldPartLayout = newLayoutChord; //save for next update // --- END SOURCES (3) --- \\ // For hide, maybe on the fill function use a filter to hide stuff then? } // end updateChord() /* (Array of Arrays of ints) -> None Creates a new chord layout with matrix as it's matrix. Just breaking things up in to smaller chunks */ , newChord: function (matrix, arcPadding) { var arcPadding = arcPadding || 0.03; return d3.layout.chord() // padding between sections .padding(arcPadding) .sortSubgroups(d3.descending) .sortChords(d3.ascending) .matrix(matrix) ; } // ~~~ Sources (3) , arcTween: function (oldLayout) { //this function will be called once per update cycle //Create a key:value version of the old layout's groups array //so we can easily find the matching group //even if the group index values don't match the array index //(because of sorting) var oldGroups = {}; if (oldLayout) { oldLayout.groups().forEach( function(groupData) { oldGroups[ groupData.index ] = groupData; }); } return function (d, i) { var tween; var old = oldGroups[d.index]; if (old) { //there's a matching old group tween = d3.interpolate(old, d); } else { //create a zero-width arc object var emptyArc = {startAngle:d.startAngle, endAngle:d.startAngle}; tween = d3.interpolate(emptyArc, d); } return function (t) { return entang.arcForGroups( tween(t) ); }; }; } // end arcTween() , chordKey: function (data) { return (data.source.index < data.target.index) ? data.source.index + "-" + data.target.index: data.target.index + "-" + data.source.index; //create a key that will represent the relationship //between these two groups *regardless* //of which group is called 'source' and which 'target' } , chordTween: function (oldLayout) { //this function will be called once per update cycle //Create a key:value version of the old layout's chords array //so we can easily find the matching chord //(which may not have a matching index) var oldChords = {}; if (oldLayout) { oldLayout.chords().forEach( function(chordData) { oldChords[ entang.chordKey(chordData) ] = chordData; }); } return function (d, i) { //this function will be called for each active chord var tween; var old = oldChords[ entang.chordKey(d) ]; if (old) { //old is not undefined, i.e. //there is a matching old chord value //check whether source and target have been switched: if (d.source.index != old.source.index ){ //swap source and target to match the new data old = { source: old.target, target: old.source }; } tween = d3.interpolate(old, d); } else { //create a zero-width chord object var emptyChord = { source: { startAngle: d.source.startAngle, endAngle: d.source.startAngle}, target: { startAngle: d.target.startAngle, endAngle: d.target.startAngle} }; tween = d3.interpolate( emptyChord, d ); } return function (t) { //this function calculates the intermediary shapes return entang.pathForChords(tween(t)); }; }; } // end chordTween() // ~~~ end Sources (3) /* (num) -> No idea Uses a number between 0 and 1 (opacity) to animate the fading out (or in) the filtered paths. I don't know what kind of thing it returns. Sources (1) (I think says "Returns an event handler for fading a given chord group.") */ , fade: function (opacity) { return function(g, indx) { d3.selectAll(".chord") .filter(function(dat) { return dat.source.index != indx && dat.target.index != indx // Added by knod to keep own chords hidden (for qromp) && dat.target.index != dat.target.subindex; }) .transition() .style("opacity", opacity); }; } /* Custom code for qromp */ /* (None) -> None Hides non-pairwise paths - paths that don't make a bridge between one section or another. I'm not sure how else to do this, so I've just decided to put a barnacle on this ship. */ , hideOwn: function () { // Unless the path crosses to somewhere, it's opacity will be 0 d3.selectAll(".chord") // Get the paths whose index and subindex match // (the path is refering to its own section) .filter(function (dat) { return dat.target.index == dat.target.subindex; }) .style("opacity", 0); } } // /* (int, int) -> array of ints // Create one row of the matrix for the qubit // */ // createRow: function (indx, numQubits) { // // Make one array for reach qubit with the right number of 0's // var newRow = []; // for (var indx2 = 0; indx2 < numQubits; indx2++) { // newRow.push(0); // } // // Give it some starting value for itself // newRow[indx] = 100; // return newRow; // }, // /* // Create the initial matrix for the qubits // */ // /* (Array of arrays of ints, num, str) -> None // In future matrix should be passed in. // Creates a chord diagram with the number of sections and // chords provided in matrix. Chords that refer to their own // section are given an opacity of 0. // */ // createChord: function (matrix, outerRadius, center) { // // From http://bl.ocks.org/mbostock/4062006 // // From http://mkweb.bcgsc.ca/circos/guide/tables/ // var matrix = matrix || [ // [100, 20, 0, 0], // [0, 100, 0, 0], // [0, 0, 100, 0], // [0, 0, 0, 100] // ]; // var rotation = -(360/matrix.length)/2; // var chord = d3.layout.chord() // .padding(.05) // .sortSubgroups(d3.descending) // .matrix(matrix); // // var width = 960, // // height = 500, // // innerRadius = Math.min(width, height) * .41, // // outerRadius = innerRadius * 1.1; // var innerRadius = outerRadius/1.1; // var fill = d3.scale.ordinal() // .domain(d3.range(4)) // // .range(["#000000", "#FFDD89", "#957244", "#F26223"]); // .range(["#9986b3", "red", "green", "blue"]); // svg = d3.select("#qubit-svg") // .append("g") // .attr("class", "entang") // .attr("transform", "translate(" + center + ") rotate(" + rotation + ")"); // svg.append("g").selectAll("path") // .data(chord.groups) // .enter().append("path") // .style("fill", function(d) { return fill(d.index); }) // .style("stroke", function(d) { return fill(d.index); }) // .attr("d", d3.svg.arc().innerRadius(innerRadius).outerRadius(outerRadius)) // .on("mouseover", fade(.1)) // .on("mouseout", fade(1)); // // var ticks = svg.append("g").selectAll("g") // // .data(chord.groups) // // .enter().append("g").selectAll("g") // // .data(groupTicks) // // .enter().append("g") // // .attr("transform", function(d) { // // return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")" // // + "translate(" + outerRadius + ",0)"; // // }); // // ticks.append("line") // // .attr("x1", 1) // // .attr("y1", 0) // // .attr("x2", 5) // // .attr("y2", 0) // // .style("stroke", "#000"); // // ticks.append("text") // // .attr("x", 8) // // .attr("dy", ".35em") // // .attr("transform", function(d) { // // return d.angle > Math.PI ? "rotate(180)translate(-16)" : null; // // }) // // .style("text-anchor", function(d) { return d.angle > Math.PI ? "end" : null; }) // // .text(function(d) { return d.label; }); // svg.append("g") // .attr("class", "chord") // .selectAll("path") // .data(chord.chords) // .enter().append("path") // .attr("d", d3.svg.chord().radius(innerRadius)) // .style("fill", function(d) { return fill(d.target.index); }) // .style("opacity", 1); // // // Returns an array of tick angles and labels, given a group. // // function groupTicks(d) { // // var k = (d.endAngle - d.startAngle) / d.value; // // return d3.range(0, d.value, 1000).map(function(v, i) { // // return { // // angle: v * k + d.startAngle, // // label: i % 5 ? null : v / 1000 + "k" // // }; // // }); // // } // // Returns an event handler for fading a given chord group. // function fade(opacity) { // return function(g, indx) { // svg.selectAll(".chord path") // .filter(function(dat) { return dat.source.index != indx && dat.target.index != indx // // Added by knod to keep own chords hidden (for qromp) // && dat.target.index != dat.target.subindex; }) // .transition() // .style("opacity", opacity); // }; // } // // /* Custom code for qromp */ // function hideOwn() { // // Unless the path crosses to somewhere, it's opacity will be 0 // svg.selectAll(".chord path") // // Get the paths whose index and subindex match // // (the path is refering to its own section) // .filter(function (dat) { // return dat.target.index == dat.target.subindex; // }) // .style("opacity", 0); // } // }, // /* (?) -> None // Shoud handle the animation from one chord state to // another, not sure how yet. // */ // transChord: function () { // }, // }
Eh, other little things
static/entang.js
Eh, other little things
<ide><path>tatic/entang.js <ide> <ide> // Call the function that will animate the diagram's appearance <ide> entang.updateChord(center, firstOuterRadius, entangMatrix); <del> } <add> } // end initChord() <ide> <ide> /* (str, num, Array of Arrays of ints) -> None <ide> <ide> //groups are sorted differently between updates <ide> }); <ide> return groupOfArcs; <del> }; <add> } <ide> <ide> /* (d3 collection?) -> None <ide> <ide> .duration(animTime) <ide> .attr("opacity", 0) <ide> .remove(); //remove after transitions are complete <del> }; <add> } <ide> <ide> /* (d3 collection?, str) -> d3 collection? <ide> <ide> ; <ide> <ide> return newGroups; <del> }; <add> } // end addArcs() <ide> <ide> /* (d3 collection?, layout.chord?) -> None <ide> <ide> .duration(animTime) <ide> .attrTween("d", entang.arcTween( thisLayout )) <ide> ; <del> }; <add> } <ide> <ide> updateFull(); <ide> <ide> function updateFull () { <ide> var newFullMatrix = entang.newFullEntangMatrix(newEntangMatrix.length); <ide> var newFullEntangLayout = entang.newChord(newFullMatrix); <del> }; // end updateFull() <add> } // end updateFull() <ide> <ide> // *** PARTIAL ENTANGLEMENT *** \\ <ide> // Make and store a new layout.chord() with the new matrix that <ide> .style("stroke", function(d) { return bridgeColors[d.source.index]; }) <ide> .attrTween("d", entang.chordTween( oldPartLayout )) <ide> ; <del> }; // end updatePart() <add> } // end updatePart() <ide> <ide> // *** EVENT HANDLERS *** \\ <ide> // ~~~ !!! Make this not in a function in future !!!
Java
apache-2.0
9df5f3496eefee3d6c91750383c44fbb69595b0c
0
Valkryst/Schillsaver
package handler; import controller.MainScreenController; import misc.Logger; import org.apache.commons.lang3.exception.ExceptionUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class CommandHandler { /** * Executes the specified command on the commandline. * @param command The command to execute. * @param controller The controller for the main screen. */ public static void runProgram(final String command, final MainScreenController controller) { try { final ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); final Process process = builder.start(); final InputStream is = process.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // Ensure the process shuts down if the program exits: Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { process.destroy(); } })); String line; while((line = reader.readLine()) != null) { controller.getView().getTextArea_output().appendText(line + System.lineSeparator()); } is.close(); } catch(final IOException e) { Logger.writeLog(e.getMessage() + "\n\n" + ExceptionUtils.getStackTrace(e), Logger.LOG_TYPE_ERROR); System.exit(1); } } }
src/main/java/handler/CommandHandler.java
package handler; import gui.MainScreenController; import misc.Logger; import org.apache.commons.lang3.exception.ExceptionUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class CommandHandler { /** * Executes the specified command on the commandline. * @param command The command to execute. * @param controller The controller for the main screen. */ public static void runProgram(final String command, final MainScreenController controller) { try { final ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); final Process process = builder.start(); final InputStream is = process.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // Ensure the process shuts down if the program exits: Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { process.destroy(); } })); String line; while((line = reader.readLine()) != null) { controller.getView().getTextArea_ffmpegOutput().append(line + System.lineSeparator()); } is.close(); } catch(final IOException e) { Logger.writeLog(e.getMessage() + "\n\n" + ExceptionUtils.getStackTrace(e), Logger.LOG_TYPE_ERROR); System.exit(1); } } }
Updated to work with the new UI elements.
src/main/java/handler/CommandHandler.java
Updated to work with the new UI elements.
<ide><path>rc/main/java/handler/CommandHandler.java <ide> package handler; <ide> <del>import gui.MainScreenController; <add>import controller.MainScreenController; <ide> import misc.Logger; <ide> import org.apache.commons.lang3.exception.ExceptionUtils; <ide> <ide> <ide> String line; <ide> while((line = reader.readLine()) != null) { <del> controller.getView().getTextArea_ffmpegOutput().append(line + System.lineSeparator()); <add> controller.getView().getTextArea_output().appendText(line + System.lineSeparator()); <ide> } <ide> <ide> is.close();
Java
apache-2.0
76ebc3244135a2eb4f208699140123d8850794dd
0
leonchen83/redis-replicator
/* * Copyright 2016 leon chen * * 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.moilioncircle.redis.replicator; import com.moilioncircle.redis.replicator.cmd.*; import com.moilioncircle.redis.replicator.io.AsyncBufferedInputStream; import com.moilioncircle.redis.replicator.io.RedisInputStream; import com.moilioncircle.redis.replicator.io.RedisOutputStream; import com.moilioncircle.redis.replicator.net.RedisSocketFactory; import com.moilioncircle.redis.replicator.rdb.RdbParser; import com.moilioncircle.redis.replicator.util.Arrays; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.net.Socket; import java.util.Objects; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicBoolean; import static com.moilioncircle.redis.replicator.Constants.*; /** * @author Leon Chen * @since 2.1.0 */ public class RedisSocketReplicator extends AbstractReplicator { protected static final Log logger = LogFactory.getLog(RedisSocketReplicator.class); protected Socket socket; protected final int port; protected Timer heartbeat; protected final String host; protected ReplyParser replyParser; protected RedisOutputStream outputStream; protected final RedisSocketFactory socketFactory; protected final AtomicBoolean connected = new AtomicBoolean(false); public RedisSocketReplicator(String host, int port, Configuration configuration) { Objects.requireNonNull(host); if (port <= 0 || port > 65535) throw new IllegalArgumentException("illegal argument port: " + port); Objects.requireNonNull(configuration); this.host = host; this.port = port; this.configuration = configuration; this.socketFactory = new RedisSocketFactory(configuration); builtInCommandParserRegister(); if (configuration.isUseDefaultExceptionListener()) addExceptionListener(new DefaultExceptionListener()); } /** * PSYNC * <p> * * @throws IOException when read timeout or connect timeout */ @Override public void open() throws IOException { try { doOpen(); } finally { close(); doCloseListener(this); } } /** * PSYNC * <p> * * @throws IOException when read timeout or connect timeout */ protected void doOpen() throws IOException { for (int i = 0; i < configuration.getRetries() || configuration.getRetries() <= 0; i++) { try { establishConnection(); //reset retries i = 0; if (logger.isInfoEnabled()) { logger.info("PSYNC " + configuration.getReplId() + " " + String.valueOf(configuration.getReplOffset())); } send("PSYNC".getBytes(), configuration.getReplId().getBytes(), String.valueOf(configuration.getReplOffset()).getBytes()); final String reply = new String((byte[]) reply(), CHARSET); SyncMode syncMode = trySync(reply); //bug fix. if (syncMode == SyncMode.PSYNC && connected.get()) { //heartbeat send REPLCONF ACK ${slave offset} heartbeat(); } else if (syncMode == SyncMode.SYNC_LATER && connected.get()) { //sync later i = 0; close(); try { Thread.sleep(configuration.getRetryTimeInterval()); } catch (InterruptedException interrupt) { Thread.currentThread().interrupt(); } continue; } //sync command while (connected.get()) { Object obj = replyParser.parse(new OffsetHandler() { @Override public void handle(long len) { configuration.addOffset(len); } }); //command if (obj instanceof Object[]) { if (configuration.isVerbose() && logger.isDebugEnabled()) logger.debug(Arrays.deepToString((Object[]) obj)); Object[] command = (Object[]) obj; CommandName cmdName = CommandName.name(new String((byte[]) command[0], CHARSET)); final CommandParser<? extends Command> operations; //if command do not register. ignore if ((operations = commands.get(cmdName)) == null) { if (logger.isWarnEnabled()) { logger.warn("command [" + cmdName + "] not register. raw command:[" + Arrays.deepToString(command) + "]"); } continue; } //do command replyParser Command parsedCommand = operations.parse(command); //submit event this.submitEvent(parsedCommand); } else { if (logger.isInfoEnabled()) { logger.info("redis reply:" + obj); } } } //connected = false break; } catch (IOException | UncheckedIOException e) { //close socket manual if (!connected.get()) break; logger.error("socket error", e); //connect refused,connect timeout,read timeout,connect abort,server disconnect,connection EOFException close(); //retry psync in next loop. if (logger.isInfoEnabled()) { logger.info("reconnect to redis-server. retry times:" + (i + 1)); } try { Thread.sleep(configuration.getRetryTimeInterval()); } catch (InterruptedException interrupt) { Thread.currentThread().interrupt(); } } } } protected SyncMode trySync(final String reply) throws IOException { logger.info(reply); if (reply.startsWith("FULLRESYNC")) { //sync rdb dump file parseDump(this); //after parsed dump file,cache master run id and offset so that next psync. String[] ary = reply.split(" "); configuration.setReplId(ary[1]); configuration.setReplOffset(Long.parseLong(ary[2])); return SyncMode.PSYNC; } else if (reply.startsWith("CONTINUE")) { String[] ary = reply.split(" "); //redis-4.0 compatible String masterRunId = configuration.getReplId(); if (ary.length > 1 && masterRunId != null && !masterRunId.equals(ary[1])) configuration.setReplId(ary[1]); return SyncMode.PSYNC; } else if (reply.startsWith("NOMASTERLINK") || reply.startsWith("LOADING")) { return SyncMode.SYNC_LATER; } else { //server don't support psync logger.info("SYNC"); send("SYNC".getBytes()); parseDump(this); return SyncMode.SYNC; } } protected void parseDump(final AbstractReplicator replicator) throws IOException { //sync dump byte[] reply = reply(new BulkReplyHandler() { @Override public byte[] handle(long len, RedisInputStream in) throws IOException { if (logger.isInfoEnabled()) { logger.info("RDB dump file size:" + len); } if (configuration.isDiscardRdbEvent()) { if (logger.isInfoEnabled()) { logger.info("discard " + len + " bytes"); } in.skip(len); } else { RdbParser parser = new RdbParser(in, replicator); parser.parse(); } return "OK".getBytes(); } }); //sync command if ("OK".equals(new String(reply, CHARSET))) return; throw new AssertionError("SYNC failed. reason : [" + new String(reply, CHARSET) + "]"); } protected void establishConnection() throws IOException { connect(); if (configuration.getAuthPassword() != null) auth(configuration.getAuthPassword()); sendSlavePort(); sendSlaveIp(); sendSlaveCapa("eof"); sendSlaveCapa("psync2"); } protected void auth(String password) throws IOException { if (password != null) { if (logger.isInfoEnabled()) { logger.info("AUTH " + password); } send("AUTH".getBytes(), password.getBytes()); final String reply = new String((byte[]) reply(), CHARSET); logger.info(reply); if ("OK".equals(reply)) return; throw new AssertionError("[AUTH " + password + "] failed." + reply); } } protected void sendSlavePort() throws IOException { //REPLCONF listening-prot ${port} if (logger.isInfoEnabled()) { logger.info("REPLCONF listening-port " + socket.getLocalPort()); } send("REPLCONF".getBytes(), "listening-port".getBytes(), String.valueOf(socket.getLocalPort()).getBytes()); final String reply = new String((byte[]) reply(), CHARSET); logger.info(reply); if ("OK".equals(reply)) return; if (logger.isWarnEnabled()) { logger.warn("[REPLCONF listening-port " + socket.getLocalPort() + "] failed." + reply); } } protected void sendSlaveIp() throws IOException { //REPLCONF ip-address ${address} if (logger.isInfoEnabled()) { logger.info("REPLCONF ip-address " + socket.getLocalAddress().getHostAddress()); } send("REPLCONF".getBytes(), "ip-address".getBytes(), socket.getLocalAddress().getHostAddress().getBytes()); final String reply = new String((byte[]) reply(), CHARSET); logger.info(reply); if ("OK".equals(reply)) return; //redis 3.2+ if (logger.isWarnEnabled()) { logger.warn("[REPLCONF ip-address " + socket.getLocalAddress().getHostAddress() + "] failed." + reply); } } protected void sendSlaveCapa(String cmd) throws IOException { //REPLCONF capa eof if (logger.isInfoEnabled()) { logger.info("REPLCONF capa " + cmd); } send("REPLCONF".getBytes(), "capa".getBytes(), cmd.getBytes()); final String reply = new String((byte[]) reply(), CHARSET); logger.info(reply); if ("OK".equals(reply)) return; if (logger.isWarnEnabled()) { logger.warn("[REPLCONF capa " + cmd + "] failed." + reply); } } protected synchronized void heartbeat() { heartbeat = new Timer("heartbeat", true); //bug fix. in this point closed by other thread. multi-thread issue heartbeat.schedule(new TimerTask() { @Override public void run() { try { send("REPLCONF".getBytes(), "ACK".getBytes(), String.valueOf(configuration.getReplOffset()).getBytes()); } catch (IOException e) { //NOP } } }, configuration.getHeartBeatPeriod(), configuration.getHeartBeatPeriod()); logger.info("heartbeat thread started."); } protected void send(byte[] command) throws IOException { send(command, new byte[0][]); } protected void send(byte[] command, final byte[]... args) throws IOException { outputStream.write(STAR); outputStream.write(String.valueOf(args.length + 1).getBytes()); outputStream.writeCrLf(); outputStream.write(DOLLAR); outputStream.write(String.valueOf(command.length).getBytes()); outputStream.writeCrLf(); outputStream.write(command); outputStream.writeCrLf(); for (final byte[] arg : args) { outputStream.write(DOLLAR); outputStream.write(String.valueOf(arg.length).getBytes()); outputStream.writeCrLf(); outputStream.write(arg); outputStream.writeCrLf(); } outputStream.flush(); } @SuppressWarnings("unchecked") protected <T> T reply() throws IOException { return (T) replyParser.parse(); } @SuppressWarnings("unchecked") protected <T> T reply(BulkReplyHandler handler) throws IOException { return (T) replyParser.parse(handler); } protected void connect() throws IOException { if (!connected.compareAndSet(false, true)) return; socket = socketFactory.createSocket(host, port, configuration.getConnectionTimeout()); outputStream = new RedisOutputStream(socket.getOutputStream()); inputStream = new RedisInputStream( configuration.getAsyncCachedBytes() > 0 ? new AsyncBufferedInputStream(socket.getInputStream(), configuration.getAsyncCachedBytes()) : socket.getInputStream(), configuration.getBufferSize()); inputStream.setRawByteListeners(this.rawByteListeners); replyParser = new ReplyParser(inputStream); } @Override public void close() { if (!connected.compareAndSet(true, false)) return; synchronized (this) { if (heartbeat != null) { heartbeat.cancel(); heartbeat = null; logger.info("heartbeat canceled."); } } try { if (inputStream != null) { inputStream.setRawByteListeners(null); inputStream.close(); } } catch (IOException e) { //NOP } try { if (outputStream != null) outputStream.close(); } catch (IOException e) { //NOP } try { if (socket != null && !socket.isClosed()) socket.close(); } catch (IOException e) { //NOP } logger.info("socket closed"); } protected enum SyncMode {SYNC, PSYNC, SYNC_LATER} }
src/main/java/com/moilioncircle/redis/replicator/RedisSocketReplicator.java
/* * Copyright 2016 leon chen * * 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.moilioncircle.redis.replicator; import com.moilioncircle.redis.replicator.cmd.*; import com.moilioncircle.redis.replicator.io.AsyncBufferedInputStream; import com.moilioncircle.redis.replicator.io.RedisInputStream; import com.moilioncircle.redis.replicator.io.RedisOutputStream; import com.moilioncircle.redis.replicator.net.RedisSocketFactory; import com.moilioncircle.redis.replicator.rdb.RdbParser; import com.moilioncircle.redis.replicator.util.Arrays; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.net.Socket; import java.util.Objects; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicBoolean; import static com.moilioncircle.redis.replicator.Constants.*; /** * @author Leon Chen * @since 2.1.0 */ public class RedisSocketReplicator extends AbstractReplicator { protected static final Log logger = LogFactory.getLog(RedisSocketReplicator.class); protected Socket socket; protected final int port; protected Timer heartbeat; protected final String host; protected ReplyParser replyParser; protected RedisOutputStream outputStream; protected final RedisSocketFactory socketFactory; protected final AtomicBoolean connected = new AtomicBoolean(false); public RedisSocketReplicator(String host, int port, Configuration configuration) { Objects.requireNonNull(host); if (port <= 0) throw new IllegalArgumentException("illegal argument port: " + port); Objects.requireNonNull(configuration); this.host = host; this.port = port; this.configuration = configuration; this.socketFactory = new RedisSocketFactory(configuration); builtInCommandParserRegister(); if (configuration.isUseDefaultExceptionListener()) addExceptionListener(new DefaultExceptionListener()); } /** * PSYNC * <p> * * @throws IOException when read timeout or connect timeout */ @Override public void open() throws IOException { try { doOpen(); } finally { close(); doCloseListener(this); } } /** * PSYNC * <p> * * @throws IOException when read timeout or connect timeout */ protected void doOpen() throws IOException { for (int i = 0; i < configuration.getRetries() || configuration.getRetries() <= 0; i++) { try { establishConnection(); //reset retries i = 0; if (logger.isInfoEnabled()) { logger.info("PSYNC " + configuration.getReplId() + " " + String.valueOf(configuration.getReplOffset())); } send("PSYNC".getBytes(), configuration.getReplId().getBytes(), String.valueOf(configuration.getReplOffset()).getBytes()); final String reply = new String((byte[]) reply(), CHARSET); SyncMode syncMode = trySync(reply); //bug fix. if (syncMode == SyncMode.PSYNC && connected.get()) { //heartbeat send REPLCONF ACK ${slave offset} heartbeat(); } else if (syncMode == SyncMode.SYNC_LATER && connected.get()) { //sync later i = 0; close(); try { Thread.sleep(configuration.getRetryTimeInterval()); } catch (InterruptedException interrupt) { Thread.currentThread().interrupt(); } continue; } //sync command while (connected.get()) { Object obj = replyParser.parse(new OffsetHandler() { @Override public void handle(long len) { configuration.addOffset(len); } }); //command if (obj instanceof Object[]) { if (configuration.isVerbose() && logger.isDebugEnabled()) logger.debug(Arrays.deepToString((Object[]) obj)); Object[] command = (Object[]) obj; CommandName cmdName = CommandName.name(new String((byte[]) command[0], CHARSET)); final CommandParser<? extends Command> operations; //if command do not register. ignore if ((operations = commands.get(cmdName)) == null) { if (logger.isWarnEnabled()) { logger.warn("command [" + cmdName + "] not register. raw command:[" + Arrays.deepToString(command) + "]"); } continue; } //do command replyParser Command parsedCommand = operations.parse(command); //submit event this.submitEvent(parsedCommand); } else { if (logger.isInfoEnabled()) { logger.info("redis reply:" + obj); } } } //connected = false break; } catch (IOException | UncheckedIOException e) { //close socket manual if (!connected.get()) break; logger.error("socket error", e); //connect refused,connect timeout,read timeout,connect abort,server disconnect,connection EOFException close(); //retry psync in next loop. if (logger.isInfoEnabled()) { logger.info("reconnect to redis-server. retry times:" + (i + 1)); } try { Thread.sleep(configuration.getRetryTimeInterval()); } catch (InterruptedException interrupt) { Thread.currentThread().interrupt(); } } } } protected SyncMode trySync(final String reply) throws IOException { logger.info(reply); if (reply.startsWith("FULLRESYNC")) { //sync rdb dump file parseDump(this); //after parsed dump file,cache master run id and offset so that next psync. String[] ary = reply.split(" "); configuration.setReplId(ary[1]); configuration.setReplOffset(Long.parseLong(ary[2])); return SyncMode.PSYNC; } else if (reply.startsWith("CONTINUE")) { String[] ary = reply.split(" "); //redis-4.0 compatible String masterRunId = configuration.getReplId(); if (ary.length > 1 && masterRunId != null && !masterRunId.equals(ary[1])) configuration.setReplId(ary[1]); return SyncMode.PSYNC; } else if (reply.startsWith("NOMASTERLINK") || reply.startsWith("LOADING")) { return SyncMode.SYNC_LATER; } else { //server don't support psync logger.info("SYNC"); send("SYNC".getBytes()); parseDump(this); return SyncMode.SYNC; } } protected void parseDump(final AbstractReplicator replicator) throws IOException { //sync dump byte[] reply = reply(new BulkReplyHandler() { @Override public byte[] handle(long len, RedisInputStream in) throws IOException { if (logger.isInfoEnabled()) { logger.info("RDB dump file size:" + len); } if (configuration.isDiscardRdbEvent()) { if (logger.isInfoEnabled()) { logger.info("discard " + len + " bytes"); } in.skip(len); } else { RdbParser parser = new RdbParser(in, replicator); parser.parse(); } return "OK".getBytes(); } }); //sync command if ("OK".equals(new String(reply, CHARSET))) return; throw new AssertionError("SYNC failed. reason : [" + new String(reply, CHARSET) + "]"); } protected void establishConnection() throws IOException { connect(); if (configuration.getAuthPassword() != null) auth(configuration.getAuthPassword()); sendSlavePort(); sendSlaveIp(); sendSlaveCapa("eof"); sendSlaveCapa("psync2"); } protected void auth(String password) throws IOException { if (password != null) { if (logger.isInfoEnabled()) { logger.info("AUTH " + password); } send("AUTH".getBytes(), password.getBytes()); final String reply = new String((byte[]) reply(), CHARSET); logger.info(reply); if ("OK".equals(reply)) return; throw new AssertionError("[AUTH " + password + "] failed." + reply); } } protected void sendSlavePort() throws IOException { //REPLCONF listening-prot ${port} if (logger.isInfoEnabled()) { logger.info("REPLCONF listening-port " + socket.getLocalPort()); } send("REPLCONF".getBytes(), "listening-port".getBytes(), String.valueOf(socket.getLocalPort()).getBytes()); final String reply = new String((byte[]) reply(), CHARSET); logger.info(reply); if ("OK".equals(reply)) return; if (logger.isWarnEnabled()) { logger.warn("[REPLCONF listening-port " + socket.getLocalPort() + "] failed." + reply); } } protected void sendSlaveIp() throws IOException { //REPLCONF ip-address ${address} if (logger.isInfoEnabled()) { logger.info("REPLCONF ip-address " + socket.getLocalAddress().getHostAddress()); } send("REPLCONF".getBytes(), "ip-address".getBytes(), socket.getLocalAddress().getHostAddress().getBytes()); final String reply = new String((byte[]) reply(), CHARSET); logger.info(reply); if ("OK".equals(reply)) return; //redis 3.2+ if (logger.isWarnEnabled()) { logger.warn("[REPLCONF ip-address " + socket.getLocalAddress().getHostAddress() + "] failed." + reply); } } protected void sendSlaveCapa(String cmd) throws IOException { //REPLCONF capa eof if (logger.isInfoEnabled()) { logger.info("REPLCONF capa " + cmd); } send("REPLCONF".getBytes(), "capa".getBytes(), cmd.getBytes()); final String reply = new String((byte[]) reply(), CHARSET); logger.info(reply); if ("OK".equals(reply)) return; if (logger.isWarnEnabled()) { logger.warn("[REPLCONF capa " + cmd + "] failed." + reply); } } protected synchronized void heartbeat() { heartbeat = new Timer("heartbeat", true); //bug fix. in this point closed by other thread. multi-thread issue heartbeat.schedule(new TimerTask() { @Override public void run() { try { send("REPLCONF".getBytes(), "ACK".getBytes(), String.valueOf(configuration.getReplOffset()).getBytes()); } catch (IOException e) { //NOP } } }, configuration.getHeartBeatPeriod(), configuration.getHeartBeatPeriod()); logger.info("heartbeat thread started."); } protected void send(byte[] command) throws IOException { send(command, new byte[0][]); } protected void send(byte[] command, final byte[]... args) throws IOException { outputStream.write(STAR); outputStream.write(String.valueOf(args.length + 1).getBytes()); outputStream.writeCrLf(); outputStream.write(DOLLAR); outputStream.write(String.valueOf(command.length).getBytes()); outputStream.writeCrLf(); outputStream.write(command); outputStream.writeCrLf(); for (final byte[] arg : args) { outputStream.write(DOLLAR); outputStream.write(String.valueOf(arg.length).getBytes()); outputStream.writeCrLf(); outputStream.write(arg); outputStream.writeCrLf(); } outputStream.flush(); } @SuppressWarnings("unchecked") protected <T> T reply() throws IOException { return (T) replyParser.parse(); } @SuppressWarnings("unchecked") protected <T> T reply(BulkReplyHandler handler) throws IOException { return (T) replyParser.parse(handler); } protected void connect() throws IOException { if (!connected.compareAndSet(false, true)) return; socket = socketFactory.createSocket(host, port, configuration.getConnectionTimeout()); outputStream = new RedisOutputStream(socket.getOutputStream()); inputStream = new RedisInputStream( configuration.getAsyncCachedBytes() > 0 ? new AsyncBufferedInputStream(socket.getInputStream(), configuration.getAsyncCachedBytes()) : socket.getInputStream(), configuration.getBufferSize()); inputStream.setRawByteListeners(this.rawByteListeners); replyParser = new ReplyParser(inputStream); } @Override public void close() { if (!connected.compareAndSet(true, false)) return; synchronized (this) { if (heartbeat != null) { heartbeat.cancel(); heartbeat = null; logger.info("heartbeat canceled."); } } try { if (inputStream != null) { inputStream.setRawByteListeners(null); inputStream.close(); } } catch (IOException e) { //NOP } try { if (outputStream != null) outputStream.close(); } catch (IOException e) { //NOP } try { if (socket != null && !socket.isClosed()) socket.close(); } catch (IOException e) { //NOP } logger.info("socket closed"); } protected enum SyncMode {SYNC, PSYNC, SYNC_LATER} }
fix port sanity check
src/main/java/com/moilioncircle/redis/replicator/RedisSocketReplicator.java
fix port sanity check
<ide><path>rc/main/java/com/moilioncircle/redis/replicator/RedisSocketReplicator.java <ide> <ide> public RedisSocketReplicator(String host, int port, Configuration configuration) { <ide> Objects.requireNonNull(host); <del> if (port <= 0) throw new IllegalArgumentException("illegal argument port: " + port); <add> if (port <= 0 || port > 65535) throw new IllegalArgumentException("illegal argument port: " + port); <ide> Objects.requireNonNull(configuration); <ide> this.host = host; <ide> this.port = port;
Java
apache-2.0
6655dd4a5bffcc589fd0cf55b89777a7a4c9fcb6
0
mythguided/hydra,mythguided/hydra,mythguided/hydra,mythguided/hydra
/* * 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.addthis.hydra.data.filter.util; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.text.NumberFormat; import java.text.ParseException; import com.addthis.basis.util.Strings; import com.addthis.bundle.core.Bundle; import com.addthis.bundle.core.BundleFormatted; import com.addthis.bundle.util.BundleColumnBinder; import com.addthis.bundle.util.ValueUtil; import com.addthis.bundle.value.ValueFactory; import com.addthis.bundle.value.ValueNumber; import com.addthis.bundle.value.ValueObject; import com.addthis.bundle.value.ValueString; import com.google.common.primitives.Doubles; public class BundleCalculator { private static final BundleCalculatorVector vector = BundleCalculatorVector.getSingleton(); private static enum Operation { OP_ADD, OP_SUB, OP_DIV, OP_MULT, OP_REM, OP_SET, OP_COLVAL, OP_VAL, OP_SWAP, OP_GT, OP_LT, OP_GT_EQ, OP_LT_EQ, OP_EQ, OP_DUP, OP_LOG, OP_DMULT, OP_DDIV, OP_TOINT, OP_TOFLOAT, OP_SHIFTOUT, OP_SQRT, OP_DGT, OP_DLT, OP_DGT_EQ, OP_DLT_EQ, OP_DEQ, OP_MEAN, OP_VARIANCE, OP_MIN, OP_MAX, OP_MINIF, OP_MAXIF, OP_ABS, OP_COLNAMEVAL, OP_VECTOR } private List<MathOp> ops; private boolean diverr; private BundleColumnBinder sourceBinder; public BundleCalculator(String args) { String op[] = Strings.splitArray(args, ","); ops = new ArrayList<>(op.length); for (String o : op) { switch (o) { case "+": case "add": ops.add(new MathOp(Operation.OP_ADD, null)); break; case "-": case "sub": ops.add(new MathOp(Operation.OP_SUB, null)); break; case "*": case "mult": case "prod": ops.add(new MathOp(Operation.OP_MULT, null)); break; case "dmult": case "dprod": ops.add(new MathOp(Operation.OP_DMULT, null)); break; case "/": case "div": ops.add(new MathOp(Operation.OP_DIV, null)); break; case "ddiv": ops.add(new MathOp(Operation.OP_DDIV, null)); break; case "log": ops.add(new MathOp(Operation.OP_LOG, null)); break; case "%": case "rem": ops.add(new MathOp(Operation.OP_REM, null)); break; case "=": case "s": case "set": ops.add(new MathOp(Operation.OP_SET, null)); break; case "x": case "swap": ops.add(new MathOp(Operation.OP_SWAP, null)); break; case "d": case "dup": ops.add(new MathOp(Operation.OP_DUP, null)); break; case ">": case "gt": ops.add(new MathOp(Operation.OP_GT, null)); break; case ">=": case "gteq": ops.add(new MathOp(Operation.OP_GT_EQ, null)); break; case "<": case "lt": ops.add(new MathOp(Operation.OP_LT, null)); break; case "<=": case "lteq": ops.add(new MathOp(Operation.OP_LT_EQ, null)); break; case "eq": ops.add(new MathOp(Operation.OP_EQ, null)); break; case "toi": case "toint": ops.add(new MathOp(Operation.OP_TOINT, null)); break; case "tof": case "tofloat": ops.add(new MathOp(Operation.OP_TOFLOAT, null)); break; case "out": case "shiftout": ops.add(new MathOp(Operation.OP_SHIFTOUT, null)); break; case "sqrt": ops.add(new MathOp(Operation.OP_SQRT, null)); break; case "diverr": diverr = true; break; case ">>": case "dgt": ops.add(new MathOp(Operation.OP_DGT, null)); break; case ">>=": case "dgteq": ops.add(new MathOp(Operation.OP_DGT_EQ, null)); break; case "<<": case "dlt": ops.add(new MathOp(Operation.OP_DLT, null)); break; case "<<=": case "dlteq": ops.add(new MathOp(Operation.OP_DLT_EQ, null)); break; case "==": case "deq": ops.add(new MathOp(Operation.OP_DEQ, null)); break; case "min": ops.add(new MathOp(Operation.OP_MIN, null)); break; case "max": ops.add(new MathOp(Operation.OP_MAX, null)); break; case "minif": ops.add(new MathOp(Operation.OP_MINIF, null)); break; case "maxif": ops.add(new MathOp(Operation.OP_MAXIF, null)); break; case "abs": ops.add(new MathOp(Operation.OP_ABS, null)); break; case "mean": ops.add(new MathOp(Operation.OP_MEAN, null)); break; case "variance": ops.add(new MathOp(Operation.OP_VARIANCE, null)); break; case "vector": ops.add(new MathOp(Operation.OP_VECTOR, null)); break; default: { if (o.startsWith("c")) { String cols[] = Strings.splitArray(o.substring(1), ":"); for (String col : cols) { ops.add(new MathOp(Operation.OP_COLVAL, ValueFactory.create(col))); } } else if (o.startsWith("C")) { String cols[] = Strings.splitArray(o.substring(1), ":"); for (String col : cols) { ops.add(new MathOp(Operation.OP_COLNAMEVAL, ValueFactory.create(col))); } } else if (o.startsWith("n")) { String nums[] = Strings.splitArray(o.substring(1), ":"); for (String num : nums) { if (num.indexOf(".") >= 0) { ops.add(new MathOp(Operation.OP_VAL, ValueFactory.create(Double.parseDouble(num)))); } else { ops.add(new MathOp(Operation.OP_VAL, ValueFactory.create(Long.parseLong(num)))); } } } else if (o.startsWith("v")) { ops.add(new MathOp(Operation.OP_VAL, ValueFactory.create(o.substring(1)))); } } } } } /** * If the value object contains one or more "," characters then attempt * to parse it as an array. Otherwise assume the input is a number. */ private void insertNumbers(LinkedList<ValueNumber> stack, ValueObject input) { try { /** * When all custom value types implement the asString() method correctly * then the (input instanceof ValueString) test can be removed. **/ if (input instanceof ValueString) { String targetString = input.asString().toString(); if (targetString.indexOf(',') >= 0) { String[] targets = targetString.split(","); for (int i = 0; i < targets.length; i++) { Number number = NumberFormat.getInstance().parse(targets[i]); if (number instanceof Long) { stack.push(ValueFactory.create(number.longValue())); } else if (number instanceof Double) { stack.push(ValueFactory.create(number.doubleValue())); } else { throw new IllegalStateException(number + " is neither Long nor Double"); } } } else { stack.push(input.asNumber()); } } else { stack.push(input.asNumber()); } } catch (ParseException ex) { throw new RuntimeException(ex); } } public Bundle calculate(Bundle line) { LinkedList<ValueNumber> stack = new LinkedList<ValueNumber>(); long maxcol = line.getCount() - 1; for (MathOp op : ops) { ValueNumber v1, v2; switch (op.type) { case OP_ADD: v1 = stack.pop(); if (v1 == vector) { v1 = stack.pop(); while (!stack.isEmpty()) { v1 = v1.sum(stack.pop()); } stack.push(v1); } else { v2 = stack.pop(); stack.push(v1.sum(v2)); } break; case OP_SUB: v1 = stack.pop(); v2 = stack.pop(); stack.push(v2.diff(v1)); break; case OP_MULT: { v1 = stack.pop(); if (v1 == vector) { v1 = stack.pop(); long mult = v1.asLong().getLong(); while (!stack.isEmpty()) { mult *= stack.pop().asLong().getLong(); } stack.push(ValueFactory.create(mult)); } else { v2 = stack.pop(); long mult = v1.asLong().getLong() * v2.asLong().getLong(); stack.push(ValueFactory.create(mult)); } break; } case OP_DMULT: { v1 = stack.pop(); if (v1 == vector) { v1 = stack.pop(); double mult = v1.asDouble().getDouble(); while (!stack.isEmpty()) { mult *= stack.pop().asDouble().getDouble(); } stack.push(ValueFactory.create(mult)); } else { v2 = stack.pop(); double mult = v1.asDouble().getDouble() * v2.asDouble().getDouble(); stack.push(ValueFactory.create(mult)); } break; } case OP_DIV: v1 = stack.pop(); v2 = stack.pop(); if (!diverr && v1.asLong().getLong() == 0) { stack.push(ValueFactory.create(0)); } else { stack.push(ValueFactory.create(v2.asLong().getLong() / v1.asLong().getLong())); } break; case OP_DDIV: v1 = stack.pop(); v2 = stack.pop(); if (!diverr && v1.asDouble().getDouble() == 0d) { stack.push(ValueFactory.create(0)); } else { stack.push(ValueFactory.create(v2.asDouble().getDouble() / v1.asDouble().getDouble())); } break; case OP_REM: v1 = stack.pop(); v2 = stack.pop(); if (!diverr && v1.asLong().getLong() == 0) { stack.push(ValueFactory.create(0)); } else { stack.push(ValueFactory.create(v2.asLong().getLong() % v1.asLong().getLong())); } break; case OP_LOG: stack.push(ValueFactory.create(Math.log10(stack.pop().asDouble().getDouble()))); break; case OP_SQRT: stack.push(ValueFactory.create(Math.sqrt(stack.pop().asDouble().getDouble()))); break; case OP_VAL: stack.push(op.val.asNumber()); break; case OP_COLVAL: { ValueObject target = getSourceColumnBinder(line).getColumn(line, (int) op.val.asLong().getLong()); insertNumbers(stack, target); break; } case OP_COLNAMEVAL: { ValueObject target = line.getValue(line.getFormat().getField(op.val.toString())); insertNumbers(stack, target); break; } case OP_DUP: stack.push(stack.peek()); break; case OP_TOINT: stack.push(ValueUtil.asNumberOrParseLong(stack.pop(), 10).asLong()); break; case OP_TOFLOAT: stack.push(ValueUtil.asNumberOrParseDouble(stack.pop())); break; case OP_DGT: v1 = stack.pop(); v2 = stack.pop(); if (!(v2.asDouble().getDouble() > v1.asDouble().getDouble())) { return null; } break; case OP_DGT_EQ: v1 = stack.pop(); v2 = stack.pop(); if (!(v2.asDouble().getDouble() >= v1.asDouble().getDouble())) { return null; } break; case OP_DLT: v1 = stack.pop(); v2 = stack.pop(); if (!(v2.asDouble().getDouble() < v1.asDouble().getDouble())) { return null; } break; case OP_DLT_EQ: v1 = stack.pop(); v2 = stack.pop(); if (!(v2.asDouble().getDouble() <= v1.asDouble().getDouble())) { return null; } break; case OP_DEQ: v1 = stack.pop(); v2 = stack.pop(); if (v2.asDouble().getDouble() != v1.asDouble().getDouble()) { return null; } break; case OP_GT: v1 = stack.pop(); v2 = stack.pop(); if (!(v2.asLong().getLong() > v1.asLong().getLong())) { return null; } break; case OP_GT_EQ: v1 = stack.pop(); v2 = stack.pop(); if (!(v2.asLong().getLong() >= v1.asLong().getLong())) { return null; } break; case OP_LT: v1 = stack.pop(); v2 = stack.pop(); if (!(v2.asLong().getLong() < v1.asLong().getLong())) { return null; } break; case OP_LT_EQ: v1 = stack.pop(); v2 = stack.pop(); if (!(v2.asLong().getLong() <= v1.asLong().getLong())) { return null; } break; case OP_EQ: v1 = stack.pop(); v2 = stack.pop(); if (v2.asLong().getLong() != v1.asLong().getLong()) { return null; } break; case OP_SWAP: v1 = stack.pop(); v2 = stack.pop(); stack.push(v1); stack.push(v2); break; case OP_SHIFTOUT: getSourceColumnBinder(line).appendColumn(line, stack.pop()); break; case OP_SET: int col = (int) stack.pop().asLong().getLong(); ValueNumber val = stack.pop(); if (col < 0 || col > maxcol) { getSourceColumnBinder(line).appendColumn(line, val); } else { getSourceColumnBinder(line).setColumn(line, col, val); } break; case OP_MIN: v1 = stack.pop(); if (v1 == vector) { v1 = stack.pop(); while (!stack.isEmpty()) { v1 = v1.min(stack.pop()); } stack.push(v1); } else { v2 = stack.pop(); stack.push(v1.min(v2)); } break; case OP_MAX: v1 = stack.pop(); if (v1 == vector) { v1 = stack.pop(); while (!stack.isEmpty()) { v1 = v1.max(stack.pop()); } stack.push(v1); } else { v2 = stack.pop(); stack.push(v1.max(v2)); } break; case OP_MINIF: v1 = stack.pop(); v2 = stack.pop(); stack.push(v1.max(v2).equals(v1) ? v1 : v2); break; case OP_MAXIF: v1 = stack.pop(); v2 = stack.pop(); stack.push(v1.min(v2).equals(v1) ? v1 : v2); break; case OP_MEAN: { long count = 0; double mean = 0.0; while (!stack.isEmpty()) { count++; double num = stack.pop().asDouble().getDouble(); double delta = num - mean; mean += delta / count; } stack.push(ValueFactory.create(mean)); break; } case OP_VARIANCE: { long count = 0; double mean = 0.0; double m2 = 0.0; while (!stack.isEmpty()) { count++; double num = stack.pop().asDouble().getDouble(); double delta = num - mean; mean += delta / count; m2 += delta * (num - mean); } if (count < 2) { stack.push(ValueFactory.create(0.0)); } else { double variance = m2 / count; stack.push(ValueFactory.create(variance)); } break; } case OP_VECTOR: stack.push(vector); break; case OP_ABS: v1 = stack.pop(); stack.push(ValueFactory.create(Math.abs(v1.asDouble().getDouble()))); default: break; } } return line; } /** */ private class MathOp { private @Nonnull Operation type; private @Nullable ValueObject val; MathOp(Operation type, ValueObject val) { this.type = type; this.val = val; } } /* Copied from AbstractQueryOp */ public BundleColumnBinder getSourceColumnBinder(BundleFormatted row) { return getSourceColumnBinder(row, null); } /* Copied from AbstractQueryOp */ public BundleColumnBinder getSourceColumnBinder(BundleFormatted row, String fields[]) { if (sourceBinder == null) { sourceBinder = new BundleColumnBinder(row, fields); } return sourceBinder; } }
hydra-filters/src/main/java/com/addthis/hydra/data/filter/util/BundleCalculator.java
/* * 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.addthis.hydra.data.filter.util; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.text.NumberFormat; import java.text.ParseException; import com.addthis.basis.util.Strings; import com.addthis.bundle.core.Bundle; import com.addthis.bundle.core.BundleFormatted; import com.addthis.bundle.util.BundleColumnBinder; import com.addthis.bundle.util.ValueUtil; import com.addthis.bundle.value.ValueFactory; import com.addthis.bundle.value.ValueNumber; import com.addthis.bundle.value.ValueObject; import com.google.common.primitives.Doubles; public class BundleCalculator { private static final BundleCalculatorVector vector = BundleCalculatorVector.getSingleton(); private static enum Operation { OP_ADD, OP_SUB, OP_DIV, OP_MULT, OP_REM, OP_SET, OP_COLVAL, OP_VAL, OP_SWAP, OP_GT, OP_LT, OP_GT_EQ, OP_LT_EQ, OP_EQ, OP_DUP, OP_LOG, OP_DMULT, OP_DDIV, OP_TOINT, OP_TOFLOAT, OP_SHIFTOUT, OP_SQRT, OP_DGT, OP_DLT, OP_DGT_EQ, OP_DLT_EQ, OP_DEQ, OP_MEAN, OP_VARIANCE, OP_MIN, OP_MAX, OP_MINIF, OP_MAXIF, OP_ABS, OP_COLNAMEVAL, OP_VECTOR } private List<MathOp> ops; private boolean diverr; private BundleColumnBinder sourceBinder; public BundleCalculator(String args) { String op[] = Strings.splitArray(args, ","); ops = new ArrayList<>(op.length); for (String o : op) { switch (o) { case "+": case "add": ops.add(new MathOp(Operation.OP_ADD, null)); break; case "-": case "sub": ops.add(new MathOp(Operation.OP_SUB, null)); break; case "*": case "mult": case "prod": ops.add(new MathOp(Operation.OP_MULT, null)); break; case "dmult": case "dprod": ops.add(new MathOp(Operation.OP_DMULT, null)); break; case "/": case "div": ops.add(new MathOp(Operation.OP_DIV, null)); break; case "ddiv": ops.add(new MathOp(Operation.OP_DDIV, null)); break; case "log": ops.add(new MathOp(Operation.OP_LOG, null)); break; case "%": case "rem": ops.add(new MathOp(Operation.OP_REM, null)); break; case "=": case "s": case "set": ops.add(new MathOp(Operation.OP_SET, null)); break; case "x": case "swap": ops.add(new MathOp(Operation.OP_SWAP, null)); break; case "d": case "dup": ops.add(new MathOp(Operation.OP_DUP, null)); break; case ">": case "gt": ops.add(new MathOp(Operation.OP_GT, null)); break; case ">=": case "gteq": ops.add(new MathOp(Operation.OP_GT_EQ, null)); break; case "<": case "lt": ops.add(new MathOp(Operation.OP_LT, null)); break; case "<=": case "lteq": ops.add(new MathOp(Operation.OP_LT_EQ, null)); break; case "eq": ops.add(new MathOp(Operation.OP_EQ, null)); break; case "toi": case "toint": ops.add(new MathOp(Operation.OP_TOINT, null)); break; case "tof": case "tofloat": ops.add(new MathOp(Operation.OP_TOFLOAT, null)); break; case "out": case "shiftout": ops.add(new MathOp(Operation.OP_SHIFTOUT, null)); break; case "sqrt": ops.add(new MathOp(Operation.OP_SQRT, null)); break; case "diverr": diverr = true; break; case ">>": case "dgt": ops.add(new MathOp(Operation.OP_DGT, null)); break; case ">>=": case "dgteq": ops.add(new MathOp(Operation.OP_DGT_EQ, null)); break; case "<<": case "dlt": ops.add(new MathOp(Operation.OP_DLT, null)); break; case "<<=": case "dlteq": ops.add(new MathOp(Operation.OP_DLT_EQ, null)); break; case "==": case "deq": ops.add(new MathOp(Operation.OP_DEQ, null)); break; case "min": ops.add(new MathOp(Operation.OP_MIN, null)); break; case "max": ops.add(new MathOp(Operation.OP_MAX, null)); break; case "minif": ops.add(new MathOp(Operation.OP_MINIF, null)); break; case "maxif": ops.add(new MathOp(Operation.OP_MAXIF, null)); break; case "abs": ops.add(new MathOp(Operation.OP_ABS, null)); break; case "mean": ops.add(new MathOp(Operation.OP_MEAN, null)); break; case "variance": ops.add(new MathOp(Operation.OP_VARIANCE, null)); break; case "vector": ops.add(new MathOp(Operation.OP_VECTOR, null)); break; default: { if (o.startsWith("c")) { String cols[] = Strings.splitArray(o.substring(1), ":"); for (String col : cols) { ops.add(new MathOp(Operation.OP_COLVAL, ValueFactory.create(col))); } } else if (o.startsWith("C")) { String cols[] = Strings.splitArray(o.substring(1), ":"); for (String col : cols) { ops.add(new MathOp(Operation.OP_COLNAMEVAL, ValueFactory.create(col))); } } else if (o.startsWith("n")) { String nums[] = Strings.splitArray(o.substring(1), ":"); for (String num : nums) { if (num.indexOf(".") >= 0) { ops.add(new MathOp(Operation.OP_VAL, ValueFactory.create(Double.parseDouble(num)))); } else { ops.add(new MathOp(Operation.OP_VAL, ValueFactory.create(Long.parseLong(num)))); } } } else if (o.startsWith("v")) { ops.add(new MathOp(Operation.OP_VAL, ValueFactory.create(o.substring(1)))); } } } } } /** * If the value object contains one or more "," characters then attempt * to parse it as an array. Otherwise assume the input is a number. */ private void insertNumbers(LinkedList<ValueNumber> stack, ValueObject input) { try { String targetString = input.asString().toString(); if (targetString.indexOf(',') >= 0) { String[] targets = targetString.split(","); for (int i = 0; i < targets.length; i++) { Number number = NumberFormat.getInstance().parse(targets[i]); if (number instanceof Long) { stack.push(ValueFactory.create(number.longValue())); } else if (number instanceof Double) { stack.push(ValueFactory.create(number.doubleValue())); } else { throw new IllegalStateException(number + " is neither Long nor Double"); } } } else { stack.push(input.asNumber()); } } catch (ParseException ex) { throw new RuntimeException(ex); } } public Bundle calculate(Bundle line) { LinkedList<ValueNumber> stack = new LinkedList<ValueNumber>(); long maxcol = line.getCount() - 1; for (MathOp op : ops) { ValueNumber v1, v2; switch (op.type) { case OP_ADD: v1 = stack.pop(); if (v1 == vector) { v1 = stack.pop(); while (!stack.isEmpty()) { v1 = v1.sum(stack.pop()); } stack.push(v1); } else { v2 = stack.pop(); stack.push(v1.sum(v2)); } break; case OP_SUB: v1 = stack.pop(); v2 = stack.pop(); stack.push(v2.diff(v1)); break; case OP_MULT: { v1 = stack.pop(); if (v1 == vector) { v1 = stack.pop(); long mult = v1.asLong().getLong(); while (!stack.isEmpty()) { mult *= stack.pop().asLong().getLong(); } stack.push(ValueFactory.create(mult)); } else { v2 = stack.pop(); long mult = v1.asLong().getLong() * v2.asLong().getLong(); stack.push(ValueFactory.create(mult)); } break; } case OP_DMULT: { v1 = stack.pop(); if (v1 == vector) { v1 = stack.pop(); double mult = v1.asDouble().getDouble(); while (!stack.isEmpty()) { mult *= stack.pop().asDouble().getDouble(); } stack.push(ValueFactory.create(mult)); } else { v2 = stack.pop(); double mult = v1.asDouble().getDouble() * v2.asDouble().getDouble(); stack.push(ValueFactory.create(mult)); } break; } case OP_DIV: v1 = stack.pop(); v2 = stack.pop(); if (!diverr && v1.asLong().getLong() == 0) { stack.push(ValueFactory.create(0)); } else { stack.push(ValueFactory.create(v2.asLong().getLong() / v1.asLong().getLong())); } break; case OP_DDIV: v1 = stack.pop(); v2 = stack.pop(); if (!diverr && v1.asDouble().getDouble() == 0d) { stack.push(ValueFactory.create(0)); } else { stack.push(ValueFactory.create(v2.asDouble().getDouble() / v1.asDouble().getDouble())); } break; case OP_REM: v1 = stack.pop(); v2 = stack.pop(); if (!diverr && v1.asLong().getLong() == 0) { stack.push(ValueFactory.create(0)); } else { stack.push(ValueFactory.create(v2.asLong().getLong() % v1.asLong().getLong())); } break; case OP_LOG: stack.push(ValueFactory.create(Math.log10(stack.pop().asDouble().getDouble()))); break; case OP_SQRT: stack.push(ValueFactory.create(Math.sqrt(stack.pop().asDouble().getDouble()))); break; case OP_VAL: stack.push(op.val.asNumber()); break; case OP_COLVAL: { ValueObject target = getSourceColumnBinder(line).getColumn(line, (int) op.val.asLong().getLong()); insertNumbers(stack, target); break; } case OP_COLNAMEVAL: { ValueObject target = line.getValue(line.getFormat().getField(op.val.toString())); insertNumbers(stack, target); break; } case OP_DUP: stack.push(stack.peek()); break; case OP_TOINT: stack.push(ValueUtil.asNumberOrParseLong(stack.pop(), 10).asLong()); break; case OP_TOFLOAT: stack.push(ValueUtil.asNumberOrParseDouble(stack.pop())); break; case OP_DGT: v1 = stack.pop(); v2 = stack.pop(); if (!(v2.asDouble().getDouble() > v1.asDouble().getDouble())) { return null; } break; case OP_DGT_EQ: v1 = stack.pop(); v2 = stack.pop(); if (!(v2.asDouble().getDouble() >= v1.asDouble().getDouble())) { return null; } break; case OP_DLT: v1 = stack.pop(); v2 = stack.pop(); if (!(v2.asDouble().getDouble() < v1.asDouble().getDouble())) { return null; } break; case OP_DLT_EQ: v1 = stack.pop(); v2 = stack.pop(); if (!(v2.asDouble().getDouble() <= v1.asDouble().getDouble())) { return null; } break; case OP_DEQ: v1 = stack.pop(); v2 = stack.pop(); if (v2.asDouble().getDouble() != v1.asDouble().getDouble()) { return null; } break; case OP_GT: v1 = stack.pop(); v2 = stack.pop(); if (!(v2.asLong().getLong() > v1.asLong().getLong())) { return null; } break; case OP_GT_EQ: v1 = stack.pop(); v2 = stack.pop(); if (!(v2.asLong().getLong() >= v1.asLong().getLong())) { return null; } break; case OP_LT: v1 = stack.pop(); v2 = stack.pop(); if (!(v2.asLong().getLong() < v1.asLong().getLong())) { return null; } break; case OP_LT_EQ: v1 = stack.pop(); v2 = stack.pop(); if (!(v2.asLong().getLong() <= v1.asLong().getLong())) { return null; } break; case OP_EQ: v1 = stack.pop(); v2 = stack.pop(); if (v2.asLong().getLong() != v1.asLong().getLong()) { return null; } break; case OP_SWAP: v1 = stack.pop(); v2 = stack.pop(); stack.push(v1); stack.push(v2); break; case OP_SHIFTOUT: getSourceColumnBinder(line).appendColumn(line, stack.pop()); break; case OP_SET: int col = (int) stack.pop().asLong().getLong(); ValueNumber val = stack.pop(); if (col < 0 || col > maxcol) { getSourceColumnBinder(line).appendColumn(line, val); } else { getSourceColumnBinder(line).setColumn(line, col, val); } break; case OP_MIN: v1 = stack.pop(); if (v1 == vector) { v1 = stack.pop(); while (!stack.isEmpty()) { v1 = v1.min(stack.pop()); } stack.push(v1); } else { v2 = stack.pop(); stack.push(v1.min(v2)); } break; case OP_MAX: v1 = stack.pop(); if (v1 == vector) { v1 = stack.pop(); while (!stack.isEmpty()) { v1 = v1.max(stack.pop()); } stack.push(v1); } else { v2 = stack.pop(); stack.push(v1.max(v2)); } break; case OP_MINIF: v1 = stack.pop(); v2 = stack.pop(); stack.push(v1.max(v2).equals(v1) ? v1 : v2); break; case OP_MAXIF: v1 = stack.pop(); v2 = stack.pop(); stack.push(v1.min(v2).equals(v1) ? v1 : v2); break; case OP_MEAN: { long count = 0; double mean = 0.0; while (!stack.isEmpty()) { count++; double num = stack.pop().asDouble().getDouble(); double delta = num - mean; mean += delta / count; } stack.push(ValueFactory.create(mean)); break; } case OP_VARIANCE: { long count = 0; double mean = 0.0; double m2 = 0.0; while (!stack.isEmpty()) { count++; double num = stack.pop().asDouble().getDouble(); double delta = num - mean; mean += delta / count; m2 += delta * (num - mean); } if (count < 2) { stack.push(ValueFactory.create(0.0)); } else { double variance = m2 / count; stack.push(ValueFactory.create(variance)); } break; } case OP_VECTOR: stack.push(vector); break; case OP_ABS: v1 = stack.pop(); stack.push(ValueFactory.create(Math.abs(v1.asDouble().getDouble()))); default: break; } } return line; } /** */ private class MathOp { private @Nonnull Operation type; private @Nullable ValueObject val; MathOp(Operation type, ValueObject val) { this.type = type; this.val = val; } } /* Copied from AbstractQueryOp */ public BundleColumnBinder getSourceColumnBinder(BundleFormatted row) { return getSourceColumnBinder(row, null); } /* Copied from AbstractQueryOp */ public BundleColumnBinder getSourceColumnBinder(BundleFormatted row, String fields[]) { if (sourceBinder == null) { sourceBinder = new BundleColumnBinder(row, fields); } return sourceBinder; } }
Bugfix for BundleCalculator recent pull request. Not all custom value types implement the asString() method. This fix is a workaround for that fact.
hydra-filters/src/main/java/com/addthis/hydra/data/filter/util/BundleCalculator.java
Bugfix for BundleCalculator recent pull request.
<ide><path>ydra-filters/src/main/java/com/addthis/hydra/data/filter/util/BundleCalculator.java <ide> import com.addthis.bundle.value.ValueFactory; <ide> import com.addthis.bundle.value.ValueNumber; <ide> import com.addthis.bundle.value.ValueObject; <add>import com.addthis.bundle.value.ValueString; <ide> <ide> import com.google.common.primitives.Doubles; <ide> <ide> */ <ide> private void insertNumbers(LinkedList<ValueNumber> stack, ValueObject input) { <ide> try { <del> String targetString = input.asString().toString(); <del> if (targetString.indexOf(',') >= 0) { <del> String[] targets = targetString.split(","); <del> for (int i = 0; i < targets.length; i++) { <del> Number number = NumberFormat.getInstance().parse(targets[i]); <del> if (number instanceof Long) { <del> stack.push(ValueFactory.create(number.longValue())); <del> } else if (number instanceof Double) { <del> stack.push(ValueFactory.create(number.doubleValue())); <del> } else { <del> throw new IllegalStateException(number + " is neither Long nor Double"); <del> } <add> /** <add> * When all custom value types implement the asString() method correctly <add> * then the (input instanceof ValueString) test can be removed. <add> **/ <add> if (input instanceof ValueString) { <add> String targetString = input.asString().toString(); <add> if (targetString.indexOf(',') >= 0) { <add> String[] targets = targetString.split(","); <add> for (int i = 0; i < targets.length; i++) { <add> Number number = NumberFormat.getInstance().parse(targets[i]); <add> if (number instanceof Long) { <add> stack.push(ValueFactory.create(number.longValue())); <add> } else if (number instanceof Double) { <add> stack.push(ValueFactory.create(number.doubleValue())); <add> } else { <add> throw new IllegalStateException(number + " is neither Long nor Double"); <add> } <add> } <add> } else { <add> stack.push(input.asNumber()); <ide> } <ide> } else { <ide> stack.push(input.asNumber());
JavaScript
mit
7de66727dffef7f0c88a230d0582c6fbea761c1f
0
untoldone/bloomapi,untoldone/bloomapi
require('shelljs/make'); var logger = require('./lib/logger'); // default target target.all = function () { console.log("\nAvailable commands:\n-------------------"); console.log(" node make bootstrap # fetch, process, and insert NPI data into database") console.log(" node make fetch # like 'bootstrap' but assumes you already have the base sql database setup") console.log(" node make server # run web/API server") console.log(" node make check # checks your environment for configuration files and some dependencies") console.log("\n For more information, visit the project README file on github at https://github.com/untoldone/bloomapi\n") } var Q = require('q'); Q.longStackSupport = true; target.fetch = function () { var pg = require('./lib/sources/pg'), npi = require('./lib/sources/npi'); logger.data.info('attempting to sync datasources'); npi.update() .fail(function (e) { console.error("Error:\n" + e.stack); process.exit(1); }) .done(function () { pg.end(); }); }; target.bootstrap = function () { var pg = require('./lib/sources/pg'), npi = require('./lib/sources/npi'), fs = require('fs'); logger.data.info('bootstrapping bloomapi'); target.docs(); Q.nfcall(fs.readFile, './lib/bootstrap.sql', {encoding: 'utf8'}) .then(function (data) { return Q.ninvoke(pg, 'query', data); }) .then(npi.update) .fail(function (e) { console.error("Error:\n", e.stack); process.exit(1); }) .done(function () { pg.end(); }); } target.server = function () { logger.server.info('starting bloomapi'); require('./lib/api/server'); }; target.docs = function () { logger.data.info('building documentation'); var docs = require('./lib/docs'); docs.build().done(); }; target.check = function () { if (!test('-f', './config.js')) { console.log('ERROR: no configuration file found, copy and configure ./config.js.sample to ./config.js'); } var valid = true, pg = require('./lib/sources/pg'), query = pg.query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'", function (err, result) { if (err) { console.log('ERROR: running query on database, check credentials'); valid = false; } if (!which('7z')) { console.log('ERROR: p7zip is required for bootstrap task'); valid = false; } if (!which('pdftotext')) { console.log('ERROR: pdftotext is required for bootstrap task'); valid = false; } if (valid) { console.log('PASSED: all checks'); } }); query.on('end', function () { pg.end(); }); };
make.js
require('shelljs/make'); var logger = require('./lib/logger'); // default target target.all = function () { console.log("\nAvailable commands:\n-------------------"); console.log(" node make bootstrap # fetch, process, and insert NPI data into database") console.log(" node make fetch # like 'bootstrap' but assumes you already have the base sql database setup") console.log(" node make server # run web/API server") console.log(" node make check # checks your environment for configuration files and some dependencies") console.log("\n For more information, visit the project README file on github at https://github.com/untoldone/bloomapi\n") } var Q = require('q'); Q.longStackSupport = true; target.fetch = function () { var pg = require('./lib/sources/pg'), npi = require('./lib/sources/npi'); logger.data.info('attempting to sync datasources'); npi.update() .fail(function (e) { console.error("Error:\n" + e.stack); process.exit(1); }) .done(function () { pg.end(); }); }; target.bootstrap = function () { var pg = require('./lib/sources/pg'), npi = require('./lib/sources/npi'), fs = require('fs'); logger.data.info('bootstrapping bloomapi'); Q.nfcall(fs.readFile, './lib/bootstrap.sql', {encoding: 'utf8'}) .then(function (data) { return Q.ninvoke(pg, 'query', data); }) .then(npi.update) .fail(function (e) { console.error("Error:\n", e.stack); process.exit(1); }) .done(function () { pg.end(); }); } target.server = function () { logger.server.info('starting bloomapi'); require('./lib/api/server'); }; target.docs = function () { logger.data.info('building documentation'); var docs = require('./lib/docs'); docs.build().done(); }; target.check = function () { if (!test('-f', './config.js')) { console.log('ERROR: no configuration file found, copy and configure ./config.js.sample to ./config.js'); } var valid = true, pg = require('./lib/sources/pg'), query = pg.query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'", function (err, result) { if (err) { console.log('ERROR: running query on database, check credentials'); valid = false; } if (!which('7z')) { console.log('ERROR: p7zip is required for bootstrap task'); valid = false; } if (!which('pdftotext')) { console.log('ERROR: pdftotext is required for bootstrap task'); valid = false; } if (valid) { console.log('PASSED: all checks'); } }); query.on('end', function () { pg.end(); }); };
bootstrap task now depends on building the documentation
make.js
bootstrap task now depends on building the documentation
<ide><path>ake.js <ide> fs = require('fs'); <ide> <ide> logger.data.info('bootstrapping bloomapi'); <add> <add> target.docs(); <ide> <ide> Q.nfcall(fs.readFile, './lib/bootstrap.sql', {encoding: 'utf8'}) <ide> .then(function (data) {
Java
apache-2.0
b13674cf47a590852fbece34dde21e5f13be43bb
0
InfomediaLtd/pinpoint,lioolli/pinpoint,philipz/pinpoint,jiaqifeng/pinpoint,sbcoba/pinpoint,minwoo-jung/pinpoint,majinkai/pinpoint,dawidmalina/pinpoint,emeroad/pinpoint,jiaqifeng/pinpoint,nstopkimsk/pinpoint,InfomediaLtd/pinpoint,koo-taejin/pinpoint,barneykim/pinpoint,hcapitaine/pinpoint,sbcoba/pinpoint,breadval/pinpoint,carpedm20/pinpoint,87439247/pinpoint,krishnakanthpps/pinpoint,eBaoTech/pinpoint,gspandy/pinpoint,shuvigoss/pinpoint,cit-lab/pinpoint,hcapitaine/pinpoint,Allive1/pinpoint,sbcoba/pinpoint,shuvigoss/pinpoint,coupang/pinpoint,majinkai/pinpoint,dawidmalina/pinpoint,lioolli/pinpoint,cit-lab/pinpoint,PerfGeeks/pinpoint,wziyong/pinpoint,majinkai/pinpoint,masonmei/pinpoint,shuvigoss/pinpoint,jiaqifeng/pinpoint,breadval/pinpoint,Allive1/pinpoint,hcapitaine/pinpoint,carpedm20/pinpoint,87439247/pinpoint,gspandy/pinpoint,wziyong/pinpoint,KRDeNaT/pinpoint,barneykim/pinpoint,philipz/pinpoint,krishnakanthpps/pinpoint,barneykim/pinpoint,sjmittal/pinpoint,koo-taejin/pinpoint,andyspan/pinpoint,suraj-raturi/pinpoint,barneykim/pinpoint,KRDeNaT/pinpoint,suraj-raturi/pinpoint,dawidmalina/pinpoint,Allive1/pinpoint,InfomediaLtd/pinpoint,jaehong-kim/pinpoint,eBaoTech/pinpoint,coupang/pinpoint,gspandy/pinpoint,citywander/pinpoint,naver/pinpoint,sjmittal/pinpoint,KRDeNaT/pinpoint,jiaqifeng/pinpoint,citywander/pinpoint,chenguoxi1985/pinpoint,KimTaehee/pinpoint,tsyma/pinpoint,nstopkimsk/pinpoint,krishnakanthpps/pinpoint,Skkeem/pinpoint,citywander/pinpoint,minwoo-jung/pinpoint,andyspan/pinpoint,Allive1/pinpoint,andyspan/pinpoint,coupang/pinpoint,PerfGeeks/pinpoint,lioolli/pinpoint,KimTaehee/pinpoint,tsyma/pinpoint,tsyma/pinpoint,emeroad/pinpoint,87439247/pinpoint,gspandy/pinpoint,chenguoxi1985/pinpoint,nstopkimsk/pinpoint,koo-taejin/pinpoint,carpedm20/pinpoint,lioolli/pinpoint,andyspan/pinpoint,KimTaehee/pinpoint,Xylus/pinpoint,cit-lab/pinpoint,naver/pinpoint,tsyma/pinpoint,masonmei/pinpoint,philipz/pinpoint,sjmittal/pinpoint,dawidmalina/pinpoint,denzelsN/pinpoint,masonmei/pinpoint,sjmittal/pinpoint,KimTaehee/pinpoint,krishnakanthpps/pinpoint,InfomediaLtd/pinpoint,philipz/pinpoint,nstopkimsk/pinpoint,jaehong-kim/pinpoint,majinkai/pinpoint,hcapitaine/pinpoint,cijung/pinpoint,koo-taejin/pinpoint,hcapitaine/pinpoint,tsyma/pinpoint,citywander/pinpoint,breadval/pinpoint,sbcoba/pinpoint,masonmei/pinpoint,coupang/pinpoint,shuvigoss/pinpoint,breadval/pinpoint,PerfGeeks/pinpoint,Xylus/pinpoint,denzelsN/pinpoint,emeroad/pinpoint,gspandy/pinpoint,jaehong-kim/pinpoint,Allive1/pinpoint,cijung/pinpoint,Skkeem/pinpoint,nstopkimsk/pinpoint,PerfGeeks/pinpoint,jiaqifeng/pinpoint,denzelsN/pinpoint,87439247/pinpoint,KimTaehee/pinpoint,jaehong-kim/pinpoint,barneykim/pinpoint,Allive1/pinpoint,KRDeNaT/pinpoint,PerfGeeks/pinpoint,tsyma/pinpoint,87439247/pinpoint,cit-lab/pinpoint,Skkeem/pinpoint,masonmei/pinpoint,breadval/pinpoint,cijung/pinpoint,Xylus/pinpoint,cijung/pinpoint,cijung/pinpoint,suraj-raturi/pinpoint,eBaoTech/pinpoint,wziyong/pinpoint,jaehong-kim/pinpoint,Xylus/pinpoint,barneykim/pinpoint,andyspan/pinpoint,philipz/pinpoint,dawidmalina/pinpoint,jiaqifeng/pinpoint,nstopkimsk/pinpoint,eBaoTech/pinpoint,Skkeem/pinpoint,sbcoba/pinpoint,chenguoxi1985/pinpoint,sjmittal/pinpoint,sbcoba/pinpoint,cit-lab/pinpoint,suraj-raturi/pinpoint,wziyong/pinpoint,hcapitaine/pinpoint,KRDeNaT/pinpoint,dawidmalina/pinpoint,sjmittal/pinpoint,minwoo-jung/pinpoint,denzelsN/pinpoint,gspandy/pinpoint,naver/pinpoint,chenguoxi1985/pinpoint,krishnakanthpps/pinpoint,InfomediaLtd/pinpoint,jaehong-kim/pinpoint,citywander/pinpoint,cit-lab/pinpoint,denzelsN/pinpoint,Xylus/pinpoint,coupang/pinpoint,KRDeNaT/pinpoint,andyspan/pinpoint,minwoo-jung/pinpoint,naver/pinpoint,chenguoxi1985/pinpoint,suraj-raturi/pinpoint,lioolli/pinpoint,denzelsN/pinpoint,eBaoTech/pinpoint,carpedm20/pinpoint,koo-taejin/pinpoint,Skkeem/pinpoint,denzelsN/pinpoint,KimTaehee/pinpoint,Xylus/pinpoint,Skkeem/pinpoint,majinkai/pinpoint,coupang/pinpoint,shuvigoss/pinpoint,emeroad/pinpoint,minwoo-jung/pinpoint,masonmei/pinpoint,cijung/pinpoint,carpedm20/pinpoint,87439247/pinpoint,barneykim/pinpoint,emeroad/pinpoint,breadval/pinpoint,shuvigoss/pinpoint,krishnakanthpps/pinpoint,wziyong/pinpoint,suraj-raturi/pinpoint,wziyong/pinpoint,PerfGeeks/pinpoint,naver/pinpoint,Xylus/pinpoint,emeroad/pinpoint,majinkai/pinpoint,minwoo-jung/pinpoint,koo-taejin/pinpoint,eBaoTech/pinpoint,lioolli/pinpoint,citywander/pinpoint,InfomediaLtd/pinpoint,chenguoxi1985/pinpoint,philipz/pinpoint
package com.nhn.pinpoint.profiler.sender; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; import java.util.Collection; import com.nhn.pinpoint.profiler.logging.Logger; import com.nhn.pinpoint.profiler.logging.LoggerFactory; import org.apache.thrift.TBase; import org.apache.thrift.TException; import com.nhn.pinpoint.profiler.io.HeaderTBaseSerializer; import com.nhn.pinpoint.profiler.context.Thriftable; /** * @author netspider */ public class UdpDataSender extends AbstractQueueingDataSender implements DataSender { private final Logger logger = LoggerFactory.getLogger(UdpDataSender.class.getName()); private final boolean isTrace = logger.isTraceEnabled(); // 주의 single thread용임 private DatagramPacket reusePacket = new DatagramPacket(new byte[1], 1); private final DatagramSocket udpSocket; // 주의 single thread용임 private HeaderTBaseSerializer serializer = new HeaderTBaseSerializer(); public UdpDataSender(String host, int port) { super(1024, "UdpDataSender"); if (host == null ) { throw new NullPointerException("host must not be null"); } // Socket 생성에 에러가 발생하면 Agent start가 안되게 변경. logger.info("UdpDataSender initialized. host={}, port={}", host, port); this.udpSocket = createSocket(host, port); } private DatagramSocket createSocket(String host, int port) { try { DatagramSocket datagramSocket = new DatagramSocket(); datagramSocket.setSoTimeout(1000 * 5); datagramSocket.setSendBufferSize(1024 * 64 * 16); InetSocketAddress serverAddress = new InetSocketAddress(host, port); datagramSocket.connect(serverAddress); return datagramSocket; } catch (SocketException e) { throw new IllegalStateException("DataramSocket create fail. Cause" + e.getMessage(), e); } } public boolean send(TBase<?, ?> data) { return putQueue(data); } public boolean send(Thriftable thriftable) { return putQueue(thriftable); } protected void sendPacketN(Collection<Object> dtoList) { Object[] dataList = dtoList.toArray(); // for (Object data : dataList) { // 이렇게 바꾸지 말것. copy해서 return 하는게 아니라 항상 max치가 나옴. final int size = dtoList.size(); for (int i = 0; i < size; i++) { try { sendPacket(dataList[i]); } catch (Throwable th) { logger.warn("Unexpected Error. Cause:" + th.getMessage(), th); } } } protected void sendPacket(Object dto) { TBase<?, ?> tBase; if (dto instanceof TBase) { tBase = (TBase<?, ?>) dto; } else if (dto instanceof Thriftable) { tBase = ((Thriftable) dto).toThrift(); } else { logger.warn("sendPacket fail. invalid type:{}", dto.getClass()); return; } // single thread이므로 데이터 array를 nocopy해서 보냄. byte[] interBufferData = serialize(tBase); int interBufferSize = serializer.getInterBufferSize(); if (interBufferData == null) { logger.warn("interBufferData is null"); return; } // single thread이므로 그냥 재활용한다. reusePacket.setData(interBufferData, 0, interBufferSize); try { udpSocket.send(reusePacket); if (isTrace) { logger.trace("Data sent. {}", dto); } } catch (IOException e) { logger.warn("packet send error {}", dto, e); } } private byte[] serialize(TBase<?, ?> dto) { try { return serializer.serialize(dto); } catch (TException e) { if (logger.isWarnEnabled()) { logger.warn("Serialize fail:{} Caused:{}", new Object[] { dto, e.getMessage(), e}); } return null; } } private int beforeSerializeLength() { return serializer.getInterBufferSize(); } }
src/main/java/com/nhn/pinpoint/profiler/sender/UdpDataSender.java
package com.nhn.pinpoint.profiler.sender; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; import java.util.Collection; import com.nhn.pinpoint.profiler.logging.Logger; import com.nhn.pinpoint.profiler.logging.LoggerFactory; import org.apache.thrift.TBase; import org.apache.thrift.TException; import com.nhn.pinpoint.profiler.io.HeaderTBaseSerializer; import com.nhn.pinpoint.profiler.context.Thriftable; /** * @author netspider */ public class UdpDataSender extends AbstractQueueingDataSender implements DataSender { private final Logger logger = LoggerFactory.getLogger(UdpDataSender.class.getName()); private final boolean isTrace = logger.isTraceEnabled(); // 주의 single thread용임 private DatagramPacket reusePacket = new DatagramPacket(new byte[1], 1); private final DatagramSocket udpSocket; // 주의 single thread용임 private HeaderTBaseSerializer serializer = new HeaderTBaseSerializer(); public UdpDataSender(String host, int port) { super(1024, "UdpDataSender"); if (host == null ) { throw new NullPointerException("host must not be null"); } // Socket 생성에 에러가 발생하면 Agent start가 안되게 변경. logger.info("UdpDataSender initialized. host={}, port={}", host, port); this.udpSocket = createSocket(host, port); } private DatagramSocket createSocket(String host, int port) { try { DatagramSocket datagramSocket = new DatagramSocket(); datagramSocket.setSoTimeout(1000 * 5); datagramSocket.setSendBufferSize(1024 * 64); InetSocketAddress serverAddress = new InetSocketAddress(host, port); datagramSocket.connect(serverAddress); return datagramSocket; } catch (SocketException e) { throw new IllegalStateException("DataramSocket create fail. Cause" + e.getMessage(), e); } } public boolean send(TBase<?, ?> data) { return putQueue(data); } public boolean send(Thriftable thriftable) { return putQueue(thriftable); } protected void sendPacketN(Collection<Object> dtoList) { Object[] dataList = dtoList.toArray(); // for (Object data : dataList) { // 이렇게 바꾸지 말것. copy해서 return 하는게 아니라 항상 max치가 나옴. final int size = dtoList.size(); for (int i = 0; i < size; i++) { try { sendPacket(dataList[i]); } catch (Throwable th) { logger.warn("Unexpected Error. Cause:" + th.getMessage(), th); } } } protected void sendPacket(Object dto) { TBase<?, ?> tBase; if (dto instanceof TBase) { tBase = (TBase<?, ?>) dto; } else if (dto instanceof Thriftable) { tBase = ((Thriftable) dto).toThrift(); } else { logger.warn("sendPacket fail. invalid type:{}", dto.getClass()); return; } // single thread이므로 데이터 array를 nocopy해서 보냄. byte[] interBufferData = serialize(tBase); int interBufferSize = serializer.getInterBufferSize(); if (interBufferData == null) { logger.warn("interBufferData is null"); return; } // single thread이므로 그냥 재활용한다. reusePacket.setData(interBufferData, 0, interBufferSize); try { udpSocket.send(reusePacket); if (isTrace) { logger.trace("Data sent. {}", dto); } } catch (IOException e) { logger.warn("packet send error {}", dto, e); } } private byte[] serialize(TBase<?, ?> dto) { try { return serializer.serialize(dto); } catch (TException e) { if (logger.isWarnEnabled()) { logger.warn("Serialize fail:{} Caused:{}", new Object[] { dto, e.getMessage(), e}); } return null; } } private int beforeSerializeLength() { return serializer.getInterBufferSize(); } }
[강운덕] [LUCYSUS-1744] udp socket option 조정. git-svn-id: 0b0b9d2345dd6c69dda6a7bc6c9d6f99a5385c2e@2092 84d0f5b1-2673-498c-a247-62c4ff18d310
src/main/java/com/nhn/pinpoint/profiler/sender/UdpDataSender.java
[강운덕] [LUCYSUS-1744] udp socket option 조정.
<ide><path>rc/main/java/com/nhn/pinpoint/profiler/sender/UdpDataSender.java <ide> DatagramSocket datagramSocket = new DatagramSocket(); <ide> <ide> datagramSocket.setSoTimeout(1000 * 5); <del> datagramSocket.setSendBufferSize(1024 * 64); <add> datagramSocket.setSendBufferSize(1024 * 64 * 16); <ide> <ide> InetSocketAddress serverAddress = new InetSocketAddress(host, port); <ide> datagramSocket.connect(serverAddress);
Java
apache-2.0
7af7a4c6641ad91e609ecac0b16eb9f3a8c9d3cc
0
imazen/folioxml,imazen/folioxml
package folioxml.text; import folioxml.core.InvalidMarkupException; import folioxml.core.TokenUtils; import folioxml.xml.Node; import folioxml.xml.NodeList; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by nathanael on 6/18/15. */ public class TextLinesBuilder { private Pattern tabsAtTheSides = Pattern.compile("(\\A\\s*?\\t+|\\t+\\s*\\Z)"); private Pattern tabsInTheMiddle = Pattern.compile("\\A\\s*[^\\t\\r\\n]+\\t+\\s*[^\\t \\r\\n]"); private Pattern listAlignment = Pattern.compile("\\A\\s*?(•|[0-9iv]+[\\.\\)]?)\\t+[^\\t\\n]*\\Z"); public TextLinesBuilder(){} public List<StringBuilder> generateLines(NodeList nl){ List<StringBuilder> lines = new ArrayList<StringBuilder>(); for(Node n: nl.list()){ line_new(lines); add_lines(n, lines); } return lines; } public TabUsage analyzeTabUsage(List<StringBuilder> lines) throws InvalidMarkupException { TabUsage result = TabUsage.None; for(StringBuilder l:lines){ Matcher m = listAlignment.matcher(l); if (m.find()) return TabUsage.ListAlignment; //Numbered list indentation; m = tabsInTheMiddle.matcher(l); if (m.find()) return TabUsage.Tabulation; //Tabulation is a quick exit, no escalation from there m = tabsAtTheSides.matcher(l); if (m.find()){ result = TabUsage.Indentation; //Escalate to indentation. }else if (l.indexOf("\t") > -1) { throw new InvalidMarkupException("Tab analysis missed a code path for line '" + l.toString() + "'"); } } return result; } public TabUsage analyzeTabUsage(NodeList nl) throws InvalidMarkupException { List<StringBuilder> lines = generateLines(nl); return analyzeTabUsage(lines); } public enum TabUsage{ Indentation, ListAlignment, Tabulation, None } private void add_lines(Node n, List<StringBuilder> lines){ if (n.matches("p|br|table|td|th|note|div|record")) line_new(lines); if (n.isTag() && n.children != null){ for(Node c:n.children.list()){ add_lines(c,lines); } }else if (n.isTextOrEntity()){ String s = n.markup; if (n.isEntity()) s = TokenUtils.entityDecodeString(s); last_line(lines).append(s); } if (n.matches("p|br|table|td|th|note|div|record")) line_new(lines); } private StringBuilder last_line(List<StringBuilder> lines){ if (lines.size() == 0){ lines.add(new StringBuilder()); } return lines.get(lines.size() - 1); } private void line_new(List<StringBuilder> lines){ if (lines.size() == 0 || lines.get(lines.size() - 1).length() > 0){ lines.add(new StringBuilder()); } } }
core/folioxml/src/folioxml/text/TextLinesBuilder.java
package folioxml.text; import folioxml.core.InvalidMarkupException; import folioxml.core.TokenUtils; import folioxml.xml.Node; import folioxml.xml.NodeList; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by nathanael on 6/18/15. */ public class TextLinesBuilder { private Pattern tabsAtTheSides = Pattern.compile("(\\A\\s*?\\t+|\\t+\\s*\\Z)"); private Pattern tabsInTheMiddle = Pattern.compile("\\A\\s*[^\\t\\r\\n]+\\t+[^\\t \\r\\n]"); private Pattern listAlignment = Pattern.compile("\\A\\s*?(•|[0-9iv]+[\\.\\)]?)\\t+[^\\t\\n]*\\Z"); public TextLinesBuilder(){} public List<StringBuilder> generateLines(NodeList nl){ List<StringBuilder> lines = new ArrayList<StringBuilder>(); for(Node n: nl.list()){ line_new(lines); add_lines(n, lines); } return lines; } public TabUsage analyzeTabUsage(List<StringBuilder> lines) throws InvalidMarkupException { TabUsage result = TabUsage.None; for(StringBuilder l:lines){ Matcher m = listAlignment.matcher(l); if (m.find()) return TabUsage.ListAlignment; //Numbered list indentation; m = tabsInTheMiddle.matcher(l); if (m.find()) return TabUsage.Tabulation; //Tabulation is a quick exit, no escalation from there m = tabsAtTheSides.matcher(l); if (m.find()){ result = TabUsage.Indentation; //Escalate to indentation. }else if (l.indexOf("\t") > -1) { throw new InvalidMarkupException("Tab analysis missed a code path."); } } return result; } public TabUsage analyzeTabUsage(NodeList nl) throws InvalidMarkupException { List<StringBuilder> lines = generateLines(nl); return analyzeTabUsage(lines); } public enum TabUsage{ Indentation, ListAlignment, Tabulation, None } private void add_lines(Node n, List<StringBuilder> lines){ if (n.matches("p|br|table|td|th|note|div|record")) line_new(lines); if (n.isTag() && n.children != null){ for(Node c:n.children.list()){ add_lines(c,lines); } }else if (n.isTextOrEntity()){ String s = n.markup; if (n.isEntity()) s = TokenUtils.entityDecodeString(s); last_line(lines).append(s); } if (n.matches("p|br|table|td|th|note|div|record")) line_new(lines); } private StringBuilder last_line(List<StringBuilder> lines){ if (lines.size() == 0){ lines.add(new StringBuilder()); } return lines.get(lines.size() - 1); } private void line_new(List<StringBuilder> lines){ if (lines.size() == 0 || lines.get(lines.size() - 1).length() > 0){ lines.add(new StringBuilder()); } } }
TextLinesBuilder.analyzeTabUsage no longer fails on tabs followed by whitespace
core/folioxml/src/folioxml/text/TextLinesBuilder.java
TextLinesBuilder.analyzeTabUsage no longer fails on tabs followed by whitespace
<ide><path>ore/folioxml/src/folioxml/text/TextLinesBuilder.java <ide> <ide> private Pattern tabsAtTheSides = Pattern.compile("(\\A\\s*?\\t+|\\t+\\s*\\Z)"); <ide> <del> private Pattern tabsInTheMiddle = Pattern.compile("\\A\\s*[^\\t\\r\\n]+\\t+[^\\t \\r\\n]"); <add> private Pattern tabsInTheMiddle = Pattern.compile("\\A\\s*[^\\t\\r\\n]+\\t+\\s*[^\\t \\r\\n]"); <ide> <ide> private Pattern listAlignment = Pattern.compile("\\A\\s*?(•|[0-9iv]+[\\.\\)]?)\\t+[^\\t\\n]*\\Z"); <ide> <ide> if (m.find()){ <ide> result = TabUsage.Indentation; //Escalate to indentation. <ide> }else if (l.indexOf("\t") > -1) { <del> throw new InvalidMarkupException("Tab analysis missed a code path."); <add> throw new InvalidMarkupException("Tab analysis missed a code path for line '" + l.toString() + "'"); <ide> <ide> } <ide> }
JavaScript
mit
b0d303159fa3b98fac862e698d1ca5e597c483bd
0
fboes/blogophon,fboes/blogophon,fboes/blogophon
'use strict'; var inquirer = require('inquirer'); var glob = require('glob'); var fs = require('fs-extra-promise'); var path = require('path'); var chalk = require('chalk'); var shell = require('shelljs'); var SuperString = require('./helpers/super-string'); var config = require('./config'); var Mustache = require('./helpers/blogophon-mustache'); var MustacheQuoters= require('./helpers/blogophon-mustache-quoters'); var setup = require('./setup')(); var Generator = require('./generator'); var https = require('https'); var blogophonDate = require('./models/blogophon-date'); /** * Represents the Inquirer dialog with which to edit articles. * @constructor * @return {Object} [description] */ var BlogophonConsole = function() { var external = {}; var internal = {}; var files = []; var choicesStr = [ 'Create new article', 'Edit existing article', 'Rename article', 'Delete article', 'Generate & publish articles', config.notInitialized ? 'Setup' : 'Change settings', 'Exit' ]; Mustache.getTemplates(); /** * Get all Markdown files as a simple array. * Array values can be simple strings, or objects containing * a name (to display in list), * a value (to save in the answers hash) and * a short (to display after selection) properties. * The choices array can also contain a Separator. * @return {Array} [description] */ internal.makeChoices = function() { var choices = []; if (!config.notInitialized) { internal.makeFiles(); choices.push(choicesStr[0]); if (files.length > 0) { choices.push(choicesStr[1], choicesStr[2], choicesStr[3], choicesStr[4]); } choices.push(new inquirer.Separator()); } choices.push(choicesStr[5], new inquirer.Separator(), choicesStr[6]); return choices; }; /** * Get listing of all Markdown files which may be edited * @return {Array} [description] */ internal.makeFiles = function() { if (config.notInitialized) { files = []; } else { files = glob.sync(config.directories.data + "/**/*.{md,md~}").map(function(v) { var filename = v.replace(/^.+\/(.+?)$/, '$1'); var fileStat = fs.lstatSync(v); return { name: fileStat.mtime.toLocaleString(config.locale.language || 'en') + "\t" + filename + "\t" +Math.ceil(fileStat.size/1000)+' kB', value: filename, short: filename }; }); if (files.length > 1) { files.push(new inquirer.Separator()); } } return files; }; /** * Returns the title to be used for generating a filename. * @param {String} title [description] * @param {Object} config [description] * @param {String} date [description] * @return {String} [description] */ internal.titleForFilename = function(title, config, date) { date = date || new Date(); if (config.postFileMode) { return config.postFileMode .replace(/Title/, title) .replace(/Date/, blogophonDate(date).format('yyyy-mm-dd')) ; } return title; }; /** * Convert title to Markdown filename * @param {String} title [description] * @return {String} [description] */ internal.filenameFromTitle = function(title) { return path.join(config.directories.data, internal.shortfilenameFromTitle(title)); }; /** * Remove stop words from filename and limit it to a sane length. * @param {String} title [description] * @return {String} [description] */ internal.shortfilenameFromTitle = function(title) { return SuperString(title.trim().toLowerCase()) .asciify() .replace(/(^|\-)([a-z]|de[rnms]|die(s|se|ser|ses|sen|sem)?|d[aoe]s|[msd]?ein(e|es|er|em|en)?|th(e|is|at|ese|ose)|my|[ea]l|l[ao]s?|[ia][nm]|o[nf]|ist?|[ua]nd)\-/g, '$1') .replace(/(^[\-]+|[\-]+$)/g, '') .replace(/([\-])[\-]+/g, '$1') .replace(/\-(md~?)$/, '.$1') .replace(/^(.{64}[^-]*).*?(\.md~?)?$/, '$1$2') ; }; /** * Convert Markdown filename into corresponding directory name (e.g. for images) * @param {String} filename [description] * @return {String} [description] */ internal.dirnameFromFilename = function(filename) { return filename.replace(/\.md~?$/, ''); }; /** * Get coordinates for address * @param {String} address [description] * @param {String} language [description] * @param {Function} callback [description] * @return {Object} with `latitude, longitude` */ internal.convertAddress = function(address, language, callback) { https.get({ host: 'nominatim.openstreetmap.org', path: '/search?q='+encodeURIComponent(address)+'&format=json&accept-language='+encodeURIComponent(language || 'en') }, function(response) { var body = ''; response.on('data', function(d) { body += d; }); response.on('end', function() { var parsed = JSON.parse(body); callback(null, { latitude: parsed[0] ? parsed[0].lat : null, longitude: parsed[0] ? parsed[0].lon : null }); }); }); }; /** * Display the setup dialog. * @return {[type]} [description] */ external.setupDialog = function() { var themesAvailable= fs.readdirSync(config.directories.theme).filter(function(file) { return fs.statSync(path.join(config.directories.theme, file)).isDirectory(); }); var questions = [ { type: 'input', name: 'name', message: 'The name of your site', default: config.name, validate: function(v) { return v ? true : 'Please supply at least a short name for your site.'; } }, { type: 'list', name: 'theme', message: 'Choose theme', default: config.theme, choices: themesAvailable, when: function() { return (themesAvailable.length > 1); } }, { type: 'input', name: 'baseUrl', message: 'Domain of your site, starting with `http`', default: config.baseUrl, validate: function(v) { return v.match(/^http(s)?:\/\/\S+[^/]$/) ? true : 'Please supply a valid url, starting with `http://`, but without trailing `/`.'; }, filter: function(v) { return v.replace(/\/$/, ''); } }, { type: 'input', name: 'basePath', message: 'Base URL path, usually just `/`', default: config.basePath, validate: function(v) { return v.match(/^[a-zA-Z0-9\.\/_-]*\/$/) ? true : 'Please supply a valid path with a trailing `/`.'; }, filter: function(v) { return v.replace(/^([^\/])/, '/$1').replace(/([^\/])$/, '$1/'); } }, { type: 'input', name: 'description', message: 'A short description of your blog (optional)', default: config.description }, { type: 'input', name: 'locale.language', message: 'Standard language of your blog, like `en` for English', default: config.locale.language || config.language, validate: function(v) { return v.match(/^[a-zA-Z]+([\-_][a-zA-Z]+)?$/) ? true : 'Please supply a valid language code like `en`, `es`, `fr`, `de` or `pt-br`.'; }, filter: function(v) { return v.toLowerCase().replace(/_/, '-'); } }, { type: 'list', name: 'postPathMode', message: 'Choose URL path pattern for your posts:', default: config.postPathMode, choices: [ 'Static path', 'Year', 'Year/Month', 'Year/Month/Day' ] }, { type: 'list', name: 'postFileMode', message: 'Choose URL file pattern for your posts:', default: config.postFileMode || 'Title', choices: [ 'Title', 'Title-Date', 'Date-Title', 'Date' ] }, { type: 'input', name: 'itemsPerPage', message: 'How many articles per page?', default: config.itemsPerPage, validate: function(v) { return Number(v)> 0 ? true : 'Please supply a positive number.'; }, filter: function(v) { return Number(v); } }, { type: 'input', name: 'defaultAuthor.name', message: 'Default name of author', default: config.defaultAuthor.name, validate: function(v) { return v ? true : 'Please supply at least a short name for your site.'; } }, { type: 'input', name: 'defaultAuthor.email', message: 'Default email address of author', default: config.defaultAuthor.email, validate: function(v) { return (v.match(/^\S+@\S+$/)) ? true : 'Please supply a valid email address.'; } }, { type: 'input', name: 'twitterAccount', message: 'Twitter account name (optional)', default: config.twitterAccount, validate: function(v) { return (!v || v.match(/^[a-zA-z0-9_-]+$/)) ? true : 'Please supply a Twitter account name or leave field empty.'; } }, { type: 'input', name: 'deployCmd', message: 'CLI command to copy files to your live server (optional)', default: config.deployCmd }, { type: 'checkbox', name: 'useSpecialFeature', message: 'Do you want to use the following special features?', default: config.useSpecialFeature, choices: [ "Multiple authors", "RSS", "ATOM", "JSON for Slack", "JSON-RSS", "Apple News", "Facebook Instant Articles", "Accelerated Mobile Pages", "Microsoft tiles", "ICS-Calendar", "GeoJSON", "KML", "AJAX" ] } ]; inquirer.prompt(questions).then( function(answers) { answers.theme = config.theme ? config.theme : themesAvailable[0]; answers.locale.direction = answers.locale.direction || config.locale.direction || (answers.language.match(/^(ar|zh|fa|he)/) ? 'rtl' : 'ltr'); setup .buildBasicFiles(config, answers) .then(function() { console.log("Settings changed, please restart the Blogophon."); // TODO: reload config and return to main menu // external.init(); }) ; }, function(err) { console.error(err); process.exit(1); } ); }; /** * This is the Inquirer dialog for creating a new articles. Will call external.init() on finish. * @return {[type]} [description] */ external.createArticleDialog = function() { var defaults = { classes: 'Normal article', link: '', location: '', images: false, keywords: '', date: blogophonDate(new Date()).iso, author: config.defaultAuthor.name +' <'+config.defaultAuthor.email + '>', draft: false, edit: true, lead: '', mainText: 'Lorem ipsum…' }; var questions = [ { type: 'input', name: 'title', message: 'Title', validate: function(v) { if (v.trim().length <= 2) { return 'This title is way too short.'; } var filename = internal.filenameFromTitle(v); if (fs.existsSync(filename)) { return ("File " + filename + ' already exists'); } return true; }, filter: function(v) { return v.trim(); } }, { type: 'list', name: 'classes', message: 'Type of article', choices: ['Normal article', 'Images', 'Video', 'Link', 'Quote', 'Location'], default: defaults.classes, filter: function(v) { return (v === 'Normal article') ? null : v; } }, { type: 'input', name: 'link', message: 'URL of page you want to link to', default: defaults.link, when: function(answers) { return answers.classes === 'Link'; }, validate: function(v) { return v.match(/^http(s)?:\/\/\S+$/) ? true : 'Please supply a valid url, starting with `http://` or `https://`.'; } }, { type: 'input', name: 'location', message: 'Place name or address', default: defaults.location, when: function(answers) { return answers.classes === 'Location'; } }, { type: 'confirm', name: 'images', message: 'Do you want to use images?', default: defaults.images, when: function(answers) { return answers.classes !== 'Images'; } }, { type: 'input', name: 'keywords', message: 'Keywords, comma-separated', default: defaults.keywords, filter: function(v) { return v.trim(); } }, { type: 'input', name: 'author', message: 'Author <E-Mail-Address>', default: defaults.author, when: function() { return config.specialFeatures.multipleauthors; } }, { type: 'input', name: 'date', message: 'Publishing date', default: defaults.date, filter: function(v) { return blogophonDate(v).iso; }, validate: function(v) { return v.match(/^\d[\d:\-\+T]+\d$/) ? true : 'Please supply a valid date like ' + defaults.date + '.'; } }, { type: 'confirm', name: 'draft', message: 'Is this a draft?', default: defaults.draft, when: function(answers) { return answers.date !== defaults.date; } }, { type: 'confirm', name: 'edit', message: 'Open this in editor right away?', default: defaults.edit }, { type: 'input', name: 'lead', message: 'Lead / teaser text', default: defaults.lead, when: function(answers) { return !answers.edit && answers.classes !== 'Link'; } }, { type: 'input', name: 'mainText', message: 'Main text', default: defaults.mainText, when: function(answers) { return !answers.edit; } } ]; inquirer.prompt(questions).then( function(answers) { var markdownFilename = internal.filenameFromTitle(internal.titleForFilename(answers.title, config, answers.date)) + (answers.draft ? '.md~' : '.md') ; var filename = internal.dirnameFromFilename(markdownFilename); // TODO: There is a class for that var templateData = answers; switch (templateData.classes) { case 'Images': templateData.lead = templateData.lead || "![](image.jpg#default)\n\nLorem ipsum…"; break; case 'Video': templateData.lead = templateData.lead || "https://www.youtube.com/watch?v=6A5EpqqDOdk\n\nLorem ipsum…"; break; case 'Link': templateData.mainText = templateData.mainText || "[Lorem ipsum…](" + answers.link + ")"; break; case 'Quote': templateData.mainText = templateData.mainText || "> Lorem ipsum…\n> <cite>Cicero</cite>"; break; case 'Location': templateData.latitude = 0.00001; templateData.longitude = 0.00001; break; } if (templateData.location) { console.log('Geocoding...'); internal.convertAddress(templateData.location, config.locale.language, function(err, geo) { templateData.latitude = geo.latitude || templateData.latitude; templateData.longitude = geo.longitude || templateData.longitude; internal.makePost(markdownFilename, filename, templateData); }); } else { internal.makePost(markdownFilename, filename, templateData); } }, function(err) { console.error(err); } ); }; internal.makePost = function(markdownFilename, filename, templateData) { templateData.ymlQuote = MustacheQuoters.ymlQuote; fs.writeFile(markdownFilename, Mustache.render(Mustache.templates.postMd, templateData), function(err) { if (err) { console.error(chalk.red( markdownFilename + ' could not be written' )); } else { console.log( markdownFilename + ' created'); var cmd = config.isWin ? 'START ' + markdownFilename : 'open ' + markdownFilename + ' || vi '+ markdownFilename; console.log(chalk.grey(cmd)); if (templateData.edit) { shell.exec(cmd); } if (templateData.classes === 'Images' || templateData.images) { shell.mkdir('-p', filename); } external.init(); } }); }; /** * This is the Inquirer dialog for editing an existing article. Will call external.init() on finish. * @return {void} [description] */ external.editArticleDialog = function() { var questions = [ { type: 'list', name: 'file', message: 'Select file to edit ('+files.length+')', choices: files } ]; inquirer.prompt(questions).then( function(answers) { var markdownFilename = path.join(config.directories.data, answers.file); var cmd = config.isWin ? 'START ' + markdownFilename : 'open ' + markdownFilename + ' || vi '+ markdownFilename; console.log(chalk.grey(cmd)); shell.exec(cmd); external.init(); }, function(err) { console.error(err); } ); }; /** * This is the Inquirer dialog for renaming an existing article. Will call external.init() on finish. * @return {void} [description] */ external.renameArticleDialog = function() { var questions = [ { type: 'list', name: 'file', message: 'Select filen to rename ('+files.length+')', choices: files }, { type: 'input', name: 'fileNew', message: 'Please enter a new filename or leave empty to cancel', filter: function(v) { return internal.shortfilenameFromTitle(v); }, validate: function(v) { return v.match(/\.md\~?$/) ? true : 'Please supply a file ending like `.md` or `.md~`.'; } } ]; inquirer.prompt(questions).then( function(answers) { if (answers.fileNew) { var processed = 0, maxProcessed = 2; var checkProcessed = function(err) { if (err) { console.error(err); } if (++processed === maxProcessed) { console.log(answers.file + " files moved to "+answers.fileNew+", you may want to generate & publish all index pages"); external.init(); } }; fs.move( config.directories.data + '/' + answers.file, config.directories.data + '/' + answers.fileNew, checkProcessed ); fs.move( config.directories.data + '/' + internal.dirnameFromFilename(answers.file), config.directories.data + '/' + internal.dirnameFromFilename(answers.fileNew), checkProcessed ); if (! answers.file.match(/~$/)) { maxProcessed ++; fs.move( config.directories.data.replace(/^user/, 'htdocs') + '/' + internal.dirnameFromFilename(answers.file), config.directories.data.replace(/^user/, 'htdocs') + '/' + internal.dirnameFromFilename(answers.fileNew), checkProcessed ); } } else { external.init(); } }, function(err) { console.error(err); } ); }; /** * This is the Inquirer dialog for deleting an existing article. Will call external.init() on finish. * @return {void} [description] */ external.deleteArticleDialog = function() { var questions = [ { type: 'list', name: 'file', message: 'Select file to delete ('+files.length+')', choices: files }, { type: 'confirm', name: 'sure', message: 'Are you sure?', default: true } ]; inquirer.prompt(questions).then( function(answers) { if (answers.sure) { var processed = 0, maxProcessed = 3; var checkProcessed = function(err) { if (err) { console.error(err); } if (++processed === maxProcessed) { console.log(answers.file + " files deleted, you may want to generate & publish all index pages"); external.init(); } }; fs.remove(path.join(config.directories.data, answers.file), checkProcessed); fs.remove(path.join(config.directories.data, internal.dirnameFromFilename(answers.file)), checkProcessed); fs.remove(path.join(config.directories.data.replace(/^user/, 'htdocs'), internal.dirnameFromFilename(answers.file)), checkProcessed); } else { external.init(); } }, function(err) { console.error(err); } ); }; /** * This is the Inquirer dialog for generating all HTML files. Will call external.init() on finish. * @return {void} [description] */ external.generateDialog = function() { var questions = [ { type: 'confirm', name: 'noforce', message: 'Only generate new files?', default: true }, { type: 'confirm', name: 'deploy', message: 'Do you want to publish all files?', default: true, when: function() { // answers return config.deployCmd; } } ]; var generator = Generator(config); inquirer .prompt(questions) .then( function(answers) { generator .getArticles() .then(function() { generator .buildAll(!answers.noforce) .then(function() { if(answers.deploy) { generator.deploy(); } external.init(); }) .catch( function(err) { console.error(err); } ) ; }) .catch( function(err) { console.error(err); } ) ; }) .catch( function(err) { console.error(err); } ) ; }; /** * This is the Inquirer dialog for showing the main menu. This will be called in a loop until `Exit` is selected. * @return {void} [description] */ external.init = function() { if (config.notInitialized) { fs.ensureDirSync(config.directories.data); fs.ensureDirSync(config.directories.htdocs); fs.copySync(path.join(__dirname, '..', 'htdocs', 'themes'), config.directories.theme); external.setupDialog(); } else { var questions = [ { type: 'list', name: 'action', message: 'Select action', choices: internal.makeChoices() } ]; inquirer.prompt(questions).then( function(answers) { switch (answers.action) { case choicesStr[0]: external.createArticleDialog(); break; case choicesStr[1]: external.editArticleDialog(); break; case choicesStr[2]: external.renameArticleDialog(); break; case choicesStr[3]: external.deleteArticleDialog(); break; case choicesStr[4]: external.generateDialog(); break; case choicesStr[5]: external.setupDialog(); break; case choicesStr[choicesStr.length -1]: console.log("Good bye"); break; default: external.init(); break; } }, function(err) { console.error(err); } ); } }; return external; }; module.exports = BlogophonConsole;
src/blogophon-console.js
'use strict'; var inquirer = require('inquirer'); var glob = require('glob'); var fs = require('fs-extra-promise'); var path = require('path'); var chalk = require('chalk'); var shell = require('shelljs'); var SuperString = require('./helpers/super-string'); var config = require('./config'); var Mustache = require('./helpers/blogophon-mustache'); var MustacheQuoters= require('./helpers/blogophon-mustache-quoters'); var setup = require('./setup')(); var Generator = require('./generator'); var https = require('https'); var blogophonDate = require('./models/blogophon-date'); /** * Represents the Inquirer dialog with which to edit articles. * @constructor * @return {Object} [description] */ var BlogophonConsole = function() { var external = {}; var internal = {}; var files = []; var choicesStr = [ 'Create new article', 'Edit existing article', 'Rename article', 'Delete article', 'Generate & publish articles', config.notInitialized ? 'Setup' : 'Change settings', 'Exit' ]; Mustache.getTemplates(); /** * Get all Markdown files as a simple array. * Array values can be simple strings, or objects containing * a name (to display in list), * a value (to save in the answers hash) and * a short (to display after selection) properties. * The choices array can also contain a Separator. * @return {Array} [description] */ internal.makeChoices = function() { var choices = []; if (!config.notInitialized) { internal.makeFiles(); choices.push(choicesStr[0]); if (files.length > 0) { choices.push(choicesStr[1], choicesStr[2], choicesStr[3], choicesStr[4]); } choices.push(new inquirer.Separator()); } choices.push(choicesStr[5], new inquirer.Separator(), choicesStr[6]); return choices; }; /** * Get listing of all Markdown files which may be edited * @return {Array} [description] */ internal.makeFiles = function() { if (config.notInitialized) { files = []; } else { files = glob.sync(config.directories.data + "/**/*.{md,md~}").map(function(v) { var filename = v.replace(/^.+\/(.+?)$/, '$1'); var fileStat = fs.lstatSync(v); return { name: fileStat.mtime.toLocaleString(config.locale.language || 'en') + "\t" + filename + "\t" +Math.ceil(fileStat.size/1000)+' kB', value: filename, short: filename }; }); if (files.length > 1) { files.push(new inquirer.Separator()); } } return files; }; /** * Returns the title to be used for generating a filename. * @param {String} title [description] * @param {Object} config [description] * @param {String} date [description] * @return {String} [description] */ internal.titleForFilename = function(title, config, date) { date = date || new Date(); if (config.postFileMode) { return config.postFileMode .replace(/Title/, title) .replace(/Date/, blogophonDate(date).format('yyyy-mm-dd')) ; } return title; }; /** * Convert title to Markdown filename * @param {String} title [description] * @return {String} [description] */ internal.filenameFromTitle = function(title) { return path.join(config.directories.data, internal.shortfilenameFromTitle(title)); }; /** * Remove stop words from filename and limit it to a sane length. * @param {String} title [description] * @return {String} [description] */ internal.shortfilenameFromTitle = function(title) { return SuperString(title.trim().toLowerCase()) .asciify() .replace(/(^|\-)([a-z]|de[rnms]|die(s|se|ser|ses|sen|sem)?|d[aoe]s|[msd]?ein(e|es|er|em|en)?|th(e|is|at|ese|ose)|my|[ea]l|l[ao]s?|[ia][nm]|o[nf]|ist?|[ua]nd)\-/g, '$1') .replace(/(^[\-]+|[\-]+$)/g, '') .replace(/([\-])[\-]+/g, '$1') .replace(/\-(md~?)$/, '.$1') .replace(/^(.{64}[^-]*).*?(\.md~?)?$/, '$1$2') ; }; /** * Convert Markdown filename into corresponding directory name (e.g. for images) * @param {String} filename [description] * @return {String} [description] */ internal.dirnameFromFilename = function(filename) { return filename.replace(/\.md~?$/, ''); }; /** * Get coordinates for address * @param {String} address [description] * @param {String} language [description] * @param {Function} callback [description] * @return {Object} with `latitude, longitude` */ internal.convertAddress = function(address, language, callback) { https.get({ host: 'nominatim.openstreetmap.org', path: '/search?q='+encodeURIComponent(address)+'&format=json&accept-language='+encodeURIComponent(language || 'en') }, function(response) { var body = ''; response.on('data', function(d) { body += d; }); response.on('end', function() { var parsed = JSON.parse(body); callback(null, { latitude: parsed[0] ? parsed[0].lat : null, longitude: parsed[0] ? parsed[0].lon : null }); }); }); }; /** * Display the setup dialog. * @return {[type]} [description] */ external.setupDialog = function() { var themesAvailable= fs.readdirSync(config.directories.theme).filter(function(file) { return fs.statSync(path.join(config.directories.theme, file)).isDirectory(); }); var questions = [ { type: 'input', name: 'name', message: 'The name of your site', default: config.name, validate: function(v) { return v ? true : 'Please supply at least a short name for your site.'; } }, { type: 'list', name: 'theme', message: 'Choose theme', default: config.theme, choices: themesAvailable, when: function() { return (themesAvailable.length > 1); } }, { type: 'input', name: 'baseUrl', message: 'Domain of your site, starting with `http`', default: config.baseUrl, validate: function(v) { return v.match(/^http(s)?:\/\/\S+[^/]$/) ? true : 'Please supply a valid url, starting with `http://`, but without trailing `/`.'; }, filter: function(v) { return v.replace(/\/$/, ''); } }, { type: 'input', name: 'basePath', message: 'Base URL path, usually just `/`', default: config.basePath, validate: function(v) { return v.match(/^[a-zA-Z0-9\.\/_-]*\/$/) ? true : 'Please supply a valid path with a trailing `/`.'; }, filter: function(v) { return v.replace(/^([^\/])/, '/$1').replace(/([^\/])$/, '$1/'); } }, { type: 'input', name: 'description', message: 'A short description of your blog (optional)', default: config.description }, { type: 'input', name: 'locale.language', message: 'Standard language of your blog, like `en` for English', default: config.locale.language || config.language, validate: function(v) { return v.match(/^[a-zA-Z]+([\-_][a-zA-Z]+)?$/) ? true : 'Please supply a valid language code like `en`, `es`, `fr`, `de` or `pt-br`.'; }, filter: function(v) { return v.toLowerCase().replace(/_/, '-'); } }, { type: 'list', name: 'postPathMode', message: 'Choose URL path pattern for your posts:', default: config.postPathMode, choices: [ 'Static path', 'Year', 'Year/Month', 'Year/Month/Day' ] }, { type: 'list', name: 'postFileMode', message: 'Choose URL file pattern for your posts:', default: config.postFileMode || 'Title', choices: [ 'Title', 'Title-Date', 'Date-Title', 'Date' ] }, { type: 'input', name: 'itemsPerPage', message: 'How many articles per page?', default: config.itemsPerPage, validate: function(v) { return Number(v)> 0 ? true : 'Please supply a positive number.'; }, filter: function(v) { return Number(v); } }, { type: 'input', name: 'defaultAuthor.name', message: 'Default name of author', default: config.defaultAuthor.name, validate: function(v) { return v ? true : 'Please supply at least a short name for your site.'; } }, { type: 'input', name: 'defaultAuthor.email', message: 'Default email address of author', default: config.defaultAuthor.email, validate: function(v) { return (v.match(/^\S+@\S+$/)) ? true : 'Please supply a valid email address.'; } }, { type: 'input', name: 'twitterAccount', message: 'Twitter account name (optional)', default: config.twitterAccount, validate: function(v) { return (!v || v.match(/^[a-zA-z0-9_-]+$/)) ? true : 'Please supply a Twitter account name or leave field empty.'; } }, { type: 'input', name: 'deployCmd', message: 'CLI command to copy files to your live server (optional)', default: config.deployCmd }, { type: 'checkbox', name: 'useSpecialFeature', message: 'Do you want to use the following special features?', default: config.useSpecialFeature, choices: [ "Multiple authors", "RSS", "ATOM", "JSON for Slack", "JSON-RSS", "Apple News", "Facebook Instant Articles", "Accelerated Mobile Pages", "Microsoft tiles", "ICS-Calendar", "GeoJSON", "KML", "AJAX" ] } ]; inquirer.prompt(questions).then( function(answers) { answers.theme = config.theme ? config.theme : themesAvailable[0]; answers.locale.direction = answers.locale.direction || config.locale.direction || (answers.language.match(/^(ar|zh|fa|he)/) ? 'rtl' : 'ltr'); setup .buildBasicFiles(config, answers) .then(function() { console.log("Settings changed, please restart the Blogophon."); // TODO: reload config and return to main menu // external.init(); }) ; }, function(err) { console.error(err); process.exit(1); } ); }; /** * This is the Inquirer dialog for creating a new articles. Will call external.init() on finish. * @return {[type]} [description] */ external.createArticleDialog = function() { var defaults = { classes: 'Normal article', link: '', location: '', images: false, keywords: '', date: blogophonDate(new Date()).iso, author: config.defaultAuthor.name +' <'+config.defaultAuthor.email + '>', draft: false, edit: true, lead: '', mainText: 'Lorem ipsum…' }; var questions = [ { type: 'input', name: 'title', message: 'Title', validate: function(v) { if (v.trim().length <= 2) { return 'This title is way too short.'; } var filename = internal.filenameFromTitle(v); if (fs.existsSync(filename)) { return ("File " + filename + ' already exists'); } return true; }, filter: function(v) { return v.trim(); } }, { type: 'list', name: 'classes', message: 'Type of article', choices: ['Normal article', 'Images', 'Video', 'Link', 'Quote', 'Location'], default: defaults.classes, filter: function(v) { return (v === 'Normal article') ? null : v; } }, { type: 'input', name: 'link', message: 'URL of page you want to link to', default: defaults.link, when: function(answers) { return answers.classes === 'Link'; }, validate: function(v) { return v.match(/^http(s)?:\/\/\S+$/) ? true : 'Please supply a valid url, starting with `http://` or `https://`.'; } }, { type: 'input', name: 'location', message: 'Place name or address', default: defaults.location, when: function(answers) { return answers.classes === 'Location'; } }, { type: 'confirm', name: 'images', message: 'Do you want to use images?', default: defaults.images, when: function(answers) { return answers.classes !== 'Images'; } }, { type: 'input', name: 'keywords', message: 'Keywords, comma-separated', default: defaults.keywords, filter: function(v) { return v.trim(); } }, { type: 'input', name: 'author', message: 'Author <E-Mail-Address>', default: defaults.author, when: function() { return config.specialFeatures.multipleauthors; } }, { type: 'input', name: 'date', message: 'Publishing date', default: defaults.date, filter: function(v) { return blogophonDate(v).iso; }, validate: function(v) { return v.match(/^\d[\d:\-\+T]+\d$/) ? true : 'Please supply a valid date like ' + defaults.date + '.'; } }, { type: 'confirm', name: 'draft', message: 'Is this a draft?', default: defaults.draft, when: function(answers) { return answers.date !== defaults.date; } }, { type: 'confirm', name: 'edit', message: 'Open this in editor right away?', default: defaults.edit }, { type: 'input', name: 'lead', message: 'Lead / teaser text', default: defaults.lead, when: function(answers) { return !answers.edit && answers.classes !== 'Link'; } }, { type: 'input', name: 'mainText', message: 'Main text', default: defaults.mainText, when: function(answers) { return !answers.edit; } } ]; inquirer.prompt(questions).then( function(answers) { var markdownFilename = internal.filenameFromTitle(internal.titleForFilename(answers.title, config, answers.date)) + (answers.draft ? '.md~' : '.md') ; var filename = internal.dirnameFromFilename(markdownFilename); // TODO: There is a class for that var templateData = answers; switch (templateData.classes) { case 'Images': templateData.lead = templateData.lead || "![](image.jpg#default)\n\nLorem ipsum…"; break; case 'Video': templateData.lead = templateData.lead || "https://www.youtube.com/watch?v=6A5EpqqDOdk\n\nLorem ipsum…"; break; case 'Link': templateData.mainText = templateData.mainText || "[Lorem ipsum…](" + answers.link + ")"; break; case 'Quote': templateData.mainText = templateData.mainText || "> Lorem ipsum…\n> <cite>Cicero</cite>"; break; case 'Location': templateData.latitude = 0.00001; templateData.longitude = 0.00001; break; } if (templateData.location) { console.log('Geocoding...'); internal.convertAddress(templateData.location, config.locale.language, function(err, geo) { templateData.latitude = geo.latitude || templateData.latitude; templateData.longitude = geo.longitude || templateData.longitude; internal.makePost(markdownFilename, filename, templateData); }); } else { internal.makePost(markdownFilename, filename, templateData); } }, function(err) { console.error(err); } ); }; internal.makePost = function(markdownFilename, filename, templateData) { templateData.ymlQuote = MustacheQuoters.ymlQuote; console.log(templateData); fs.writeFile(markdownFilename, Mustache.render(Mustache.templates.postMd, templateData), function(err) { if (err) { console.error(chalk.red( markdownFilename + ' could not be written' )); } else { console.log( markdownFilename + ' created'); var cmd = config.isWin ? 'START ' + markdownFilename : 'open ' + markdownFilename + ' || vi '+ markdownFilename; console.log(chalk.grey(cmd)); if (templateData.edit) { shell.exec(cmd); } if (templateData.classes === 'Images' || templateData.images) { shell.mkdir('-p', filename); } external.init(); } }); }; /** * This is the Inquirer dialog for editing an existing article. Will call external.init() on finish. * @return {void} [description] */ external.editArticleDialog = function() { var questions = [ { type: 'list', name: 'file', message: 'Select file to edit ('+files.length+')', choices: files } ]; inquirer.prompt(questions).then( function(answers) { var markdownFilename = path.join(config.directories.data, answers.file); var cmd = config.isWin ? 'START ' + markdownFilename : 'open ' + markdownFilename + ' || vi '+ markdownFilename; console.log(chalk.grey(cmd)); shell.exec(cmd); external.init(); }, function(err) { console.error(err); } ); }; /** * This is the Inquirer dialog for renaming an existing article. Will call external.init() on finish. * @return {void} [description] */ external.renameArticleDialog = function() { var questions = [ { type: 'list', name: 'file', message: 'Select filen to rename ('+files.length+')', choices: files }, { type: 'input', name: 'fileNew', message: 'Please enter a new filename or leave empty to cancel', filter: function(v) { return internal.shortfilenameFromTitle(v); }, validate: function(v) { return v.match(/\.md\~?$/) ? true : 'Please supply a file ending like `.md` or `.md~`.'; } } ]; inquirer.prompt(questions).then( function(answers) { if (answers.fileNew) { var processed = 0, maxProcessed = 2; var checkProcessed = function(err) { if (err) { console.error(err); } if (++processed === maxProcessed) { console.log(answers.file + " files moved to "+answers.fileNew+", you may want to generate & publish all index pages"); external.init(); } }; fs.move( config.directories.data + '/' + answers.file, config.directories.data + '/' + answers.fileNew, checkProcessed ); fs.move( config.directories.data + '/' + internal.dirnameFromFilename(answers.file), config.directories.data + '/' + internal.dirnameFromFilename(answers.fileNew), checkProcessed ); if (! answers.file.match(/~$/)) { maxProcessed ++; fs.move( config.directories.data.replace(/^user/, 'htdocs') + '/' + internal.dirnameFromFilename(answers.file), config.directories.data.replace(/^user/, 'htdocs') + '/' + internal.dirnameFromFilename(answers.fileNew), checkProcessed ); } } else { external.init(); } }, function(err) { console.error(err); } ); }; /** * This is the Inquirer dialog for deleting an existing article. Will call external.init() on finish. * @return {void} [description] */ external.deleteArticleDialog = function() { var questions = [ { type: 'list', name: 'file', message: 'Select file to delete ('+files.length+')', choices: files }, { type: 'confirm', name: 'sure', message: 'Are you sure?', default: true } ]; inquirer.prompt(questions).then( function(answers) { if (answers.sure) { var processed = 0, maxProcessed = 3; var checkProcessed = function(err) { if (err) { console.error(err); } if (++processed === maxProcessed) { console.log(answers.file + " files deleted, you may want to generate & publish all index pages"); external.init(); } }; fs.remove(path.join(config.directories.data, answers.file), checkProcessed); fs.remove(path.join(config.directories.data, internal.dirnameFromFilename(answers.file)), checkProcessed); fs.remove(path.join(config.directories.data.replace(/^user/, 'htdocs'), internal.dirnameFromFilename(answers.file)), checkProcessed); } else { external.init(); } }, function(err) { console.error(err); } ); }; /** * This is the Inquirer dialog for generating all HTML files. Will call external.init() on finish. * @return {void} [description] */ external.generateDialog = function() { var questions = [ { type: 'confirm', name: 'noforce', message: 'Only generate new files?', default: true }, { type: 'confirm', name: 'deploy', message: 'Do you want to publish all files?', default: true, when: function() { // answers return config.deployCmd; } } ]; var generator = Generator(config); inquirer .prompt(questions) .then( function(answers) { generator .getArticles() .then(function() { generator .buildAll(!answers.noforce) .then(function() { if(answers.deploy) { generator.deploy(); } external.init(); }) .catch( function(err) { console.error(err); } ) ; }) .catch( function(err) { console.error(err); } ) ; }) .catch( function(err) { console.error(err); } ) ; }; /** * This is the Inquirer dialog for showing the main menu. This will be called in a loop until `Exit` is selected. * @return {void} [description] */ external.init = function() { if (config.notInitialized) { fs.ensureDirSync(config.directories.data); fs.ensureDirSync(config.directories.htdocs); fs.copySync(path.join(__dirname, '..', 'htdocs', 'themes'), config.directories.theme); external.setupDialog(); } else { var questions = [ { type: 'list', name: 'action', message: 'Select action', choices: internal.makeChoices() } ]; inquirer.prompt(questions).then( function(answers) { switch (answers.action) { case choicesStr[0]: external.createArticleDialog(); break; case choicesStr[1]: external.editArticleDialog(); break; case choicesStr[2]: external.renameArticleDialog(); break; case choicesStr[3]: external.deleteArticleDialog(); break; case choicesStr[4]: external.generateDialog(); break; case choicesStr[5]: external.setupDialog(); break; case choicesStr[choicesStr.length -1]: console.log("Good bye"); break; default: external.init(); break; } }, function(err) { console.error(err); } ); } }; return external; }; module.exports = BlogophonConsole;
Removed debug `console.log`
src/blogophon-console.js
Removed debug `console.log`
<ide><path>rc/blogophon-console.js <ide> <ide> internal.makePost = function(markdownFilename, filename, templateData) { <ide> templateData.ymlQuote = MustacheQuoters.ymlQuote; <del> console.log(templateData); <ide> fs.writeFile(markdownFilename, Mustache.render(Mustache.templates.postMd, templateData), function(err) { <ide> if (err) { <ide> console.error(chalk.red( markdownFilename + ' could not be written' ));
Java
apache-2.0
df037b02fbb92624996e004ae84cfca43f87a769
0
apache/juddi,apache/juddi,apache/juddi,apache/juddi,apache/juddi
/* * Copyright 2001-2008 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.juddi.v3.auth; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.transform.stream.StreamSource; import javax.xml.ws.WebServiceContext; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.juddi.ClassUtil; import org.apache.juddi.config.AppConfig; import org.apache.juddi.config.PersistenceManager; import org.apache.juddi.config.Property; import org.apache.juddi.model.Publisher; import org.apache.juddi.model.UddiEntityPublisher; import org.apache.juddi.v3.error.AuthenticationException; import org.apache.juddi.v3.error.ErrorMessage; import org.apache.juddi.v3.error.FatalErrorException; import org.apache.juddi.v3.error.UnknownUserException; /** * This is a simple implementation of jUDDI's Authenticator interface. The credential * store is simply an unencrypted xml document called 'juddi.users' that can be * found in jUDDI's config directory. Below is an example of what you might find * in this document. * * Example juddi.users document: * ============================= * <?xml version="1.0" encoding="UTF-8"?> * <juddi-users> * <user userid="sviens" password="password" /> * <user userid="griddell" password="password" /> * <user userid="bhablutzel" password="password" /> * </juddi-users> * * @author Steve Viens ([email protected]) * @author <a href="mailto:[email protected]">Kurt T Stam</a> * @author <a href="mailto:[email protected]">Jeff Faath</a> */ public class XMLDocAuthenticator implements Authenticator { private static Log log = LogFactory.getLog(AuthenticatorFactory.class); /** Container for the user credentials */ Map<String,User> userTable; /** * */ public XMLDocAuthenticator() throws JAXBException, IOException, ConfigurationException { readUserFile(); } /** * an empty constructor */ public XMLDocAuthenticator(boolean b) { } protected String getFilename() throws ConfigurationException { return AppConfig.getConfiguration().getString(Property.JUDDI_USERSFILE, Property.DEFAULT_XML_USERSFILE); } /** * Read user data from the juddi-users file. * * @throws IOException when the file cannot be opened * JAXBException when the content is misformed. * @throws ConfigurationException */ public synchronized void readUserFile() throws JAXBException, IOException, ConfigurationException { userTable = new HashMap<String, User> (); String usersFileName = getFilename(); if (usersFileName==null || usersFileName.length()==0) throw new ConfigurationException("usersFileName value is null!"); File file = new File(usersFileName); InputStream stream = null; if (file.exists()) { log.info("Reading jUDDI Users File: " + usersFileName + "..."); stream = new FileInputStream(file); } else { URL resource = ClassUtil.getResource(usersFileName, this.getClass()); if (resource!=null) log.info("Reading jUDDI Users File: " + usersFileName + "...from " + resource.toExternalForm()); else log.info("Reading jUDDI Users File: " + usersFileName + "..."); stream = ClassUtil.getResource(usersFileName, this.getClass()).openStream(); } JAXBContext jaxbContext=JAXBContext.newInstance(JuddiUsers.class); Unmarshaller unMarshaller = jaxbContext.createUnmarshaller(); JAXBElement<JuddiUsers> element = unMarshaller.unmarshal(new StreamSource(stream),JuddiUsers.class); JuddiUsers users = element.getValue(); for (User user : users.getUser()) { userTable.put(user.getUserid(), user); log.debug("Loading user credentials for user: " + user.getUserid()); } } /** * * @param userID * @param credential */ public String authenticate(String userID,String credential) throws AuthenticationException, FatalErrorException { // a userID must be specified. if (userID == null) throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidUserId")); // credential (password) must be specified. if (credential == null) throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidCredentials")); if (userTable.containsKey(userID)) { User user = (User)userTable.get(userID); if ((user.getPassword() == null) || (!credential.equals(user.getPassword()))) throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidCredentials")); } else throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidUserId", userID)); return userID; } public UddiEntityPublisher identify(String authInfo, String authorizedName, WebServiceContext ctx) throws AuthenticationException { EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); Publisher publisher = em.find(Publisher.class, authorizedName); if (publisher == null) throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); return publisher; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } } }
juddi-core/src/main/java/org/apache/juddi/v3/auth/XMLDocAuthenticator.java
/* * Copyright 2001-2008 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.juddi.v3.auth; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.transform.stream.StreamSource; import javax.xml.ws.WebServiceContext; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.juddi.ClassUtil; import org.apache.juddi.config.AppConfig; import org.apache.juddi.config.PersistenceManager; import org.apache.juddi.config.Property; import org.apache.juddi.model.Publisher; import org.apache.juddi.model.UddiEntityPublisher; import org.apache.juddi.v3.error.AuthenticationException; import org.apache.juddi.v3.error.ErrorMessage; import org.apache.juddi.v3.error.FatalErrorException; import org.apache.juddi.v3.error.UnknownUserException; /** * This is a simple implementation of jUDDI's Authenticator interface. The credential * store is simply an unencrypted xml document called 'juddi.users' that can be * found in jUDDI's config directory. Below is an example of what you might find * in this document. * * Example juddi.users document: * ============================= * <?xml version="1.0" encoding="UTF-8"?> * <juddi-users> * <user userid="sviens" password="password" /> * <user userid="griddell" password="password" /> * <user userid="bhablutzel" password="password" /> * </juddi-users> * * @author Steve Viens ([email protected]) * @author <a href="mailto:[email protected]">Kurt T Stam</a> * @author <a href="mailto:[email protected]">Jeff Faath</a> */ public class XMLDocAuthenticator implements Authenticator { private static Log log = LogFactory.getLog(AuthenticatorFactory.class); /** Container for the user credentials */ Map<String,User> userTable; /** * */ public XMLDocAuthenticator() throws JAXBException, IOException, ConfigurationException { readUserFile(); } /** * an empty constructor */ public XMLDocAuthenticator(boolean b) { } protected String getFilename() throws ConfigurationException { return AppConfig.getConfiguration().getString(Property.JUDDI_USERSFILE, Property.DEFAULT_XML_USERSFILE); } /** * Read user data from the juddi-users file. * * @throws IOException when the file cannot be opened * JAXBException when the content is misformed. * @throws ConfigurationException */ public synchronized void readUserFile() throws JAXBException, IOException, ConfigurationException { userTable = new HashMap<String, User> (); String usersFileName = getFilename(); if (usersFileName==null || usersFileName.length()==0) throw new ConfigurationException("usersFileName value is null!"); //log.info("Reading jUDDI Users File: " + usersFileName + "..."); URL resource = ClassUtil.getResource(usersFileName, this.getClass()); if (resource!=null) log.info("Reading jUDDI Users File: " + usersFileName + "...from " + resource.toExternalForm()); else log.info("Reading jUDDI Users File: " + usersFileName + "..."); InputStream stream = ClassUtil.getResource(usersFileName, this.getClass()).openStream(); JAXBContext jaxbContext=JAXBContext.newInstance(JuddiUsers.class); Unmarshaller unMarshaller = jaxbContext.createUnmarshaller(); JAXBElement<JuddiUsers> element = unMarshaller.unmarshal(new StreamSource(stream),JuddiUsers.class); JuddiUsers users = element.getValue(); for (User user : users.getUser()) { userTable.put(user.getUserid(), user); log.debug("Loading user credentials for user: " + user.getUserid()); } } /** * * @param userID * @param credential */ public String authenticate(String userID,String credential) throws AuthenticationException, FatalErrorException { // a userID must be specified. if (userID == null) throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidUserId")); // credential (password) must be specified. if (credential == null) throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidCredentials")); if (userTable.containsKey(userID)) { User user = (User)userTable.get(userID); if ((user.getPassword() == null) || (!credential.equals(user.getPassword()))) throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidCredentials")); } else throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidUserId", userID)); return userID; } public UddiEntityPublisher identify(String authInfo, String authorizedName, WebServiceContext ctx) throws AuthenticationException { EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); Publisher publisher = em.find(Publisher.class, authorizedName); if (publisher == null) throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); return publisher; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } } }
JUDDI-840 adding the ability to specify a full path
juddi-core/src/main/java/org/apache/juddi/v3/auth/XMLDocAuthenticator.java
JUDDI-840 adding the ability to specify a full path
<ide><path>uddi-core/src/main/java/org/apache/juddi/v3/auth/XMLDocAuthenticator.java <ide> <ide> package org.apache.juddi.v3.auth; <ide> <add>import java.io.File; <add>import java.io.FileInputStream; <ide> import java.io.IOException; <ide> import java.io.InputStream; <ide> import java.net.URL; <ide> import java.util.HashMap; <del>import java.util.Hashtable; <ide> import java.util.Map; <ide> <ide> import javax.persistence.EntityManager; <ide> { <ide> <ide> userTable = new HashMap<String, User> (); <del> String usersFileName = getFilename(); <del> if (usersFileName==null || usersFileName.length()==0) <del> throw new ConfigurationException("usersFileName value is null!"); <del> //log.info("Reading jUDDI Users File: " + usersFileName + "..."); <del> URL resource = ClassUtil.getResource(usersFileName, this.getClass()); <del> if (resource!=null) <del> log.info("Reading jUDDI Users File: " + usersFileName + "...from " + resource.toExternalForm()); <del> else <del> log.info("Reading jUDDI Users File: " + usersFileName + "..."); <del> InputStream stream = ClassUtil.getResource(usersFileName, this.getClass()).openStream(); <add> String usersFileName = getFilename(); <add> if (usersFileName==null || usersFileName.length()==0) <add> throw new ConfigurationException("usersFileName value is null!"); <add> File file = new File(usersFileName); <add> InputStream stream = null; <add> if (file.exists()) { <add> log.info("Reading jUDDI Users File: " + usersFileName + "..."); <add> stream = new FileInputStream(file); <add> } else { <add> URL resource = ClassUtil.getResource(usersFileName, this.getClass()); <add> if (resource!=null) <add> log.info("Reading jUDDI Users File: " + usersFileName + "...from " + resource.toExternalForm()); <add> else <add> log.info("Reading jUDDI Users File: " + usersFileName + "..."); <add> stream = ClassUtil.getResource(usersFileName, this.getClass()).openStream(); <add> } <ide> JAXBContext jaxbContext=JAXBContext.newInstance(JuddiUsers.class); <ide> Unmarshaller unMarshaller = jaxbContext.createUnmarshaller(); <ide> JAXBElement<JuddiUsers> element = unMarshaller.unmarshal(new StreamSource(stream),JuddiUsers.class);
Java
apache-2.0
8b5348bc2991c4deec9adfdd9b8bcef3d8a22083
0
winklerm/drools,romartin/drools,droolsjbpm/drools,romartin/drools,romartin/drools,winklerm/drools,jomarko/drools,reynoldsm88/drools,sotty/drools,manstis/drools,manstis/drools,romartin/drools,manstis/drools,manstis/drools,winklerm/drools,sotty/drools,lanceleverich/drools,reynoldsm88/drools,sutaakar/drools,jomarko/drools,lanceleverich/drools,sutaakar/drools,romartin/drools,sutaakar/drools,sotty/drools,manstis/drools,lanceleverich/drools,droolsjbpm/drools,winklerm/drools,jomarko/drools,sotty/drools,sutaakar/drools,sutaakar/drools,jomarko/drools,lanceleverich/drools,ngs-mtech/drools,droolsjbpm/drools,sotty/drools,ngs-mtech/drools,lanceleverich/drools,reynoldsm88/drools,droolsjbpm/drools,ngs-mtech/drools,jomarko/drools,ngs-mtech/drools,reynoldsm88/drools,reynoldsm88/drools,droolsjbpm/drools,ngs-mtech/drools,winklerm/drools
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.drools.scorecards; import org.dmg.pmml.pmml_4_2.descr.Attribute; import org.dmg.pmml.pmml_4_2.descr.Characteristic; import org.dmg.pmml.pmml_4_2.descr.Characteristics; import org.dmg.pmml.pmml_4_2.descr.PMML; import org.dmg.pmml.pmml_4_2.descr.Scorecard; import org.drools.pmml.pmml_4_2.PMML4Helper; import org.junit.Assert; import org.junit.Test; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; import org.kie.api.builder.Results; import org.kie.api.definition.type.FactType; import org.kie.api.io.ResourceType; import org.kie.api.runtime.ClassObjectFilter; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import static org.drools.scorecards.ScorecardCompiler.DrlType.INTERNAL_DECLARED_TYPES; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class ScorecardReasonCodeTest { @Test public void testPMMLDocument() throws Exception { final ScorecardCompiler scorecardCompiler = new ScorecardCompiler(INTERNAL_DECLARED_TYPES); boolean compileResult = scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls")); if (!compileResult) { assertErrors(scorecardCompiler); } Assert.assertNotNull(scorecardCompiler.getPMMLDocument()); String pmml = scorecardCompiler.getPMML(); Assert.assertNotNull(pmml); assertTrue(pmml.length() > 0); } @Test public void testAbsenceOfReasonCodes() throws Exception { ScorecardCompiler scorecardCompiler = new ScorecardCompiler(INTERNAL_DECLARED_TYPES); scorecardCompiler.compileFromExcel( PMMLDocumentTest.class.getResourceAsStream( "/scoremodel_c.xls" ) ); PMML pmml = scorecardCompiler.getPMMLDocument(); for (Object serializable : pmml.getAssociationModelsAndBaselineModelsAndClusteringModels()){ if (serializable instanceof Scorecard){ assertFalse(((Scorecard) serializable).getUseReasonCodes()); } } } @Test public void testUseReasonCodes() throws Exception { final ScorecardCompiler scorecardCompiler = new ScorecardCompiler( INTERNAL_DECLARED_TYPES ); boolean compileResult = scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls")); if (!compileResult) { assertErrors(scorecardCompiler); } final PMML pmmlDocument = scorecardCompiler.getPMMLDocument(); for (Object serializable : pmmlDocument.getAssociationModelsAndBaselineModelsAndClusteringModels()){ if (serializable instanceof Scorecard){ assertTrue(((Scorecard)serializable).getUseReasonCodes()); assertEquals(100.0, ((Scorecard)serializable).getInitialScore(), 0.0); assertEquals("pointsBelow",((Scorecard)serializable).getReasonCodeAlgorithm()); } } } @Test public void testReasonCodes() throws Exception { final ScorecardCompiler scorecardCompiler = new ScorecardCompiler( INTERNAL_DECLARED_TYPES ); boolean compileResult = scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls")); if (!compileResult) { assertErrors(scorecardCompiler); } final PMML pmmlDocument = scorecardCompiler.getPMMLDocument(); for (Object serializable : pmmlDocument.getAssociationModelsAndBaselineModelsAndClusteringModels()){ if (serializable instanceof Scorecard){ for (Object obj :((Scorecard)serializable) .getExtensionsAndCharacteristicsAndMiningSchemas()){ if (obj instanceof Characteristics){ Characteristics characteristics = (Characteristics)obj; assertEquals(4, characteristics.getCharacteristics().size()); for (Characteristic characteristic : characteristics.getCharacteristics()){ for (Attribute attribute : characteristic.getAttributes()){ assertNotNull(attribute.getReasonCode()); } } return; } } } } fail(); } @Test public void testBaselineScores() throws Exception { ScorecardCompiler scorecardCompiler = new ScorecardCompiler( INTERNAL_DECLARED_TYPES ); boolean compileResult = scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls")); if (!compileResult) { assertErrors(scorecardCompiler); } final PMML pmmlDocument = scorecardCompiler.getPMMLDocument(); for (Object serializable : pmmlDocument.getAssociationModelsAndBaselineModelsAndClusteringModels()){ if (serializable instanceof Scorecard){ for (Object obj :((Scorecard)serializable) .getExtensionsAndCharacteristicsAndMiningSchemas()){ if (obj instanceof Characteristics){ Characteristics characteristics = (Characteristics)obj; assertEquals(4, characteristics.getCharacteristics().size()); assertEquals(10.0, characteristics.getCharacteristics().get(0).getBaselineScore(), 0.0); assertEquals(99.0, characteristics.getCharacteristics().get(1).getBaselineScore(), 0.0); assertEquals(12.0, characteristics.getCharacteristics().get(2).getBaselineScore(), 0.0); assertEquals(15.0, characteristics.getCharacteristics().get(3).getBaselineScore(), 0.0); assertEquals(25.0, ((Scorecard)serializable).getBaselineScore(), 0.0); return; } } } } fail(); } @Test public void testMissingReasonCodes() throws Exception { ScorecardCompiler scorecardCompiler = new ScorecardCompiler(); scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls"), "scorecards_reason_error"); assertEquals(3, scorecardCompiler.getScorecardParseErrors().size()); assertEquals("$F$13", scorecardCompiler.getScorecardParseErrors().get(0).getErrorLocation()); assertEquals("$F$22", scorecardCompiler.getScorecardParseErrors().get(1).getErrorLocation()); } @Test public void testMissingBaselineScores() throws Exception { ScorecardCompiler scorecardCompiler = new ScorecardCompiler(INTERNAL_DECLARED_TYPES); scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls"), "scorecards_reason_error"); assertEquals(3, scorecardCompiler.getScorecardParseErrors().size()); assertEquals("$D$30", scorecardCompiler.getScorecardParseErrors().get(2).getErrorLocation()); } @Test public void testReasonCodesCombinations() throws Exception { KieServices ks = KieServices.Factory.get(); KieFileSystem kfs = ks.newKieFileSystem(); kfs.write( ks.getResources().newClassPathResource( "scoremodel_reasoncodes.xls" ) .setSourcePath( "scoremodel_reasoncodes.xls" ) .setResourceType( ResourceType.SCARD ) ); KieBuilder kieBuilder = ks.newKieBuilder( kfs ); Results res = kieBuilder.buildAll().getResults(); KieContainer kieContainer = ks.newKieContainer( kieBuilder.getKieModule().getReleaseId() ); KieBase kbase = kieContainer.getKieBase(); KieSession session = kbase.newKieSession(); FactType scorecardType = kbase.getFactType( "org.drools.scorecards.example","SampleScore" ); FactType scorecardInternalsType = kbase.getFactType( PMML4Helper.pmmlDefaultPackageName(),"ScoreCard" ); FactType scorecardOutputType = kbase.getFactType( "org.drools.scorecards.example","SampleScoreOutput" ); Object scorecard = scorecardType.newInstance(); scorecardType.set(scorecard, "age", 10); session.insert(scorecard); session.fireAllRules(); assertEquals( 129.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); Object scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); assertEquals( 129.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); Map reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 2, reasonCodesMap.size() ); assertEquals( 16.0, reasonCodesMap.get( "VL002" ) ); assertEquals( -20.0, reasonCodesMap.get( "AGE02" ) ); Object scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( 129.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "VL002", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); session = kbase.newKieSession(); scorecard = scorecardType.newInstance(); scorecardType.set( scorecard, "age", 0 ); scorecardType.set( scorecard, "occupation", "SKYDIVER" ); session.insert( scorecard ); session.fireAllRules(); assertEquals( 99.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); System.out.println( scorecardInternals ); assertEquals( 99.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 3, reasonCodesMap.size() ); assertEquals( 109.0, reasonCodesMap.get( "OCC01" ) ); assertEquals( 16.0, reasonCodesMap.get( "VL002" ) ); assertEquals( 0.0, reasonCodesMap.get( "AGE01" ) ); scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( 99.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "OCC01", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); session = kbase.newKieSession(); scorecard = scorecardType.newInstance(); scorecardType.set( scorecard, "age", 20 ); scorecardType.set( scorecard, "occupation", "TEACHER" ); scorecardType.set( scorecard, "residenceState", "AP" ); scorecardType.set( scorecard, "validLicense", true ); session.insert( scorecard ); session.fireAllRules(); assertEquals( 141.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); System.out.println( scorecardInternals ); assertEquals( 141.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 4, reasonCodesMap.size() ); assertEquals( 89.0, reasonCodesMap.get( "OCC02" ) ); assertEquals( 22.0, reasonCodesMap.get( "RS001" ) ); assertEquals( 14.0, reasonCodesMap.get( "VL001" ) ); assertEquals( -30.0, reasonCodesMap.get( "AGE03" ) ); scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( 141.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "OCC02", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); } @Test public void testPointsAbove() throws Exception { ScorecardCompiler scorecardCompiler = new ScorecardCompiler(INTERNAL_DECLARED_TYPES); scorecardCompiler.compileFromExcel( PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls"), "scorecards_pointsAbove" ); assertEquals( 0, scorecardCompiler.getScorecardParseErrors().size() ); String drl = scorecardCompiler.getDRL(); assertNotNull(drl); KieServices ks = KieServices.Factory.get(); KieFileSystem kfs = ks.newKieFileSystem(); kfs.write( ks.getResources().newByteArrayResource( drl.getBytes() ) .setSourcePath( "scoremodel_pointsAbove.drl" ) .setResourceType( ResourceType.DRL ) ); KieBuilder kieBuilder = ks.newKieBuilder( kfs ); Results res = kieBuilder.buildAll().getResults(); KieContainer kieContainer = ks.newKieContainer( kieBuilder.getKieModule().getReleaseId() ); KieBase kbase = kieContainer.getKieBase(); KieSession session = kbase.newKieSession(); FactType scorecardType = kbase.getFactType( "org.drools.scorecards.example","SampleScore" ); FactType scorecardInternalsType = kbase.getFactType( PMML4Helper.pmmlDefaultPackageName(),"ScoreCard" ); FactType scorecardOutputType = kbase.getFactType( "org.drools.scorecards.example","SampleScoreOutput" ); Object scorecard = scorecardType.newInstance(); scorecardType.set(scorecard, "age", 10); session.insert(scorecard); session.fireAllRules(); assertEquals( 29.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); Object scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); assertEquals( 29.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); Map reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 2, reasonCodesMap.size() ); assertEquals( -16.0, reasonCodesMap.get( "VL002" ) ); assertEquals( 20.0, reasonCodesMap.get( "AGE02" ) ); Object scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( 29.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "AGE02", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); session = kbase.newKieSession(); scorecard = scorecardType.newInstance(); scorecardType.set( scorecard, "age", 0 ); scorecardType.set( scorecard, "occupation", "SKYDIVER" ); session.insert( scorecard ); session.fireAllRules(); assertEquals( -1.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); System.out.println( scorecardInternals ); assertEquals( -1.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 3, reasonCodesMap.size() ); assertEquals( -109.0, reasonCodesMap.get( "OCC01" ) ); assertEquals( -16.0, reasonCodesMap.get( "VL002" ) ); assertEquals( 0.0, reasonCodesMap.get( "AGE01" ) ); assertEquals( Arrays.asList( "AGE01", "VL002", "OCC01" ), new ArrayList( reasonCodesMap.keySet() ) ); scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( -1.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "AGE01", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); session = kbase.newKieSession(); scorecard = scorecardType.newInstance(); scorecardType.set( scorecard, "age", 20 ); scorecardType.set( scorecard, "occupation", "TEACHER" ); scorecardType.set( scorecard, "residenceState", "AP" ); scorecardType.set( scorecard, "validLicense", true ); session.insert( scorecard ); session.fireAllRules(); assertEquals( 41.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); System.out.println( scorecardInternals ); assertEquals( 41.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 4, reasonCodesMap.size() ); assertEquals( -89.0, reasonCodesMap.get( "OCC02" ) ); assertEquals( -22.0, reasonCodesMap.get( "RS001" ) ); assertEquals( -14.0, reasonCodesMap.get( "VL001" ) ); assertEquals( 30.0, reasonCodesMap.get( "AGE03" ) ); assertEquals( Arrays.asList( "AGE03", "VL001", "RS001", "OCC02" ), new ArrayList( reasonCodesMap.keySet() ) ); scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( 41.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "AGE03", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); } @Test public void testPointsBelow() throws Exception { ScorecardCompiler scorecardCompiler = new ScorecardCompiler(INTERNAL_DECLARED_TYPES); scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls"), "scorecards_pointsBelow"); assertEquals(0, scorecardCompiler.getScorecardParseErrors().size()); String drl = scorecardCompiler.getDRL(); KieServices ks = KieServices.Factory.get(); KieFileSystem kfs = ks.newKieFileSystem(); kfs.write( ks.getResources().newByteArrayResource( drl.getBytes() ) .setSourcePath( "scoremodel_pointsAbove.drl" ) .setResourceType( ResourceType.DRL ) ); KieBuilder kieBuilder = ks.newKieBuilder( kfs ); Results res = kieBuilder.buildAll().getResults(); KieContainer kieContainer = ks.newKieContainer( kieBuilder.getKieModule().getReleaseId() ); KieBase kbase = kieContainer.getKieBase(); KieSession session = kbase.newKieSession(); FactType scorecardType = kbase.getFactType( "org.drools.scorecards.example","SampleScore" ); FactType scorecardInternalsType = kbase.getFactType( PMML4Helper.pmmlDefaultPackageName(),"ScoreCard" ); FactType scorecardOutputType = kbase.getFactType( "org.drools.scorecards.example","SampleScoreOutput" ); Object scorecard = scorecardType.newInstance(); scorecardType.set(scorecard, "age", 10); session.insert(scorecard); session.fireAllRules(); assertEquals( 29.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); Object scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); assertEquals( 29.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); Map reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 2, reasonCodesMap.size() ); assertEquals( 16.0, reasonCodesMap.get( "VL002" ) ); assertEquals( -20.0, reasonCodesMap.get( "AGE02" ) ); Object scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( 29.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "VL002", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); session = kbase.newKieSession(); scorecard = scorecardType.newInstance(); scorecardType.set( scorecard, "age", 0 ); scorecardType.set( scorecard, "occupation", "SKYDIVER" ); session.insert( scorecard ); session.fireAllRules(); assertEquals( -1.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); System.out.println( scorecardInternals ); assertEquals( -1.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 3, reasonCodesMap.size() ); assertEquals( 109.0, reasonCodesMap.get( "OCC01" ) ); assertEquals( 16.0, reasonCodesMap.get( "VL002" ) ); assertEquals( 0.0, reasonCodesMap.get( "AGE01" ) ); scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( -1.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "OCC01", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); session = kbase.newKieSession(); scorecard = scorecardType.newInstance(); scorecardType.set( scorecard, "age", 20 ); scorecardType.set( scorecard, "occupation", "TEACHER" ); scorecardType.set( scorecard, "residenceState", "AP" ); scorecardType.set( scorecard, "validLicense", true ); session.insert( scorecard ); session.fireAllRules(); assertEquals( 41.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); System.out.println( scorecardInternals ); assertEquals( 41.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 4, reasonCodesMap.size() ); assertEquals( 89.0, reasonCodesMap.get( "OCC02" ) ); assertEquals( 22.0, reasonCodesMap.get( "RS001" ) ); assertEquals( 14.0, reasonCodesMap.get( "VL001" ) ); assertEquals( -30.0, reasonCodesMap.get( "AGE03" ) ); scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( 41.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "OCC02", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); } private void assertErrors(final ScorecardCompiler compiler) { final StringBuilder errorBuilder = new StringBuilder(); compiler.getScorecardParseErrors().forEach((error) -> errorBuilder.append(error.getErrorLocation() + " -> " + error.getErrorMessage() + "\n")); final String errors = errorBuilder.toString(); Assert.fail("There are compile errors: \n" + errors); } }
drools-scorecards/src/test/java/org/drools/scorecards/ScorecardReasonCodeTest.java
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.drools.scorecards; import org.dmg.pmml.pmml_4_2.descr.Attribute; import org.dmg.pmml.pmml_4_2.descr.Characteristic; import org.dmg.pmml.pmml_4_2.descr.Characteristics; import org.dmg.pmml.pmml_4_2.descr.PMML; import org.dmg.pmml.pmml_4_2.descr.Scorecard; import org.drools.pmml.pmml_4_2.PMML4Helper; import org.junit.Assert; import org.junit.Test; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; import org.kie.api.builder.Results; import org.kie.api.definition.type.FactType; import org.kie.api.io.ResourceType; import org.kie.api.runtime.ClassObjectFilter; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import static org.drools.scorecards.ScorecardCompiler.DrlType.INTERNAL_DECLARED_TYPES; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class ScorecardReasonCodeTest { private static PMML pmmlDocument; private static ScorecardCompiler scorecardCompiler; @Test public void testPMMLDocument() throws Exception { Assert.assertNotNull(pmmlDocument); String pmml = scorecardCompiler.getPMML(); Assert.assertNotNull(pmml); assertTrue(pmml.length() > 0); //System.out.println(pmml); } @Test public void testAbsenceOfReasonCodes() throws Exception { ScorecardCompiler scorecardCompiler = new ScorecardCompiler(INTERNAL_DECLARED_TYPES); scorecardCompiler.compileFromExcel( PMMLDocumentTest.class.getResourceAsStream( "/scoremodel_c.xls" ) ); PMML pmml = scorecardCompiler.getPMMLDocument(); for (Object serializable : pmml.getAssociationModelsAndBaselineModelsAndClusteringModels()){ if (serializable instanceof Scorecard){ assertFalse(((Scorecard) serializable).getUseReasonCodes()); } } } @Test public void testUseReasonCodes() throws Exception { scorecardCompiler = new ScorecardCompiler( INTERNAL_DECLARED_TYPES ); boolean compileResult = scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls")); if (!compileResult) { for(ScorecardError error : scorecardCompiler.getScorecardParseErrors()){ System.out.println("setup :"+error.getErrorLocation()+"->"+error.getErrorMessage()); } } pmmlDocument = scorecardCompiler.getPMMLDocument(); for (Object serializable : pmmlDocument.getAssociationModelsAndBaselineModelsAndClusteringModels()){ if (serializable instanceof Scorecard){ assertTrue(((Scorecard)serializable).getUseReasonCodes()); assertEquals(100.0, ((Scorecard)serializable).getInitialScore(), 0.0); assertEquals("pointsBelow",((Scorecard)serializable).getReasonCodeAlgorithm()); } } } @Test public void testReasonCodes() throws Exception { scorecardCompiler = new ScorecardCompiler( INTERNAL_DECLARED_TYPES ); boolean compileResult = scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls")); if (!compileResult) { for(ScorecardError error : scorecardCompiler.getScorecardParseErrors()){ System.out.println("setup :"+error.getErrorLocation()+"->"+error.getErrorMessage()); } } pmmlDocument = scorecardCompiler.getPMMLDocument(); for (Object serializable : pmmlDocument.getAssociationModelsAndBaselineModelsAndClusteringModels()){ if (serializable instanceof Scorecard){ for (Object obj :((Scorecard)serializable) .getExtensionsAndCharacteristicsAndMiningSchemas()){ if (obj instanceof Characteristics){ Characteristics characteristics = (Characteristics)obj; assertEquals(4, characteristics.getCharacteristics().size()); for (Characteristic characteristic : characteristics.getCharacteristics()){ for (Attribute attribute : characteristic.getAttributes()){ assertNotNull(attribute.getReasonCode()); } } return; } } } } fail(); } @Test public void testBaselineScores() throws Exception { ScorecardCompiler scorecardCompiler = new ScorecardCompiler( INTERNAL_DECLARED_TYPES ); boolean compileResult = scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls")); if (!compileResult) { for(ScorecardError error : scorecardCompiler.getScorecardParseErrors()){ System.out.println("setup :"+error.getErrorLocation()+"->"+error.getErrorMessage()); } } pmmlDocument = scorecardCompiler.getPMMLDocument(); for (Object serializable : pmmlDocument.getAssociationModelsAndBaselineModelsAndClusteringModels()){ if (serializable instanceof Scorecard){ for (Object obj :((Scorecard)serializable) .getExtensionsAndCharacteristicsAndMiningSchemas()){ if (obj instanceof Characteristics){ Characteristics characteristics = (Characteristics)obj; assertEquals(4, characteristics.getCharacteristics().size()); assertEquals(10.0, characteristics.getCharacteristics().get(0).getBaselineScore(), 0.0); assertEquals(99.0, characteristics.getCharacteristics().get(1).getBaselineScore(), 0.0); assertEquals(12.0, characteristics.getCharacteristics().get(2).getBaselineScore(), 0.0); assertEquals(15.0, characteristics.getCharacteristics().get(3).getBaselineScore(), 0.0); assertEquals(25.0, ((Scorecard)serializable).getBaselineScore(), 0.0); return; } } } } fail(); } @Test public void testMissingReasonCodes() throws Exception { ScorecardCompiler scorecardCompiler = new ScorecardCompiler(); scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls"), "scorecards_reason_error"); assertEquals(3, scorecardCompiler.getScorecardParseErrors().size()); assertEquals("$F$13", scorecardCompiler.getScorecardParseErrors().get(0).getErrorLocation()); assertEquals("$F$22", scorecardCompiler.getScorecardParseErrors().get(1).getErrorLocation()); } @Test public void testMissingBaselineScores() throws Exception { ScorecardCompiler scorecardCompiler = new ScorecardCompiler(INTERNAL_DECLARED_TYPES); scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls"), "scorecards_reason_error"); assertEquals(3, scorecardCompiler.getScorecardParseErrors().size()); assertEquals("$D$30", scorecardCompiler.getScorecardParseErrors().get(2).getErrorLocation()); } @Test public void testReasonCodesCombinations() throws Exception { KieServices ks = KieServices.Factory.get(); KieFileSystem kfs = ks.newKieFileSystem(); kfs.write( ks.getResources().newClassPathResource( "scoremodel_reasoncodes.xls" ) .setSourcePath( "scoremodel_reasoncodes.xls" ) .setResourceType( ResourceType.SCARD ) ); KieBuilder kieBuilder = ks.newKieBuilder( kfs ); Results res = kieBuilder.buildAll().getResults(); KieContainer kieContainer = ks.newKieContainer( kieBuilder.getKieModule().getReleaseId() ); KieBase kbase = kieContainer.getKieBase(); KieSession session = kbase.newKieSession(); FactType scorecardType = kbase.getFactType( "org.drools.scorecards.example","SampleScore" ); FactType scorecardInternalsType = kbase.getFactType( PMML4Helper.pmmlDefaultPackageName(),"ScoreCard" ); FactType scorecardOutputType = kbase.getFactType( "org.drools.scorecards.example","SampleScoreOutput" ); Object scorecard = scorecardType.newInstance(); scorecardType.set(scorecard, "age", 10); session.insert(scorecard); session.fireAllRules(); assertEquals( 129.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); Object scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); assertEquals( 129.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); Map reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 2, reasonCodesMap.size() ); assertEquals( 16.0, reasonCodesMap.get( "VL002" ) ); assertEquals( -20.0, reasonCodesMap.get( "AGE02" ) ); Object scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( 129.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "VL002", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); session = kbase.newKieSession(); scorecard = scorecardType.newInstance(); scorecardType.set( scorecard, "age", 0 ); scorecardType.set( scorecard, "occupation", "SKYDIVER" ); session.insert( scorecard ); session.fireAllRules(); assertEquals( 99.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); System.out.println( scorecardInternals ); assertEquals( 99.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 3, reasonCodesMap.size() ); assertEquals( 109.0, reasonCodesMap.get( "OCC01" ) ); assertEquals( 16.0, reasonCodesMap.get( "VL002" ) ); assertEquals( 0.0, reasonCodesMap.get( "AGE01" ) ); scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( 99.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "OCC01", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); session = kbase.newKieSession(); scorecard = scorecardType.newInstance(); scorecardType.set( scorecard, "age", 20 ); scorecardType.set( scorecard, "occupation", "TEACHER" ); scorecardType.set( scorecard, "residenceState", "AP" ); scorecardType.set( scorecard, "validLicense", true ); session.insert( scorecard ); session.fireAllRules(); assertEquals( 141.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); System.out.println( scorecardInternals ); assertEquals( 141.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 4, reasonCodesMap.size() ); assertEquals( 89.0, reasonCodesMap.get( "OCC02" ) ); assertEquals( 22.0, reasonCodesMap.get( "RS001" ) ); assertEquals( 14.0, reasonCodesMap.get( "VL001" ) ); assertEquals( -30.0, reasonCodesMap.get( "AGE03" ) ); scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( 141.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "OCC02", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); } @Test public void testPointsAbove() throws Exception { ScorecardCompiler scorecardCompiler = new ScorecardCompiler(INTERNAL_DECLARED_TYPES); scorecardCompiler.compileFromExcel( PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls"), "scorecards_pointsAbove" ); assertEquals( 0, scorecardCompiler.getScorecardParseErrors().size() ); String drl = scorecardCompiler.getDRL(); assertNotNull(drl); KieServices ks = KieServices.Factory.get(); KieFileSystem kfs = ks.newKieFileSystem(); kfs.write( ks.getResources().newByteArrayResource( drl.getBytes() ) .setSourcePath( "scoremodel_pointsAbove.drl" ) .setResourceType( ResourceType.DRL ) ); KieBuilder kieBuilder = ks.newKieBuilder( kfs ); Results res = kieBuilder.buildAll().getResults(); KieContainer kieContainer = ks.newKieContainer( kieBuilder.getKieModule().getReleaseId() ); KieBase kbase = kieContainer.getKieBase(); KieSession session = kbase.newKieSession(); FactType scorecardType = kbase.getFactType( "org.drools.scorecards.example","SampleScore" ); FactType scorecardInternalsType = kbase.getFactType( PMML4Helper.pmmlDefaultPackageName(),"ScoreCard" ); FactType scorecardOutputType = kbase.getFactType( "org.drools.scorecards.example","SampleScoreOutput" ); Object scorecard = scorecardType.newInstance(); scorecardType.set(scorecard, "age", 10); session.insert(scorecard); session.fireAllRules(); assertEquals( 29.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); Object scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); assertEquals( 29.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); Map reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 2, reasonCodesMap.size() ); assertEquals( -16.0, reasonCodesMap.get( "VL002" ) ); assertEquals( 20.0, reasonCodesMap.get( "AGE02" ) ); Object scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( 29.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "AGE02", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); session = kbase.newKieSession(); scorecard = scorecardType.newInstance(); scorecardType.set( scorecard, "age", 0 ); scorecardType.set( scorecard, "occupation", "SKYDIVER" ); session.insert( scorecard ); session.fireAllRules(); assertEquals( -1.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); System.out.println( scorecardInternals ); assertEquals( -1.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 3, reasonCodesMap.size() ); assertEquals( -109.0, reasonCodesMap.get( "OCC01" ) ); assertEquals( -16.0, reasonCodesMap.get( "VL002" ) ); assertEquals( 0.0, reasonCodesMap.get( "AGE01" ) ); assertEquals( Arrays.asList( "AGE01", "VL002", "OCC01" ), new ArrayList( reasonCodesMap.keySet() ) ); scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( -1.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "AGE01", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); session = kbase.newKieSession(); scorecard = scorecardType.newInstance(); scorecardType.set( scorecard, "age", 20 ); scorecardType.set( scorecard, "occupation", "TEACHER" ); scorecardType.set( scorecard, "residenceState", "AP" ); scorecardType.set( scorecard, "validLicense", true ); session.insert( scorecard ); session.fireAllRules(); assertEquals( 41.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); System.out.println( scorecardInternals ); assertEquals( 41.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 4, reasonCodesMap.size() ); assertEquals( -89.0, reasonCodesMap.get( "OCC02" ) ); assertEquals( -22.0, reasonCodesMap.get( "RS001" ) ); assertEquals( -14.0, reasonCodesMap.get( "VL001" ) ); assertEquals( 30.0, reasonCodesMap.get( "AGE03" ) ); assertEquals( Arrays.asList( "AGE03", "VL001", "RS001", "OCC02" ), new ArrayList( reasonCodesMap.keySet() ) ); scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( 41.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "AGE03", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); } @Test public void testPointsBelow() throws Exception { ScorecardCompiler scorecardCompiler = new ScorecardCompiler(INTERNAL_DECLARED_TYPES); scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls"), "scorecards_pointsBelow"); assertEquals(0, scorecardCompiler.getScorecardParseErrors().size()); String drl = scorecardCompiler.getDRL(); KieServices ks = KieServices.Factory.get(); KieFileSystem kfs = ks.newKieFileSystem(); kfs.write( ks.getResources().newByteArrayResource( drl.getBytes() ) .setSourcePath( "scoremodel_pointsAbove.drl" ) .setResourceType( ResourceType.DRL ) ); KieBuilder kieBuilder = ks.newKieBuilder( kfs ); Results res = kieBuilder.buildAll().getResults(); KieContainer kieContainer = ks.newKieContainer( kieBuilder.getKieModule().getReleaseId() ); KieBase kbase = kieContainer.getKieBase(); KieSession session = kbase.newKieSession(); FactType scorecardType = kbase.getFactType( "org.drools.scorecards.example","SampleScore" ); FactType scorecardInternalsType = kbase.getFactType( PMML4Helper.pmmlDefaultPackageName(),"ScoreCard" ); FactType scorecardOutputType = kbase.getFactType( "org.drools.scorecards.example","SampleScoreOutput" ); Object scorecard = scorecardType.newInstance(); scorecardType.set(scorecard, "age", 10); session.insert(scorecard); session.fireAllRules(); assertEquals( 29.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); Object scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); assertEquals( 29.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); Map reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 2, reasonCodesMap.size() ); assertEquals( 16.0, reasonCodesMap.get( "VL002" ) ); assertEquals( -20.0, reasonCodesMap.get( "AGE02" ) ); Object scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( 29.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "VL002", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); session = kbase.newKieSession(); scorecard = scorecardType.newInstance(); scorecardType.set( scorecard, "age", 0 ); scorecardType.set( scorecard, "occupation", "SKYDIVER" ); session.insert( scorecard ); session.fireAllRules(); assertEquals( -1.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); System.out.println( scorecardInternals ); assertEquals( -1.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 3, reasonCodesMap.size() ); assertEquals( 109.0, reasonCodesMap.get( "OCC01" ) ); assertEquals( 16.0, reasonCodesMap.get( "VL002" ) ); assertEquals( 0.0, reasonCodesMap.get( "AGE01" ) ); scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( -1.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "OCC01", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); session = kbase.newKieSession(); scorecard = scorecardType.newInstance(); scorecardType.set( scorecard, "age", 20 ); scorecardType.set( scorecard, "occupation", "TEACHER" ); scorecardType.set( scorecard, "residenceState", "AP" ); scorecardType.set( scorecard, "validLicense", true ); session.insert( scorecard ); session.fireAllRules(); assertEquals( 41.0, scorecardType.get( scorecard, "scorecard__calculatedScore" ) ); scorecardInternals = session.getObjects( new ClassObjectFilter( scorecardInternalsType.getFactClass() ) ).iterator().next(); System.out.println( scorecardInternals ); assertEquals( 41.0, scorecardInternalsType.get( scorecardInternals, "score" ) ); reasonCodesMap = (Map) scorecardInternalsType.get( scorecardInternals, "ranking" ); assertNotNull( reasonCodesMap ); assertEquals( 4, reasonCodesMap.size() ); assertEquals( 89.0, reasonCodesMap.get( "OCC02" ) ); assertEquals( 22.0, reasonCodesMap.get( "RS001" ) ); assertEquals( 14.0, reasonCodesMap.get( "VL001" ) ); assertEquals( -30.0, reasonCodesMap.get( "AGE03" ) ); scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); assertEquals( 41.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); assertEquals( "OCC02", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); session.dispose(); } }
Fixes testPMMLDocument() which passed only accidentally in previous runs (#1109) Test testPMMLDocument() used uninitialized variables from class. In previous runs it passed only accidentally, because the variables were initialized from previous tests in the class.
drools-scorecards/src/test/java/org/drools/scorecards/ScorecardReasonCodeTest.java
Fixes testPMMLDocument() which passed only accidentally in previous runs (#1109)
<ide><path>rools-scorecards/src/test/java/org/drools/scorecards/ScorecardReasonCodeTest.java <ide> <ide> public class ScorecardReasonCodeTest { <ide> <del> private static PMML pmmlDocument; <del> private static ScorecardCompiler scorecardCompiler; <del> <del> <ide> @Test <ide> public void testPMMLDocument() throws Exception { <del> Assert.assertNotNull(pmmlDocument); <del> <add> final ScorecardCompiler scorecardCompiler = new ScorecardCompiler(INTERNAL_DECLARED_TYPES); <add> boolean compileResult = scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls")); <add> if (!compileResult) { <add> assertErrors(scorecardCompiler); <add> } <add> Assert.assertNotNull(scorecardCompiler.getPMMLDocument()); <ide> String pmml = scorecardCompiler.getPMML(); <ide> Assert.assertNotNull(pmml); <ide> assertTrue(pmml.length() > 0); <del> //System.out.println(pmml); <ide> } <ide> <ide> @Test <ide> <ide> @Test <ide> public void testUseReasonCodes() throws Exception { <del> scorecardCompiler = new ScorecardCompiler( INTERNAL_DECLARED_TYPES ); <add> final ScorecardCompiler scorecardCompiler = new ScorecardCompiler( INTERNAL_DECLARED_TYPES ); <ide> boolean compileResult = scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls")); <ide> if (!compileResult) { <del> for(ScorecardError error : scorecardCompiler.getScorecardParseErrors()){ <del> System.out.println("setup :"+error.getErrorLocation()+"->"+error.getErrorMessage()); <del> } <del> } <del> <del> pmmlDocument = scorecardCompiler.getPMMLDocument(); <add> assertErrors(scorecardCompiler); <add> } <add> <add> final PMML pmmlDocument = scorecardCompiler.getPMMLDocument(); <ide> <ide> for (Object serializable : pmmlDocument.getAssociationModelsAndBaselineModelsAndClusteringModels()){ <ide> if (serializable instanceof Scorecard){ <ide> <ide> @Test <ide> public void testReasonCodes() throws Exception { <del> scorecardCompiler = new ScorecardCompiler( INTERNAL_DECLARED_TYPES ); <add> final ScorecardCompiler scorecardCompiler = new ScorecardCompiler( INTERNAL_DECLARED_TYPES ); <ide> boolean compileResult = scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls")); <ide> if (!compileResult) { <del> for(ScorecardError error : scorecardCompiler.getScorecardParseErrors()){ <del> System.out.println("setup :"+error.getErrorLocation()+"->"+error.getErrorMessage()); <del> } <del> } <del> <del> pmmlDocument = scorecardCompiler.getPMMLDocument(); <add> assertErrors(scorecardCompiler); <add> } <add> <add> final PMML pmmlDocument = scorecardCompiler.getPMMLDocument(); <ide> <ide> for (Object serializable : pmmlDocument.getAssociationModelsAndBaselineModelsAndClusteringModels()){ <ide> if (serializable instanceof Scorecard){ <ide> ScorecardCompiler scorecardCompiler = new ScorecardCompiler( INTERNAL_DECLARED_TYPES ); <ide> boolean compileResult = scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_reasoncodes.xls")); <ide> if (!compileResult) { <del> for(ScorecardError error : scorecardCompiler.getScorecardParseErrors()){ <del> System.out.println("setup :"+error.getErrorLocation()+"->"+error.getErrorMessage()); <del> } <del> } <del> <del> pmmlDocument = scorecardCompiler.getPMMLDocument(); <add> assertErrors(scorecardCompiler); <add> } <add> <add> final PMML pmmlDocument = scorecardCompiler.getPMMLDocument(); <ide> <ide> for (Object serializable : pmmlDocument.getAssociationModelsAndBaselineModelsAndClusteringModels()){ <ide> if (serializable instanceof Scorecard){ <ide> assertEquals("$D$30", scorecardCompiler.getScorecardParseErrors().get(2).getErrorLocation()); <ide> } <ide> <del> <del> <ide> @Test <ide> public void testReasonCodesCombinations() throws Exception { <ide> <ide> session.dispose(); <ide> } <ide> <del> <del> <del> <del> <del> <ide> @Test <ide> public void testPointsAbove() throws Exception { <ide> ScorecardCompiler scorecardCompiler = new ScorecardCompiler(INTERNAL_DECLARED_TYPES); <ide> <ide> String drl = scorecardCompiler.getDRL(); <ide> assertNotNull(drl); <del> <ide> <ide> KieServices ks = KieServices.Factory.get(); <ide> KieFileSystem kfs = ks.newKieFileSystem(); <ide> <ide> session.dispose(); <ide> <del> <del> <del> <ide> session = kbase.newKieSession(); <ide> scorecard = scorecardType.newInstance(); <ide> scorecardType.set( scorecard, "age", 0 ); <ide> session.dispose(); <ide> <ide> } <del> <del> <del> <ide> <ide> @Test <ide> public void testPointsBelow() throws Exception { <ide> <ide> session.dispose(); <ide> <del> <ide> session = kbase.newKieSession(); <ide> scorecard = scorecardType.newInstance(); <ide> scorecardType.set( scorecard, "age", 0 ); <ide> scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); <ide> assertEquals( -1.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); <ide> assertEquals( "OCC01", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); <del> <ide> <ide> session.dispose(); <ide> <ide> assertEquals( 14.0, reasonCodesMap.get( "VL001" ) ); <ide> assertEquals( -30.0, reasonCodesMap.get( "AGE03" ) ); <ide> <del> <ide> scorecardOutput = session.getObjects( new ClassObjectFilter( scorecardOutputType.getFactClass() ) ).iterator().next(); <ide> assertEquals( 41.0, scorecardOutputType.get( scorecardOutput, "calculatedScore" ) ); <ide> assertEquals( "OCC02", scorecardOutputType.get( scorecardOutput, "reasonCode" ) ); <ide> session.dispose(); <ide> } <ide> <del> <del> <add> private void assertErrors(final ScorecardCompiler compiler) { <add> final StringBuilder errorBuilder = new StringBuilder(); <add> compiler.getScorecardParseErrors().forEach((error) -> errorBuilder.append(error.getErrorLocation() + " -> " + error.getErrorMessage() + "\n")); <add> final String errors = errorBuilder.toString(); <add> Assert.fail("There are compile errors: \n" + errors); <add> } <ide> }
JavaScript
apache-2.0
c74cc2f6b3021e888d7f6d18889a3c123740040e
0
Drooids/Eve,brunotag/Eve,sagittaros/Eve,brunotag/Eve,dirvine/Eve,jhftrifork/Eve,hrishimittal/Eve,sherbondy/Eve,bjtitus/Eve,hrishimittal/Eve,shamim8888/Eve,kidaa/Eve-1,agumonkey/Eve,jhftrifork/Eve,nonZero/Eve,adjohnson916/Eve,nonZero/Eve,shaunstanislaus/Eve-1,kidaa/Eve-1,dirvine/Eve,bjtitus/Eve,nonZero/Eve,pel-daniel/Eve,rschroll/Eve,bluesnowman/Eve,shamim8888/Eve,rschroll/Eve,adjohnson916/Eve,sagittaros/Eve,sherbondy/Eve,steveklabnik/Eve,pel-daniel/Eve,nonZero/Eve,Drooids/Eve,ViniciusAtaide/Eve,kidaa/Eve-1,Drooids/Eve,pel-daniel/Eve,agumonkey/Eve,hrishimittal/Eve,shaunstanislaus/Eve-1,tobyjsullivan/Eve,rschroll/Eve,rschroll/Eve,pel-daniel/Eve,8l/Eve,fineline/Eve,justintaft/Eve,jhftrifork/Eve,8l/Eve,kidaa/Eve-1,ViniciusAtaide/Eve,hrishimittal/Eve,tobyjsullivan/Eve,tobyjsullivan/Eve,shaunstanislaus/Eve-1,fineline/Eve,rschroll/Eve,justintaft/Eve,dirvine/Eve,sherbondy/Eve,agumonkey/Eve,shamim8888/Eve,fineline/Eve,tobyjsullivan/Eve,Drooids/Eve,brunotag/Eve,adjohnson916/Eve,shamim8888/Eve,bluesnowman/Eve,ViniciusAtaide/Eve,shaunstanislaus/Eve-1,nonZero/Eve,sherbondy/Eve,bluesnowman/Eve,agumonkey/Eve,tobyjsullivan/Eve,bjtitus/Eve,brunotag/Eve,bjtitus/Eve,bluesnowman/Eve,jhftrifork/Eve,steveklabnik/Eve,steveklabnik/Eve,sagittaros/Eve,8l/Eve,steveklabnik/Eve,Drooids/Eve,dirvine/Eve,steveklabnik/Eve,fineline/Eve,fineline/Eve,sagittaros/Eve,justintaft/Eve,ViniciusAtaide/Eve,hrishimittal/Eve,sherbondy/Eve,agumonkey/Eve,adjohnson916/Eve,adjohnson916/Eve,8l/Eve,jhftrifork/Eve,dirvine/Eve,brunotag/Eve,justintaft/Eve,ViniciusAtaide/Eve,8l/Eve,shaunstanislaus/Eve-1,shamim8888/Eve,sagittaros/Eve
var queryEditor = (function(window, microReact, api) { var document = window.document; var ixer = api.ixer; var code = api.code; var diff = api.diff; var localState = api.localState; var clone = api.clone; if(window.queryEditor) { try { document.body.removeChild(window.queryEditor.container); } catch (err) { // meh } } window.addEventListener("resize", render); document.body.addEventListener("drop", preventDefault); var renderer = new microReact.Renderer(); document.body.appendChild(renderer.content); renderer.queued = false; function render() { if(renderer.queued === false) { renderer.queued = true; requestAnimationFrame(function() { renderer.queued = false; renderer.render(root()); }); } } function preventDefault(evt) { evt.preventDefault(); } function focusOnce(node, elem) { if(!elem.__focused) { setTimeout(function() { node.focus(); }, 5); elem.__focused = true; } } //--------------------------------------------------------- // utils //--------------------------------------------------------- var alphabet = ["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"]; var KEYS = {UP: 38, DOWN: 40, ENTER: 13, Z: 90}; function coerceInput(input) { if(input.match(/^-?[\d]+$/gim)) { return parseInt(input); } else if(input.match(/^-?[\d]+\.[\d]+$/gim)) { return parseFloat(input); } return input; } function reverseDiff(diff) { var neue = []; for(var diffIx = 0, diffLen = diff.length; diffIx < diffLen; diffIx++) { var copy = diff[diffIx].slice(); neue[diffIx] = copy if(copy[1] === "inserted") { copy[1] = "removed"; } else { copy[1] = "inserted"; } } return neue; } //--------------------------------------------------------- // Local state //--------------------------------------------------------- var eventStack = {root: true, children: [], localState: clone(localState)}; function scaryUndoEvent() { if(!eventStack.parent || !eventStack.diffs) return {}; var old = eventStack; eventStack = old.parent; localState = clone(eventStack.localState); api.localState = localState; return reverseDiff(old.diffs); } function scaryRedoEvent() { if(!eventStack.children.length) return {}; eventStack = eventStack.children[eventStack.children.length - 1]; localState = clone(eventStack.localState); return eventStack.diffs; } //--------------------------------------------------------- // Dispatch //--------------------------------------------------------- function dispatch(evt, info) { // console.info("[dispatch]", evt, info); var storeEvent = true; var sendToServer = true; var txId = ++localState.txId; var diffs = []; switch(evt) { case "addTable": var id = uuid(); var fieldId = uuid(); diffs.push(["editor item", "inserted", [id, "table"]], ["view", "inserted", [id, "table"]], ["field", "inserted", [id, fieldId, "output"]], ["display order", "inserted", [fieldId, 0]], ["display name", "inserted", [id, "Untitled Table"]], ["display name", "inserted", [fieldId, "A"]]); localState.activeItem = id; localState.adderRows = [[], []]; break; case "addQuery": var id = uuid(); diffs.push(["editor item", "inserted", [id, "query"]], ["display name", "inserted", [id, "Untitled Query"]]); localState.activeItem = id; break; case "addUi": var id = uuid(); var layerId = uuid(); diffs.push(["editor item", "inserted", [id, "ui"]], ["display name", "inserted", [id, "Untitled Page"]], ["uiComponentLayer", "inserted", [txId, layerId, id, 0, false, false, id]], ["display name", "inserted", [layerId, "Page"]]); localState.activeItem = id; localState.uiActiveLayer = layerId; localState.openLayers[layerId] = true; break; case "addUiLayer": var layerId = uuid(); var groupNum = ixer.index("uiComponentToLayers")[info.componentId].length; var groupIx = (ixer.index("parentLayerToLayers")[info.parentLayer] || []).length; diffs.push(["uiComponentLayer", "inserted", [txId, layerId, info.componentId, groupIx, false, false, info.parentLayer]], ["display name", "inserted", [layerId, "Group " + groupNum]]); localState.uiActiveLayer = layerId; localState.openLayers[layerId] = true; break; case "updateUiLayer": var subLayers = code.layerToChildLayers(info.neue); var neueLocked = info.neue[4]; var neueHidden = info.neue[5]; subLayers.forEach(function(sub) { if(sub[4] !== neueLocked || sub[5] !== neueHidden) { var neue = sub.slice(); neue[4] = neueLocked; neue[5] = neueHidden; diffs.push(["uiComponentLayer", "inserted", neue], ["uiComponentLayer", "removed", sub]) } }); diffs.push(["uiComponentLayer", "inserted", info.neue], ["uiComponentLayer", "removed", info.old]) break; case "deleteLayer": var subLayers = code.layerToChildLayers(info.layer); var elementsLookup = ixer.index("uiLayerToElements"); subLayers.push(info.layer); subLayers.forEach(function(sub) { diffs.push(["uiComponentLayer", "removed", sub]); var elements = elementsLookup[sub[1]]; if(elements) { elements.forEach(function(element) { diffs.push(["uiComponentElement", "removed", element]); }); } }); break; case "changeParentLayer": var layer = ixer.index("uiComponentLayer")[info.layerId]; if(layer[6] !== info.parentLayerId) { var neue = layer.slice(); neue[0] = txId; neue[6] = info.parentLayerId; diffs.push(["uiComponentLayer", "inserted", neue], ["uiComponentLayer", "removed", layer]) } break; case "changeElementLayer": var elem = ixer.index("uiComponentElement")[info.elementId]; if(elem[3] !== info.parentLayerId) { var neue = elem.slice(); neue[0] = txId; neue[3] = info.parentLayerId; diffs.push(["uiComponentElement", "inserted", neue], ["uiComponentElement", "removed", elem]) } break; case "rename": var id = info.id; sendToServer = !!info.sendToServer; if(info.value === undefined || info.value === info.initial[1]) { return; } diffs.push(["display name", "inserted", [id, info.value]], ["display name", "removed", info.initial]) break; case "addField": var fieldId = uuid(); var ix = ixer.index("view to fields")[info.table].length; diffs.push(["field", "inserted", [info.table, fieldId, "output"]], // @NOTE: Can this be any other kind? ["display name", "inserted", [fieldId, alphabet[ix]]], ["display order", "inserted", [fieldId, ix]]); break; case "addRow": var ix = ixer.facts(info.table).length; diffs.push([info.table, "inserted", info.neue], ["display order", "inserted", [info.table + JSON.stringify(info.neue), ix]]); break; case "updateRow": sendToServer = info.submit; var oldString = info.table + JSON.stringify(info.old); var ix = info.ix; var neueString = info.table + JSON.stringify(info.neue); if(oldString === neueString) return; diffs.push([info.table, "inserted", info.neue], [info.table, "removed", info.old], ["display order", "removed", [oldString, ix]], ["display order", "inserted", [neueString, ix]]); break; case "addViewBlock": var queryId = (info.queryId !== undefined) ? info.queryId: code.activeItemId(); diffs = diff.addViewBlock(queryId, info.sourceId, info.kind); break; case "addAggregateBlock": var queryId = (info.queryId !== undefined) ? info.queryId: code.activeItemId(); diffs = diff.addAggregateBlock(queryId, info.kind); break; case "addUnionBlock": var queryId = (info.queryId !== undefined) ? info.queryId: code.activeItemId(); diffs = diff.addUnionBlock(queryId); break; case "removeViewBlock": var view = ixer.index("view")[info.viewId]; var blockId = ixer.index("view to block")[info.viewId]; var block = ixer.index("block")[blockId]; var sources = ixer.index("view to sources")[info.viewId] || []; diffs = [["view", "removed", view], ["block", "removed", block]]; for(var ix = 0; ix < sources.length; ix++) { var sourceId = sources[ix][code.ix("source", "source")]; diffs = diffs.concat(diff.removeViewSource(info.viewId, sourceId)); } if(view[code.ix("view", "kind")] === "aggregate") { console.warn("@FIXME: Remove aggregate entries for view on removal."); } break; case "addViewSelection": diffs = diff.addViewSelection(info.viewId, info.sourceId, info.sourceFieldId, info.fieldId); break; case "addUnionSelection": diffs = diff.addViewSelection(info.viewId, info.sourceId, info.sourceFieldId, info.fieldId); // do not send to server unless selects.length = fields.length * sources.length var sourceIdIx = code.ix("source", "source"); var numSources = (ixer.index("view to sources")[info.viewId] || []).reduce(function(memo, source) { if(source[sourceIdIx] !== info.sourceId) { return memo + 1; } return memo; }, 1); var fieldIdIx = code.ix("field", "field"); var numFields = (ixer.index("view to fields")[info.viewId] || []).reduce(function(memo, field) { if(field[fieldIdIx] !== info.fieldId) { return memo + 1; } return memo; }, 1); var selectSourceIx = code.ix("select", "source"); var selectFieldIx = code.ix("select", "view field"); var selects = (ixer.index("view to selects")[info.viewId] || []); var numSelects = selects.reduce(function(memo, select) { if(select[selectSourceIx] !== info.sourceId || select[selectFieldIx] !== info.fieldId) { return memo + 1; } return memo; }, 1); // @FIXME: This went from okay to bad fast. if(numSelects !== numFields * numSources) { sendToServer = false; } else { diffs = diffs.concat(selects.map(function(select) { return ["select", "inserted", select]; })); var sources = ixer.index("view to sources")[info.viewId] || []; diffs = diffs.concat(sources.map(function(source) { return ["source", "inserted", source]; })); var blockFields = ixer.index("view and source to block fields")[info.viewId]["selection"] || []; diffs = diffs.concat(blockFields.map(function(blockField) { return ["block field", "inserted", blockField]; })); var fields = ixer.index("view to fields")[info.viewId] || []; diffs = diffs.concat(fields.map(function(field) { return ["field", "inserted", field]; })); var fieldIdIx = code.ix("field", "field"); diffs = diffs.concat(fields.map(function(field) { var id = field[fieldIdIx]; return ["display name", "inserted", [id, code.name(id)]]; })); } break; case "addViewSource": diffs = diff.addViewSource(info.viewId, info.sourceId, info.kind); var view = ixer.index("view")[info.viewId]; var kind = view[code.ix("view", "kind")]; if(kind === "union") { var selects = (ixer.index("view to selects")[info.viewId] || []); if(selects.length) { sendToServer = false; } } break; case "removeViewSource": diffs = diff.removeViewSource(info.viewId, info.sourceId); break; case "addViewConstraint": diffs = diff.addViewConstraint(info.viewId, {operation: "=", leftSource: info.leftSource, leftField: info.leftField}); sendToServer = false; break; case "groupView": var old = ixer.index("grouped by")[info.inner]; if(old) { throw new Error("Cannot group by multiple views."); } var left = ixer.index("constraint left")[info.constraintId] || []; var innerField = left[code.ix("constraint left", "left field")]; diffs = [["grouped by", "inserted", [info.inner, innerField, info.outer, info.outerField]]]; diffs = diffs.concat(diff.removeViewConstraint(info.constraintId)); break; case "addUiComponentElement": var elemId = uuid(); var neue = [txId, elemId, info.componentId, info.layerId, info.control, info.left, info.top, info.right, info.bottom]; var appStyleId = uuid(); var typStyleId = uuid(); diffs.push(["uiComponentElement", "inserted", neue]); diffs.push(["uiStyle", "inserted", [txId, appStyleId, "appearance", elemId, false]], ["uiStyle", "inserted", [txId, typStyleId, "typography", elemId, false]], ["uiStyle", "inserted", [txId, typStyleId, "content", elemId, false]]); // @TODO: Instead of hardcoding, have a map of special element diff handlers. if(info.control === "map") { var mapId = uuid(); diffs.push(["uiMap", "inserted", [txId, mapId, elemId, 0, 0, 4]], ["uiMapAttr", "inserted", [txId, mapId, "lat", 0]], ["uiMapAttr", "inserted", [txId, mapId, "lng", 0]], ["uiMapAttr", "inserted", [txId, mapId, "zoom", 0]]); } localState.uiSelection = [elemId]; break; case "resizeSelection": storeEvent = false; sendToServer = false; var sel = localState.uiSelection; var elementIndex = ixer.index("uiComponentElement"); var ratioX = info.widthRatio; var ratioY = info.heightRatio; var oldBounds = info.oldBounds; var neueBounds = info.neueBounds; sel.forEach(function(cur) { var elem = elementIndex[cur]; var neue = elem.slice(); neue[0] = txId; //We first find out the relative position of the item in the selection //then adjust by the given ratio and finall add the position of the selection //back in to get the new absolute coordinates neue[5] = Math.floor(((neue[5] - oldBounds.left) * ratioX) + neueBounds.left); //left neue[7] = Math.floor(((neue[7] - oldBounds.right) * ratioX) + neueBounds.right); //right neue[6] = Math.floor(((neue[6] - oldBounds.top) * ratioY) + neueBounds.top); //top neue[8] = Math.floor(((neue[8] - oldBounds.bottom) * ratioY) + neueBounds.bottom); //bottom diffs.push(["uiComponentElement", "inserted", neue], ["uiComponentElement", "removed", elem]); }); break; case "moveSelection": storeEvent = false; sendToServer = false; var sel = localState.uiSelection; var elementIndex = ixer.index("uiComponentElement"); var elem = elementIndex[info.elemId]; var diffX = info.x !== undefined ? info.x - elem[5] : 0; var diffY = info.y !== undefined ? info.y - elem[6] : 0; if(diffX || diffY) { sel.forEach(function(cur) { var elem = elementIndex[cur]; var neue = elem.slice(); neue[0] = txId; neue[3] = info.layer || neue[3]; neue[5] += diffX; //left neue[7] += diffX; //right neue[6] += diffY; //top neue[8] += diffY; //bottom diffs.push(["uiComponentElement", "inserted", neue], ["uiComponentElement", "removed", elem]); }); } break; case "bindGroup": var prev = ixer.index("groupToBinding")[info.groupId]; if(prev) { diffs.push(["uiGroupBinding", "removed", [info.groupId, prev]]); } diffs.push(["uiGroupBinding", "inserted", [info.groupId, info.itemId]]); break; case "bindAttr": var elemId = info.elementId; var attr = info.attr; var field = info.field; var prev = (ixer.index("elementAttrToBinding")[elemId] || {})[attr]; if(prev) { diffs.push(["uiAttrBinding", "removed", [elemId, attr, prev]]); } diffs.push(["uiAttrBinding", "inserted", [elemId, attr, field]]); break; case "stopChangingSelection": var sel = localState.uiSelection; var elementIndex = ixer.index("uiComponentElement"); var elem = elementIndex[info.elemId]; var oldElements = info.oldElements; sel.forEach(function(cur, ix) { var elem = elementIndex[cur]; var old = oldElements[ix]; diffs.push(["uiComponentElement", "inserted", elem], ["uiComponentElement", "removed", old]); }); break; case "offsetSelection": storeEvent = false; sendToServer = false; var sel = localState.uiSelection; var elementIndex = ixer.index("uiComponentElement"); var diffX = info.diffX; var diffY = info.diffY; if(diffX || diffY) { sel.forEach(function(cur) { var elem = elementIndex[cur]; var neue = elem.slice(); neue[0] = txId; neue[3] = info.layer || neue[3]; neue[5] += diffX; //left neue[7] += diffX; //right neue[6] += diffY; //top neue[8] += diffY; //bottom diffs.push(["uiComponentElement", "inserted", neue], ["uiComponentElement", "removed", elem]); }); } break; case "deleteSelection": var sel = localState.uiSelection; var elementIndex = ixer.index("uiComponentElement"); sel.forEach(function(cur) { var elem = elementIndex[cur]; diffs.push(["uiComponentElement", "removed", elem]); }); localState.uiSelection = null; break; case "setAttributeForSelection": storeEvent = info.storeEvent; sendToServer = info.storeEvent; var style = getUiPropertyType(info.property); if(!style) { throw new Error("Unknown attribute type for property:", info.property, "known types:", uiProperties); } var sel = localState.uiSelection; sel.forEach(function(cur) { var id = cur; var styleId = ixer.index("uiElementToStyle")[id][style][1]; var oldProps = ixer.index("uiStyleToAttr")[styleId]; if(oldProps && oldProps[info.property]) { diffs.push(["uiComponentAttribute", "removed", oldProps[info.property]]); } diffs.push(["uiComponentAttribute", "inserted", [0, styleId, info.property, info.value, false]]); }); break; case "stopSetAttributeForSelection": var style = getUiPropertyType(info.property); if(!style) { throw new Error("Unknown attribute type for property:", info.property, "known types:", uiProperties); } var sel = localState.uiSelection; var oldAttrs = info.oldAttrs; sel.forEach(function(cur, ix) { var id = cur; var styleId = ixer.index("uiElementToStyle")[id][style][1]; var oldProps = ixer.index("uiStyleToAttr")[styleId]; if(oldProps && oldProps[info.property]) { diffs.push(["uiComponentAttribute", "inserted", oldProps[info.property]]); } if(oldAttrs[ix]) { diffs.push(["uiComponentAttribute", "removed", oldAttrs[ix]]); } }); break; case "setSelectionStyle": var styleId = info.id; var type = info.type; var sel = localState.uiSelection; sel.forEach(function(id) { var prevStyle = ixer.index("uiElementToStyle")[id][type]; diffs.push(["uiStyle", "inserted", [txId, styleId, type, id, info.shared]], ["uiStyle", "removed", prevStyle]); }); break; case "duplicateSelection": var sel = localState.uiSelection; var elementIndex = ixer.index("uiComponentElement"); sel.forEach(function(cur) { var elem = elementIndex[cur]; var neueId = uuid(); diffs.push.apply(diffs, diff.duplicateElement(elem, neueId, localState.txId++)); }); break; case "updateViewConstraint": var viewId = ixer.index("constraint to view")[info.constraintId]; // @TODO: redesign this to pass in opts directly. var opts = {}; if(info.type === "left") { opts.leftField = info.value; opts.leftSource = info.source; } else if(info.type === "right") { opts.rightField = info.value; opts.rightSource = info.source; } else if(info.type === "operation") { opts.operation = info.value; } diffs = diff.updateViewConstraint(info.constraintId, opts); var constraint = ixer.index("constraint")[info.constraintId]; var constraintLeft = ixer.index("constraint left")[info.constraintId] || []; var constraintRight = ixer.index("constraint right")[info.constraintId] || []; var constraintOperation = ixer.index("constraint operation")[info.constraintId] || []; var constraintFieldIx = code.ix("constraint left", "left field"); var constraintSourceIx = code.ix("constraint left", "left source"); var constraintOperationIx = code.ix("constraint operation", "operation"); opts.leftField = opts.leftField || constraintLeft[constraintFieldIx]; opts.leftSource = opts.leftSource || constraintLeft[constraintSourceIx]; opts.RightField = opts.RightField || constraintRight[constraintFieldIx]; opts.RightSource = opts.RightSource || constraintRight[constraintSourceIx]; opts.operation = opts.operation || constraintOperation[constraintOperationIx]; if(opts.leftField && opts.leftSource && opts.rightField && opts.rightSource && opts.operation) { diffs.push(["constraint", "inserted", constraint]); if(info.type !== "left") { diffs.push(["constraint left", "inserted", constraintLeft]); } if(info.type !== "right") { diffs.push(["constraint right", "inserted", constraintRight]); } if(info.type !== "operation") { diffs.push(["constraint operation", "inserted", constraintOperation]); } } else { sendToServer = false; console.log("incomplete"); } break; case "removeViewConstraint": diffs = diff.removeViewConstraint(info.constraintId); break; case "undo": storeEvent = false; diffs = scaryUndoEvent(); break; case "redo": storeEvent = false; diffs = scaryRedoEvent(); break; default: console.error("Unhandled dispatch:", evt, info); break; } if(diffs && diffs.length) { if(storeEvent) { var eventItem = {event: event, diffs: diffs, children: [], parent: eventStack, localState: clone(localState)}; eventStack.children.push(eventItem); eventStack = eventItem; } ixer.handleDiffs(diffs); if(sendToServer) { window.client.sendToServer(diffs); } render(); } else { // console.warn("No diffs to index, skipping."); } } //--------------------------------------------------------- // Root //--------------------------------------------------------- function root() { var itemId = code.activeItemId(); var type = ixer.index("editor item to type")[itemId]; var workspace; if(type === "query") { workspace = queryWorkspace(itemId); } else if(type === "ui") { workspace = uiWorkspace(itemId); } else if(type === "table") { workspace = tableWorkspace(itemId); } return {id: "root", c: "root", children: [ editorItemList(itemId), workspace, ]}; } function editorItemList(itemId) { var items = ixer.facts("editor item").map(function(cur) { var id = cur[0]; var type = cur[1]; var klass = "editor-item " + type; var icon = "ion-grid"; if(type === "query") { icon = "ion-cube"; } else if(type === "ui") { icon = "ion-image"; } if(itemId === id) { klass += " selected"; } return {c: klass, click: selectEditorItem, dblclick: closeSelectEditorItem, dragData: {value: id, type: "view"}, itemId: id, draggable: true, dragstart: dragItem, children: [ {c: "icon " + icon}, {text: code.name(id)}, ]}; }) var width = 0; if(localState.showMenu) { width = 200; } return {c: "editor-item-list", width:width, children: [ {c: "title", click: toggleMenu, text: "items"}, {c: "adder", children: [ {c: "button table", click: addItem, event: "addTable", children: [ {c: "ion-grid"}, {c: "ion-plus"}, ]}, {c: "button query", click: addItem, event: "addQuery", children: [ {c: "ion-cube"}, {c: "ion-plus"}, ]}, {c: "button ui", click: addItem, event: "addUi", children: [ {c: "ion-image"}, {c: "ion-plus"}, ]}, ]}, {c: "items", children: items} ]}; } function addItem(e, elem) { dispatch(elem.event, {}); } function selectEditorItem(e, elem) { localState.activeItem = elem.itemId; var type = ixer.index("editor item to type")[elem.itemId]; if(type === "table") { localState.adderRows = [[], []]; } else if(type === "ui") { var layer = ixer.index("parentLayerToLayers")[elem.itemId][0]; localState.uiActiveLayer = layer[1]; } render(); } function closeSelectEditorItem(e, elem) { localState.showMenu = false; selectEditorItem(e, elem); } function genericWorkspace(klass, controls, options, content) { var finalControls = controls; if(!localState.showMenu) { var finalControls = [{c: "menu-toggle", click: toggleMenu, text: "items"}].concat(controls); } return {id: "workspace", c: "workspace-container " + klass, children: [ {c: "control-bar", children: finalControls}, {c: "option-bar", children: options}, {c: "content", children: [content]} ]}; } function toggleMenu() { localState.showMenu = !localState.showMenu; render(); } function controlGroup(controls) { return {c: "control-group", children: controls}; } //--------------------------------------------------------- // Table workspace //--------------------------------------------------------- function tableWorkspace(tableId) { var fields = ixer.index("view to fields")[tableId].map(function(cur) { return {name: code.name(cur[1]), id: cur[1]}; }); var rows = ixer.facts(tableId); var order = ixer.index("display order"); rows.sort(function(a, b) { var aIx = order[tableId + JSON.stringify(a)]; var bIx = order[tableId + JSON.stringify(b)]; return aIx - bIx; }); return genericWorkspace("", [], [input(code.name(tableId), tableId, rename, rename)], {c: "table-editor", children: [ virtualizedTable(tableId, fields, rows, true) ]}); } function rename(e, elem, sendToServer) { var value = e.currentTarget.textContent; if(value !== undefined) { dispatch("rename", {value: value, id: elem.key, sendToServer: sendToServer, initial: [localState.initialKey, localState.initialValue]}); } } function virtualizedTable(id, fields, rows, isEditable) { var ths = fields.map(function(cur) { var oninput, onsubmit; if(cur.id) { oninput = onsubmit = rename; } return {c: "header", children: [input(cur.name, cur.id, oninput, onsubmit)]}; }); if(isEditable) { ths.push({c: "header add-column ion-plus", click: addField, table: id}); } var trs = []; rows.forEach(function(cur, rowIx) { var tds = []; for(var tdIx = 0, len = fields.length; tdIx < len; tdIx++) { tds[tdIx] = {c: "field"}; // @NOTE: We can hoist this if perf is an issue. if(isEditable) { tds[tdIx].children = [input(cur[tdIx], {rowIx: rowIx, row: cur, ix: tdIx, view: id}, updateRow, submitRow)]; } else { tds[tdIx].text = cur[tdIx]; } } trs.push({c: "row", children: tds}); }) if(isEditable) { var adderRows = localState.adderRows; adderRows.forEach(function(cur, rowNum) { var tds = []; for(var i = 0, len = fields.length; i < len; i++) { tds[i] = {c: "field", children: [input(cur[i], {row: cur, numFields:len, rowNum: rowNum, ix: i, view: id}, updateAdder, maybeSubmitAdder)]}; } trs.push({c: "row", children: tds}); }); } // trs.push({id: "spacer2", c: "spacer", height: Math.max(totalRows - start - numRows, 0) * itemHeight}); return {c: "table", children: [ {c: "headers", children: ths}, {c: "rows", children: trs} ]}; } function addField(e, elem) { dispatch("addField", {table: elem.table}); } function updateAdder(e, elem) { var key = elem.key; var row = localState.adderRows[key.rowNum]; row[key.ix] = coerceInput(e.currentTarget.textContent); } function maybeSubmitAdder(e, elem, type) { var key = elem.key; var row = localState.adderRows[key.rowNum]; row[key.ix] = coerceInput(e.currentTarget.textContent); if(row.length !== key.numFields) { return; } var isValid = row.every(function(cell) { return cell !== undefined; }); if(!isValid) { return; } localState.adderRows.splice(key.rowNum, 1); if(localState.adderRows.length <= 1) { localState.adderRows.push([]); } dispatch("addRow", {table: key.view, neue: row}); } function updateRow(e, elem) { var neue = elem.key.row.slice(); neue[elem.key.ix] = coerceInput(e.currentTarget.textContent); dispatch("updateRow", {table: elem.key.view, ix:localState.initialKey.rowIx, old: elem.key.row.slice(), neue: neue, submit: false}) } function submitRow(e, elem, type) { var neue = elem.key.row.slice(); neue[elem.key.ix] = coerceInput(e.currentTarget.textContent); dispatch("updateRow", {table: elem.key.view, ix:localState.initialKey.rowIx, old: localState.initialKey.row.slice(), neue: neue, submit: true}) } function input(value, key, oninput, onsubmit) { var blur, keydown; if(onsubmit) { blur = function inputBlur(e, elem) { onsubmit(e, elem, "blurred"); } keydown = function inputKeyDown(e, elem) { if(e.keyCode === KEYS.ENTER) { onsubmit(e, elem, "enter"); } } } return {c: "input text-input", contentEditable: true, input: oninput, focus: storeInitialInput, text: value, key: key, blur: blur, keydown: keydown}; } function storeInitialInput(e, elem) { localState.initialKey = elem.key; localState.initialValue = elem.text; } //--------------------------------------------------------- // UI workspace //--------------------------------------------------------- function uiWorkspace(componentId) { var elements = ixer.index("uiComponentToElements")[componentId] || []; var layers = ixer.index("uiComponentToLayers")[componentId] || []; var layerLookup = ixer.index("uiComponentLayer"); var activeLayerId = localState.uiActiveLayer; if(activeLayerId && layerLookup[activeLayerId]) { activeLayer = layerLookup[activeLayerId]; } var selectionInfo = getSelectionInfo(componentId, true); var canvasLayers = (ixer.index("parentLayerToLayers")[componentId] || []).map(function(layer) { return canvasLayer(layer, selectionInfo); }); if(selectionInfo) { canvasLayers.push(selection(selectionInfo)); } if(localState.boxSelectStart) { var rect = boxSelectRect(); canvasLayers.push({c: "box-selection", top: rect.top, left: rect.left, width: rect.width, height: rect.height}); } return genericWorkspace("query", [uiControls(componentId, activeLayer)], uiInspectors(componentId, selectionInfo, layers, activeLayer), {c: "ui-editor", children: [ {c: "ui-canvas", componentId: componentId, children: canvasLayers, mousedown: startBoxSelection, mouseup: stopBoxSelection, mousemove: adjustBoxSelection}, layersBox(componentId, layers, activeLayer), ]}); } function canvasLayer(layer, selectionInfo) { var layerId = layer[1]; var subLayers = (ixer.index("parentLayerToLayers")[layerId] || []).map(function(sub) { return canvasLayer(sub, selectionInfo); }); if(selectionInfo && layerId === localState.uiActiveLayer) { subLayers.unshift(uiGrid()); } var elements = ixer.index("uiLayerToElements")[layerId] || []; var attrsIndex = ixer.index("uiStyleToAttrs"); var stylesIndex = ixer.index("uiElementToStyles"); var els = elements.map(function(cur) { var id = cur[1]; var selected = selectionInfo ? selectionInfo.selectedIds[id] : false; var attrs = []; var styles = stylesIndex[id] || []; for(var ix = 0, len = styles.length; ix < len; ix++) { var style = styles[ix]; attrs.push.apply(attrs, attrsIndex[style[1]]); } return control(cur, attrs, selected, layer); }); return {c: "ui-canvas-layer", id: layer[1], zIndex: layer[3] + 1, children: subLayers.concat(els)}; } function layersBox(componentId, layers, activeLayer) { var parentIndex = ixer.index("parentLayerToLayers"); var rootLayers = parentIndex[componentId] || []; rootLayers.sort(function(a, b) { return a[3] - b[3]; }); var items = rootLayers.map(function(cur) { return layerListItem(cur, 0) }); return {c: "layers-box", children: [ {c: "controls", children: [ {c: "add-layer ion-plus", click: addLayer, componentId: componentId}, {c: "add-layer ion-ios-trash", click: deleteLayer, componentId: componentId}, ]}, {c: "layers-list", children: items} ]}; } function addLayer(e, elem) { localState.openLayers[localState.uiActiveLayer] = true; dispatch("addUiLayer", {componentId: elem.componentId, parentLayer: localState.uiActiveLayer}) } function deleteLayer(e, elem) { var layerId = localState.uiActiveLayer; var layer = ixer.index("uiComponentLayer")[layerId]; localState.uiActiveLayer = layer[6]; localState.uiSelection = false; dispatch("deleteLayer", {layer: layer}); } function layerListItem(layer, depth) { var layerId = layer[1]; var isOpen = localState.openLayers[layerId]; var subItems = []; var indent = 15; if(isOpen) { var binding = ixer.index("groupToBinding")[layerId]; if(binding) { var fieldItems = code.sortedViewFields(binding).map(function(field) { return {c: "layer-element group-binding", children: [ {c: "layer-row", draggable:true, dragstart: layerDrag, type: "binding", itemId: field, children:[ {c: "icon ion-ios-arrow-thin-right"}, {text: code.name(field)} ]}, ]} }); subItems.push({c: "layer-element group-binding", children: [ {c: "layer-row", children:[ {c: "icon ion-ios-photos"}, {text: code.name(binding)} ]}, {c: "layer-items", children: fieldItems} ]}); } var subLayers = ixer.index("parentLayerToLayers")[layerId]; if(subLayers) { subLayers.sort(function(a, b) { return a[3] - b[3]; }); subLayers.forEach(function(cur) { subItems.push(layerListItem(cur, depth+1)); }); } var elements = ixer.index("uiLayerToElements")[layerId] || []; elements.forEach(function(cur) { var elemId = cur[1]; var selectedClass = ""; if(localState.uiSelection && localState.uiSelection.indexOf(elemId) > -1) { selectedClass = " selected"; } subItems.push({c: "layer-element depth-" + (depth + 1) + selectedClass, control: cur, click: addToSelection, children: [ {c: "layer-row", itemId: elemId, draggable:true, dragstart: layerDrag, type: "element", children:[ {c: "icon ion-ios-crop" + (selectedClass ? "-strong" : "")}, {text: cur[4]} ]} ]}); }); } var icon = isOpen ? "ion-ios-arrow-down" : "ion-ios-arrow-right"; var activeClass = localState.uiActiveLayer === layerId ? " active" : ""; var lockedClass = layer[4] ? "ion-locked" : "ion-unlocked"; var hiddenClass = layer[5] ? "ion-eye-disabled" : "ion-eye"; return {c: "layer-item depth-" + depth + activeClass, layerId: layerId, dragover: preventDefault, drop: layerDrop, click: activateLayer, dblclick: selectAllFromLayer, children: [ {c: "layer-row", draggable: true, itemId: layerId, dragstart: layerDrag, type: "layer", children:[ {c: "icon " + icon, click: toggleOpenLayer, layerId: layerId}, input(code.name(layerId), layerId, rename, rename), {c: "controls", children: [ {c: hiddenClass, click: toggleHidden, dblclick:stopPropagation, layer: layer}, {c: lockedClass, click: toggleLocked, dblclick:stopPropagation, layer: layer}, ]} ]}, {c: "layer-items", children: subItems} ]}; } function toggleOpenLayer(e, elem) { localState.openLayers[elem.layerId] = !localState.openLayers[elem.layerId]; render(); } function layerDrag(e, elem) { e.dataTransfer.setData("type", elem.type); e.dataTransfer.setData("itemId", elem.itemId); e.stopPropagation(); } function layerDrop(e, elem) { e.stopPropagation(); var type = e.dataTransfer.getData("type"); if(type === "view" || type === "table" || type === "query") { //if it's a data item, then we need to setup a binding dispatch("bindGroup", {groupId: elem.layerId, itemId: e.dataTransfer.getData("value")}); } else if(type === "layer") { //if it's a layer, we need to reparent it var layerId = e.dataTransfer.getData("itemId"); if(layerId === elem.layerId) return; dispatch("changeParentLayer", {parentLayerId: elem.layerId, layerId: layerId}); } else if(type === "element") { //if it's an element, set the layer var elementId = e.dataTransfer.getData("itemId"); dispatch("changeElementLayer", {parentLayerId: elem.layerId, elementId: elementId}); } } function activateLayer(e, elem) { e.stopPropagation(); if(localState.uiActiveLayer !== elem.layerId) { localState.uiActiveLayer = elem.layerId; clearSelection(); } } function selectAllFromLayer(e, elem) { e.stopPropagation(); var layer = ixer.index("uiComponentLayer")[elem.layerId]; if(layer[4] || layer[5]) return; var elements = ixer.index("uiLayerToElements")[elem.layerId] || []; var sel = e.shiftKey ? localState.uiSelection : []; elements.forEach(function(cur) { sel.push(cur[1]); }); if(sel.length) { localState.uiSelection = sel; } else { localState.uiSelection = false; } render(); } function toggleHidden(e, elem) { e.stopPropagation(); //@TODO: this needs to recursively hide or unhide sub groups var neue = elem.layer.slice(); neue[5] = !neue[5]; dispatch("updateUiLayer", {neue: neue, old: elem.layer}); } function toggleLocked(e, elem) { e.stopPropagation(); //@TODO: this needs to recursively lock or unlock sub groups var neue = elem.layer.slice(); neue[4] = !neue[4]; dispatch("updateUiLayer", {neue: neue, old: elem.layer}); } function boxSelectRect() { var start = localState.boxSelectStart; var stop = localState.boxSelectStop; var topBottom = start[1] < stop[1] ? [start[1], stop[1]] : [stop[1], start[1]]; var leftRight = start[0] < stop[0] ? [start[0], stop[0]] : [stop[0], start[0]]; var width = leftRight[1] - leftRight[0]; var height = topBottom[1] - topBottom[0]; return {top: topBottom[0], bottom: topBottom[1], left: leftRight[0], right: leftRight[1], width: width, height: height}; } function startBoxSelection(e, elem) { if(!e.shiftKey) { clearSelection(e, elem); } var x = e.clientX; var y = e.clientY; var canvasRect = e.currentTarget.getBoundingClientRect(); x -= Math.floor(canvasRect.left); y -= Math.floor(canvasRect.top); localState.boxSelectStart = [x, y]; localState.boxSelectStop = [x, y]; render(); } function adjustBoxSelection(e, elem) { if(!localState.boxSelectStart) return; var x = e.clientX; var y = e.clientY; var canvasRect = e.currentTarget.getBoundingClientRect(); x -= Math.floor(canvasRect.left); y -= Math.floor(canvasRect.top); localState.boxSelectStop[0] = x; localState.boxSelectStop[1] = y; render(); } function elementIntersects(elem, rect) { var left = elem[5]; var top = elem[6]; var right = elem[7]; var bottom = elem[8]; return !(rect.left > right || rect.right < left || rect.top > bottom || rect.bottom < top); } function stopBoxSelection(e, elem) { if(!localState.boxSelectStart) return; var sel = e.shiftKey ? localState.uiSelection : []; var rect = boxSelectRect(); var componentId = elem.componentId; var elems = ixer.index("uiComponentToElements")[componentId]; var layerLookup = ixer.index("uiComponentLayer"); if(elems) { elems.forEach(function(cur) { // @TODO: this allows you to select from layers that are either hidden or locked var elemId = cur[1]; var layer = layerLookup[cur[3]]; if(layer[4] || layer[5]) return; if(elementIntersects(cur, rect)) { sel.push(elemId); } }); } localState.boxSelectStart = null; localState.boxSelectStop = null; if(sel.length) { localState.uiSelection = sel; } else { localState.uiSelection = false; } render(); } function canvasRatio(context) { var devicePixelRatio = window.devicePixelRatio || 1; var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; return devicePixelRatio / backingStoreRatio; } function uiGrid() { return {c: "grid", id: "ui-editor-grid", t: "canvas", top: 0, left: 0, postRender: function(canvas) { var uiGridCount = 3000; if(canvas._rendered) return; var bounds = document.querySelector(".ui-canvas").getBoundingClientRect(); var ctx = canvas.getContext("2d"); var ratio = canvasRatio(ctx); canvas.width = bounds.width * ratio; canvas.height = bounds.height * ratio; canvas.style.width = bounds.width; canvas.style.height = bounds.height; ctx.scale(ratio, ratio); ctx.lineWidth = 1; ctx.strokeStyle = "#999999"; for(var i = 0; i < uiGridCount; i++) { if(i % localState.uiGridSize === 0) { ctx.globalAlpha = 0.3; } else { ctx.globalAlpha = 0.1; } ctx.beginPath(); ctx.moveTo(i * localState.uiGridSize, 0); ctx.lineTo(i * localState.uiGridSize, bounds.height * 2); ctx.stroke(); ctx.beginPath(); ctx.moveTo(0, i * localState.uiGridSize); ctx.lineTo(bounds.width * 2, i * localState.uiGridSize); ctx.stroke(); } canvas._rendered = true; }}; } var resizeHandleSize = 7; function resizeHandle(componentId, bounds, y, x) { var top, left; var halfSize = Math.floor(resizeHandleSize / 2); var height = bounds.bottom - bounds.top; var width = bounds.right - bounds.left; if(x === "left") { left = 0 - halfSize - 1; } else if(x === "right") { left = width - halfSize - 2; } else { left = (width / 2) - halfSize; } if(y === "top") { top = 0 - halfSize - 1; } else if(y === "bottom") { top = height - halfSize - 2; } else { top = (height / 2) - halfSize; } return {c: "resize-handle", y: y, x: x, top: top, left: left, width: resizeHandleSize, height: resizeHandleSize, componentId: componentId, draggable: true, drag: resizeSelection, dragend: stopResizeSelection, bounds: bounds, dragstart: startResizeSelection, mousedown: stopPropagation}; } function stopPropagation(e) { e.stopPropagation(); } function preventDefault(e) { e.preventDefault(); } function clearDragImage(e, elem) { if(e.dataTransfer) { e.dataTransfer.setData("text", "foo"); e.dataTransfer.setDragImage(document.getElementById("clear-pixel"), 0, 0); } } function startResizeSelection(e, elem) { localState.oldElements = selectionToElements(); clearDragImage(e); } function stopResizeSelection(e, elem) { var elems = localState.oldElements; localState.oldElements = null; dispatch("stopChangingSelection", {oldElements: elems}) } function resizeSelection(e, elem) { var x = Math.floor(e.clientX || __clientX); var y = Math.floor(e.clientY || __clientY); if(x === 0 && y === 0) return; var canvasRect = e.currentTarget.parentNode.parentNode.getBoundingClientRect(); x -= Math.floor(canvasRect.left); y -= Math.floor(canvasRect.top); var old = elem.bounds; var neueBounds = {left: old.left, right: old.right, top: old.top, bottom: old.bottom}; if(elem.x === "left") { neueBounds.left = toGrid(localState.uiGridSize, x); } else if(elem.x === "right") { neueBounds.right = toGrid(localState.uiGridSize, x); } if(elem.y === "top") { neueBounds.top = toGrid(localState.uiGridSize, y); } else if(elem.y === "bottom") { neueBounds.bottom = toGrid(localState.uiGridSize, y); } var neueWidth = neueBounds.right - neueBounds.left; var neueHeight = neueBounds.bottom - neueBounds.top; if(neueWidth < 10) { neueWidth = 10; if(elem.x === "left") { neueBounds.left = neueBounds.right - 10; } else { neueBounds.right = neueBounds.left + 10; } } if(neueHeight < 10) { neueHeight = 10; if(elem.y === "top") { neueBounds.top = neueBounds.bottom - 10; } else { neueBounds.bottom = neueBounds.top + 10; } } var widthRatio = neueWidth / (old.right - old.left); var heightRatio = neueHeight / (old.bottom - old.top); if(widthRatio !== 1 || heightRatio !== 1) { dispatch("resizeSelection", {widthRatio: widthRatio, heightRatio: heightRatio, oldBounds: old, neueBounds: neueBounds, componentId: elem.componentId}); elem.bounds = neueBounds; } } function selection(selectionInfo) { var componentId = selectionInfo.componentId; var bounds = selectionInfo.bounds; return {c: "selection", top: bounds.top, left: bounds.left, width: bounds.right - bounds.left, height: bounds.bottom - bounds.top, children: [ resizeHandle(componentId, bounds, "top", "left"), resizeHandle(componentId, bounds, "top", "center"), resizeHandle(componentId, bounds, "top", "right"), resizeHandle(componentId, bounds, "middle", "right"), resizeHandle(componentId, bounds, "bottom", "right"), resizeHandle(componentId, bounds, "bottom", "center"), resizeHandle(componentId, bounds, "bottom", "left"), resizeHandle(componentId, bounds, "middle", "left"), {c: "trash ion-ios-trash", componentId: componentId, mousedown:stopPropagation, click: deleteSelection}, ]}; } function deleteSelection(e, elem) { dispatch("deleteSelection", {componentId: elem.componentId}); } function clearSelection(e, elem) { localState.uiSelection = null; render(); } function control(cur, attrs, selected, layer) { var id = cur[1]; var type = cur[4]; var selClass = selected ? " selected" : ""; var hidden = layer[5] ? " hidden" : ""; var locked = layer[4] ? " locked" : ""; var klass = type + " ui-element" + selClass + hidden + locked; var elem = {c: klass, id: "elem" + id, left: cur[5], top: cur[6], width: cur[7] - cur[5], height: cur[8] - cur[6], control: cur, mousedown: addToSelection, selected: selected, zIndex: layer[3] + 1, draggable: true, dragover: preventDefault, drop: dropOnControl, drag: moveSelection, dragend: stopMoveSelection, dragstart: startMoveSelection, dblclick: setModifyingText}; if(attrs) { for(var i = 0, len = attrs.length; i < len; i++) { var curAttr = attrs[i]; var name = attrMappings[curAttr[2]] || curAttr[2]; if(curAttr[3].constructor !== Array) { elem[name] = curAttr[3]; } } } if(type === "image") { elem.attr = "backgroundImage"; } else { elem.attr = "text"; } var binding = (ixer.index("elementAttrToBinding")[id] || {})[elem.attr]; if(binding) { elem.children = [ {c: "attr-binding", children: [ {c: "icon ion-ios-arrow-thin-right"}, {text: code.name(binding)} ]} ]; elem.text = undefined; } if(localState.modifyingUiText === id) { if(type === "image") { var curInput = input(elem.backgroundImage, {id: id}, updateImage, submitContent); curInput.postRender = focusOnce; elem.children = [curInput]; curInput.attr = "backgroundImage"; elem.text = undefined; } else { var curInput = input(elem.text, {id: id}, updateContent, submitContent); curInput.postRender = focusOnce; elem.children = [curInput]; curInput.attr = "text"; elem.text = undefined; } } // if(uiCustomControlRender[type]) { // elem = uiCustomControlRender[type](elem); // } return elem; } function dropOnControl(e, elem) { var type = e.dataTransfer.getData("type"); if(type === "binding") { dispatch("bindAttr", {attr: elem.attr, elementId: elem.control[1], field: e.dataTransfer.getData("itemId")}) e.stopPropagation(); } } function setModifyingText(e, elem) { localState.modifyingUiText = elem.control[1]; startAdjustAttr(e, elem); render(); } function updateContent(e, elem) { dispatch("setAttributeForSelection", {componentId: elem.key.id, property: "text", value: e.currentTarget.textContent}); } function updateImage(e, elem) { dispatch("setAttributeForSelection", {componentId: elem.key.id, property: "backgroundImage", value: e.currentTarget.textContent}); } function submitContent(e, elem) { localState.modifyingUiText = false; dispatch("stopSetAttributeForSelection", {oldAttrs: localState.initialAttrs, property: elem.attr}); render(); } function addToSelection(e, elem) { e.stopPropagation(); if(elem.selected) return; if(!e.shiftKey || !localState.uiSelection) { localState.uiSelection = []; } var layer = ixer.index("uiComponentLayer")[elem.control[3]]; if(layer[4] || layer[5]) return; localState.uiSelection.push(elem.control[1]); localState.uiActiveLayer = elem.control[3]; render(); } var __clientX, __clientY; document.body.addEventListener("dragover", function(e) { //@HACK: because Firefox is a browser full of sadness, they refuse to //set clientX and clientY on drag events. As such we have this ridiculous //workaround of tracking position at the body. __clientX = e.clientX; __clientY = e.clientY; }); function toGrid(size, value) { return Math.round(value / size) * size; } function startMoveSelection(e, elem) { var x = e.clientX || __clientX; var y = e.clientY || __clientY; if(x === 0 && y === 0) return; var canvasRect = e.currentTarget.parentNode.getBoundingClientRect(); localState.dragOffsetX = x - elem.left - canvasRect.left; localState.dragOffsetY = y - elem.top - canvasRect.top; localState.initialElements = selectionToElements(); clearDragImage(e); if(e.altKey) { //@HACK: if you cause a rerender before the event finishes, the drag is killed? setTimeout(function() { dispatch("duplicateSelection", {componentId: elem.control[2]}); }, 0); } } function moveSelection(e, elem) { var x = Math.floor(e.clientX || __clientX); var y = Math.floor(e.clientY || __clientY); if(x === 0 && y === 0) return; var canvasRect = e.currentTarget.parentNode.getBoundingClientRect(); x -= Math.floor(canvasRect.left); y -= Math.floor(canvasRect.top); var neueX = toGrid(localState.uiGridSize, Math.floor(x - localState.dragOffsetX)); var neueY = toGrid(localState.uiGridSize, Math.floor(y - localState.dragOffsetY)); dispatch("moveSelection", {x: neueX, y: neueY, elemId: elem.control[1], componentId: elem.control[2]}); } function stopMoveSelection(e, elem) { var elems = localState.initialElements; localState.initialElements = null; dispatch("stopChangingSelection", {oldElements: elems}) } function selectionToElements() { if(localState.uiSelection) { var elementIndex = ixer.index("uiComponentElement"); return localState.uiSelection.map(function(cur) { return elementIndex[cur]; }); } return []; } function getSelectionInfo(componentId, withAttributes) { var sel = localState.uiSelection; var elements; if(sel) { var elementIndex = ixer.index("uiComponentElement"); elements = sel.map(function(cur) { return elementIndex[cur]; }); var result = getGroupInfo(elements, withAttributes); result.componentId = componentId; result.selectedIds = result.ids; return result; } return false; } function getGroupInfo(elements, withAttributes) { elements = elements || []; var attrsIndex = ixer.index("uiStyleToAttrs"); var stylesIndex = ixer.index("uiElementToStyles"); var ids = {}; var attributes = {}; var styles = {}; var els = elements.map(function(cur) { var id = cur[1]; ids[id] = true; if(withAttributes !== undefined) { var elStyles = stylesIndex[id]; if(!elStyles) { return cur; } var attrs = []; for(var ix = 0, len = elStyles.length; ix < len; ix++) { var style = elStyles[ix]; var type = style[2]; if(styles[type] === undefined) { styles[type] = style; } else if(!style || !styles[type] || styles[type][1] !== style[1]) { styles[type] = null; } attrs.push.apply(attrs, attrsIndex[style[1]]); } if(attrs) { attrs.forEach(function(cur) { var key = cur[2]; var value = cur[3]; if(attributes[key] === undefined) { attributes[key] = value; } else if(attributes[key] !== value) { attributes[key] = null; } }); } } return cur; }); var bounds = boundElements(els); return {ids: ids, elements: els, bounds: bounds, attributes: attributes, styles: styles}; } function boundElements(elems) { var bounds = {top: Infinity, left: Infinity, bottom: -Infinity, right: -Infinity}; elems.forEach(function(cur) { var left = cur[5], top = cur[6], right = cur[7], bottom = cur[8]; if(left < bounds.left) { bounds.left = left; } if(top < bounds.top) { bounds.top = top; } if(right > bounds.right) { bounds.right = right; } if(bottom > bounds.bottom) { bounds.bottom = bottom; } }); return bounds; } var uiControlInfo = [{text: "text", icon: ""}, {text: "image", icon: ""}, {text: "box", icon: ""}, {text: "button", icon: ""}, {text: "input", icon: ""}, {text: "map", icon: ""} ]; function uiControls(componentId, activeLayer) { var items = uiControlInfo.map(function(cur) { return {c: "control", click: addElement, controlType: cur.text, componentId: componentId, layer: activeLayer, children: [ {c: "icon"}, {text: cur.text} ]}; }) return controlGroup(items); } function addElement(e, elem) { dispatch("addUiComponentElement", {componentId: elem.componentId, layerId: elem.layer[1], control: elem.controlType, left: elem.left || 100, right: elem.right || 200, top: elem.top || 100, bottom: elem.bottom || 200}) } var attrMappings = {"content": "text"}; var uiProperties = {}; function uiInspectors(componentId, selectionInfo, layers, activeLayer) { var inspectors = []; var activeLayerId; var binding; var elements; if(activeLayer) { activeLayerId = activeLayer[1]; elements = ixer.index("uiLayerToElements")[activeLayerId]; binding = ixer.index("groupToBinding")[activeLayerId]; } if(selectionInfo) { // @TODO: Only show appropriate inspectors for each type based on trait instead of hardcoding. inspectors.push(layoutInspector(selectionInfo, binding), appearanceInspector(selectionInfo, binding), textInspector(selectionInfo, binding)); // var showMapInspector = selectionInfo.elements.every(function(cur) { // return cur[4] === "map"; // }); // if(showMapInspector) { // var mapInfo = getMapGroupInfo(selectionInfo.elements, true) // inspectors.push(mapInspector(selectionInfo, mapInfo, binding)); // } } else if(activeLayer) { inspectors.push(layerInspector(activeLayer, elements)); } return inspectors; } function adjustable(value, start, stop, step) { return {c: "adjustable", mousedown: startAdjusting, adjustHandler: adjustAdjustable, value: value, start: start, stop: stop, step: step, text: value}; } var adjustableShade = document.createElement("div"); adjustableShade.className = "adjustable-shade"; adjustableShade.addEventListener("mousemove", function(e) { if(adjusterInfo) { adjusterInfo.handler(e, renderer.tree[adjusterInfo.elem.id]); } }) adjustableShade.addEventListener("mouseup", function(e) { if(adjusterInfo.elem.finalizer) { adjusterInfo.elem.finalizer(e, renderer.tree[adjusterInfo.elem.id]); } adjusterInfo = false; document.body.removeChild(adjustableShade); }) var adjusterInfo; function startAdjusting(e, elem) { if(elem.initializer) { elem.initializer(e, elem); } adjusterInfo = {elem: elem, startValue: elem.value, handler: elem.adjustHandler, bounds: {left: e.clientX, top: e.clientY}}; document.body.appendChild(adjustableShade); } function adjustAdjustable(e, elem) { var x = e.clientX || __clientX; var y = e.clientY || __clientY; if(x === 0 && y === 0) return; var rect = adjusterInfo.bounds; var offsetX = Math.floor(x - rect.left); var offsetY = Math.floor(y - rect.top); var adjusted = Math.floor(adjusterInfo.startValue + offsetX); var neue = Math.min(Math.max(elem.start, adjusted), elem.stop); if(elem.handler) { elem.handler(elem, neue); } } uiProperties.layout = ["top", "left", "width", "height"]; function layoutInspector(selectionInfo, binding) { var componentId = selectionInfo.componentId; var bounds = selectionInfo.bounds; var width = bounds.right - bounds.left; var height = bounds.bottom - bounds.top; var widthAdjuster = adjustable(width, 1, 1000, 1); widthAdjuster.handler = adjustWidth; widthAdjuster.componentId = componentId; widthAdjuster.bounds = bounds; widthAdjuster.initializer = startResizeSelection; widthAdjuster.finalizer = stopResizeSelection; var heightAdjuster = adjustable(height, 1, 1000, 1); heightAdjuster.handler = adjustHeight; heightAdjuster.componentId = componentId; heightAdjuster.bounds = bounds; heightAdjuster.initializer = startResizeSelection; heightAdjuster.finalizer = stopResizeSelection; var topAdjuster = adjustable(bounds.top, 0, 100000, 1); topAdjuster.handler = adjustPosition; topAdjuster.componentId = componentId; topAdjuster.coord = "top"; topAdjuster.initializer = startMoveSelection; topAdjuster.finalizer = stopMoveSelection; var leftAdjuster = adjustable(bounds.left, 0, 100000, 1); leftAdjuster.handler = adjustPosition; leftAdjuster.componentId = componentId; leftAdjuster.coord = "left"; leftAdjuster.initializer = startMoveSelection; leftAdjuster.finalizer = stopMoveSelection; //pos, size return {c: "option-group", children: [ {c: "label", text: "x:"}, leftAdjuster, {c: "label", text: "y:"}, topAdjuster, {c: "label", text: "w:"}, widthAdjuster, {c: "label", text: "h:"}, heightAdjuster, ]}; } uiProperties.appearance = ["backgroundColor", "backgroundImage", "borderColor", "borderWidth", "borderRadius", "opacity"]; function appearanceInspector(selectionInfo, binding) { var attrs = selectionInfo.attributes; var componentId = selectionInfo.componentId; var styleName; if(selectionInfo.styles.appearance && selectionInfo.styles.appearance[4]) { styleName = {value:selectionInfo.styles.appearance[1], text: code.name(selectionInfo.styles.appearance[1])}; } else { styleName = {text: "No visual style", value: "none"}; } var borderColorPicker = colorSelector(componentId, "borderColor", attrs["borderColor"]); borderColorPicker.backgroundColor = undefined; var opacity = attrs["opacity"] == undefined ? 100 : attrs["opacity"] * 100; var opacityAdjuster = adjustable(opacity, 0, 100, 1); opacityAdjuster.text = Math.floor(opacity) + "%"; opacityAdjuster.handler = adjustOpacity; opacityAdjuster.componentId = componentId; opacityAdjuster.initializer = startAdjustAttr; opacityAdjuster.finalizer = stopAdjustAttr; opacityAdjuster.attr = "opacity"; var borderWidth = attrs["borderWidth"] === undefined ? 0 : attrs["borderWidth"]; var borderWidthAdjuster = adjustable(borderWidth, 0, 20, 1); borderWidthAdjuster.text = borderWidth + "px"; borderWidthAdjuster.handler = adjustAttr; borderWidthAdjuster.attr = "borderWidth"; borderWidthAdjuster.componentId = componentId; borderWidthAdjuster.initializer = startAdjustAttr; borderWidthAdjuster.finalizer = stopAdjustAttr; var borderRadius = attrs["borderRadius"] === undefined ? 0 : attrs["borderRadius"]; var borderRadiusAdjuster = adjustable(borderRadius, 0, 100, 1); borderRadiusAdjuster.text = borderRadius + "px"; borderRadiusAdjuster.handler = adjustAttr; borderRadiusAdjuster.attr = "borderRadius"; borderRadiusAdjuster.componentId = componentId; borderRadiusAdjuster.initializer = startAdjustAttr; borderRadiusAdjuster.finalizer = stopAdjustAttr; if(!localState.addingAppearanceStyle) { var sharedAppearance = (ixer.index("stylesBySharedAndType")[true] || {})["appearance"] || []; var styles = sharedAppearance.map(function(cur) { return {value: cur[1], text: code.name(cur[1])}; }); styles.unshift({text: "No text style", value: "none"}); styles.push({text: "Add a new style", value: "addStyle"}); var visualStyle = selectable(styleName, styles); visualStyle.c += " styleSelector"; visualStyle.handler = function(elem, value) { if(value === "none") { dispatch("setSelectionStyle", {type: "appearance", id: uuid(), shared: false}); } else if(value === "addStyle") { localState.addingAppearanceStyle = uuid(); dispatch("setSelectionStyle", {type: "appearance", id: localState.addingAppearanceStyle, shared: true}); } else { dispatch("setSelectionStyle", {type: "appearance", id: value, shared: true}); } render(); } } else { visualStyle = input("", localState.addingAppearanceStyle, rename, doneAddingStyle); visualStyle.postRender = focusOnce; } return {c: "option-group", children: [ visualStyle, {c: "layout-box-filled", borderRadius: attrs["borderRadius"], children: [ colorSelector(componentId, "backgroundColor", attrs["backgroundColor"]) ]}, {c: "layout-box-outline", borderRadius: attrs["borderRadius"], borderWidth: (borderWidth > 10 ? 10 : borderWidth || 1), borderColor: attrs["borderColor"], children: [borderColorPicker]}, {c: "label", text: "w:"}, borderWidthAdjuster, {c: "label", text: "r:"}, borderRadiusAdjuster, {c: "label", text: "opacity:"}, opacityAdjuster ]}; } function selectable(activeItem, items, setFont) { var options = items.map(function(cur) { var value, text; if(typeof cur === "string") { value = cur; text = cur; } else { value = cur.value; text = cur.text; } var item = {t: "option", value: value, text: text}; if(setFont) { item.fontFamily = cur; } if((activeItem.value || activeItem) === value) { item.selected = "selected"; } return item; }) var value = typeof activeItem === "string" ? activeItem : activeItem.text; return {c: "selectable", change: selectSelectable, children: [ {t: "select", children: options}, {c: "selectable-value", text: value} ]} } function selectSelectable(e, elem) { if(elem.handler) { elem.handler(elem, e.target.value); } } var alignMapping = { "flex-start": "Left", "center": "Center", "flex-end": "Right", } var vAlignMapping = { "flex-start": "Top", "center": "Center", "flex-end": "Bottom", } function selectVerticalAlign(elem, value) { var final = "center"; if(value === "Top") { final = "flex-start"; } else if(value === "Bottom") { final = "flex-end"; } dispatch("setAttributeForSelection", {componentId: elem.componentId, property: "verticalAlign", value: final, storeEvent: true}); } function selectAlign(elem, value) { var final = "center"; if(value === "Left") { final = "flex-start"; } else if(value === "Right") { final = "flex-end"; } dispatch("setAttributeForSelection", {componentId: elem.componentId, property: "textAlign", value: final, storeEvent: true}); } uiProperties.typography = ["fontFamily", "fontSize", "color", "textAlign", "verticalAlign"]; uiProperties.content = ["text"]; function textInspector(selectionInfo, binding) { var componentId = selectionInfo.componentId; var attrs = selectionInfo.attributes; var styleName; if(selectionInfo.styles.typography && selectionInfo.styles.typography[4]) { styleName = {value:selectionInfo.styles.typography[1], text: code.name(selectionInfo.styles.typography[1])}; } else { styleName = {text: "No text style", value: "none"}; } var font = attrs["fontFamily"] || "Helvetica Neue"; var fontPicker = selectable(font, ["Times New Roman", "Verdana", "Arial", "Georgia", "Avenir", "Helvetica Neue"], true); fontPicker.componentId = componentId; fontPicker.handler = adjustAttr; fontPicker.attr = "fontFamily"; fontPicker.storeEvent = true; var fontSize = attrs["fontSize"] === undefined ? 16 : attrs["fontSize"]; var fontSizeAdjuster = adjustable(fontSize, 0, 300, 1); fontSizeAdjuster.handler = adjustAttr; fontSizeAdjuster.attr = "fontSize"; fontSizeAdjuster.componentId = componentId; fontSizeAdjuster.initializer = startAdjustAttr; fontSizeAdjuster.finalizer = stopAdjustAttr; var fontColor = colorSelector(componentId, "color", attrs["color"]); fontColor.color = attrs["color"]; fontColor.c += " font-color"; var verticalAlign = vAlignMapping[attrs["verticalAlign"]] || "Top"; var valign = selectable(verticalAlign, ["Top", "Center", "Bottom"]); valign.componentId = componentId; valign.handler = selectVerticalAlign; var textAlign = alignMapping[attrs["textAlign"]] || "Left"; var align = selectable(textAlign, ["Left", "Center", "Right"]); align.componentId = componentId; align.handler = selectAlign; if(!localState.addingTypographyStyle) { var sharedTypography = (ixer.index("stylesBySharedAndType")[true] || {})["typography"] || []; var styles = sharedTypography.map(function(cur) { return {value: cur[1], text: code.name(cur[1])}; }); styles.unshift({text: "No text style", value: "none"}); styles.push({text: "Add a new style", value: "addStyle"}); var typographyStyle = selectable(styleName, styles); typographyStyle.c += " styleSelector"; typographyStyle.handler = function(elem, value) { if(value === "none") { dispatch("setSelectionStyle", {type: "typography", id: uuid(), shared: false}); } else if(value === "addStyle") { localState.addingTypographyStyle = uuid(); dispatch("setSelectionStyle", {type: "typography", id: localState.addingTypographyStyle, shared: true}); } else { dispatch("setSelectionStyle", {type: "typography", id: value, shared: true}); } render(); } } else { typographyStyle = input("", localState.addingTypographyStyle, rename, doneAddingStyle); typographyStyle.postRender = focusOnce; } return {c: "option-group", children: [ typographyStyle, fontColor, {c: "label", text: "size:"}, fontSizeAdjuster, {c: "label", text: "font:"}, fontPicker, {c: "label", text: "align:"}, valign, align, ]}; } function doneAddingStyle(e, elem) { localState.addingTypographyStyle = null; localState.addingAppearanceStyle = null; render(); } uiProperties.layer = []; function layerInspector(layer, elements) { var componentId = layer[2]; var info = getGroupInfo(elements, true); var attrs = info.attributes; // @FIXME: Layer attributes. var bounds = info.bounds; return {c: "inspector-panel", children: []}; } uiProperties.map = []; function mapInspector(selectionInfo, mapInfo, binding) { var componentId = selectionInfo.componentId; var attrs = mapInfo.attributes; return {c: "inspector-panel", children: [ {c: "title", text: "Map"}, {c: "pair", children: [{c: "label", text: "lat."}, inspectorInput(attrs["lat"], [componentId, "lat"], setMapAttribute, binding)]}, {c: "pair", children: [{c: "label", text: "long."}, inspectorInput(attrs["lng"], [componentId, "lng"], setMapAttribute, binding)]}, {c: "pair", children: [{c: "label", text: "zoom"}, inspectorInput(attrs["zoom"], [componentId, "zoom"], setMapAttribute, binding)]}, {c: "pair", children: [{c: "label", text: "interactive"}, inspectorCheckbox(attrs["draggable"], [componentId, "draggable"], setMapAttribute, binding)]}, ]}; } uiProperties.repeat = []; function repeatInspector() { } // Inputs function inspectorInput(value, key, onChange, binding) { if(value === null) { input.placeholder = "---"; } else if(typeof value === "number" && !isNaN(value)) { value = value.toFixed(2); } else if(value && value.constructor === Array) { value = "Bound to " + code.name(value[2]); } var field = input(value, key, onChange, preventDefault); field.mousedown = stopPropagation; field.editorType = "binding"; field.binding = binding; field.focus = activateTokenEditor; field.blur = closeTokenEditor; return field; } function inspectorCheckbox(value, key, onChange, binding) { if(value && value.constructor === Array) { value = "Bound to " + code.name(value[2]); } var field = checkboxInput(value, key, onChange); field.mousedown = stopPropagation; field.editorType = "binding"; field.binding = binding; field.focus = activateTokenEditor; field.blur = closeTokenEditor; return field; } function closeBindingEditor(e, elem) { if(editorInfo.element === e.currentTarget) { setTimeout(function() { editorInfo = false; rerender(); }, 0); } } function bindingEditor(editorInfo) { var binding = editorInfo.info.binding; if(!binding) return; var fields = code.viewToFields(binding).map(function(cur) { return ["field", binding, cur[2]]; }); return genericEditor(fields, false, false, false, "column", setBinding); } function setBinding(e, elem) { var info = editorInfo.info; var componentId = info.key[0]; var property = info.key[1]; console.log("SET", componentId, property, elem.cur); editorInfo = false; dispatch("setAttributeForSelection", {componentId: componentId, property: property, value: ["binding", elem.cur[1], elem.cur[2]]}); } function colorSelector(componentId, attr, value) { return {c: "color-picker", backgroundColor: value || "#999999", mousedown: stopPropagation, children: [ {t: "input", type: "color", key: [componentId, attr], value: value, input: setAttribute} ]}; } function styleSelector(id, opts, onClose) { var options = {}; if(opts.initial === "---") { options["default"] = "---"; } var styles = ixer.index("uiStyles"); for(var key in styles) { var cur = styles[key][0]; if(cur[2] === opts.type && code.name(cur[1])) { options[cur[1]] = code.name(cur[1]); } } return selectInput(opts.initial, opts.id, options, onClose); } // Layout handlers function adjustWidth(elem, value) { var componentId = elem.componentId; var old = elem.bounds; var neue = {left: old.left, right: (old.left + value), top: old.top, bottom: old.bottom}; var widthRatio = value / (old.right - old.left); if(widthRatio === 1) return; dispatch("resizeSelection", {widthRatio: widthRatio, heightRatio: 1, oldBounds: old, neueBounds: neue, componentId: componentId}); elem.bounds = neue; } function adjustHeight(elem, value) { var componentId = elem.componentId; var old = elem.bounds; var neue = {left: old.left, right: old.right, top: old.top, bottom: (old.top + value)}; var heightRatio = value / (old.bottom - old.top); if(heightRatio === 1) return; dispatch("resizeSelection", {widthRatio: 1, heightRatio: heightRatio, oldBounds: old, neueBounds: neue, componentId: componentId}); elem.bounds = neue; } function adjustPosition(elem, value) { var componentId = elem.componentId; var coord = elem.coord; var diffX = 0, diffY = 0; if(coord === "top") { diffY = value - elem.value; } else { diffX = value - elem.value; } dispatch("offsetSelection", {diffX: diffX, diffY: diffY, componentId: componentId}); elem.value = value; } function startAdjustAttr(e, elem) { var attrs = [] var style = getUiPropertyType(elem.attr); if(!style) { throw new Error("Unknown attribute type for property:", elem.attr, "known types:", uiProperties); } var sel = localState.uiSelection; sel.forEach(function(cur) { var id = cur; var styleId = ixer.index("uiElementToStyle")[id][style][1]; var oldProps = ixer.index("uiStyleToAttr")[styleId]; if(oldProps) { attrs.push(oldProps[elem.attr]); } }); localState.initialAttrs = attrs; } function stopAdjustAttr(e, elem) { var initial = localState.initialAttrs; localState.initialAttrs = null; dispatch("stopSetAttributeForSelection", {oldAttrs: initial, property: elem.attr}); } function adjustOpacity(elem, value) { dispatch("setAttributeForSelection", {componentId: elem.componentId, property: "opacity", value: value / 100, storeEvent: false}); } function adjustAttr(elem, value) { dispatch("setAttributeForSelection", {componentId: elem.componentId, property: elem.attr, value: value, storeEvent: elem.storeEvent}); } // Generic attribute handler function setAttribute(e, elem) { var componentId = elem.key[0]; var property = elem.key[1]; var target = e.currentTarget; var value = target.value; if(target.type === "color") { value = target.value; } else if(target.type === "checkbox") { value = target.checked; } else if(target.type === undefined) { value = target.textContent; } dispatch("setAttributeForSelection", {componentId: componentId, property: property, value: value}); } // Map attribute handler function setMapAttribute(e, elem) { var componentId = elem.key[0]; var property = elem.key[1]; var target = e.currentTarget; var value = target.checked !== undefined ? target.checked : target.value !== undefined ? target.value : target.textContent; dispatch("setMapAttributeForSelection", {componentId: componentId, property: property, value: value}); } function getUiPropertyType(prop) { if(uiProperties.typography.indexOf(prop) !== -1) { return "typography"; } if(uiProperties.appearance.indexOf(prop) !== -1) { return "appearance"; } if(uiProperties.layout.indexOf(prop) !== -1) { return "layout"; } if(uiProperties.content.indexOf(prop) !== -1) { return "content"; } return undefined; } //--------------------------------------------------------- // Query workspace //--------------------------------------------------------- function queryWorkspace(queryId) { return genericWorkspace("query", [queryControls(queryId)], [], {c: "query-editor", children: [ {c: "query-workspace", children: [ editor(queryId) ]}, queryResult(queryId) ]}); } //--------------------------------------------------------- // Tree + Toolbar //--------------------------------------------------------- function treeItem(name, value, type, opts) { opts = opts || {}; return {c: "tree-item " + opts.c, dragData: {value: value, type: type}, draggable: true, dragstart: dragItem, children: [ (opts.icon ? {c: "opts.icon"} : undefined), (name ? {text: name} : undefined), opts.content ]}; } function fieldItem(name, fieldId, opts) { opts = opts || {}; return {c: "tree-item " + opts.c, dragData: {fieldId: fieldId, type: "field"}, draggable: true, dragstart: dragItem, children: [ (opts.icon ? {c: "opts.icon"} : undefined), (name ? {text: name} : undefined), opts.content ]}; } function dragItem(evt, elem) { for(var key in elem.dragData) { evt.dataTransfer.setData(key, elem.dragData[key]); } } var queryTools = { union: ["merge"], aggregate: ["sort+limit", "sum", "count", "min", "max", "empty"] }; function queryControls(queryId) { var items = []; var toolTypes = Object.keys(queryTools); for(var typeIx = 0; typeIx < toolTypes.length; typeIx++) { var type = toolTypes[typeIx]; var tools = queryTools[type]; for(var toolIx = 0; toolIx < tools.length; toolIx++) { var tool = tools[toolIx]; items.push(treeItem(tool, tool, type, {c: "control tool query-tool"})); } } return controlGroup(items); } //--------------------------------------------------------- // Editor //--------------------------------------------------------- function editor(queryId) { var blocks = ixer.index("query to blocks")[queryId] || []; var items = []; for(var ix = 0; ix < blocks.length; ix++) { var viewId = blocks[ix][code.ix("block", "view")]; var viewKind = ixer.index("view to kind")[viewId]; var editorPane; if(viewKind === "join") { editorPane = viewBlock(viewId); } if(viewKind === "union") { editorPane = unionBlock(viewId); } if(viewKind === "aggregate") { editorPane =aggregateBlock(viewId); } var rows = ixer.facts(viewId) || []; var fields = (ixer.index("view to fields")[viewId] || []).map(function(field) { var id = field[code.ix("field", "field")]; return {name: code.name(id), id: id}; }); // This is a weird way to use display order. var order = ixer.index("display order"); rows.sort(function(a, b) { var aIx = order[viewId + JSON.stringify(a)]; var bIx = order[viewId + JSON.stringify(b)]; return aIx - bIx; }); var inspectorPane = {c: "inspector-pane", children: [virtualizedTable(viewId, fields, rows, false)]}; items.push({c: "block " + viewKind, children: [ editorPane, inspectorPane ]}); } if(items.length) { items.push({c: "add-aggregate-btn", text: "Add an aggregate by dragging it here...", queryId: queryId}); } return {c: "workspace", queryId: queryId, drop: editorDrop, dragover: preventDefault, children: items.length ? items : [ {c: "feed", text: "Feed me sources"} ]}; } function editorDrop(evt, elem) { var type = evt.dataTransfer.getData("type"); var value = evt.dataTransfer.getData("value"); if(type === "view") { return dispatch("addViewBlock", {queryId: elem.queryId, sourceId: value, kind: "join"}); } if(type === "aggregate") { return dispatch("addAggregateBlock", {queryId: elem.queryId, kind: value}); } if(type === "union") { return dispatch("addUnionBlock", {queryId: elem.queryId}); } } /** * View Block */ function viewBlock(viewId) { var fields = ixer.index("view and source to block fields")[viewId] || {}; fields = fields["selection"] || []; var selectionItems = fields.map(function(field) { var id = field[code.ix("block field", "block field")]; return fieldItem(code.name(id) || "Untitled", id, {c: "pill field"}); }); if(!selectionItems.length) { selectionItems.push({text: "Drag local fields into me to make them available in the query."}); } var groupedBy = ixer.index("grouped by")[viewId]; return {c: "block view-block", viewId: viewId, drop: viewBlockDrop, dragover: preventDefault, children: [ {c: "block-title", children: [ {t: "h3", text: "Untitled Block"}, {c: "hover-reveal close-btn ion-android-close", viewId: viewId, click: removeViewBlock} ]}, viewSources(viewId), viewConstraints(viewId), (groupedBy ? {c: "block-section view-grouping", children: [ {text: "Grouped by"}, {text: code.name(groupedBy[code.ix("grouped by", "inner field")])}, {text: "="}, {text: code.name(groupedBy[code.ix("grouped by", "outer field")])}, ]} : undefined), {c: "block-section view-selections tree bar", viewId: viewId, drop: viewSelectionsDrop, dragover: preventDefault, children: selectionItems} ]}; } function viewBlockDrop(evt, elem) { var viewId = elem.viewId; var type = evt.dataTransfer.getData("type"); var value = evt.dataTransfer.getData("value"); if(type === "view") { if(viewId === value) { return console.error("Cannot join view with parent."); } dispatch("addViewSource", {viewId: viewId, sourceId: value}); evt.stopPropagation(); return; } } function removeViewBlock(evt, elem) { dispatch("removeViewBlock", {viewId: elem.viewId}); } function viewSelectionsDrop(evt, elem) { var type = evt.dataTransfer.getData("type"); if(type !== "field") { return; } var id = evt.dataTransfer.getData("fieldId"); var blockField = ixer.index("block field")[id]; if(blockField[code.ix("block field", "view")] !== elem.viewId) { return; } var fieldId = blockField[code.ix("block field", "field")]; var sourceId = blockField[code.ix("block field", "source")]; dispatch("addViewSelection", {viewId: elem.viewId, sourceFieldId: fieldId, sourceId: sourceId}); evt.stopPropagation(); } // Sources function viewSources(viewId) { var sourceIdIx = code.ix("source", "source"); var sources = ixer.index("view to sources")[viewId] || []; var sourceIds = sources.map(function(source) { return source[sourceIdIx]; }); sources.sort(function(idA, idB) { var orderA = ixer.index("display order")[idA]; var orderB = ixer.index("display order")[idB]; if(orderB - orderA) { return orderB - orderA; } else { return idA > idB } }); var sourceItems = sourceIds.map(function(sourceId) { return viewSource(viewId, sourceId); }); return {c: "block-section view-sources", children: sourceItems}; } function viewSource(viewId, sourceId) { var fields = ixer.index("view and source to block fields")[viewId] || {}; fields = fields[sourceId] || []; var fieldItems = fields.map(function(field) { var id = field[code.ix("block field", "block field")]; return fieldItem(code.name(id) || "Untitled", id, {c: "pill field"}); }); var children = [ {c: "view-source-title", children: [ {t: "h4", text: code.name(sourceId) || "Untitled"}, {c: "hover-reveal close-btn ion-android-close", viewId: viewId, sourceId: sourceId, click: removeSource} ]} ].concat(fieldItems); return {c: "tree bar view-source", children: children}; } function removeSource(evt, elem) { dispatch("removeViewSource", {viewId: elem.viewId, sourceId: elem.sourceId}); } // Constraints function viewConstraints(viewId) { var constraintIdIx = code.ix("constraint", "constraint"); var constraints = ixer.index("view to constraints")[viewId] || []; var constraintItems = constraints.map(function(constraint) { var id = constraint[constraintIdIx]; var op = ixer.index("constraint operation")[id] || []; var operation = op[code.ix("constraint operation", "operation")]; var left = ixer.index("constraint left")[id] || []; var leftSource = left[code.ix("constraint left", "left source")]; var leftField = left[code.ix("constraint left", "left field")]; var right = ixer.index("constraint right")[id] || []; var rightSource = right[code.ix("constraint right", "right source")]; var rightField = right[code.ix("constraint right", "right field")]; return {c: "view-constraint", children: [ {c: "hover-reveal grip", children: [{c: "ion-android-more-vertical"}, {c: "ion-android-more-vertical"}]}, token.blockField({key: "left", constraintId: id, source: leftSource, field: leftField}, updateViewConstraint, dropConstraintField), token.operation({key: "operation", constraintId: id, operation: operation}, updateViewConstraint), token.blockField({key: "right", constraintId: id, source: rightSource, field: rightField}, updateViewConstraint, dropConstraintField), {c: "hover-reveal close-btn ion-android-close", constraintId: id, click: removeConstraint} ]}; }); return {c: "block-section view-constraints", viewId: viewId, drop: viewConstraintsDrop, dragover: preventDefault, children: constraintItems}; } function viewConstraintsDrop(evt, elem) { var viewId = elem.viewId; var type = evt.dataTransfer.getData("type"); var value = evt.dataTransfer.getData("value"); if(type === "tool" && value === "filter") { dispatch("addViewConstraint", {viewId: viewId}); evt.stopPropagation(); return; } if(type === "field") { var id = evt.dataTransfer.getData("fieldId"); var blockField = ixer.index("block field")[id]; if(blockField[code.ix("block field", "view")] !== viewId) { return; } var fieldId = blockField[code.ix("block field", "field")]; var sourceId = blockField[code.ix("block field", "source")]; dispatch("addViewConstraint", {viewId: viewId, leftSource: sourceId, leftField: fieldId}); } } function updateViewConstraint(evt, elem) { var id = elem.constraintId; dispatch("updateViewConstraint", {constraintId: id, type: elem.key, value: elem.value}); stopEditToken(evt, elem); evt.stopPropagation(); } function dropConstraintField(evt, elem) { var type = evt.dataTransfer.getData("type"); if(type !== "field") { return; } var viewId = ixer.index("constraint to view")[elem.constraintId]; var id = evt.dataTransfer.getData("fieldId"); var blockField = ixer.index("block field")[id]; var draggedViewId = blockField[code.ix("block field", "view")]; var fieldId = blockField[code.ix("block field", "field")]; var sourceId = blockField[code.ix("block field", "source")]; if(draggedViewId === viewId) { // If the field is block local, add it as a constraint. dispatch("updateViewConstraint", {constraintId: elem.constraintId, type: elem.key, value: fieldId, source: sourceId}); evt.stopPropagation(); } else if(elem.key === "right") { // If the field is accessible in the query, use it for grouping. var select = ixer.index("view and source field to select")[draggedViewId] || {}; select = select[fieldId]; if(!select) { return; } if(ixer.index("view to query")[viewId] !== ixer.index("view to query")[draggedViewId]) { return; } console.warn("@TODO: group by", draggedViewId, fieldId); dispatch("groupView", {constraintId: elem.constraintId, inner: viewId, outer: draggedViewId, outerField: fieldId}); evt.stopPropagation(); } } function removeConstraint(evt, elem) { dispatch("removeViewConstraint", {constraintId: elem.constraintId}); } //--------------------------------------------------------- // Tokens //--------------------------------------------------------- var tokenState = {}; var token = { operation: function(params, onChange, onDrop) { var state = tokenState[params.constraintId]; if(state) { state = state[params.key]; } return {c: "token operation", key: params.key, constraintId: params.constraintId, children: [{c: "name", text: params.operation || "<op>"}, (state === 1) ? tokenEditor.operation(params, onChange) : undefined], click: editToken}; }, blockField: function(params, onChange, onDrop) { var state = tokenState[params.constraintId]; if(state) { state = state[params.key]; } var name = "<field>"; var source; if(params.field) { name = code.name(params.field); if(params.source) { source = code.name(params.source); } } return {c: "token field", key: params.key, constraintId: params.constraintId, children: [{c: "name", text: name}, (source ? {c: "source", text: "(" + source +")"} : undefined), (state === 1) ? tokenEditor.blockField(params, onChange) : undefined], click: editToken, dragover: preventDefault, drop: onDrop}; } }; function editToken(evt, elem) { var state = tokenState[elem.constraintId]; if(!state) { state = tokenState[elem.constraintId] = {}; } state[elem.key] = 1; render(); } function stopEditToken(evt, elem) { var state = tokenState[elem.constraintId]; state[elem.key] = 0; render(); } var tokenEditor = { operation: function(params, onChange) { var items = ["=", "<", "≤", ">", "≥", "≠"].map(function(rel) { var item = selectorItem({c: "operation", key: params.key, name: rel, value: rel}, onChange); item.constraintId = params.constraintId; return item; }); var select = selector(items, {c: "operation", key: params.key, tabindex: -1, focus: true}, stopEditToken); select.constraintId = params.constraintId; return select; }, blockField: function(params, onChange) { var viewId = ixer.index("constraint to view")[params.constraintId]; var fields = getBlockFields(viewId); var items = fields.map(function(field) { var fieldId = field[code.ix("field", "field")]; var item = selectorItem({c: "field", key: params.key, name: code.name(fieldId) || "Untitled", value: fieldId}, onChange); item.constraintId = params.constraintId; return item; }); var select = selector(items, {c: "field", key: params.key, tabindex: -1, focus: true}, stopEditToken); select.constraintId = params.constraintId; return select; } }; function getSourceFields(viewId, sourceId) { var source = ixer.index("source")[viewId][sourceId]; var sourceViewId = source[code.ix("source", "source view")]; return ixer.index("view to fields")[sourceViewId] || []; } function getBlockFields(viewId) { var sources = ixer.index("view to sources")[viewId] || []; return sources.reduce(function(memo, source) { var sourceViewId = source[code.ix("source", "source view")]; memo.push.apply(memo, ixer.index("view to fields")[sourceViewId]); return memo; }, []); } function getQueryFields(queryId, exclude) { var viewIds = ixer.index("query to views")[queryId] || []; return viewIds.reduce(function(memo, viewId) { if(viewId !== exclude && viewId) { memo.push.apply(memo, getBlockFields(viewId)); } return memo; }, []); } /** * Union Block */ function unionBlock(viewId) { var fields = ixer.index("view and source to block fields")[viewId] || {}; fields = fields.selection || []; var selectSources = ixer.index("view and source and field to select")[viewId] || {}; var sources = ixer.index("source")[viewId] || {}; var sourceIds = Object.keys(sources); var sourceItems = []; var fieldMappingItems = []; for(var sourceIx = 0; sourceIx < sourceIds.length; sourceIx++) { var sourceId = sourceIds[sourceIx]; var source = sources[sourceId]; var sourceFields = ixer.index("view and source to block fields")[viewId] || {}; sourceFields = sourceFields[sourceId] || []; var fieldItems = []; for(var fieldIx = 0; fieldIx < sourceFields.length; fieldIx++) { var field = sourceFields[fieldIx]; var fieldId = field[code.ix("block field", "block field")]; fieldItems.push(fieldItem(code.name(fieldId) || "Untitled", fieldId, {c: "pill field"})); } sourceItems.push({c: "union-source", children: [ {text: code.name(sourceId)}, {c: "tree bar union-source-fields", children: fieldItems} ]}); if(!fields.length) { continue; } var selectFields = selectSources[sourceId] || []; var mappingPairs = []; for(var fieldIx = 0; fieldIx < fields.length; fieldIx++) { var field = fields[fieldIx]; var fieldId = field[code.ix("block field", "field")]; var selectField = selectFields[fieldId] || []; var mappedFieldId = selectField[code.ix("select", "source field")]; mappingPairs.push({c: "mapping-pair", viewId: viewId, sourceId: sourceId, fieldId: fieldId, dragover: preventDefault, drop: unionSourceMappingDrop, children: [ {c: "mapping-header", text: code.name(fieldId) || "Untitled"}, // @FIXME: code.name(fieldId) not set? (mappedFieldId ? {c: "mapping-row", text: code.name(mappedFieldId) || "Untitled"} : {c: "mapping-row", text: "---"}) ]}); } fieldMappingItems.push({c: "field-mapping", children: mappingPairs}); } if(!fields.length) { fieldMappingItems.push({c: "field-mapping", children: [{text: "drag fields to begin mapping; or"}, {text: "drag an existing union to begin merging"}]}); } return {c: "block union-block", viewId: viewId, dragover: preventDefault, drop: viewBlockDrop, children: [ {c: "block-title", children: [ {t: "h3", text: "Untitled Union Block"}, {c: "hover-reveal close-btn ion-android-close", viewId: viewId, click: removeViewBlock} ]}, {c: "content", children: [ {c: "block-pane", children: sourceItems}, {c: "block-pane mapping", viewId: viewId, dragover: preventDefault, drop: unionSourceMappingDrop, children: fieldMappingItems}, ]} ]}; } function unionSourceMappingDrop(evt, elem) { var type = evt.dataTransfer.getData("type"); if(type !== "field") { return; } var blockFieldId = evt.dataTransfer.getData("fieldId"); var blockField = ixer.index("block field")[blockFieldId]; var fieldId = blockField[code.ix("block field", "field")]; var viewId = blockField[code.ix("block field", "view")]; var sourceId = blockField[code.ix("block field", "source")]; if(viewId !== elem.viewId) { return; } console.log({viewId: viewId, sourceFieldId: fieldId, sourceId: sourceId, fieldId: elem.fieldId}); dispatch("addUnionSelection", {viewId: viewId, sourceFieldId: fieldId, sourceId: sourceId, fieldId: elem.fieldId}); evt.stopPropagation(); } /** * Aggregate Block */ function aggregateBlock(viewId) { var sources = ixer.index("source")[viewId] || {}; var outerSource = sources.outer; var innerSource = sources.inner; var groupBy = ixer.index("grouped by")[innerSource] || []; console.log(groupBy); var fields = ixer.index("view and source to block fields")[viewId] || {}; fields = fields["selection"] || []; var selectionItems = fields.map(function(field) { var id = field[code.ix("block field", "block field")]; return fieldItem(code.name(id) || "Untitled", id, {c: "pill field"}); }); if(!selectionItems.length) { selectionItems.push({text: "Drag local fields into me to make them available in the query."}); } return {c: "block aggregate-block", viewId: viewId, children: [ {c: "block-title", children: [ {t: "h3", text: "Untitled Agg. Block"}, {c: "hover-reveal close-btn ion-android-close", viewId: viewId, click: removeViewBlock} ]}, {text: "With"}, {c: "block-section view-sources", viewId: viewId, sourceId: "inner", drop: aggregateSourceDrop, dragover: preventDefault, children: [ innerSource ? viewSource(viewId, "inner") : undefined ]}, {text: "Where"}, viewConstraints(viewId), {c: "block-section view-selections tree bar", viewId: viewId, drop: viewSelectionsDrop, dragover: preventDefault, children: selectionItems}, ]}; } function sortLimitAggregate(viewId, outerSource, innerSource) { return {c: "sort-limit-aggregate", viewId: viewId, children: [ {text: "Sort by"}, {c: "block-section aggregate-sort", children: [ {text: "<field>"}, {text: "<direction>"} ]}, {text: "Limit"}, {c: "block-section aggregate-limit", children: [ {text: "<constant>"}, {text: "<constant>"} ]}, ]}; } function primitiveAggregate(viewId, outerSource, innerSource) { return {c: "primitive-aggregate", viewId: viewId, children: [ {text: "argument mapping here"} ]}; } function aggregateSourceDrop(evt, elem) { var viewId = elem.viewId; var sourceId = elem.sourceId; var type = evt.dataTransfer.getData("type"); var value = evt.dataTransfer.getData("value"); if(type === "view") { if(viewId === value) { return console.error("Cannot join view with parent."); } dispatch("addViewSource", {viewId: viewId, sourceId: value, kind: sourceId}); evt.stopPropagation(); return; } } function selector(options, opts, onBlur) { return {t: "ul", c: "selector " + opts.c, tabindex: opts.tabindex, key: opts.key, postRender: (opts.focus ? focusOnce : undefined), blur: onBlur, children: options}; } function selectorItem(opts, onChange) { return {t: "li", c: "selector-item field " + opts.c, key: opts.key, text: opts.name, value: opts.value, click: onChange}; } //--------------------------------------------------------- // Inspector //--------------------------------------------------------- function inspectorPane(queryId) { return {c: "inspector pane"}; } //--------------------------------------------------------- // Result //--------------------------------------------------------- function queryResult(queryId) { return {c: "query-result"}; } //--------------------------------------------------------- // Global key handling //--------------------------------------------------------- document.addEventListener("keydown", function(e) { //Don't capture keys if they are if(e.defaultPrevented || e.target.nodeName === "INPUT" || e.target.getAttribute("contentEditable")) { return; } //undo + redo if((e.metaKey || e.ctrlKey) && e.shiftKey && e.keyCode === KEYS.Z) { dispatch("redo"); } else if((e.metaKey || e.ctrlKey) && e.keyCode === KEYS.Z) { dispatch("undo"); } }); //--------------------------------------------------------- // Go //--------------------------------------------------------- if(window.queryEditor) { render(); } return { container: renderer.content, localState: localState, renderer: renderer, render: render, eventStack: eventStack }; })(window, microReact, api);
ui/src/query-editor.js
var queryEditor = (function(window, microReact, api) { var document = window.document; var ixer = api.ixer; var code = api.code; var diff = api.diff; var localState = api.localState; var clone = api.clone; if(window.queryEditor) { try { document.body.removeChild(window.queryEditor.container); } catch (err) { // meh } } window.addEventListener("resize", render); document.body.addEventListener("drop", preventDefault); var renderer = new microReact.Renderer(); document.body.appendChild(renderer.content); renderer.queued = false; function render() { if(renderer.queued === false) { renderer.queued = true; requestAnimationFrame(function() { renderer.queued = false; renderer.render(root()); }); } } function preventDefault(evt) { evt.preventDefault(); } function focusOnce(node, elem) { if(!elem.__focused) { setTimeout(function() { node.focus(); }, 5); elem.__focused = true; } } //--------------------------------------------------------- // utils //--------------------------------------------------------- var alphabet = ["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"]; var KEYS = {UP: 38, DOWN: 40, ENTER: 13, Z: 90}; function coerceInput(input) { if(input.match(/^-?[\d]+$/gim)) { return parseInt(input); } else if(input.match(/^-?[\d]+\.[\d]+$/gim)) { return parseFloat(input); } return input; } function reverseDiff(diff) { var neue = []; for(var diffIx = 0, diffLen = diff.length; diffIx < diffLen; diffIx++) { var copy = diff[diffIx].slice(); neue[diffIx] = copy if(copy[1] === "inserted") { copy[1] = "removed"; } else { copy[1] = "inserted"; } } return neue; } //--------------------------------------------------------- // Local state //--------------------------------------------------------- var eventStack = {root: true, children: [], localState: clone(localState)}; function scaryUndoEvent() { if(!eventStack.parent || !eventStack.diffs) return {}; var old = eventStack; eventStack = old.parent; localState = clone(eventStack.localState); api.localState = localState; return reverseDiff(old.diffs); } function scaryRedoEvent() { if(!eventStack.children.length) return {}; eventStack = eventStack.children[eventStack.children.length - 1]; localState = clone(eventStack.localState); return eventStack.diffs; } //--------------------------------------------------------- // Dispatch //--------------------------------------------------------- function dispatch(evt, info) { // console.info("[dispatch]", evt, info); var storeEvent = true; var sendToServer = true; var txId = ++localState.txId; var diffs = []; switch(evt) { case "addTable": var id = uuid(); var fieldId = uuid(); diffs.push(["editor item", "inserted", [id, "table"]], ["view", "inserted", [id, "table"]], ["field", "inserted", [id, fieldId, "output"]], ["display order", "inserted", [fieldId, 0]], ["display name", "inserted", [id, "Untitled Table"]], ["display name", "inserted", [fieldId, "A"]]); localState.activeItem = id; localState.adderRows = [[]]; break; case "addQuery": var id = uuid(); diffs.push(["editor item", "inserted", [id, "query"]], ["display name", "inserted", [id, "Untitled Query"]]); localState.activeItem = id; break; case "addUi": var id = uuid(); var layerId = uuid(); diffs.push(["editor item", "inserted", [id, "ui"]], ["display name", "inserted", [id, "Untitled Page"]], ["uiComponentLayer", "inserted", [txId, layerId, id, 0, false, false, id]], ["display name", "inserted", [layerId, "Page"]]); localState.activeItem = id; localState.uiActiveLayer = layerId; localState.openLayers[layerId] = true; break; case "addUiLayer": var layerId = uuid(); var groupNum = ixer.index("uiComponentToLayers")[info.componentId].length; var groupIx = (ixer.index("parentLayerToLayers")[info.parentLayer] || []).length; diffs.push(["uiComponentLayer", "inserted", [txId, layerId, info.componentId, groupIx, false, false, info.parentLayer]], ["display name", "inserted", [layerId, "Group " + groupNum]]); localState.uiActiveLayer = layerId; localState.openLayers[layerId] = true; break; case "updateUiLayer": var subLayers = code.layerToChildLayers(info.neue); var neueLocked = info.neue[4]; var neueHidden = info.neue[5]; subLayers.forEach(function(sub) { if(sub[4] !== neueLocked || sub[5] !== neueHidden) { var neue = sub.slice(); neue[4] = neueLocked; neue[5] = neueHidden; diffs.push(["uiComponentLayer", "inserted", neue], ["uiComponentLayer", "removed", sub]) } }); diffs.push(["uiComponentLayer", "inserted", info.neue], ["uiComponentLayer", "removed", info.old]) break; case "deleteLayer": var subLayers = code.layerToChildLayers(info.layer); var elementsLookup = ixer.index("uiLayerToElements"); subLayers.push(info.layer); subLayers.forEach(function(sub) { diffs.push(["uiComponentLayer", "removed", sub]); var elements = elementsLookup[sub[1]]; if(elements) { elements.forEach(function(element) { diffs.push(["uiComponentElement", "removed", element]); }); } }); break; case "changeParentLayer": var layer = ixer.index("uiComponentLayer")[info.layerId]; if(layer[6] !== info.parentLayerId) { var neue = layer.slice(); neue[0] = txId; neue[6] = info.parentLayerId; diffs.push(["uiComponentLayer", "inserted", neue], ["uiComponentLayer", "removed", layer]) } break; case "changeElementLayer": var elem = ixer.index("uiComponentElement")[info.elementId]; if(elem[3] !== info.parentLayerId) { var neue = elem.slice(); neue[0] = txId; neue[3] = info.parentLayerId; diffs.push(["uiComponentElement", "inserted", neue], ["uiComponentElement", "removed", elem]) } break; case "rename": var id = info.id; sendToServer = !!info.sendToServer; if(info.value === undefined || info.value === info.initial[1]) { return; } diffs.push(["display name", "inserted", [id, info.value]], ["display name", "removed", info.initial]) break; case "addField": var fieldId = uuid(); var ix = ixer.index("view to fields")[info.table].length; diffs.push(["field", "inserted", [info.table, fieldId, "output"]], // @NOTE: Can this be any other kind? ["display name", "inserted", [fieldId, alphabet[ix]]], ["display order", "inserted", [fieldId, ix]]); break; case "addRow": var ix = ixer.facts(info.table).length; diffs.push([info.table, "inserted", info.neue], ["display order", "inserted", [info.table + JSON.stringify(info.neue), ix]]); break; case "updateRow": var oldString = info.table + JSON.stringify(info.old); var ix = ixer.index("display order")[oldString]; diffs.push([info.table, "inserted", info.neue], [info.table, "removed", info.old], ["display order", "removed", [oldString, ix]], ["display order", "inserted", [info.table + JSON.stringify(info.neue), ix]]); break; case "addViewBlock": var queryId = (info.queryId !== undefined) ? info.queryId: code.activeItemId(); diffs = diff.addViewBlock(queryId, info.sourceId, info.kind); break; case "addAggregateBlock": var queryId = (info.queryId !== undefined) ? info.queryId: code.activeItemId(); diffs = diff.addAggregateBlock(queryId, info.kind); break; case "addUnionBlock": var queryId = (info.queryId !== undefined) ? info.queryId: code.activeItemId(); diffs = diff.addUnionBlock(queryId); break; case "removeViewBlock": var view = ixer.index("view")[info.viewId]; var blockId = ixer.index("view to block")[info.viewId]; var block = ixer.index("block")[blockId]; var sources = ixer.index("view to sources")[info.viewId] || []; diffs = [["view", "removed", view], ["block", "removed", block]]; for(var ix = 0; ix < sources.length; ix++) { var sourceId = sources[ix][code.ix("source", "source")]; diffs = diffs.concat(diff.removeViewSource(info.viewId, sourceId)); } if(view[code.ix("view", "kind")] === "aggregate") { console.warn("@FIXME: Remove aggregate entries for view on removal."); } break; case "addViewSelection": diffs = diff.addViewSelection(info.viewId, info.sourceId, info.sourceFieldId, info.fieldId); break; case "addUnionSelection": diffs = diff.addViewSelection(info.viewId, info.sourceId, info.sourceFieldId, info.fieldId); // do not send to server unless selects.length = fields.length * sources.length var sourceIdIx = code.ix("source", "source"); var numSources = (ixer.index("view to sources")[info.viewId] || []).reduce(function(memo, source) { if(source[sourceIdIx] !== info.sourceId) { return memo + 1; } return memo; }, 1); var fieldIdIx = code.ix("field", "field"); var numFields = (ixer.index("view to fields")[info.viewId] || []).reduce(function(memo, field) { if(field[fieldIdIx] !== info.fieldId) { return memo + 1; } return memo; }, 1); var selectSourceIx = code.ix("select", "source"); var selectFieldIx = code.ix("select", "view field"); var selects = (ixer.index("view to selects")[info.viewId] || []); var numSelects = selects.reduce(function(memo, select) { if(select[selectSourceIx] !== info.sourceId || select[selectFieldIx] !== info.fieldId) { return memo + 1; } return memo; }, 1); // @FIXME: This went from okay to bad fast. if(numSelects !== numFields * numSources) { sendToServer = false; } else { diffs = diffs.concat(selects.map(function(select) { return ["select", "inserted", select]; })); var sources = ixer.index("view to sources")[info.viewId] || []; diffs = diffs.concat(sources.map(function(source) { return ["source", "inserted", source]; })); var blockFields = ixer.index("view and source to block fields")[info.viewId]["selection"] || []; diffs = diffs.concat(blockFields.map(function(blockField) { return ["block field", "inserted", blockField]; })); var fields = ixer.index("view to fields")[info.viewId] || []; diffs = diffs.concat(fields.map(function(field) { return ["field", "inserted", field]; })); var fieldIdIx = code.ix("field", "field"); diffs = diffs.concat(fields.map(function(field) { var id = field[fieldIdIx]; return ["display name", "inserted", [id, code.name(id)]]; })); } break; case "addViewSource": diffs = diff.addViewSource(info.viewId, info.sourceId, info.kind); var view = ixer.index("view")[info.viewId]; var kind = view[code.ix("view", "kind")]; if(kind === "union") { var selects = (ixer.index("view to selects")[info.viewId] || []); if(selects.length) { sendToServer = false; } } break; case "removeViewSource": diffs = diff.removeViewSource(info.viewId, info.sourceId); break; case "addViewConstraint": diffs = diff.addViewConstraint(info.viewId, {operation: "=", leftSource: info.leftSource, leftField: info.leftField}); sendToServer = false; break; case "groupView": var old = ixer.index("grouped by")[info.inner]; if(old) { throw new Error("Cannot group by multiple views."); } var left = ixer.index("constraint left")[info.constraintId] || []; var innerField = left[code.ix("constraint left", "left field")]; diffs = [["grouped by", "inserted", [info.inner, innerField, info.outer, info.outerField]]]; diffs = diffs.concat(diff.removeViewConstraint(info.constraintId)); break; case "addUiComponentElement": var elemId = uuid(); var neue = [txId, elemId, info.componentId, info.layerId, info.control, info.left, info.top, info.right, info.bottom]; var appStyleId = uuid(); var typStyleId = uuid(); diffs.push(["uiComponentElement", "inserted", neue]); diffs.push(["uiStyle", "inserted", [txId, appStyleId, "appearance", elemId, false]], ["uiStyle", "inserted", [txId, typStyleId, "typography", elemId, false]], ["uiStyle", "inserted", [txId, typStyleId, "content", elemId, false]]); // @TODO: Instead of hardcoding, have a map of special element diff handlers. if(info.control === "map") { var mapId = uuid(); diffs.push(["uiMap", "inserted", [txId, mapId, elemId, 0, 0, 4]], ["uiMapAttr", "inserted", [txId, mapId, "lat", 0]], ["uiMapAttr", "inserted", [txId, mapId, "lng", 0]], ["uiMapAttr", "inserted", [txId, mapId, "zoom", 0]]); } localState.uiSelection = [elemId]; break; case "resizeSelection": storeEvent = false; sendToServer = false; var sel = localState.uiSelection; var elementIndex = ixer.index("uiComponentElement"); var ratioX = info.widthRatio; var ratioY = info.heightRatio; var oldBounds = info.oldBounds; var neueBounds = info.neueBounds; sel.forEach(function(cur) { var elem = elementIndex[cur]; var neue = elem.slice(); neue[0] = txId; //We first find out the relative position of the item in the selection //then adjust by the given ratio and finall add the position of the selection //back in to get the new absolute coordinates neue[5] = Math.floor(((neue[5] - oldBounds.left) * ratioX) + neueBounds.left); //left neue[7] = Math.floor(((neue[7] - oldBounds.right) * ratioX) + neueBounds.right); //right neue[6] = Math.floor(((neue[6] - oldBounds.top) * ratioY) + neueBounds.top); //top neue[8] = Math.floor(((neue[8] - oldBounds.bottom) * ratioY) + neueBounds.bottom); //bottom diffs.push(["uiComponentElement", "inserted", neue], ["uiComponentElement", "removed", elem]); }); break; case "moveSelection": storeEvent = false; sendToServer = false; var sel = localState.uiSelection; var elementIndex = ixer.index("uiComponentElement"); var elem = elementIndex[info.elemId]; var diffX = info.x !== undefined ? info.x - elem[5] : 0; var diffY = info.y !== undefined ? info.y - elem[6] : 0; if(diffX || diffY) { sel.forEach(function(cur) { var elem = elementIndex[cur]; var neue = elem.slice(); neue[0] = txId; neue[3] = info.layer || neue[3]; neue[5] += diffX; //left neue[7] += diffX; //right neue[6] += diffY; //top neue[8] += diffY; //bottom diffs.push(["uiComponentElement", "inserted", neue], ["uiComponentElement", "removed", elem]); }); } break; case "bindGroup": var prev = ixer.index("groupToBinding")[info.groupId]; if(prev) { diffs.push(["uiGroupBinding", "removed", [info.groupId, prev]]); } diffs.push(["uiGroupBinding", "inserted", [info.groupId, info.itemId]]); break; case "bindAttr": var elemId = info.elementId; var attr = info.attr; var field = info.field; var prev = (ixer.index("elementAttrToBinding")[elemId] || {})[attr]; if(prev) { diffs.push(["uiAttrBinding", "removed", [elemId, attr, prev]]); } diffs.push(["uiAttrBinding", "inserted", [elemId, attr, field]]); break; case "stopChangingSelection": var sel = localState.uiSelection; var elementIndex = ixer.index("uiComponentElement"); var elem = elementIndex[info.elemId]; var oldElements = info.oldElements; sel.forEach(function(cur, ix) { var elem = elementIndex[cur]; var old = oldElements[ix]; diffs.push(["uiComponentElement", "inserted", elem], ["uiComponentElement", "removed", old]); }); break; case "offsetSelection": storeEvent = false; sendToServer = false; var sel = localState.uiSelection; var elementIndex = ixer.index("uiComponentElement"); var diffX = info.diffX; var diffY = info.diffY; if(diffX || diffY) { sel.forEach(function(cur) { var elem = elementIndex[cur]; var neue = elem.slice(); neue[0] = txId; neue[3] = info.layer || neue[3]; neue[5] += diffX; //left neue[7] += diffX; //right neue[6] += diffY; //top neue[8] += diffY; //bottom diffs.push(["uiComponentElement", "inserted", neue], ["uiComponentElement", "removed", elem]); }); } break; case "deleteSelection": var sel = localState.uiSelection; var elementIndex = ixer.index("uiComponentElement"); sel.forEach(function(cur) { var elem = elementIndex[cur]; diffs.push(["uiComponentElement", "removed", elem]); }); localState.uiSelection = null; break; case "setAttributeForSelection": storeEvent = info.storeEvent; sendToServer = info.storeEvent; var style = getUiPropertyType(info.property); if(!style) { throw new Error("Unknown attribute type for property:", info.property, "known types:", uiProperties); } var sel = localState.uiSelection; sel.forEach(function(cur) { var id = cur; var styleId = ixer.index("uiElementToStyle")[id][style][1]; var oldProps = ixer.index("uiStyleToAttr")[styleId]; if(oldProps && oldProps[info.property]) { diffs.push(["uiComponentAttribute", "removed", oldProps[info.property]]); } diffs.push(["uiComponentAttribute", "inserted", [0, styleId, info.property, info.value, false]]); }); break; case "stopSetAttributeForSelection": var style = getUiPropertyType(info.property); if(!style) { throw new Error("Unknown attribute type for property:", info.property, "known types:", uiProperties); } var sel = localState.uiSelection; var oldAttrs = info.oldAttrs; sel.forEach(function(cur, ix) { var id = cur; var styleId = ixer.index("uiElementToStyle")[id][style][1]; var oldProps = ixer.index("uiStyleToAttr")[styleId]; if(oldProps && oldProps[info.property]) { diffs.push(["uiComponentAttribute", "inserted", oldProps[info.property]]); } if(oldAttrs[ix]) { diffs.push(["uiComponentAttribute", "removed", oldAttrs[ix]]); } }); break; case "setSelectionStyle": var styleId = info.id; var type = info.type; var sel = localState.uiSelection; sel.forEach(function(id) { var prevStyle = ixer.index("uiElementToStyle")[id][type]; diffs.push(["uiStyle", "inserted", [txId, styleId, type, id, info.shared]], ["uiStyle", "removed", prevStyle]); }); break; case "duplicateSelection": var sel = localState.uiSelection; var elementIndex = ixer.index("uiComponentElement"); sel.forEach(function(cur) { var elem = elementIndex[cur]; var neueId = uuid(); diffs.push.apply(diffs, diff.duplicateElement(elem, neueId, localState.txId++)); }); break; case "updateViewConstraint": var viewId = ixer.index("constraint to view")[info.constraintId]; // @TODO: redesign this to pass in opts directly. var opts = {}; if(info.type === "left") { opts.leftField = info.value; opts.leftSource = info.source; } else if(info.type === "right") { opts.rightField = info.value; opts.rightSource = info.source; } else if(info.type === "operation") { opts.operation = info.value; } diffs = diff.updateViewConstraint(info.constraintId, opts); var constraint = ixer.index("constraint")[info.constraintId]; var constraintLeft = ixer.index("constraint left")[info.constraintId] || []; var constraintRight = ixer.index("constraint right")[info.constraintId] || []; var constraintOperation = ixer.index("constraint operation")[info.constraintId] || []; var constraintFieldIx = code.ix("constraint left", "left field"); var constraintSourceIx = code.ix("constraint left", "left source"); var constraintOperationIx = code.ix("constraint operation", "operation"); opts.leftField = opts.leftField || constraintLeft[constraintFieldIx]; opts.leftSource = opts.leftSource || constraintLeft[constraintSourceIx]; opts.RightField = opts.RightField || constraintRight[constraintFieldIx]; opts.RightSource = opts.RightSource || constraintRight[constraintSourceIx]; opts.operation = opts.operation || constraintOperation[constraintOperationIx]; if(opts.leftField && opts.leftSource && opts.rightField && opts.rightSource && opts.operation) { diffs.push(["constraint", "inserted", constraint]); if(info.type !== "left") { diffs.push(["constraint left", "inserted", constraintLeft]); } if(info.type !== "right") { diffs.push(["constraint right", "inserted", constraintRight]); } if(info.type !== "operation") { diffs.push(["constraint operation", "inserted", constraintOperation]); } } else { sendToServer = false; console.log("incomplete"); } break; case "removeViewConstraint": diffs = diff.removeViewConstraint(info.constraintId); break; case "undo": storeEvent = false; diffs = scaryUndoEvent(); break; case "redo": storeEvent = false; diffs = scaryRedoEvent(); break; default: console.error("Unhandled dispatch:", evt, info); break; } if(diffs && diffs.length) { if(storeEvent) { var eventItem = {event: event, diffs: diffs, children: [], parent: eventStack, localState: clone(localState)}; eventStack.children.push(eventItem); eventStack = eventItem; } ixer.handleDiffs(diffs); if(sendToServer) { window.client.sendToServer(diffs); } render(); } else { // console.warn("No diffs to index, skipping."); } } //--------------------------------------------------------- // Root //--------------------------------------------------------- function root() { var itemId = code.activeItemId(); var type = ixer.index("editor item to type")[itemId]; var workspace; if(type === "query") { workspace = queryWorkspace(itemId); } else if(type === "ui") { workspace = uiWorkspace(itemId); } else if(type === "table") { workspace = tableWorkspace(itemId); } return {id: "root", c: "root", children: [ editorItemList(itemId), workspace, ]}; } function editorItemList(itemId) { var items = ixer.facts("editor item").map(function(cur) { var id = cur[0]; var type = cur[1]; var klass = "editor-item " + type; var icon = "ion-grid"; if(type === "query") { icon = "ion-cube"; } else if(type === "ui") { icon = "ion-image"; } if(itemId === id) { klass += " selected"; } return {c: klass, click: selectEditorItem, dblclick: closeSelectEditorItem, dragData: {value: id, type: "view"}, itemId: id, draggable: true, dragstart: dragItem, children: [ {c: "icon " + icon}, {text: code.name(id)}, ]}; }) var width = 0; if(localState.showMenu) { width = 200; } return {c: "editor-item-list", width:width, children: [ {c: "title", click: toggleMenu, text: "items"}, {c: "adder", children: [ {c: "button table", click: addItem, event: "addTable", children: [ {c: "ion-grid"}, {c: "ion-plus"}, ]}, {c: "button query", click: addItem, event: "addQuery", children: [ {c: "ion-cube"}, {c: "ion-plus"}, ]}, {c: "button ui", click: addItem, event: "addUi", children: [ {c: "ion-image"}, {c: "ion-plus"}, ]}, ]}, {c: "items", children: items} ]}; } function addItem(e, elem) { dispatch(elem.event, {}); } function selectEditorItem(e, elem) { localState.activeItem = elem.itemId; var type = ixer.index("editor item to type")[elem.itemId]; if(type === "table") { localState.adderRows = [[]]; } else if(type === "ui") { var layer = ixer.index("parentLayerToLayers")[elem.itemId][0]; localState.uiActiveLayer = layer[1]; } render(); } function closeSelectEditorItem(e, elem) { localState.showMenu = false; selectEditorItem(e, elem); } function genericWorkspace(klass, controls, options, content) { var finalControls = controls; if(!localState.showMenu) { var finalControls = [{c: "menu-toggle", click: toggleMenu, text: "items"}].concat(controls); } return {id: "workspace", c: "workspace-container " + klass, children: [ {c: "control-bar", children: finalControls}, {c: "option-bar", children: options}, {c: "content", children: [content]} ]}; } function toggleMenu() { localState.showMenu = !localState.showMenu; render(); } function controlGroup(controls) { return {c: "control-group", children: controls}; } //--------------------------------------------------------- // Table workspace //--------------------------------------------------------- function tableWorkspace(tableId) { var fields = ixer.index("view to fields")[tableId].map(function(cur) { return {name: code.name(cur[1]), id: cur[1]}; }); var rows = ixer.facts(tableId); var order = ixer.index("display order"); rows.sort(function(a, b) { var aIx = order[tableId + JSON.stringify(a)]; var bIx = order[tableId + JSON.stringify(b)]; return aIx - bIx; }); return genericWorkspace("", [], [input(code.name(tableId), tableId, rename, rename)], {c: "table-editor", children: [ virtualizedTable(tableId, fields, rows, true) ]}); } function rename(e, elem, sendToServer) { var value = e.currentTarget.textContent; if(value !== undefined) { dispatch("rename", {value: value, id: elem.key, sendToServer: sendToServer, initial: [localState.initialKey, localState.initialValue]}); } } function virtualizedTable(id, fields, rows, isEditable) { var ths = fields.map(function(cur) { var oninput, onsubmit; if(cur.id) { oninput = onsubmit = rename; } return {c: "header", children: [input(cur.name, cur.id, oninput, onsubmit)]}; }); if(isEditable) { ths.push({c: "header add-column ion-plus", click: addField, table: id}); } var trs = []; rows.forEach(function(cur) { var tds = []; for(var tdIx = 0, len = fields.length; tdIx < len; tdIx++) { tds[tdIx] = {c: "field"}; // @NOTE: We can hoist this if perf is an issue. if(isEditable) { tds[tdIx].children = [input(cur[tdIx], {row: cur, ix: tdIx, view: id}, updateRow, submitRow)]; } else { tds[tdIx].text = cur[tdIx]; } } trs.push({c: "row", children: tds}); }) if(isEditable) { var adderRows = localState.adderRows; adderRows.forEach(function(cur, rowNum) { var tds = []; for(var i = 0, len = fields.length; i < len; i++) { tds[i] = {c: "field", children: [input(cur[i], {numFields:len, rowNum: rowNum, ix: i, view: id}, updateAdder, maybeSubmitAdder)]}; } trs.push({c: "row", children: tds}); }); } // trs.push({id: "spacer2", c: "spacer", height: Math.max(totalRows - start - numRows, 0) * itemHeight}); return {c: "table", children: [ {c: "headers", children: ths}, {c: "rows", children: trs} ]}; } function addField(e, elem) { dispatch("addField", {table: elem.table}); } function updateAdder(e, elem) { var key = elem.key; var row = localState.adderRows[key.rowNum]; row[key.ix] = coerceInput(e.currentTarget.textContent); } function maybeSubmitAdder(e, elem, type) { var key = elem.key; var row = localState.adderRows[key.rowNum]; row[key.ix] = coerceInput(e.currentTarget.textContent); if(row.length !== key.numFields) { return; } var isValid = row.every(function(cell) { return cell !== undefined; }); if(!isValid) { return; } localState.adderRows.splice(key.rowNum, 1); if(localState.adderRows.length === 0) { localState.adderRows.push([]); } dispatch("addRow", {table: key.view, neue: row}); } function updateRow(e, elem) { var neue = elem.key.row.slice(); neue[elem.key.ix] = coerceInput(e.currentTarget.textContent); } function submitRow(e, elem, type) { var neue = elem.key.row.slice(); neue[elem.key.ix] = coerceInput(e.currentTarget.textContent); dispatch("updateRow", {table: elem.key.view, old: elem.key.row, neue: neue}) } function input(value, key, oninput, onsubmit) { var blur, keydown; if(onsubmit) { blur = function inputBlur(e, elem) { onsubmit(e, elem, "blurred"); } keydown = function inputKeyDown(e, elem) { if(e.keyCode === KEYS.ENTER) { onsubmit(e, elem, "enter"); } } } return {c: "input text-input", contentEditable: true, input: oninput, focus: storeInitialInput, text: value, key: key, blur: blur, keydown: keydown}; } function storeInitialInput(e, elem) { localState.initialKey = elem.key; localState.initialValue = elem.text; } //--------------------------------------------------------- // UI workspace //--------------------------------------------------------- function uiWorkspace(componentId) { var elements = ixer.index("uiComponentToElements")[componentId] || []; var layers = ixer.index("uiComponentToLayers")[componentId] || []; var layerLookup = ixer.index("uiComponentLayer"); var activeLayerId = localState.uiActiveLayer; if(activeLayerId && layerLookup[activeLayerId]) { activeLayer = layerLookup[activeLayerId]; } var selectionInfo = getSelectionInfo(componentId, true); var canvasLayers = (ixer.index("parentLayerToLayers")[componentId] || []).map(function(layer) { return canvasLayer(layer, selectionInfo); }); if(selectionInfo) { canvasLayers.push(selection(selectionInfo)); } if(localState.boxSelectStart) { var rect = boxSelectRect(); canvasLayers.push({c: "box-selection", top: rect.top, left: rect.left, width: rect.width, height: rect.height}); } return genericWorkspace("query", [uiControls(componentId, activeLayer)], uiInspectors(componentId, selectionInfo, layers, activeLayer), {c: "ui-editor", children: [ {c: "ui-canvas", componentId: componentId, children: canvasLayers, mousedown: startBoxSelection, mouseup: stopBoxSelection, mousemove: adjustBoxSelection}, layersBox(componentId, layers, activeLayer), ]}); } function canvasLayer(layer, selectionInfo) { var layerId = layer[1]; var subLayers = (ixer.index("parentLayerToLayers")[layerId] || []).map(function(sub) { return canvasLayer(sub, selectionInfo); }); if(selectionInfo && layerId === localState.uiActiveLayer) { subLayers.unshift(uiGrid()); } var elements = ixer.index("uiLayerToElements")[layerId] || []; var attrsIndex = ixer.index("uiStyleToAttrs"); var stylesIndex = ixer.index("uiElementToStyles"); var els = elements.map(function(cur) { var id = cur[1]; var selected = selectionInfo ? selectionInfo.selectedIds[id] : false; var attrs = []; var styles = stylesIndex[id] || []; for(var ix = 0, len = styles.length; ix < len; ix++) { var style = styles[ix]; attrs.push.apply(attrs, attrsIndex[style[1]]); } return control(cur, attrs, selected, layer); }); return {c: "ui-canvas-layer", id: layer[1], zIndex: layer[3] + 1, children: subLayers.concat(els)}; } function layersBox(componentId, layers, activeLayer) { var parentIndex = ixer.index("parentLayerToLayers"); var rootLayers = parentIndex[componentId] || []; rootLayers.sort(function(a, b) { return a[3] - b[3]; }); var items = rootLayers.map(function(cur) { return layerListItem(cur, 0) }); return {c: "layers-box", children: [ {c: "controls", children: [ {c: "add-layer ion-plus", click: addLayer, componentId: componentId}, {c: "add-layer ion-ios-trash", click: deleteLayer, componentId: componentId}, ]}, {c: "layers-list", children: items} ]}; } function addLayer(e, elem) { localState.openLayers[localState.uiActiveLayer] = true; dispatch("addUiLayer", {componentId: elem.componentId, parentLayer: localState.uiActiveLayer}) } function deleteLayer(e, elem) { var layerId = localState.uiActiveLayer; var layer = ixer.index("uiComponentLayer")[layerId]; localState.uiActiveLayer = layer[6]; localState.uiSelection = false; dispatch("deleteLayer", {layer: layer}); } function layerListItem(layer, depth) { var layerId = layer[1]; var isOpen = localState.openLayers[layerId]; var subItems = []; var indent = 15; if(isOpen) { var binding = ixer.index("groupToBinding")[layerId]; if(binding) { var fieldItems = code.sortedViewFields(binding).map(function(field) { return {c: "layer-element group-binding", children: [ {c: "layer-row", draggable:true, dragstart: layerDrag, type: "binding", itemId: field, children:[ {c: "icon ion-ios-arrow-thin-right"}, {text: code.name(field)} ]}, ]} }); subItems.push({c: "layer-element group-binding", children: [ {c: "layer-row", children:[ {c: "icon ion-ios-photos"}, {text: code.name(binding)} ]}, {c: "layer-items", children: fieldItems} ]}); } var subLayers = ixer.index("parentLayerToLayers")[layerId]; if(subLayers) { subLayers.sort(function(a, b) { return a[3] - b[3]; }); subLayers.forEach(function(cur) { subItems.push(layerListItem(cur, depth+1)); }); } var elements = ixer.index("uiLayerToElements")[layerId] || []; elements.forEach(function(cur) { var elemId = cur[1]; var selectedClass = ""; if(localState.uiSelection && localState.uiSelection.indexOf(elemId) > -1) { selectedClass = " selected"; } subItems.push({c: "layer-element depth-" + (depth + 1) + selectedClass, control: cur, click: addToSelection, children: [ {c: "layer-row", itemId: elemId, draggable:true, dragstart: layerDrag, type: "element", children:[ {c: "icon ion-ios-crop" + (selectedClass ? "-strong" : "")}, {text: cur[4]} ]} ]}); }); } var icon = isOpen ? "ion-ios-arrow-down" : "ion-ios-arrow-right"; var activeClass = localState.uiActiveLayer === layerId ? " active" : ""; var lockedClass = layer[4] ? "ion-locked" : "ion-unlocked"; var hiddenClass = layer[5] ? "ion-eye-disabled" : "ion-eye"; return {c: "layer-item depth-" + depth + activeClass, layerId: layerId, dragover: preventDefault, drop: layerDrop, click: activateLayer, dblclick: selectAllFromLayer, children: [ {c: "layer-row", draggable: true, itemId: layerId, dragstart: layerDrag, type: "layer", children:[ {c: "icon " + icon, click: toggleOpenLayer, layerId: layerId}, input(code.name(layerId), layerId, rename, rename), {c: "controls", children: [ {c: hiddenClass, click: toggleHidden, dblclick:stopPropagation, layer: layer}, {c: lockedClass, click: toggleLocked, dblclick:stopPropagation, layer: layer}, ]} ]}, {c: "layer-items", children: subItems} ]}; } function toggleOpenLayer(e, elem) { localState.openLayers[elem.layerId] = !localState.openLayers[elem.layerId]; render(); } function layerDrag(e, elem) { e.dataTransfer.setData("type", elem.type); e.dataTransfer.setData("itemId", elem.itemId); e.stopPropagation(); } function layerDrop(e, elem) { e.stopPropagation(); var type = e.dataTransfer.getData("type"); if(type === "view" || type === "table" || type === "query") { //if it's a data item, then we need to setup a binding dispatch("bindGroup", {groupId: elem.layerId, itemId: e.dataTransfer.getData("value")}); } else if(type === "layer") { //if it's a layer, we need to reparent it var layerId = e.dataTransfer.getData("itemId"); if(layerId === elem.layerId) return; dispatch("changeParentLayer", {parentLayerId: elem.layerId, layerId: layerId}); } else if(type === "element") { //if it's an element, set the layer var elementId = e.dataTransfer.getData("itemId"); dispatch("changeElementLayer", {parentLayerId: elem.layerId, elementId: elementId}); } } function activateLayer(e, elem) { e.stopPropagation(); if(localState.uiActiveLayer !== elem.layerId) { localState.uiActiveLayer = elem.layerId; clearSelection(); } } function selectAllFromLayer(e, elem) { e.stopPropagation(); var layer = ixer.index("uiComponentLayer")[elem.layerId]; if(layer[4] || layer[5]) return; var elements = ixer.index("uiLayerToElements")[elem.layerId] || []; var sel = e.shiftKey ? localState.uiSelection : []; elements.forEach(function(cur) { sel.push(cur[1]); }); if(sel.length) { localState.uiSelection = sel; } else { localState.uiSelection = false; } render(); } function toggleHidden(e, elem) { e.stopPropagation(); //@TODO: this needs to recursively hide or unhide sub groups var neue = elem.layer.slice(); neue[5] = !neue[5]; dispatch("updateUiLayer", {neue: neue, old: elem.layer}); } function toggleLocked(e, elem) { e.stopPropagation(); //@TODO: this needs to recursively lock or unlock sub groups var neue = elem.layer.slice(); neue[4] = !neue[4]; dispatch("updateUiLayer", {neue: neue, old: elem.layer}); } function boxSelectRect() { var start = localState.boxSelectStart; var stop = localState.boxSelectStop; var topBottom = start[1] < stop[1] ? [start[1], stop[1]] : [stop[1], start[1]]; var leftRight = start[0] < stop[0] ? [start[0], stop[0]] : [stop[0], start[0]]; var width = leftRight[1] - leftRight[0]; var height = topBottom[1] - topBottom[0]; return {top: topBottom[0], bottom: topBottom[1], left: leftRight[0], right: leftRight[1], width: width, height: height}; } function startBoxSelection(e, elem) { if(!e.shiftKey) { clearSelection(e, elem); } var x = e.clientX; var y = e.clientY; var canvasRect = e.currentTarget.getBoundingClientRect(); x -= Math.floor(canvasRect.left); y -= Math.floor(canvasRect.top); localState.boxSelectStart = [x, y]; localState.boxSelectStop = [x, y]; render(); } function adjustBoxSelection(e, elem) { if(!localState.boxSelectStart) return; var x = e.clientX; var y = e.clientY; var canvasRect = e.currentTarget.getBoundingClientRect(); x -= Math.floor(canvasRect.left); y -= Math.floor(canvasRect.top); localState.boxSelectStop[0] = x; localState.boxSelectStop[1] = y; render(); } function elementIntersects(elem, rect) { var left = elem[5]; var top = elem[6]; var right = elem[7]; var bottom = elem[8]; return !(rect.left > right || rect.right < left || rect.top > bottom || rect.bottom < top); } function stopBoxSelection(e, elem) { if(!localState.boxSelectStart) return; var sel = e.shiftKey ? localState.uiSelection : []; var rect = boxSelectRect(); var componentId = elem.componentId; var elems = ixer.index("uiComponentToElements")[componentId]; var layerLookup = ixer.index("uiComponentLayer"); if(elems) { elems.forEach(function(cur) { // @TODO: this allows you to select from layers that are either hidden or locked var elemId = cur[1]; var layer = layerLookup[cur[3]]; if(layer[4] || layer[5]) return; if(elementIntersects(cur, rect)) { sel.push(elemId); } }); } localState.boxSelectStart = null; localState.boxSelectStop = null; if(sel.length) { localState.uiSelection = sel; } else { localState.uiSelection = false; } render(); } function canvasRatio(context) { var devicePixelRatio = window.devicePixelRatio || 1; var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; return devicePixelRatio / backingStoreRatio; } function uiGrid() { return {c: "grid", id: "ui-editor-grid", t: "canvas", top: 0, left: 0, postRender: function(canvas) { var uiGridCount = 3000; if(canvas._rendered) return; var bounds = document.querySelector(".ui-canvas").getBoundingClientRect(); var ctx = canvas.getContext("2d"); var ratio = canvasRatio(ctx); canvas.width = bounds.width * ratio; canvas.height = bounds.height * ratio; canvas.style.width = bounds.width; canvas.style.height = bounds.height; ctx.scale(ratio, ratio); ctx.lineWidth = 1; ctx.strokeStyle = "#999999"; for(var i = 0; i < uiGridCount; i++) { if(i % localState.uiGridSize === 0) { ctx.globalAlpha = 0.3; } else { ctx.globalAlpha = 0.1; } ctx.beginPath(); ctx.moveTo(i * localState.uiGridSize, 0); ctx.lineTo(i * localState.uiGridSize, bounds.height * 2); ctx.stroke(); ctx.beginPath(); ctx.moveTo(0, i * localState.uiGridSize); ctx.lineTo(bounds.width * 2, i * localState.uiGridSize); ctx.stroke(); } canvas._rendered = true; }}; } var resizeHandleSize = 7; function resizeHandle(componentId, bounds, y, x) { var top, left; var halfSize = Math.floor(resizeHandleSize / 2); var height = bounds.bottom - bounds.top; var width = bounds.right - bounds.left; if(x === "left") { left = 0 - halfSize - 1; } else if(x === "right") { left = width - halfSize - 2; } else { left = (width / 2) - halfSize; } if(y === "top") { top = 0 - halfSize - 1; } else if(y === "bottom") { top = height - halfSize - 2; } else { top = (height / 2) - halfSize; } return {c: "resize-handle", y: y, x: x, top: top, left: left, width: resizeHandleSize, height: resizeHandleSize, componentId: componentId, draggable: true, drag: resizeSelection, dragend: stopResizeSelection, bounds: bounds, dragstart: startResizeSelection, mousedown: stopPropagation}; } function stopPropagation(e) { e.stopPropagation(); } function preventDefault(e) { e.preventDefault(); } function clearDragImage(e, elem) { if(e.dataTransfer) { e.dataTransfer.setData("text", "foo"); e.dataTransfer.setDragImage(document.getElementById("clear-pixel"), 0, 0); } } function startResizeSelection(e, elem) { localState.oldElements = selectionToElements(); clearDragImage(e); } function stopResizeSelection(e, elem) { var elems = localState.oldElements; localState.oldElements = null; dispatch("stopChangingSelection", {oldElements: elems}) } function resizeSelection(e, elem) { var x = Math.floor(e.clientX || __clientX); var y = Math.floor(e.clientY || __clientY); if(x === 0 && y === 0) return; var canvasRect = e.currentTarget.parentNode.parentNode.getBoundingClientRect(); x -= Math.floor(canvasRect.left); y -= Math.floor(canvasRect.top); var old = elem.bounds; var neueBounds = {left: old.left, right: old.right, top: old.top, bottom: old.bottom}; if(elem.x === "left") { neueBounds.left = toGrid(localState.uiGridSize, x); } else if(elem.x === "right") { neueBounds.right = toGrid(localState.uiGridSize, x); } if(elem.y === "top") { neueBounds.top = toGrid(localState.uiGridSize, y); } else if(elem.y === "bottom") { neueBounds.bottom = toGrid(localState.uiGridSize, y); } var neueWidth = neueBounds.right - neueBounds.left; var neueHeight = neueBounds.bottom - neueBounds.top; if(neueWidth < 10) { neueWidth = 10; if(elem.x === "left") { neueBounds.left = neueBounds.right - 10; } else { neueBounds.right = neueBounds.left + 10; } } if(neueHeight < 10) { neueHeight = 10; if(elem.y === "top") { neueBounds.top = neueBounds.bottom - 10; } else { neueBounds.bottom = neueBounds.top + 10; } } var widthRatio = neueWidth / (old.right - old.left); var heightRatio = neueHeight / (old.bottom - old.top); if(widthRatio !== 1 || heightRatio !== 1) { dispatch("resizeSelection", {widthRatio: widthRatio, heightRatio: heightRatio, oldBounds: old, neueBounds: neueBounds, componentId: elem.componentId}); elem.bounds = neueBounds; } } function selection(selectionInfo) { var componentId = selectionInfo.componentId; var bounds = selectionInfo.bounds; return {c: "selection", top: bounds.top, left: bounds.left, width: bounds.right - bounds.left, height: bounds.bottom - bounds.top, children: [ resizeHandle(componentId, bounds, "top", "left"), resizeHandle(componentId, bounds, "top", "center"), resizeHandle(componentId, bounds, "top", "right"), resizeHandle(componentId, bounds, "middle", "right"), resizeHandle(componentId, bounds, "bottom", "right"), resizeHandle(componentId, bounds, "bottom", "center"), resizeHandle(componentId, bounds, "bottom", "left"), resizeHandle(componentId, bounds, "middle", "left"), {c: "trash ion-ios-trash", componentId: componentId, mousedown:stopPropagation, click: deleteSelection}, ]}; } function deleteSelection(e, elem) { dispatch("deleteSelection", {componentId: elem.componentId}); } function clearSelection(e, elem) { localState.uiSelection = null; render(); } function control(cur, attrs, selected, layer) { var id = cur[1]; var type = cur[4]; var selClass = selected ? " selected" : ""; var hidden = layer[5] ? " hidden" : ""; var locked = layer[4] ? " locked" : ""; var klass = type + " ui-element" + selClass + hidden + locked; var elem = {c: klass, id: "elem" + id, left: cur[5], top: cur[6], width: cur[7] - cur[5], height: cur[8] - cur[6], control: cur, mousedown: addToSelection, selected: selected, zIndex: layer[3] + 1, draggable: true, dragover: preventDefault, drop: dropOnControl, drag: moveSelection, dragend: stopMoveSelection, dragstart: startMoveSelection, dblclick: setModifyingText}; if(attrs) { for(var i = 0, len = attrs.length; i < len; i++) { var curAttr = attrs[i]; var name = attrMappings[curAttr[2]] || curAttr[2]; if(curAttr[3].constructor !== Array) { elem[name] = curAttr[3]; } } } if(type === "image") { elem.attr = "backgroundImage"; } else { elem.attr = "text"; } var binding = (ixer.index("elementAttrToBinding")[id] || {})[elem.attr]; if(binding) { elem.children = [ {c: "attr-binding", children: [ {c: "icon ion-ios-arrow-thin-right"}, {text: code.name(binding)} ]} ]; elem.text = undefined; } if(localState.modifyingUiText === id) { if(type === "image") { var curInput = input(elem.backgroundImage, {id: id}, updateImage, submitContent); curInput.postRender = focusOnce; elem.children = [curInput]; curInput.attr = "backgroundImage"; elem.text = undefined; } else { var curInput = input(elem.text, {id: id}, updateContent, submitContent); curInput.postRender = focusOnce; elem.children = [curInput]; curInput.attr = "text"; elem.text = undefined; } } // if(uiCustomControlRender[type]) { // elem = uiCustomControlRender[type](elem); // } return elem; } function dropOnControl(e, elem) { var type = e.dataTransfer.getData("type"); if(type === "binding") { dispatch("bindAttr", {attr: elem.attr, elementId: elem.control[1], field: e.dataTransfer.getData("itemId")}) e.stopPropagation(); } } function setModifyingText(e, elem) { localState.modifyingUiText = elem.control[1]; startAdjustAttr(e, elem); render(); } function updateContent(e, elem) { dispatch("setAttributeForSelection", {componentId: elem.key.id, property: "text", value: e.currentTarget.textContent}); } function updateImage(e, elem) { dispatch("setAttributeForSelection", {componentId: elem.key.id, property: "backgroundImage", value: e.currentTarget.textContent}); } function submitContent(e, elem) { localState.modifyingUiText = false; dispatch("stopSetAttributeForSelection", {oldAttrs: localState.initialAttrs, property: elem.attr}); render(); } function addToSelection(e, elem) { e.stopPropagation(); if(elem.selected) return; if(!e.shiftKey || !localState.uiSelection) { localState.uiSelection = []; } var layer = ixer.index("uiComponentLayer")[elem.control[3]]; if(layer[4] || layer[5]) return; localState.uiSelection.push(elem.control[1]); localState.uiActiveLayer = elem.control[3]; render(); } var __clientX, __clientY; document.body.addEventListener("dragover", function(e) { //@HACK: because Firefox is a browser full of sadness, they refuse to //set clientX and clientY on drag events. As such we have this ridiculous //workaround of tracking position at the body. __clientX = e.clientX; __clientY = e.clientY; }); function toGrid(size, value) { return Math.round(value / size) * size; } function startMoveSelection(e, elem) { var x = e.clientX || __clientX; var y = e.clientY || __clientY; if(x === 0 && y === 0) return; var canvasRect = e.currentTarget.parentNode.getBoundingClientRect(); localState.dragOffsetX = x - elem.left - canvasRect.left; localState.dragOffsetY = y - elem.top - canvasRect.top; localState.initialElements = selectionToElements(); clearDragImage(e); if(e.altKey) { //@HACK: if you cause a rerender before the event finishes, the drag is killed? setTimeout(function() { dispatch("duplicateSelection", {componentId: elem.control[2]}); }, 0); } } function moveSelection(e, elem) { var x = Math.floor(e.clientX || __clientX); var y = Math.floor(e.clientY || __clientY); if(x === 0 && y === 0) return; var canvasRect = e.currentTarget.parentNode.getBoundingClientRect(); x -= Math.floor(canvasRect.left); y -= Math.floor(canvasRect.top); var neueX = toGrid(localState.uiGridSize, Math.floor(x - localState.dragOffsetX)); var neueY = toGrid(localState.uiGridSize, Math.floor(y - localState.dragOffsetY)); dispatch("moveSelection", {x: neueX, y: neueY, elemId: elem.control[1], componentId: elem.control[2]}); } function stopMoveSelection(e, elem) { var elems = localState.initialElements; localState.initialElements = null; dispatch("stopChangingSelection", {oldElements: elems}) } function selectionToElements() { if(localState.uiSelection) { var elementIndex = ixer.index("uiComponentElement"); return localState.uiSelection.map(function(cur) { return elementIndex[cur]; }); } return []; } function getSelectionInfo(componentId, withAttributes) { var sel = localState.uiSelection; var elements; if(sel) { var elementIndex = ixer.index("uiComponentElement"); elements = sel.map(function(cur) { return elementIndex[cur]; }); var result = getGroupInfo(elements, withAttributes); result.componentId = componentId; result.selectedIds = result.ids; return result; } return false; } function getGroupInfo(elements, withAttributes) { elements = elements || []; var attrsIndex = ixer.index("uiStyleToAttrs"); var stylesIndex = ixer.index("uiElementToStyles"); var ids = {}; var attributes = {}; var styles = {}; var els = elements.map(function(cur) { var id = cur[1]; ids[id] = true; if(withAttributes !== undefined) { var elStyles = stylesIndex[id]; if(!elStyles) { return cur; } var attrs = []; for(var ix = 0, len = elStyles.length; ix < len; ix++) { var style = elStyles[ix]; var type = style[2]; if(styles[type] === undefined) { styles[type] = style; } else if(!style || !styles[type] || styles[type][1] !== style[1]) { styles[type] = null; } attrs.push.apply(attrs, attrsIndex[style[1]]); } if(attrs) { attrs.forEach(function(cur) { var key = cur[2]; var value = cur[3]; if(attributes[key] === undefined) { attributes[key] = value; } else if(attributes[key] !== value) { attributes[key] = null; } }); } } return cur; }); var bounds = boundElements(els); return {ids: ids, elements: els, bounds: bounds, attributes: attributes, styles: styles}; } function boundElements(elems) { var bounds = {top: Infinity, left: Infinity, bottom: -Infinity, right: -Infinity}; elems.forEach(function(cur) { var left = cur[5], top = cur[6], right = cur[7], bottom = cur[8]; if(left < bounds.left) { bounds.left = left; } if(top < bounds.top) { bounds.top = top; } if(right > bounds.right) { bounds.right = right; } if(bottom > bounds.bottom) { bounds.bottom = bottom; } }); return bounds; } var uiControlInfo = [{text: "text", icon: ""}, {text: "image", icon: ""}, {text: "box", icon: ""}, {text: "button", icon: ""}, {text: "input", icon: ""}, {text: "map", icon: ""} ]; function uiControls(componentId, activeLayer) { var items = uiControlInfo.map(function(cur) { return {c: "control", click: addElement, controlType: cur.text, componentId: componentId, layer: activeLayer, children: [ {c: "icon"}, {text: cur.text} ]}; }) return controlGroup(items); } function addElement(e, elem) { dispatch("addUiComponentElement", {componentId: elem.componentId, layerId: elem.layer[1], control: elem.controlType, left: elem.left || 100, right: elem.right || 200, top: elem.top || 100, bottom: elem.bottom || 200}) } var attrMappings = {"content": "text"}; var uiProperties = {}; function uiInspectors(componentId, selectionInfo, layers, activeLayer) { var inspectors = []; var activeLayerId; var binding; var elements; if(activeLayer) { activeLayerId = activeLayer[1]; elements = ixer.index("uiLayerToElements")[activeLayerId]; binding = ixer.index("groupToBinding")[activeLayerId]; } if(selectionInfo) { // @TODO: Only show appropriate inspectors for each type based on trait instead of hardcoding. inspectors.push(layoutInspector(selectionInfo, binding), appearanceInspector(selectionInfo, binding), textInspector(selectionInfo, binding)); // var showMapInspector = selectionInfo.elements.every(function(cur) { // return cur[4] === "map"; // }); // if(showMapInspector) { // var mapInfo = getMapGroupInfo(selectionInfo.elements, true) // inspectors.push(mapInspector(selectionInfo, mapInfo, binding)); // } } else if(activeLayer) { inspectors.push(layerInspector(activeLayer, elements)); } return inspectors; } function adjustable(value, start, stop, step) { return {c: "adjustable", mousedown: startAdjusting, adjustHandler: adjustAdjustable, value: value, start: start, stop: stop, step: step, text: value}; } var adjustableShade = document.createElement("div"); adjustableShade.className = "adjustable-shade"; adjustableShade.addEventListener("mousemove", function(e) { if(adjusterInfo) { adjusterInfo.handler(e, renderer.tree[adjusterInfo.elem.id]); } }) adjustableShade.addEventListener("mouseup", function(e) { if(adjusterInfo.elem.finalizer) { adjusterInfo.elem.finalizer(e, renderer.tree[adjusterInfo.elem.id]); } adjusterInfo = false; document.body.removeChild(adjustableShade); }) var adjusterInfo; function startAdjusting(e, elem) { if(elem.initializer) { elem.initializer(e, elem); } adjusterInfo = {elem: elem, startValue: elem.value, handler: elem.adjustHandler, bounds: {left: e.clientX, top: e.clientY}}; document.body.appendChild(adjustableShade); } function adjustAdjustable(e, elem) { var x = e.clientX || __clientX; var y = e.clientY || __clientY; if(x === 0 && y === 0) return; var rect = adjusterInfo.bounds; var offsetX = Math.floor(x - rect.left); var offsetY = Math.floor(y - rect.top); var adjusted = Math.floor(adjusterInfo.startValue + offsetX); var neue = Math.min(Math.max(elem.start, adjusted), elem.stop); if(elem.handler) { elem.handler(elem, neue); } } uiProperties.layout = ["top", "left", "width", "height"]; function layoutInspector(selectionInfo, binding) { var componentId = selectionInfo.componentId; var bounds = selectionInfo.bounds; var width = bounds.right - bounds.left; var height = bounds.bottom - bounds.top; var widthAdjuster = adjustable(width, 1, 1000, 1); widthAdjuster.handler = adjustWidth; widthAdjuster.componentId = componentId; widthAdjuster.bounds = bounds; widthAdjuster.initializer = startResizeSelection; widthAdjuster.finalizer = stopResizeSelection; var heightAdjuster = adjustable(height, 1, 1000, 1); heightAdjuster.handler = adjustHeight; heightAdjuster.componentId = componentId; heightAdjuster.bounds = bounds; heightAdjuster.initializer = startResizeSelection; heightAdjuster.finalizer = stopResizeSelection; var topAdjuster = adjustable(bounds.top, 0, 100000, 1); topAdjuster.handler = adjustPosition; topAdjuster.componentId = componentId; topAdjuster.coord = "top"; topAdjuster.initializer = startMoveSelection; topAdjuster.finalizer = stopMoveSelection; var leftAdjuster = adjustable(bounds.left, 0, 100000, 1); leftAdjuster.handler = adjustPosition; leftAdjuster.componentId = componentId; leftAdjuster.coord = "left"; leftAdjuster.initializer = startMoveSelection; leftAdjuster.finalizer = stopMoveSelection; //pos, size return {c: "option-group", children: [ {c: "label", text: "x:"}, leftAdjuster, {c: "label", text: "y:"}, topAdjuster, {c: "label", text: "w:"}, widthAdjuster, {c: "label", text: "h:"}, heightAdjuster, ]}; } uiProperties.appearance = ["backgroundColor", "backgroundImage", "borderColor", "borderWidth", "borderRadius", "opacity"]; function appearanceInspector(selectionInfo, binding) { var attrs = selectionInfo.attributes; var componentId = selectionInfo.componentId; var styleName; if(selectionInfo.styles.appearance && selectionInfo.styles.appearance[4]) { styleName = {value:selectionInfo.styles.appearance[1], text: code.name(selectionInfo.styles.appearance[1])}; } else { styleName = {text: "No visual style", value: "none"}; } var borderColorPicker = colorSelector(componentId, "borderColor", attrs["borderColor"]); borderColorPicker.backgroundColor = undefined; var opacity = attrs["opacity"] == undefined ? 100 : attrs["opacity"] * 100; var opacityAdjuster = adjustable(opacity, 0, 100, 1); opacityAdjuster.text = Math.floor(opacity) + "%"; opacityAdjuster.handler = adjustOpacity; opacityAdjuster.componentId = componentId; opacityAdjuster.initializer = startAdjustAttr; opacityAdjuster.finalizer = stopAdjustAttr; opacityAdjuster.attr = "opacity"; var borderWidth = attrs["borderWidth"] === undefined ? 0 : attrs["borderWidth"]; var borderWidthAdjuster = adjustable(borderWidth, 0, 20, 1); borderWidthAdjuster.text = borderWidth + "px"; borderWidthAdjuster.handler = adjustAttr; borderWidthAdjuster.attr = "borderWidth"; borderWidthAdjuster.componentId = componentId; borderWidthAdjuster.initializer = startAdjustAttr; borderWidthAdjuster.finalizer = stopAdjustAttr; var borderRadius = attrs["borderRadius"] === undefined ? 0 : attrs["borderRadius"]; var borderRadiusAdjuster = adjustable(borderRadius, 0, 100, 1); borderRadiusAdjuster.text = borderRadius + "px"; borderRadiusAdjuster.handler = adjustAttr; borderRadiusAdjuster.attr = "borderRadius"; borderRadiusAdjuster.componentId = componentId; borderRadiusAdjuster.initializer = startAdjustAttr; borderRadiusAdjuster.finalizer = stopAdjustAttr; if(!localState.addingAppearanceStyle) { var sharedAppearance = (ixer.index("stylesBySharedAndType")[true] || {})["appearance"] || []; var styles = sharedAppearance.map(function(cur) { return {value: cur[1], text: code.name(cur[1])}; }); styles.unshift({text: "No text style", value: "none"}); styles.push({text: "Add a new style", value: "addStyle"}); var visualStyle = selectable(styleName, styles); visualStyle.c += " styleSelector"; visualStyle.handler = function(elem, value) { if(value === "none") { dispatch("setSelectionStyle", {type: "appearance", id: uuid(), shared: false}); } else if(value === "addStyle") { localState.addingAppearanceStyle = uuid(); dispatch("setSelectionStyle", {type: "appearance", id: localState.addingAppearanceStyle, shared: true}); } else { dispatch("setSelectionStyle", {type: "appearance", id: value, shared: true}); } render(); } } else { visualStyle = input("", localState.addingAppearanceStyle, rename, doneAddingStyle); visualStyle.postRender = focusOnce; } return {c: "option-group", children: [ visualStyle, {c: "layout-box-filled", borderRadius: attrs["borderRadius"], children: [ colorSelector(componentId, "backgroundColor", attrs["backgroundColor"]) ]}, {c: "layout-box-outline", borderRadius: attrs["borderRadius"], borderWidth: (borderWidth > 10 ? 10 : borderWidth || 1), borderColor: attrs["borderColor"], children: [borderColorPicker]}, {c: "label", text: "w:"}, borderWidthAdjuster, {c: "label", text: "r:"}, borderRadiusAdjuster, {c: "label", text: "opacity:"}, opacityAdjuster ]}; } function selectable(activeItem, items, setFont) { var options = items.map(function(cur) { var value, text; if(typeof cur === "string") { value = cur; text = cur; } else { value = cur.value; text = cur.text; } var item = {t: "option", value: value, text: text}; if(setFont) { item.fontFamily = cur; } if((activeItem.value || activeItem) === value) { item.selected = "selected"; } return item; }) var value = typeof activeItem === "string" ? activeItem : activeItem.text; return {c: "selectable", change: selectSelectable, children: [ {t: "select", children: options}, {c: "selectable-value", text: value} ]} } function selectSelectable(e, elem) { if(elem.handler) { elem.handler(elem, e.target.value); } } var alignMapping = { "flex-start": "Left", "center": "Center", "flex-end": "Right", } var vAlignMapping = { "flex-start": "Top", "center": "Center", "flex-end": "Bottom", } function selectVerticalAlign(elem, value) { var final = "center"; if(value === "Top") { final = "flex-start"; } else if(value === "Bottom") { final = "flex-end"; } dispatch("setAttributeForSelection", {componentId: elem.componentId, property: "verticalAlign", value: final, storeEvent: true}); } function selectAlign(elem, value) { var final = "center"; if(value === "Left") { final = "flex-start"; } else if(value === "Right") { final = "flex-end"; } dispatch("setAttributeForSelection", {componentId: elem.componentId, property: "textAlign", value: final, storeEvent: true}); } uiProperties.typography = ["fontFamily", "fontSize", "color", "textAlign", "verticalAlign"]; uiProperties.content = ["text"]; function textInspector(selectionInfo, binding) { var componentId = selectionInfo.componentId; var attrs = selectionInfo.attributes; var styleName; if(selectionInfo.styles.typography && selectionInfo.styles.typography[4]) { styleName = {value:selectionInfo.styles.typography[1], text: code.name(selectionInfo.styles.typography[1])}; } else { styleName = {text: "No text style", value: "none"}; } var font = attrs["fontFamily"] || "Helvetica Neue"; var fontPicker = selectable(font, ["Times New Roman", "Verdana", "Arial", "Georgia", "Avenir", "Helvetica Neue"], true); fontPicker.componentId = componentId; fontPicker.handler = adjustAttr; fontPicker.attr = "fontFamily"; fontPicker.storeEvent = true; var fontSize = attrs["fontSize"] === undefined ? 16 : attrs["fontSize"]; var fontSizeAdjuster = adjustable(fontSize, 0, 300, 1); fontSizeAdjuster.handler = adjustAttr; fontSizeAdjuster.attr = "fontSize"; fontSizeAdjuster.componentId = componentId; fontSizeAdjuster.initializer = startAdjustAttr; fontSizeAdjuster.finalizer = stopAdjustAttr; var fontColor = colorSelector(componentId, "color", attrs["color"]); fontColor.color = attrs["color"]; fontColor.c += " font-color"; var verticalAlign = vAlignMapping[attrs["verticalAlign"]] || "Top"; var valign = selectable(verticalAlign, ["Top", "Center", "Bottom"]); valign.componentId = componentId; valign.handler = selectVerticalAlign; var textAlign = alignMapping[attrs["textAlign"]] || "Left"; var align = selectable(textAlign, ["Left", "Center", "Right"]); align.componentId = componentId; align.handler = selectAlign; if(!localState.addingTypographyStyle) { var sharedTypography = (ixer.index("stylesBySharedAndType")[true] || {})["typography"] || []; var styles = sharedTypography.map(function(cur) { return {value: cur[1], text: code.name(cur[1])}; }); styles.unshift({text: "No text style", value: "none"}); styles.push({text: "Add a new style", value: "addStyle"}); var typographyStyle = selectable(styleName, styles); typographyStyle.c += " styleSelector"; typographyStyle.handler = function(elem, value) { if(value === "none") { dispatch("setSelectionStyle", {type: "typography", id: uuid(), shared: false}); } else if(value === "addStyle") { localState.addingTypographyStyle = uuid(); dispatch("setSelectionStyle", {type: "typography", id: localState.addingTypographyStyle, shared: true}); } else { dispatch("setSelectionStyle", {type: "typography", id: value, shared: true}); } render(); } } else { typographyStyle = input("", localState.addingTypographyStyle, rename, doneAddingStyle); typographyStyle.postRender = focusOnce; } return {c: "option-group", children: [ typographyStyle, fontColor, {c: "label", text: "size:"}, fontSizeAdjuster, {c: "label", text: "font:"}, fontPicker, {c: "label", text: "align:"}, valign, align, ]}; } function doneAddingStyle(e, elem) { localState.addingTypographyStyle = null; localState.addingAppearanceStyle = null; render(); } uiProperties.layer = []; function layerInspector(layer, elements) { var componentId = layer[2]; var info = getGroupInfo(elements, true); var attrs = info.attributes; // @FIXME: Layer attributes. var bounds = info.bounds; return {c: "inspector-panel", children: []}; } uiProperties.map = []; function mapInspector(selectionInfo, mapInfo, binding) { var componentId = selectionInfo.componentId; var attrs = mapInfo.attributes; return {c: "inspector-panel", children: [ {c: "title", text: "Map"}, {c: "pair", children: [{c: "label", text: "lat."}, inspectorInput(attrs["lat"], [componentId, "lat"], setMapAttribute, binding)]}, {c: "pair", children: [{c: "label", text: "long."}, inspectorInput(attrs["lng"], [componentId, "lng"], setMapAttribute, binding)]}, {c: "pair", children: [{c: "label", text: "zoom"}, inspectorInput(attrs["zoom"], [componentId, "zoom"], setMapAttribute, binding)]}, {c: "pair", children: [{c: "label", text: "interactive"}, inspectorCheckbox(attrs["draggable"], [componentId, "draggable"], setMapAttribute, binding)]}, ]}; } uiProperties.repeat = []; function repeatInspector() { } // Inputs function inspectorInput(value, key, onChange, binding) { if(value === null) { input.placeholder = "---"; } else if(typeof value === "number" && !isNaN(value)) { value = value.toFixed(2); } else if(value && value.constructor === Array) { value = "Bound to " + code.name(value[2]); } var field = input(value, key, onChange, preventDefault); field.mousedown = stopPropagation; field.editorType = "binding"; field.binding = binding; field.focus = activateTokenEditor; field.blur = closeTokenEditor; return field; } function inspectorCheckbox(value, key, onChange, binding) { if(value && value.constructor === Array) { value = "Bound to " + code.name(value[2]); } var field = checkboxInput(value, key, onChange); field.mousedown = stopPropagation; field.editorType = "binding"; field.binding = binding; field.focus = activateTokenEditor; field.blur = closeTokenEditor; return field; } function closeBindingEditor(e, elem) { if(editorInfo.element === e.currentTarget) { setTimeout(function() { editorInfo = false; rerender(); }, 0); } } function bindingEditor(editorInfo) { var binding = editorInfo.info.binding; if(!binding) return; var fields = code.viewToFields(binding).map(function(cur) { return ["field", binding, cur[2]]; }); return genericEditor(fields, false, false, false, "column", setBinding); } function setBinding(e, elem) { var info = editorInfo.info; var componentId = info.key[0]; var property = info.key[1]; console.log("SET", componentId, property, elem.cur); editorInfo = false; dispatch("setAttributeForSelection", {componentId: componentId, property: property, value: ["binding", elem.cur[1], elem.cur[2]]}); } function colorSelector(componentId, attr, value) { return {c: "color-picker", backgroundColor: value || "#999999", mousedown: stopPropagation, children: [ {t: "input", type: "color", key: [componentId, attr], value: value, input: setAttribute} ]}; } function styleSelector(id, opts, onClose) { var options = {}; if(opts.initial === "---") { options["default"] = "---"; } var styles = ixer.index("uiStyles"); for(var key in styles) { var cur = styles[key][0]; if(cur[2] === opts.type && code.name(cur[1])) { options[cur[1]] = code.name(cur[1]); } } return selectInput(opts.initial, opts.id, options, onClose); } // Layout handlers function adjustWidth(elem, value) { var componentId = elem.componentId; var old = elem.bounds; var neue = {left: old.left, right: (old.left + value), top: old.top, bottom: old.bottom}; var widthRatio = value / (old.right - old.left); if(widthRatio === 1) return; dispatch("resizeSelection", {widthRatio: widthRatio, heightRatio: 1, oldBounds: old, neueBounds: neue, componentId: componentId}); elem.bounds = neue; } function adjustHeight(elem, value) { var componentId = elem.componentId; var old = elem.bounds; var neue = {left: old.left, right: old.right, top: old.top, bottom: (old.top + value)}; var heightRatio = value / (old.bottom - old.top); if(heightRatio === 1) return; dispatch("resizeSelection", {widthRatio: 1, heightRatio: heightRatio, oldBounds: old, neueBounds: neue, componentId: componentId}); elem.bounds = neue; } function adjustPosition(elem, value) { var componentId = elem.componentId; var coord = elem.coord; var diffX = 0, diffY = 0; if(coord === "top") { diffY = value - elem.value; } else { diffX = value - elem.value; } dispatch("offsetSelection", {diffX: diffX, diffY: diffY, componentId: componentId}); elem.value = value; } function startAdjustAttr(e, elem) { var attrs = [] var style = getUiPropertyType(elem.attr); if(!style) { throw new Error("Unknown attribute type for property:", elem.attr, "known types:", uiProperties); } var sel = localState.uiSelection; sel.forEach(function(cur) { var id = cur; var styleId = ixer.index("uiElementToStyle")[id][style][1]; var oldProps = ixer.index("uiStyleToAttr")[styleId]; if(oldProps) { attrs.push(oldProps[elem.attr]); } }); localState.initialAttrs = attrs; } function stopAdjustAttr(e, elem) { var initial = localState.initialAttrs; localState.initialAttrs = null; dispatch("stopSetAttributeForSelection", {oldAttrs: initial, property: elem.attr}); } function adjustOpacity(elem, value) { dispatch("setAttributeForSelection", {componentId: elem.componentId, property: "opacity", value: value / 100, storeEvent: false}); } function adjustAttr(elem, value) { dispatch("setAttributeForSelection", {componentId: elem.componentId, property: elem.attr, value: value, storeEvent: elem.storeEvent}); } // Generic attribute handler function setAttribute(e, elem) { var componentId = elem.key[0]; var property = elem.key[1]; var target = e.currentTarget; var value = target.value; if(target.type === "color") { value = target.value; } else if(target.type === "checkbox") { value = target.checked; } else if(target.type === undefined) { value = target.textContent; } dispatch("setAttributeForSelection", {componentId: componentId, property: property, value: value}); } // Map attribute handler function setMapAttribute(e, elem) { var componentId = elem.key[0]; var property = elem.key[1]; var target = e.currentTarget; var value = target.checked !== undefined ? target.checked : target.value !== undefined ? target.value : target.textContent; dispatch("setMapAttributeForSelection", {componentId: componentId, property: property, value: value}); } function getUiPropertyType(prop) { if(uiProperties.typography.indexOf(prop) !== -1) { return "typography"; } if(uiProperties.appearance.indexOf(prop) !== -1) { return "appearance"; } if(uiProperties.layout.indexOf(prop) !== -1) { return "layout"; } if(uiProperties.content.indexOf(prop) !== -1) { return "content"; } return undefined; } //--------------------------------------------------------- // Query workspace //--------------------------------------------------------- function queryWorkspace(queryId) { return genericWorkspace("query", [queryControls(queryId)], [], {c: "query-editor", children: [ {c: "query-workspace", children: [ editor(queryId) ]}, queryResult(queryId) ]}); } //--------------------------------------------------------- // Tree + Toolbar //--------------------------------------------------------- function treeItem(name, value, type, opts) { opts = opts || {}; return {c: "tree-item " + opts.c, dragData: {value: value, type: type}, draggable: true, dragstart: dragItem, children: [ (opts.icon ? {c: "opts.icon"} : undefined), (name ? {text: name} : undefined), opts.content ]}; } function fieldItem(name, fieldId, opts) { opts = opts || {}; return {c: "tree-item " + opts.c, dragData: {fieldId: fieldId, type: "field"}, draggable: true, dragstart: dragItem, children: [ (opts.icon ? {c: "opts.icon"} : undefined), (name ? {text: name} : undefined), opts.content ]}; } function dragItem(evt, elem) { for(var key in elem.dragData) { evt.dataTransfer.setData(key, elem.dragData[key]); } } var queryTools = { union: ["merge"], aggregate: ["sort+limit", "sum", "count", "min", "max", "empty"] }; function queryControls(queryId) { var items = []; var toolTypes = Object.keys(queryTools); for(var typeIx = 0; typeIx < toolTypes.length; typeIx++) { var type = toolTypes[typeIx]; var tools = queryTools[type]; for(var toolIx = 0; toolIx < tools.length; toolIx++) { var tool = tools[toolIx]; items.push(treeItem(tool, tool, type, {c: "control tool query-tool"})); } } return controlGroup(items); } //--------------------------------------------------------- // Editor //--------------------------------------------------------- function editor(queryId) { var blocks = ixer.index("query to blocks")[queryId] || []; var items = []; for(var ix = 0; ix < blocks.length; ix++) { var viewId = blocks[ix][code.ix("block", "view")]; var viewKind = ixer.index("view to kind")[viewId]; var editorPane; if(viewKind === "join") { editorPane = viewBlock(viewId); } if(viewKind === "union") { editorPane = unionBlock(viewId); } if(viewKind === "aggregate") { editorPane =aggregateBlock(viewId); } var rows = ixer.facts(viewId) || []; var fields = (ixer.index("view to fields")[viewId] || []).map(function(field) { var id = field[code.ix("field", "field")]; return {name: code.name(id), id: id}; }); // This is a weird way to use display order. var order = ixer.index("display order"); rows.sort(function(a, b) { var aIx = order[viewId + JSON.stringify(a)]; var bIx = order[viewId + JSON.stringify(b)]; return aIx - bIx; }); var inspectorPane = {c: "inspector-pane", children: [virtualizedTable(viewId, fields, rows, false)]}; items.push({c: "block " + viewKind, children: [ editorPane, inspectorPane ]}); } if(items.length) { items.push({c: "add-aggregate-btn", text: "Add an aggregate by dragging it here...", queryId: queryId}); } return {c: "workspace", queryId: queryId, drop: editorDrop, dragover: preventDefault, children: items.length ? items : [ {c: "feed", text: "Feed me sources"} ]}; } function editorDrop(evt, elem) { var type = evt.dataTransfer.getData("type"); var value = evt.dataTransfer.getData("value"); if(type === "view") { return dispatch("addViewBlock", {queryId: elem.queryId, sourceId: value, kind: "join"}); } if(type === "aggregate") { return dispatch("addAggregateBlock", {queryId: elem.queryId, kind: value}); } if(type === "union") { return dispatch("addUnionBlock", {queryId: elem.queryId}); } } /** * View Block */ function viewBlock(viewId) { var fields = ixer.index("view and source to block fields")[viewId] || {}; fields = fields["selection"] || []; var selectionItems = fields.map(function(field) { var id = field[code.ix("block field", "block field")]; return fieldItem(code.name(id) || "Untitled", id, {c: "pill field"}); }); if(!selectionItems.length) { selectionItems.push({text: "Drag local fields into me to make them available in the query."}); } var groupedBy = ixer.index("grouped by")[viewId]; return {c: "block view-block", viewId: viewId, drop: viewBlockDrop, dragover: preventDefault, children: [ {c: "block-title", children: [ {t: "h3", text: "Untitled Block"}, {c: "hover-reveal close-btn ion-android-close", viewId: viewId, click: removeViewBlock} ]}, viewSources(viewId), viewConstraints(viewId), (groupedBy ? {c: "block-section view-grouping", children: [ {text: "Grouped by"}, {text: code.name(groupedBy[code.ix("grouped by", "inner field")])}, {text: "="}, {text: code.name(groupedBy[code.ix("grouped by", "outer field")])}, ]} : undefined), {c: "block-section view-selections tree bar", viewId: viewId, drop: viewSelectionsDrop, dragover: preventDefault, children: selectionItems} ]}; } function viewBlockDrop(evt, elem) { var viewId = elem.viewId; var type = evt.dataTransfer.getData("type"); var value = evt.dataTransfer.getData("value"); if(type === "view") { if(viewId === value) { return console.error("Cannot join view with parent."); } dispatch("addViewSource", {viewId: viewId, sourceId: value}); evt.stopPropagation(); return; } } function removeViewBlock(evt, elem) { dispatch("removeViewBlock", {viewId: elem.viewId}); } function viewSelectionsDrop(evt, elem) { var type = evt.dataTransfer.getData("type"); if(type !== "field") { return; } var id = evt.dataTransfer.getData("fieldId"); var blockField = ixer.index("block field")[id]; if(blockField[code.ix("block field", "view")] !== elem.viewId) { return; } var fieldId = blockField[code.ix("block field", "field")]; var sourceId = blockField[code.ix("block field", "source")]; dispatch("addViewSelection", {viewId: elem.viewId, sourceFieldId: fieldId, sourceId: sourceId}); evt.stopPropagation(); } // Sources function viewSources(viewId) { var sourceIdIx = code.ix("source", "source"); var sources = ixer.index("view to sources")[viewId] || []; var sourceIds = sources.map(function(source) { return source[sourceIdIx]; }); sources.sort(function(idA, idB) { var orderA = ixer.index("display order")[idA]; var orderB = ixer.index("display order")[idB]; if(orderB - orderA) { return orderB - orderA; } else { return idA > idB } }); var sourceItems = sourceIds.map(function(sourceId) { return viewSource(viewId, sourceId); }); return {c: "block-section view-sources", children: sourceItems}; } function viewSource(viewId, sourceId) { var fields = ixer.index("view and source to block fields")[viewId] || {}; fields = fields[sourceId] || []; var fieldItems = fields.map(function(field) { var id = field[code.ix("block field", "block field")]; return fieldItem(code.name(id) || "Untitled", id, {c: "pill field"}); }); var children = [ {c: "view-source-title", children: [ {t: "h4", text: code.name(sourceId) || "Untitled"}, {c: "hover-reveal close-btn ion-android-close", viewId: viewId, sourceId: sourceId, click: removeSource} ]} ].concat(fieldItems); return {c: "tree bar view-source", children: children}; } function removeSource(evt, elem) { dispatch("removeViewSource", {viewId: elem.viewId, sourceId: elem.sourceId}); } // Constraints function viewConstraints(viewId) { var constraintIdIx = code.ix("constraint", "constraint"); var constraints = ixer.index("view to constraints")[viewId] || []; var constraintItems = constraints.map(function(constraint) { var id = constraint[constraintIdIx]; var op = ixer.index("constraint operation")[id] || []; var operation = op[code.ix("constraint operation", "operation")]; var left = ixer.index("constraint left")[id] || []; var leftSource = left[code.ix("constraint left", "left source")]; var leftField = left[code.ix("constraint left", "left field")]; var right = ixer.index("constraint right")[id] || []; var rightSource = right[code.ix("constraint right", "right source")]; var rightField = right[code.ix("constraint right", "right field")]; return {c: "view-constraint", children: [ {c: "hover-reveal grip", children: [{c: "ion-android-more-vertical"}, {c: "ion-android-more-vertical"}]}, token.blockField({key: "left", constraintId: id, source: leftSource, field: leftField}, updateViewConstraint, dropConstraintField), token.operation({key: "operation", constraintId: id, operation: operation}, updateViewConstraint), token.blockField({key: "right", constraintId: id, source: rightSource, field: rightField}, updateViewConstraint, dropConstraintField), {c: "hover-reveal close-btn ion-android-close", constraintId: id, click: removeConstraint} ]}; }); return {c: "block-section view-constraints", viewId: viewId, drop: viewConstraintsDrop, dragover: preventDefault, children: constraintItems}; } function viewConstraintsDrop(evt, elem) { var viewId = elem.viewId; var type = evt.dataTransfer.getData("type"); var value = evt.dataTransfer.getData("value"); if(type === "tool" && value === "filter") { dispatch("addViewConstraint", {viewId: viewId}); evt.stopPropagation(); return; } if(type === "field") { var id = evt.dataTransfer.getData("fieldId"); var blockField = ixer.index("block field")[id]; if(blockField[code.ix("block field", "view")] !== viewId) { return; } var fieldId = blockField[code.ix("block field", "field")]; var sourceId = blockField[code.ix("block field", "source")]; dispatch("addViewConstraint", {viewId: viewId, leftSource: sourceId, leftField: fieldId}); } } function updateViewConstraint(evt, elem) { var id = elem.constraintId; dispatch("updateViewConstraint", {constraintId: id, type: elem.key, value: elem.value}); stopEditToken(evt, elem); evt.stopPropagation(); } function dropConstraintField(evt, elem) { var type = evt.dataTransfer.getData("type"); if(type !== "field") { return; } var viewId = ixer.index("constraint to view")[elem.constraintId]; var id = evt.dataTransfer.getData("fieldId"); var blockField = ixer.index("block field")[id]; var draggedViewId = blockField[code.ix("block field", "view")]; var fieldId = blockField[code.ix("block field", "field")]; var sourceId = blockField[code.ix("block field", "source")]; if(draggedViewId === viewId) { // If the field is block local, add it as a constraint. dispatch("updateViewConstraint", {constraintId: elem.constraintId, type: elem.key, value: fieldId, source: sourceId}); evt.stopPropagation(); } else if(elem.key === "right") { // If the field is accessible in the query, use it for grouping. var select = ixer.index("view and source field to select")[draggedViewId] || {}; select = select[fieldId]; if(!select) { return; } if(ixer.index("view to query")[viewId] !== ixer.index("view to query")[draggedViewId]) { return; } console.warn("@TODO: group by", draggedViewId, fieldId); dispatch("groupView", {constraintId: elem.constraintId, inner: viewId, outer: draggedViewId, outerField: fieldId}); evt.stopPropagation(); } } function removeConstraint(evt, elem) { dispatch("removeViewConstraint", {constraintId: elem.constraintId}); } //--------------------------------------------------------- // Tokens //--------------------------------------------------------- var tokenState = {}; var token = { operation: function(params, onChange, onDrop) { var state = tokenState[params.constraintId]; if(state) { state = state[params.key]; } return {c: "token operation", key: params.key, constraintId: params.constraintId, children: [{c: "name", text: params.operation || "<op>"}, (state === 1) ? tokenEditor.operation(params, onChange) : undefined], click: editToken}; }, blockField: function(params, onChange, onDrop) { var state = tokenState[params.constraintId]; if(state) { state = state[params.key]; } var name = "<field>"; var source; if(params.field) { name = code.name(params.field); if(params.source) { source = code.name(params.source); } } return {c: "token field", key: params.key, constraintId: params.constraintId, children: [{c: "name", text: name}, (source ? {c: "source", text: "(" + source +")"} : undefined), (state === 1) ? tokenEditor.blockField(params, onChange) : undefined], click: editToken, dragover: preventDefault, drop: onDrop}; } }; function editToken(evt, elem) { var state = tokenState[elem.constraintId]; if(!state) { state = tokenState[elem.constraintId] = {}; } state[elem.key] = 1; render(); } function stopEditToken(evt, elem) { var state = tokenState[elem.constraintId]; state[elem.key] = 0; render(); } var tokenEditor = { operation: function(params, onChange) { var items = ["=", "<", "≤", ">", "≥", "≠"].map(function(rel) { var item = selectorItem({c: "operation", key: params.key, name: rel, value: rel}, onChange); item.constraintId = params.constraintId; return item; }); var select = selector(items, {c: "operation", key: params.key, tabindex: -1, focus: true}, stopEditToken); select.constraintId = params.constraintId; return select; }, blockField: function(params, onChange) { var viewId = ixer.index("constraint to view")[params.constraintId]; var fields = getBlockFields(viewId); var items = fields.map(function(field) { var fieldId = field[code.ix("field", "field")]; var item = selectorItem({c: "field", key: params.key, name: code.name(fieldId) || "Untitled", value: fieldId}, onChange); item.constraintId = params.constraintId; return item; }); var select = selector(items, {c: "field", key: params.key, tabindex: -1, focus: true}, stopEditToken); select.constraintId = params.constraintId; return select; } }; function getSourceFields(viewId, sourceId) { var source = ixer.index("source")[viewId][sourceId]; var sourceViewId = source[code.ix("source", "source view")]; return ixer.index("view to fields")[sourceViewId] || []; } function getBlockFields(viewId) { var sources = ixer.index("view to sources")[viewId] || []; return sources.reduce(function(memo, source) { var sourceViewId = source[code.ix("source", "source view")]; memo.push.apply(memo, ixer.index("view to fields")[sourceViewId]); return memo; }, []); } function getQueryFields(queryId, exclude) { var viewIds = ixer.index("query to views")[queryId] || []; return viewIds.reduce(function(memo, viewId) { if(viewId !== exclude && viewId) { memo.push.apply(memo, getBlockFields(viewId)); } return memo; }, []); } /** * Union Block */ function unionBlock(viewId) { var fields = ixer.index("view and source to block fields")[viewId] || {}; fields = fields.selection || []; var selectSources = ixer.index("view and source and field to select")[viewId] || {}; var sources = ixer.index("source")[viewId] || {}; var sourceIds = Object.keys(sources); var sourceItems = []; var fieldMappingItems = []; for(var sourceIx = 0; sourceIx < sourceIds.length; sourceIx++) { var sourceId = sourceIds[sourceIx]; var source = sources[sourceId]; var sourceFields = ixer.index("view and source to block fields")[viewId] || {}; sourceFields = sourceFields[sourceId] || []; var fieldItems = []; for(var fieldIx = 0; fieldIx < sourceFields.length; fieldIx++) { var field = sourceFields[fieldIx]; var fieldId = field[code.ix("block field", "block field")]; fieldItems.push(fieldItem(code.name(fieldId) || "Untitled", fieldId, {c: "pill field"})); } sourceItems.push({c: "union-source", children: [ {text: code.name(sourceId)}, {c: "tree bar union-source-fields", children: fieldItems} ]}); if(!fields.length) { continue; } var selectFields = selectSources[sourceId] || []; var mappingPairs = []; for(var fieldIx = 0; fieldIx < fields.length; fieldIx++) { var field = fields[fieldIx]; var fieldId = field[code.ix("block field", "field")]; var selectField = selectFields[fieldId] || []; var mappedFieldId = selectField[code.ix("select", "source field")]; mappingPairs.push({c: "mapping-pair", viewId: viewId, sourceId: sourceId, fieldId: fieldId, dragover: preventDefault, drop: unionSourceMappingDrop, children: [ {c: "mapping-header", text: code.name(fieldId) || "Untitled"}, // @FIXME: code.name(fieldId) not set? (mappedFieldId ? {c: "mapping-row", text: code.name(mappedFieldId) || "Untitled"} : {c: "mapping-row", text: "---"}) ]}); } fieldMappingItems.push({c: "field-mapping", children: mappingPairs}); } if(!fields.length) { fieldMappingItems.push({c: "field-mapping", children: [{text: "drag fields to begin mapping; or"}, {text: "drag an existing union to begin merging"}]}); } return {c: "block union-block", viewId: viewId, dragover: preventDefault, drop: viewBlockDrop, children: [ {c: "block-title", children: [ {t: "h3", text: "Untitled Union Block"}, {c: "hover-reveal close-btn ion-android-close", viewId: viewId, click: removeViewBlock} ]}, {c: "content", children: [ {c: "block-pane", children: sourceItems}, {c: "block-pane mapping", viewId: viewId, dragover: preventDefault, drop: unionSourceMappingDrop, children: fieldMappingItems}, ]} ]}; } function unionSourceMappingDrop(evt, elem) { var type = evt.dataTransfer.getData("type"); if(type !== "field") { return; } var blockFieldId = evt.dataTransfer.getData("fieldId"); var blockField = ixer.index("block field")[blockFieldId]; var fieldId = blockField[code.ix("block field", "field")]; var viewId = blockField[code.ix("block field", "view")]; var sourceId = blockField[code.ix("block field", "source")]; if(viewId !== elem.viewId) { return; } console.log({viewId: viewId, sourceFieldId: fieldId, sourceId: sourceId, fieldId: elem.fieldId}); dispatch("addUnionSelection", {viewId: viewId, sourceFieldId: fieldId, sourceId: sourceId, fieldId: elem.fieldId}); evt.stopPropagation(); } /** * Aggregate Block */ function aggregateBlock(viewId) { var sources = ixer.index("source")[viewId] || {}; var outerSource = sources.outer; var innerSource = sources.inner; var groupBy = ixer.index("grouped by")[innerSource] || []; console.log(groupBy); var fields = ixer.index("view and source to block fields")[viewId] || {}; fields = fields["selection"] || []; var selectionItems = fields.map(function(field) { var id = field[code.ix("block field", "block field")]; return fieldItem(code.name(id) || "Untitled", id, {c: "pill field"}); }); if(!selectionItems.length) { selectionItems.push({text: "Drag local fields into me to make them available in the query."}); } return {c: "block aggregate-block", viewId: viewId, children: [ {c: "block-title", children: [ {t: "h3", text: "Untitled Agg. Block"}, {c: "hover-reveal close-btn ion-android-close", viewId: viewId, click: removeViewBlock} ]}, {text: "With"}, {c: "block-section view-sources", viewId: viewId, sourceId: "inner", drop: aggregateSourceDrop, dragover: preventDefault, children: [ innerSource ? viewSource(viewId, "inner") : undefined ]}, {text: "Where"}, viewConstraints(viewId), {c: "block-section view-selections tree bar", viewId: viewId, drop: viewSelectionsDrop, dragover: preventDefault, children: selectionItems}, ]}; } function sortLimitAggregate(viewId, outerSource, innerSource) { return {c: "sort-limit-aggregate", viewId: viewId, children: [ {text: "Sort by"}, {c: "block-section aggregate-sort", children: [ {text: "<field>"}, {text: "<direction>"} ]}, {text: "Limit"}, {c: "block-section aggregate-limit", children: [ {text: "<constant>"}, {text: "<constant>"} ]}, ]}; } function primitiveAggregate(viewId, outerSource, innerSource) { return {c: "primitive-aggregate", viewId: viewId, children: [ {text: "argument mapping here"} ]}; } function aggregateSourceDrop(evt, elem) { var viewId = elem.viewId; var sourceId = elem.sourceId; var type = evt.dataTransfer.getData("type"); var value = evt.dataTransfer.getData("value"); if(type === "view") { if(viewId === value) { return console.error("Cannot join view with parent."); } dispatch("addViewSource", {viewId: viewId, sourceId: value, kind: sourceId}); evt.stopPropagation(); return; } } function selector(options, opts, onBlur) { return {t: "ul", c: "selector " + opts.c, tabindex: opts.tabindex, key: opts.key, postRender: (opts.focus ? focusOnce : undefined), blur: onBlur, children: options}; } function selectorItem(opts, onChange) { return {t: "li", c: "selector-item field " + opts.c, key: opts.key, text: opts.name, value: opts.value, click: onChange}; } //--------------------------------------------------------- // Inspector //--------------------------------------------------------- function inspectorPane(queryId) { return {c: "inspector pane"}; } //--------------------------------------------------------- // Result //--------------------------------------------------------- function queryResult(queryId) { return {c: "query-result"}; } //--------------------------------------------------------- // Global key handling //--------------------------------------------------------- document.addEventListener("keydown", function(e) { //Don't capture keys if they are if(e.defaultPrevented || e.target.nodeName === "INPUT" || e.target.getAttribute("contentEditable")) { return; } //undo + redo if((e.metaKey || e.ctrlKey) && e.shiftKey && e.keyCode === KEYS.Z) { dispatch("redo"); } else if((e.metaKey || e.ctrlKey) && e.keyCode === KEYS.Z) { dispatch("undo"); } }); //--------------------------------------------------------- // Go //--------------------------------------------------------- if(window.queryEditor) { render(); } return { container: renderer.content, localState: localState, renderer: renderer, render: render, eventStack: eventStack }; })(window, microReact, api);
fix row updating to be resilient to the server Signed-off-by: Chris Granger <[email protected]>
ui/src/query-editor.js
fix row updating to be resilient to the server
<ide><path>i/src/query-editor.js <ide> ["display name", "inserted", [id, "Untitled Table"]], <ide> ["display name", "inserted", [fieldId, "A"]]); <ide> localState.activeItem = id; <del> localState.adderRows = [[]]; <add> localState.adderRows = [[], []]; <ide> break; <ide> case "addQuery": <ide> var id = uuid(); <ide> ["display order", "inserted", [info.table + JSON.stringify(info.neue), ix]]); <ide> break; <ide> case "updateRow": <add> sendToServer = info.submit; <ide> var oldString = info.table + JSON.stringify(info.old); <del> var ix = ixer.index("display order")[oldString]; <add> var ix = info.ix; <add> var neueString = info.table + JSON.stringify(info.neue); <add> if(oldString === neueString) return; <ide> diffs.push([info.table, "inserted", info.neue], <ide> [info.table, "removed", info.old], <ide> ["display order", "removed", [oldString, ix]], <del> ["display order", "inserted", [info.table + JSON.stringify(info.neue), ix]]); <add> ["display order", "inserted", [neueString, ix]]); <ide> break; <ide> case "addViewBlock": <ide> var queryId = (info.queryId !== undefined) ? info.queryId: code.activeItemId(); <ide> localState.activeItem = elem.itemId; <ide> var type = ixer.index("editor item to type")[elem.itemId]; <ide> if(type === "table") { <del> localState.adderRows = [[]]; <add> localState.adderRows = [[], []]; <ide> } else if(type === "ui") { <ide> var layer = ixer.index("parentLayerToLayers")[elem.itemId][0]; <ide> localState.uiActiveLayer = layer[1]; <ide> ths.push({c: "header add-column ion-plus", click: addField, table: id}); <ide> } <ide> var trs = []; <del> rows.forEach(function(cur) { <add> rows.forEach(function(cur, rowIx) { <ide> var tds = []; <ide> for(var tdIx = 0, len = fields.length; tdIx < len; tdIx++) { <ide> tds[tdIx] = {c: "field"}; <ide> <ide> // @NOTE: We can hoist this if perf is an issue. <ide> if(isEditable) { <del> tds[tdIx].children = [input(cur[tdIx], {row: cur, ix: tdIx, view: id}, updateRow, submitRow)]; <add> tds[tdIx].children = [input(cur[tdIx], {rowIx: rowIx, row: cur, ix: tdIx, view: id}, updateRow, submitRow)]; <ide> } else { <ide> tds[tdIx].text = cur[tdIx]; <ide> } <ide> adderRows.forEach(function(cur, rowNum) { <ide> var tds = []; <ide> for(var i = 0, len = fields.length; i < len; i++) { <del> tds[i] = {c: "field", children: [input(cur[i], {numFields:len, rowNum: rowNum, ix: i, view: id}, updateAdder, maybeSubmitAdder)]}; <add> tds[i] = {c: "field", children: [input(cur[i], {row: cur, numFields:len, rowNum: rowNum, ix: i, view: id}, updateAdder, maybeSubmitAdder)]}; <ide> } <ide> trs.push({c: "row", children: tds}); <ide> }); <ide> if(!isValid) { return; } <ide> <ide> localState.adderRows.splice(key.rowNum, 1); <del> if(localState.adderRows.length === 0) { <add> if(localState.adderRows.length <= 1) { <ide> localState.adderRows.push([]); <ide> } <ide> dispatch("addRow", {table: key.view, neue: row}); <ide> function updateRow(e, elem) { <ide> var neue = elem.key.row.slice(); <ide> neue[elem.key.ix] = coerceInput(e.currentTarget.textContent); <add> dispatch("updateRow", {table: elem.key.view, ix:localState.initialKey.rowIx, old: elem.key.row.slice(), neue: neue, submit: false}) <ide> } <ide> <ide> function submitRow(e, elem, type) { <ide> var neue = elem.key.row.slice(); <ide> neue[elem.key.ix] = coerceInput(e.currentTarget.textContent); <del> dispatch("updateRow", {table: elem.key.view, old: elem.key.row, neue: neue}) <add> dispatch("updateRow", {table: elem.key.view, ix:localState.initialKey.rowIx, old: localState.initialKey.row.slice(), neue: neue, submit: true}) <ide> } <ide> <ide> function input(value, key, oninput, onsubmit) {
JavaScript
mit
d78a2a7811df06f41dcdee30487f332239d9dc8b
0
SporkList/sporklist.github.io,SporkList/sporklist.github.io
function updateUserPage (user) { var name = user.get("name"); var picUrl = user.get("picture"); var friends = user.get("friends"); /* Array of strings (fb ids) */ var profile = document.getElementById("my-profile-box"); var scope = angular.element(profile).scope(); scope.$apply(function() {scope.name = name}); $("#my-picture").css("background-image", "url(" + picUrl + ")"); getFriends(friends); } function updateSporklists (sporklists, position) { var sidebarList = document.getElementById("playlists"); var scope = angular.element(sidebarList).scope(); scope.$apply(function () {scope.playlists = sporklists}); } function updateFriendSporklists (sporklists, position) { var main = document.getElementById("info-pane"); var scope = angular.element(main).scope(); scope.$apply(function() { scope.user = false; scope.friend = true; scope.sporklist = false; scope.search = false; scope.map = false; }); } function getFriends (friendIds) { var users = Parse.Object.extend("_User"); var query = new Parse.Query(users); var resList; query.containedIn("facebook_id",friendIds); query.find( { /* add info to some results */ success: function (results) { var friendListElem = document.getElementById("my-profile-box"); var scope = angular.element(friendListElem).scope(); scope.$apply(function() {scope.friendList = results} ); }, error: function (error) { console.log("You have no friends :( " + error); } }); } function shuffle(arr) { for (var j, x, i=arr.length;i;j = Math.floor(Math.random() * i), x = arr[--i],arr[i] = arr[j], arr[j] = x); return arr; } function updateSporklist(name, sporklist) { /* Randomize sporklist */ sporklist = shuffle(sporklist); var main = document.getElementById("info-pane"); var scope = angular.element(main).scope(); scope.$apply(function() { scope.user = false; scope.friend = false; scope.sporklist = true; scope.search = false; scope.map = false; }); var spork = document.getElementById("sporklist"); var scope = angular.element(spork).scope(); scope.$apply(function() { scope.name = name; scope.restaurants = sporklist; }); } function updateFriend(friend) { var name = friend.get("name"); var picture = friend.get("picture"); $("#friend-main-picture").css("background-image", "url(" + picture + ")"); var sporklist = Parse.Object.extend("Sporklist"); var query = new Parse.Query(sporklist); query.equalTo("author", friend.getUsername()); query.limit(1000); query.find({ success: function(results) { var list = document.getElementById("friend-profile-box"); var scope = angular.element(list).scope(); scope.$apply(function () { scope.sporklists = results; scope.name = name; }); updateFriendSporklists(results); }, error: function(error) { alert("Error: " + error.code + " " + error.message); } }); } function resetView () { var main = document.getElementById("info-pane"); var scope = angular.element(main).scope(); scope.$apply(function () { scope.user = true; scope.friend = false; scope.sporklist = false; scope.search = false; scope.map = false; }); } function updateSearchResults(rest_results) { var main = document.getElementById("info-pane"); var scope = angular.element(main).scope(); scope.$apply(function() { scope.user = false; scope.friend = false; scope.sporklist = false; scope.search = true; scope.map = false; }); var result_box = document.getElementById("restaurant-search-box"); var scope = angular.element(result_box).scope(); scope.$apply(function() { scope.results = rest_results; }); }
scripts/updates.js
function updateUserPage (user) { var name = user.get("name"); var picUrl = user.get("picture"); var friends = user.get("friends"); /* Array of strings (fb ids) */ var profile = document.getElementById("my-profile-box"); var scope = angular.element(profile).scope(); scope.$apply(function() {scope.name = name}); $("#my-picture").css("background-image", "url(" + picUrl + ")"); getFriends(friends); } function updateSporklists (sporklists, position) { var sidebarList = document.getElementById("playlists"); var scope = angular.element(sidebarList).scope(); scope.$apply(function () {scope.playlists = sporklists}); } function updateFriendSporklists (sporklists, position) { var main = document.getElementById("info-pane"); var scope = angular.element(main).scope(); scope.$apply(function() { scope.user = false; scope.friend = true; scope.sporklist = false; scope.search = false; scope.map = false; }); } function getFriends (friendIds) { var users = Parse.Object.extend("_User"); var query = new Parse.Query(users); var resList; query.containedIn("facebook_id",friendIds); query.find( { /* add info to some results */ success: function (results) { var friendListElem = document.getElementById("my-profile-box"); var scope = angular.element(friendListElem).scope(); scope.$apply(function() {scope.friendList = results} ); }, error: function (error) { console.log("You have no friends :( " + error); } }); } function updateSporklist(name, sporklist) { var main = document.getElementById("info-pane"); var scope = angular.element(main).scope(); scope.$apply(function() { scope.user = false; scope.friend = false; scope.sporklist = true; scope.search = false; scope.map = false; }); var spork = document.getElementById("sporklist"); var scope = angular.element(spork).scope(); scope.$apply(function() { scope.name = name; scope.restaurants = sporklist; }); } function updateFriend(friend) { var name = friend.get("name"); var picture = friend.get("picture"); $("#friend-main-picture").css("background-image", "url(" + picture + ")"); var sporklist = Parse.Object.extend("Sporklist"); var query = new Parse.Query(sporklist); query.equalTo("author", friend.getUsername()); query.limit(1000); query.find({ success: function(results) { var list = document.getElementById("friend-profile-box"); var scope = angular.element(list).scope(); scope.$apply(function () { scope.sporklists = results; scope.name = name; }); updateFriendSporklists(results); }, error: function(error) { alert("Error: " + error.code + " " + error.message); } }); } function resetView () { var main = document.getElementById("info-pane"); var scope = angular.element(main).scope(); scope.$apply(function () { scope.user = true; scope.friend = false; scope.sporklist = false; scope.search = false; scope.map = false; }); } function updateSearchResults(rest_results) { var main = document.getElementById("info-pane"); var scope = angular.element(main).scope(); scope.$apply(function() { scope.user = false; scope.friend = false; scope.sporklist = false; scope.search = true; scope.map = false; }); var result_box = document.getElementById("restaurant-search-box"); var scope = angular.element(result_box).scope(); scope.$apply(function() { scope.results = rest_results; }); }
shuffles playlists
scripts/updates.js
shuffles playlists
<ide><path>cripts/updates.js <ide> <ide> } <ide> <add>function shuffle(arr) { <add> for (var j, x, i=arr.length;i;j = Math.floor(Math.random() * i), x = arr[--i],arr[i] = arr[j], arr[j] = x); <add> return arr; <add>} <add> <ide> function updateSporklist(name, sporklist) { <add> <add> /* Randomize sporklist */ <add> sporklist = shuffle(sporklist); <add> <ide> var main = document.getElementById("info-pane"); <ide> var scope = angular.element(main).scope(); <ide>
Java
mit
9788b3986904284ffe015b749df1c5e76dbbe009
0
melnikovdv/Java-Yandex.Money-API-SDK,zerin108/Java-Yandex.Money-API-SDK
package ru.yandex.money.api.response.util; /** * Date: 18.11.13 20:38 * * @author sergeev */ public enum ProcessPaymentError { /** * Недостаточно средств на счете/привязанной карте. */ not_enough_funds, /** * Невозможно провести платеж с указанным money_source. * */ money_source_not_available, /** * В проведении платежа отказано. * При платеже со счета причиной может быть не принятая оферта. * В случае с картой возможно причина в том, что требуется 3DSecure авторизация. */ authorization_reject, /** * Превышен лимит платежей. Это может быть лимит токена за период, * общий лимит пользователя Яндекс.Денег (сумма этого лимита зависит от идентифицированности польователя) */ limit_exceeded, /** * Истекло время действия контракта платежа (примерно около 15-ти минут) */ contract_not_found, /** * Аккаунт заблокирован. Нужно отправить пользователя по url из поля "account_unblock_uri" */ account_blocked, /** * Магазин отказал в проведении платежа. * (Например, товара нет на складе) */ payment_refused, /** * Некорректный формат защитного кода карты */ illegal_param_csc, /** * Прочие ошибки */ technical_error }
yamolib/src/main/java/ru/yandex/money/api/response/util/ProcessPaymentError.java
package ru.yandex.money.api.response.util; /** * Date: 18.11.13 20:38 * * @author sergeev */ public enum ProcessPaymentError { /** * Недостаточно средств на карте. */ not_enough_funds, /** * Невозможно провести платеж с карты. Возможно требуется миграция на Skrat. * */ money_source_not_available, /** * Невозможно провести платеж с карты. Возможно требуется 3DSecure авторизация. */ authorization_reject, /** * Превышен лимит платежа за период. */ limit_exceeded, /** * Протух контракт платежа или контракт не найден в БД (протух контекст) */ contract_not_found, /** * Аккаунт заблокирован. Нужно отправить пользователя по url из поля "account_unblock_uri" */ account_blocked }
Добавил коды ошибок processPayment
yamolib/src/main/java/ru/yandex/money/api/response/util/ProcessPaymentError.java
Добавил коды ошибок processPayment
<ide><path>amolib/src/main/java/ru/yandex/money/api/response/util/ProcessPaymentError.java <ide> public enum ProcessPaymentError { <ide> <ide> /** <del> * Недостаточно средств на карте. <add> * Недостаточно средств на счете/привязанной карте. <ide> */ <ide> not_enough_funds, <ide> <ide> /** <del> * Невозможно провести платеж с карты. Возможно требуется миграция на Skrat. <add> * Невозможно провести платеж с указанным money_source. <ide> * */ <ide> money_source_not_available, <ide> <ide> /** <del> * Невозможно провести платеж с карты. Возможно требуется 3DSecure авторизация. <add> * В проведении платежа отказано. <add> * При платеже со счета причиной может быть не принятая оферта. <add> * В случае с картой возможно причина в том, что требуется 3DSecure авторизация. <ide> */ <ide> authorization_reject, <ide> <ide> /** <del> * Превышен лимит платежа за период. <add> * Превышен лимит платежей. Это может быть лимит токена за период, <add> * общий лимит пользователя Яндекс.Денег (сумма этого лимита зависит от идентифицированности польователя) <ide> */ <ide> limit_exceeded, <ide> <ide> /** <del> * Протух контракт платежа или контракт не найден в БД (протух контекст) <add> * Истекло время действия контракта платежа (примерно около 15-ти минут) <ide> */ <ide> contract_not_found, <ide> <ide> /** <ide> * Аккаунт заблокирован. Нужно отправить пользователя по url из поля "account_unblock_uri" <ide> */ <del> account_blocked <add> account_blocked, <add> <add> /** <add> * Магазин отказал в проведении платежа. <add> * (Например, товара нет на складе) <add> */ <add> payment_refused, <add> <add> /** <add> * Некорректный формат защитного кода карты <add> */ <add> illegal_param_csc, <add> <add> /** <add> * Прочие ошибки <add> */ <add> technical_error <ide> }
Java
mit
5038c69972884d744deaa78acded576f32c46681
0
conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5
package com.conveyal.r5.analyst; import com.beust.jcommander.ParameterException; import com.conveyal.r5.OneOriginResult; import com.conveyal.r5.analyst.cluster.AnalysisTask; import com.conveyal.r5.analyst.cluster.Origin; import com.conveyal.r5.analyst.cluster.RegionalTask; import com.conveyal.r5.analyst.cluster.TimeGrid; import com.conveyal.r5.analyst.cluster.TravelTimeSurfaceTask; import com.conveyal.r5.profile.FastRaptorWorker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; /** * Given a bunch of travel times from an origin to a single destination grid cell, this collapses that long list into a * limited number of percentiles, then optionally accumulates that destination's opportunity count into the appropriate * cumulative opportunities accessibility indicators at that origin. */ public class TravelTimeReducer { private static final Logger LOG = LoggerFactory.getLogger(TravelTimeReducer.class); /** The task used to create travel times being reduced herein. */ private int maxTripDurationMinutes; /** Travel time results for a whole grid of destinations. May be null if we're only recording accessibility. */ private TimeGrid timeGrid = null; private AccessibilityResult accessibilityResult = null; private final boolean retainTravelTimes; private final boolean calculateAccessibility; private final int[] percentileIndexes; private final int nPercentiles; private final int timesPerDestination; /** * Knowing the number of times that will be provided per destination and holding that constant allows us to * pre-compute and cache the positions within the sorted array at which percentiles will be found. */ public TravelTimeReducer (AnalysisTask task) { this.maxTripDurationMinutes = task.maxTripDurationMinutes; this.timesPerDestination = task.getMonteCarloDrawsPerMinute() * task.getTimeWindowLengthMinutes(); this.nPercentiles = task.percentiles.length; // We pre-compute the indexes at which we'll find each percentile in a sorted list of the given length. this.percentileIndexes = new int[nPercentiles]; for (int p = 0; p < nPercentiles; p++) { percentileIndexes[p] = findPercentileIndex(timesPerDestination, task.percentiles[p]); } // Decide whether we want to retain travel times to all destinations for this origin. retainTravelTimes = task instanceof TravelTimeSurfaceTask || task.makeStaticSite; if (retainTravelTimes) { timeGrid = new TimeGrid(task.zoom, task.west, task.north, task.width, task.height, task.percentiles.length); } // Decide whether we want to calculate cumulative opportunities accessibility indicators for this origin. calculateAccessibility = task instanceof RegionalTask && ((RegionalTask)task).gridData != null; if (calculateAccessibility) { accessibilityResult = new AccessibilityResult( new Grid[] {((RegionalTask)task).gridData}, new int[]{task.maxTripDurationMinutes}, task.percentiles ); } } /** * Compute the index into a sorted list of N elements at which a particular percentile will be found. * Our method does not interpolate, it always reports a value actually appearing in the list of elements. * That is to say, the percentile will be found at an integer-valued index into the sorted array of elements. * The definition of a non-interpolated percentile is as follows: the smallest value in the list such that no more * than P percent of the data is strictly less than the value and at least P percent of the data is less than or * equal to that value. The 100th percentile is defined as the largest value in the list. * See https://en.wikipedia.org/wiki/Percentile#Definitions * * We scale the interval between the beginning and end elements of the array (the min and max values). * In an array with N values this interval is N-1 elements. We should be scaling N-1, which makes the result * always defined even when using a high percentile and low number of elements. Previously, this caused * an error when requesting the 95th percentile when times.length = 1 (or any length less than 10). */ private static int findPercentileIndex(int nElements, double percentile) { // The definition uses ceiling for one-based indexes but we use zero-based indexes so we can truncate. // FIXME truncate rather than rounding. // TODO check the difference in results caused by using the revised formula in both single and regional analyses. return (int) Math.round(percentile / 100 * nElements); } /** * Given a list of travel times of the expected length, extract the requested percentiles. Either the extracted * percentiles or the resulting accessibility values (or both) are then stored. * WARNING: this method destructively sorts the supplied times in place. * Their positions in the array will no longer correspond to the raptor iterations that produced them. * @param times which will be destructively sorted in place to extract percentiles. * @return the extracted travel times, in minutes. This is a hack to enable scoring paths in the caller. */ public int[] recordTravelTimesForTarget (int target, int[] times) { // TODO factor out getPercentiles method for clarity // Sort the times at each target and read off percentiles at the pre-calculated indexes. int[] percentileTravelTimesMinutes = new int[nPercentiles]; if (times.length == 1) { // Handle results with no variation, e.g. from walking, biking, or driving. // TODO instead of conditionals maybe overload this function to have one version that takes a single int time and wraps this array function. int travelTimeSeconds = times[0]; int travelTimeMinutes = (travelTimeSeconds == FastRaptorWorker.UNREACHED) ? FastRaptorWorker.UNREACHED : travelTimeSeconds / 60; Arrays.fill(percentileTravelTimesMinutes, travelTimeMinutes); } else if (times.length == timesPerDestination) { // Instead of general purpose sort this could be done by performing a counting sort on the times, // converting them to minutes in the process and reusing the small histogram array (120 elements) which // should remain largely in processor cache. That's a lot of division though. Would need to be profiled. Arrays.sort(times); for (int p = 0; p < nPercentiles; p++) { int timeSeconds = times[percentileIndexes[p]]; if (timeSeconds == FastRaptorWorker.UNREACHED) { percentileTravelTimesMinutes[p] = FastRaptorWorker.UNREACHED; } else { // Int divide will floor; this is correct because value 0 has travel times of up to one minute, etc. // This means that anything less than a cutoff of (say) 60 minutes (in seconds) will have value 59, // which is what we want. But maybe converting to minutes before we actually export a binary format is tying // the backend and frontend (which makes use of UInt8 typed arrays) too closely. int timeMinutes = timeSeconds / 60; percentileTravelTimesMinutes[p] = timeMinutes; } } } else { throw new ParameterException("You must supply the expected number of travel time values (or only one value)."); } if (retainTravelTimes) { timeGrid.setTarget(target, percentileTravelTimesMinutes); } if (calculateAccessibility) { // This x/y addressing can only work with one grid at a time, // needs to be made absolute to handle multiple different extents. Grid grid = accessibilityResult.grids[0]; int x = target % grid.width; int y = target / grid.width; double amount = grid.grid[x][y]; for (int p = 0; p < nPercentiles; p++) { if (percentileTravelTimesMinutes[p] < maxTripDurationMinutes) { // TODO less than or equal? accessibilityResult.incrementAccessibility(0, 0, p, amount); } } } return percentileTravelTimesMinutes; } /** * If no travel times to destinations have been streamed in by calling recordTravelTimesForTarget, the * TimeGrid will have a buffer full of UNREACHED. This allows shortcutting around * routing and propagation when the origin point is not connected to the street network. */ public OneOriginResult finish () { return new OneOriginResult(timeGrid, accessibilityResult); } }
src/main/java/com/conveyal/r5/analyst/TravelTimeReducer.java
package com.conveyal.r5.analyst; import com.beust.jcommander.ParameterException; import com.conveyal.r5.OneOriginResult; import com.conveyal.r5.analyst.cluster.AnalysisTask; import com.conveyal.r5.analyst.cluster.Origin; import com.conveyal.r5.analyst.cluster.RegionalTask; import com.conveyal.r5.analyst.cluster.TimeGrid; import com.conveyal.r5.analyst.cluster.TravelTimeSurfaceTask; import com.conveyal.r5.profile.FastRaptorWorker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; /** * Given a bunch of travel times from an origin to a single destination grid cell, this collapses that long list into a * limited number of percentiles, then optionally accumulates that destination's opportunity count into the appropriate * cumulative opportunities accessibility indicators at that origin. */ public class TravelTimeReducer { private static final Logger LOG = LoggerFactory.getLogger(TravelTimeReducer.class); /** The task used to create travel times being reduced herein. */ private int maxTripDurationMinutes; /** Travel time results for a whole grid of destinations. May be null if we're only recording accessibility. */ private TimeGrid timeGrid = null; private AccessibilityResult accessibilityResult = null; private final boolean retainTravelTimes; private final boolean calculateAccessibility; private final int[] percentileIndexes; private final int nPercentiles; private final int timesPerDestination; /** * Knowing the number of times that will be provided per destination and holding that constant allows us to * pre-compute and cache the positions within the sorted array at which percentiles will be found. */ public TravelTimeReducer (AnalysisTask task) { this.maxTripDurationMinutes = task.maxTripDurationMinutes; this.timesPerDestination = task.getMonteCarloDrawsPerMinute() * task.getTimeWindowLengthMinutes(); this.nPercentiles = task.percentiles.length; // We pre-compute the indexes at which we'll find each percentile in a sorted list of the given length. this.percentileIndexes = new int[nPercentiles]; for (int p = 0; p < nPercentiles; p++) { percentileIndexes[p] = findPercentileIndex(timesPerDestination, task.percentiles[p]); } // Decide whether we want to retain travel times to all destinations for this origin. retainTravelTimes = task instanceof TravelTimeSurfaceTask || task.makeStaticSite; if (retainTravelTimes) { timeGrid = new TimeGrid(task.zoom, task.west, task.north, task.width, task.height, task.percentiles.length); } // Decide whether we want to calculate cumulative opportunities accessibility indicators for this origin. calculateAccessibility = task instanceof RegionalTask && ((RegionalTask)task).gridData != null; if (calculateAccessibility) { accessibilityResult = new AccessibilityResult( new Grid[] {((RegionalTask)task).gridData}, new int[]{task.maxTripDurationMinutes}, task.percentiles ); } } /** * Compute the index into a sorted list of N elements at which a particular percentile will be found. * Our method does not interpolate, it always reports a value actually appearing in the list of elements. * That is to say, the percentile will be found at an integer-valued index into the sorted array of elements. * The definition of a non-interpolated percentile is as follows: the smallest value in the list such that no more * than P percent of the data is strictly less than the value and at least P percent of the data is less than or * equal to that value. The 100th percentile is defined as the largest value in the list. * See https://en.wikipedia.org/wiki/Percentile#Definitions * * We scale the interval between the beginning and end elements of the array (the min and max values). * In an array with N values this interval is N-1 elements. We should be scaling N-1, which makes the result * always defined even when using a high percentile and low number of elements. Previously, this caused * an error when requesting the 95th percentile when times.length = 1 (or any length less than 10). */ private static int findPercentileIndex(int nElements, double percentile) { // The definition uses ceiling for one-based indexes but we use zero-based indexes so we can truncate. // FIXME truncate rather than rounding. // TODO check the difference in results caused by using the revised formula in both single and regional analyses. return (int) Math.round(percentile / 100 * nElements); } /** * Given a list of travel times of the expected length, extract the requested percentiles. Either the extracted * percentiles or the resulting accessibility values (or both) are then stored. * WARNING: this method destructively sorts the supplied times in place. * Their positions in the array will no longer correspond to the raptor iterations that produced them. * @param times which will be destructively sorted in place to extract percentiles. * @return the extracted travel times, in minutes. This is a hack to enable scoring paths in the caller. */ public int[] recordTravelTimesForTarget (int target, int[] times) { // TODO factor out getPercentiles method for clarity // Sort the times at each target and read off percentiles at the pre-calculated indexes. int[] percentileTravelTimesMinutes = new int[nPercentiles]; if (times.length == 1) { // Handle results with no variation // TODO instead of conditionals maybe overload this function to have one version that takes a single int time and wraps this array function. Arrays.fill(percentileTravelTimesMinutes, times[0]); } else if (times.length == timesPerDestination) { // Instead of general purpose sort this could be done by performing a counting sort on the times, // converting them to minutes in the process and reusing the small histogram array (120 elements) which // should remain largely in processor cache. That's a lot of division though. Would need to be profiled. Arrays.sort(times); for (int p = 0; p < nPercentiles; p++) { int timeSeconds = times[percentileIndexes[p]]; if (timeSeconds == FastRaptorWorker.UNREACHED) { percentileTravelTimesMinutes[p] = FastRaptorWorker.UNREACHED; } else { // Int divide will floor; this is correct because value 0 has travel times of up to one minute, etc. // This means that anything less than a cutoff of (say) 60 minutes (in seconds) will have value 59, // which is what we want. But maybe converting to minutes before we actually export a binary format is tying // the backend and frontend (which makes use of UInt8 typed arrays) too closely. int timeMinutes = timeSeconds / 60; percentileTravelTimesMinutes[p] = timeMinutes; } } } else { throw new ParameterException("You must supply the expected number of travel time values (or only one value)."); } if (retainTravelTimes) { timeGrid.setTarget(target, percentileTravelTimesMinutes); } if (calculateAccessibility) { // This x/y addressing can only work with one grid at a time, // needs to be made absolute to handle multiple different extents. Grid grid = accessibilityResult.grids[0]; int x = target % grid.width; int y = target / grid.width; double amount = grid.grid[x][y]; for (int p = 0; p < nPercentiles; p++) { if (percentileTravelTimesMinutes[p] < maxTripDurationMinutes) { // TODO less than or equal? accessibilityResult.incrementAccessibility(0, 0, p, amount); } } } return percentileTravelTimesMinutes; } /** * If no travel times to destinations have been streamed in by calling recordTravelTimesForTarget, the * TimeGrid will have a buffer full of UNREACHED. This allows shortcutting around * routing and propagation when the origin point is not connected to the street network. */ public OneOriginResult finish () { return new OneOriginResult(timeGrid, accessibilityResult); } }
divide seconds by 60 when reporting minutes fixes a bug that was messing up walking biking and driving results
src/main/java/com/conveyal/r5/analyst/TravelTimeReducer.java
divide seconds by 60 when reporting minutes
<ide><path>rc/main/java/com/conveyal/r5/analyst/TravelTimeReducer.java <ide> // Sort the times at each target and read off percentiles at the pre-calculated indexes. <ide> int[] percentileTravelTimesMinutes = new int[nPercentiles]; <ide> if (times.length == 1) { <del> // Handle results with no variation <add> // Handle results with no variation, e.g. from walking, biking, or driving. <ide> // TODO instead of conditionals maybe overload this function to have one version that takes a single int time and wraps this array function. <del> Arrays.fill(percentileTravelTimesMinutes, times[0]); <add> int travelTimeSeconds = times[0]; <add> int travelTimeMinutes = (travelTimeSeconds == FastRaptorWorker.UNREACHED) ? <add> FastRaptorWorker.UNREACHED : travelTimeSeconds / 60; <add> Arrays.fill(percentileTravelTimesMinutes, travelTimeMinutes); <ide> } else if (times.length == timesPerDestination) { <ide> // Instead of general purpose sort this could be done by performing a counting sort on the times, <ide> // converting them to minutes in the process and reusing the small histogram array (120 elements) which
Java
mit
5c7f4b1edd0868a91061a92701959a0bd5d422eb
0
plivo/plivo-java,plivo/plivo-java
package com.plivo.api.util; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.text.Normalizer; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.SortedSet; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import com.fasterxml.jackson.databind.ObjectMapper; import com.plivo.api.exceptions.PlivoXmlException; public class Utils { public static boolean allNotNull(Object... objects) { return Stream.of(objects) .noneMatch(Objects::isNull); } public static boolean isSubaccountIdValid(String id) { return id != null && id.startsWith("SA") && id.length() == 20; } public static boolean isAccountIdValid(String id) { return id != null && id.startsWith("MA") && id.length() == 20; } public static boolean anyNotNull(Object... objects) { return Stream.of(objects) .anyMatch(Objects::nonNull); } public static Map<String, Object> objectToMap(ObjectMapper objectMapper, Object object) { Map<String, Object> origMap = objectMapper.convertValue(object, Map.class); Map<String, Object> map = new LinkedHashMap<>(); for (Entry<String, Object> entry : origMap.entrySet()) { if (entry.getValue() != null) { if (entry.getValue() instanceof Map) { Map<String, Object> innerEntries = objectMapper.convertValue(entry.getValue(), Map.class); for (Entry<String, Object> innerEntry : innerEntries.entrySet()) { map.put(entry.getKey() + innerEntry.getKey(), innerEntry.getValue()); } } else { map.put(entry.getKey(), entry.getValue()); } } } return map; } private final static String SIGNATURE_ALGORITHM = "HmacSHA256"; public static String computeSignature(String url, String nonce, String authToken) throws NoSuchAlgorithmException, InvalidKeyException, MalformedURLException, UnsupportedEncodingException { if (!allNotNull(url, nonce, authToken)) { throw new IllegalArgumentException("url, nonce and authToken must be non-null"); } URL parsedURL = new URL(url); String baseUrl = parsedURL.getProtocol() + "://" + parsedURL.getHost(); if (parsedURL.getPort() != -1) { baseUrl += ":" + Integer.toString(parsedURL.getPort()); } baseUrl += parsedURL.getPath(); String payload = baseUrl + nonce; SecretKeySpec signingKey = new SecretKeySpec(authToken.getBytes("UTF-8"), SIGNATURE_ALGORITHM); Mac mac = Mac.getInstance(SIGNATURE_ALGORITHM); mac.init(signingKey); return new String(Base64.getEncoder().encode(mac.doFinal(payload.getBytes("UTF-8")))); } public static boolean validateSignature(String url, String nonce, String signature, String authToken) throws NoSuchAlgorithmException, InvalidKeyException, MalformedURLException, UnsupportedEncodingException { return computeSignature(url, nonce, authToken).equals(signature); } public static String generateUrl(String url, String method, HashMap<String, String> params) throws MalformedURLException { URL parsedURL = new URL(url); String paramString = ""; List<String> keys = new ArrayList<String>(params.keySet()); if(method == "GET"){ for (String key : keys) { paramString += key + "=" + params.get(key) + "&"; } paramString = paramString.substring(0, paramString.length() - 1); try{ parsedURL.getQuery().length(); url += "&" + paramString; } catch (Exception e) { url += "/?" + paramString; } } else{ for (String key : keys) { paramString += key + params.get(key); } url += "." + paramString; } return url; } public static String computeSignatureV3(String url, String nonce, String authToken, String method, HashMap<String, String> params) throws NoSuchAlgorithmException, InvalidKeyException, MalformedURLException, UnsupportedEncodingException { if (!allNotNull(url, nonce, authToken)) { throw new IllegalArgumentException("url, nonce and authToken must be non-null"); } URL parsedURL = new URL(url); String payload = generateUrl(url, method, params) + "." + nonce; SecretKeySpec signingKey = new SecretKeySpec(authToken.getBytes("UTF-8"), SIGNATURE_ALGORITHM); Mac mac = Mac.getInstance(SIGNATURE_ALGORITHM); mac.init(signingKey); return new String(Base64.getEncoder().encode(mac.doFinal(payload.getBytes("UTF-8")))); } public static boolean validateSignatureV3(String url, String nonce, String signature, String authToken, String method, HashMap<String, String> params) throws NoSuchAlgorithmException, InvalidKeyException, MalformedURLException, UnsupportedEncodingException { List<String> splitSignature = Arrays.asList(signature.split(",")); return splitSignature.contains(computeSignatureV3(url, nonce, authToken, method, params)); } private static Map<String, List<String>> getLanguageVoices() { Map<String, List<String>> languageVoices = new HashMap<>(); languageVoices.put("arb", new ArrayList<String>(Arrays.asList("Zeina"))); languageVoices.put("cmn-CN", new ArrayList<String>(Arrays.asList("Zhiyu"))); languageVoices.put("da-DK", new ArrayList<String>(Arrays.asList("Naja", "Mads"))); languageVoices.put("nl-NL", new ArrayList<String>(Arrays.asList("Lotte", "Ruben"))); languageVoices.put("en-AU", new ArrayList<String>(Arrays.asList("Nicole", "Russell"))); languageVoices.put("en-GB", new ArrayList<String>(Arrays.asList("Amy", "Emma", "Brian"))); languageVoices.put("en-IN", new ArrayList<String>(Arrays.asList("Raveena", "Aditi"))); languageVoices.put("en-US", new ArrayList<String>(Arrays.asList("Joanna", "Salli", "Kendra", "Kimberly", "Ivy", "Matthew", "Justin", "Joey"))); languageVoices.put("en-GB-WLS", new ArrayList<String>(Arrays.asList("Geraint"))); languageVoices.put("fr-CA", new ArrayList<String>(Arrays.asList("Chantal", "Chantal"))); languageVoices.put("fr-FR", new ArrayList<String>(Arrays.asList("Léa", "Céline", "Mathieu"))); languageVoices.put("de-DE", new ArrayList<String>(Arrays.asList("Vicki", "Hans"))); languageVoices.put("hi-IN", new ArrayList<String>(Arrays.asList("Aditi"))); languageVoices.put("is-IS", new ArrayList<String>(Arrays.asList("Dóra", "Karl"))); languageVoices.put("it-IT", new ArrayList<String>(Arrays.asList("Carla", "Giorgio"))); languageVoices.put("ja-JP", new ArrayList<String>(Arrays.asList("Mizuki", "Takumi"))); languageVoices.put("ko-KR", new ArrayList<String>(Arrays.asList("Seoyeon"))); languageVoices.put("nb-NO", new ArrayList<String>(Arrays.asList("Liv"))); languageVoices.put("pl-PL", new ArrayList<String>(Arrays.asList("Ewa", "Maja", "Jacek", "Jan"))); languageVoices.put("pt-BR", new ArrayList<String>(Arrays.asList("Vitória", "Ricardo"))); languageVoices.put("pt-PT", new ArrayList<String>(Arrays.asList("Inês", "Cristiano"))); languageVoices.put("ro-RO", new ArrayList<String>(Arrays.asList("Carmen"))); languageVoices.put("ru-RU", new ArrayList<String>(Arrays.asList("Tatyana", "Maxim"))); languageVoices.put("es-ES", new ArrayList<String>(Arrays.asList("Conchita", "Lucia", "Enrique"))); languageVoices.put("es-MX", new ArrayList<String>(Arrays.asList("Mia"))); languageVoices.put("es-US", new ArrayList<String>(Arrays.asList("Penélope", "Miguel"))); languageVoices.put("sv-SE", new ArrayList<String>(Arrays.asList("Astrid"))); languageVoices.put("tr-TR", new ArrayList<String>(Arrays.asList("Filiz"))); languageVoices.put("cy-GB", new ArrayList<String>(Arrays.asList("Gwyneth"))); return languageVoices; } public static void validateLanguageVoice(String language, String voice) throws PlivoXmlException { String[] voiceParts = voice.split("\\."); System.out.println(language); if (voiceParts.length != 2 || !voiceParts[0].equals("Polly")) { throw new PlivoXmlException("XML Validation Error: Invalid language. Voice " + voice + " is not valid. " + "Refer <https://www.plivo.com/docs/voice/getting-started/advanced/getting-started-with-ssml/#ssml-voices> for the list of supported voices."); } Map<String, List<String>> languageVoices = getLanguageVoices(); // Validate supported languages. if (languageVoices.get(language) == null || languageVoices.get(language).isEmpty()) { throw new PlivoXmlException("XML Validation Error: Invalid language. Language " + language + " is not supported."); } // Transform the available language voices and the voice name into a common format. List<String> availableLanguageVoices = languageVoices.get(language); for (int i = 0; i < availableLanguageVoices.size(); i++) { availableLanguageVoices.set(i, transformString(availableLanguageVoices.get(i))); } String transformedVoiceName = transformString(voiceParts[1]); if (!voiceParts[1].equals("*") && !availableLanguageVoices.contains(transformedVoiceName)) { throw new PlivoXmlException("XML Validation Error: <Speak> voice '" + voice + "' is not valid. Refer <https://www.plivo.com/docs/voice/getting-started/advanced/getting-started-with-ssml/#ssml-voices> for list of supported voices."); } } public static String transformString(String s) { String transformedString; // Replace all accented characters with comparable english alphabets transformedString = Normalizer.normalize(s.trim(), Normalizer.Form.NFD); Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); transformedString = pattern.matcher(transformedString).replaceAll(""); // To title case and replace spaces with '_' transformedString = (new ArrayList<>(Arrays.asList(transformedString.toLowerCase().split(" ")))) .stream() .map(word -> Character.toTitleCase(word.charAt(0)) + word.substring(1)) .collect(Collectors.joining("_")); return transformedString; } }
src/main/java/com/plivo/api/util/Utils.java
package com.plivo.api.util; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.text.Normalizer; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang.StringUtils; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import com.fasterxml.jackson.databind.ObjectMapper; import com.plivo.api.exceptions.PlivoXmlException; public class Utils { public static boolean allNotNull(Object... objects) { return Stream.of(objects) .noneMatch(Objects::isNull); } public static boolean isSubaccountIdValid(String id) { return id != null && id.startsWith("SA") && id.length() == 20; } public static boolean isAccountIdValid(String id) { return id != null && id.startsWith("MA") && id.length() == 20; } public static boolean anyNotNull(Object... objects) { return Stream.of(objects) .anyMatch(Objects::nonNull); } public static Map<String, Object> objectToMap(ObjectMapper objectMapper, Object object) { Map<String, Object> origMap = objectMapper.convertValue(object, Map.class); Map<String, Object> map = new LinkedHashMap<>(); for (Entry<String, Object> entry : origMap.entrySet()) { if (entry.getValue() != null) { if (entry.getValue() instanceof Map) { Map<String, Object> innerEntries = objectMapper.convertValue(entry.getValue(), Map.class); for (Entry<String, Object> innerEntry : innerEntries.entrySet()) { map.put(entry.getKey() + innerEntry.getKey(), innerEntry.getValue()); } } else { map.put(entry.getKey(), entry.getValue()); } } } return map; } private final static String SIGNATURE_ALGORITHM = "HmacSHA256"; public static String computeSignature(String url, String nonce, String authToken) throws NoSuchAlgorithmException, InvalidKeyException, MalformedURLException, UnsupportedEncodingException { if (!allNotNull(url, nonce, authToken)) { throw new IllegalArgumentException("url, nonce and authToken must be non-null"); } URL parsedURL = new URL(url); String baseUrl = parsedURL.getProtocol() + "://" + parsedURL.getHost(); if (parsedURL.getPort() != -1) { baseUrl += ":" + Integer.toString(parsedURL.getPort()); } baseUrl += parsedURL.getPath(); String payload = baseUrl + nonce; SecretKeySpec signingKey = new SecretKeySpec(authToken.getBytes("UTF-8"), SIGNATURE_ALGORITHM); Mac mac = Mac.getInstance(SIGNATURE_ALGORITHM); mac.init(signingKey); return new String(Base64.getEncoder().encode(mac.doFinal(payload.getBytes("UTF-8")))); } public static boolean validateSignature(String url, String nonce, String signature, String authToken) throws NoSuchAlgorithmException, InvalidKeyException, MalformedURLException, UnsupportedEncodingException { return computeSignature(url, nonce, authToken).equals(signature); } public static String generateUrl(String url, String method, HashMap<String, String> params){ URL parsedURL = new URL(url); paramString = ""; if method == "GET"{ keys = params.keySet(); for(String key : keys){ paramString += key + "=" + params[key] + "&"; } Strip(paramString, "&"); if parsedURL.getQuery(){ url += "/?" + paramString; } else{ url += "&" + paramString; } } else{ keys = Arrays.sort(params.keySet()); for(String key : keys){ paramString += key + params[key]; } url += "." + paramString; } return url; } public static String computeSignatureV3(String url, String nonce, String authToken, String method, HashMap<String, String> params) throws NoSuchAlgorithmException, InvalidKeyException, MalformedURLException, UnsupportedEncodingException { if (!allNotNull(url, nonce, authToken)) { throw new IllegalArgumentException("url, nonce and authToken must be non-null"); } URL parsedURL = new URL(url); String payload = generateUrl(url, method, params) + "." + nonce; SecretKeySpec signingKey = new SecretKeySpec(authToken.getBytes("UTF-8"), SIGNATURE_ALGORITHM); Mac mac = Mac.getInstance(SIGNATURE_ALGORITHM); mac.init(signingKey); return new String(Base64.getEncoder().encode(mac.doFinal(payload.getBytes("UTF-8")))); } public static boolean validateSignatureV3(String url, String nonce, String signature, String authToken, String method, HashMap<String, String> params) throws NoSuchAlgorithmException, InvalidKeyException, MalformedURLException, UnsupportedEncodingException { String[] splitSignature = signature.split(","); return splitSignature.contains(computeSignatureV3(url, nonce, authToken, method, params)); } private static Map<String, List<String>> getLanguageVoices() { Map<String, List<String>> languageVoices = new HashMap<>(); languageVoices.put("arb", new ArrayList<String>(Arrays.asList("Zeina"))); languageVoices.put("cmn-CN", new ArrayList<String>(Arrays.asList("Zhiyu"))); languageVoices.put("da-DK", new ArrayList<String>(Arrays.asList("Naja", "Mads"))); languageVoices.put("nl-NL", new ArrayList<String>(Arrays.asList("Lotte", "Ruben"))); languageVoices.put("en-AU", new ArrayList<String>(Arrays.asList("Nicole", "Russell"))); languageVoices.put("en-GB", new ArrayList<String>(Arrays.asList("Amy", "Emma", "Brian"))); languageVoices.put("en-IN", new ArrayList<String>(Arrays.asList("Raveena", "Aditi"))); languageVoices.put("en-US", new ArrayList<String>(Arrays.asList("Joanna", "Salli", "Kendra", "Kimberly", "Ivy", "Matthew", "Justin", "Joey"))); languageVoices.put("en-GB-WLS", new ArrayList<String>(Arrays.asList("Geraint"))); languageVoices.put("fr-CA", new ArrayList<String>(Arrays.asList("Chantal", "Chantal"))); languageVoices.put("fr-FR", new ArrayList<String>(Arrays.asList("Léa", "Céline", "Mathieu"))); languageVoices.put("de-DE", new ArrayList<String>(Arrays.asList("Vicki", "Hans"))); languageVoices.put("hi-IN", new ArrayList<String>(Arrays.asList("Aditi"))); languageVoices.put("is-IS", new ArrayList<String>(Arrays.asList("Dóra", "Karl"))); languageVoices.put("it-IT", new ArrayList<String>(Arrays.asList("Carla", "Giorgio"))); languageVoices.put("ja-JP", new ArrayList<String>(Arrays.asList("Mizuki", "Takumi"))); languageVoices.put("ko-KR", new ArrayList<String>(Arrays.asList("Seoyeon"))); languageVoices.put("nb-NO", new ArrayList<String>(Arrays.asList("Liv"))); languageVoices.put("pl-PL", new ArrayList<String>(Arrays.asList("Ewa", "Maja", "Jacek", "Jan"))); languageVoices.put("pt-BR", new ArrayList<String>(Arrays.asList("Vitória", "Ricardo"))); languageVoices.put("pt-PT", new ArrayList<String>(Arrays.asList("Inês", "Cristiano"))); languageVoices.put("ro-RO", new ArrayList<String>(Arrays.asList("Carmen"))); languageVoices.put("ru-RU", new ArrayList<String>(Arrays.asList("Tatyana", "Maxim"))); languageVoices.put("es-ES", new ArrayList<String>(Arrays.asList("Conchita", "Lucia", "Enrique"))); languageVoices.put("es-MX", new ArrayList<String>(Arrays.asList("Mia"))); languageVoices.put("es-US", new ArrayList<String>(Arrays.asList("Penélope", "Miguel"))); languageVoices.put("sv-SE", new ArrayList<String>(Arrays.asList("Astrid"))); languageVoices.put("tr-TR", new ArrayList<String>(Arrays.asList("Filiz"))); languageVoices.put("cy-GB", new ArrayList<String>(Arrays.asList("Gwyneth"))); return languageVoices; } public static void validateLanguageVoice(String language, String voice) throws PlivoXmlException { String[] voiceParts = voice.split("\\."); System.out.println(language); if (voiceParts.length != 2 || !voiceParts[0].equals("Polly")) { throw new PlivoXmlException("XML Validation Error: Invalid language. Voice " + voice + " is not valid. " + "Refer <https://www.plivo.com/docs/voice/getting-started/advanced/getting-started-with-ssml/#ssml-voices> for the list of supported voices."); } Map<String, List<String>> languageVoices = getLanguageVoices(); // Validate supported languages. if (languageVoices.get(language) == null || languageVoices.get(language).isEmpty()) { throw new PlivoXmlException("XML Validation Error: Invalid language. Language " + language + " is not supported."); } // Transform the available language voices and the voice name into a common format. List<String> availableLanguageVoices = languageVoices.get(language); for (int i = 0; i < availableLanguageVoices.size(); i++) { availableLanguageVoices.set(i, transformString(availableLanguageVoices.get(i))); } String transformedVoiceName = transformString(voiceParts[1]); if (!voiceParts[1].equals("*") && !availableLanguageVoices.contains(transformedVoiceName) ){ throw new PlivoXmlException("XML Validation Error: <Speak> voice '" + voice + "' is not valid. Refer <https://www.plivo.com/docs/voice/getting-started/advanced/getting-started-with-ssml/#ssml-voices> for list of supported voices."); } } public static String transformString(String s) { String transformedString; // Replace all accented characters with comparable english alphabets transformedString = Normalizer.normalize(s.trim(), Normalizer.Form.NFD); Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); transformedString = pattern.matcher(transformedString).replaceAll(""); // To title case and replace spaces with '_' transformedString = (new ArrayList<>(Arrays.asList(transformedString.toLowerCase().split(" ")))) .stream() .map(word -> Character.toTitleCase(word.charAt(0)) + word.substring(1)) .collect(Collectors.joining("_")); return transformedString; } }
fix syntactic and semantic issues
src/main/java/com/plivo/api/util/Utils.java
fix syntactic and semantic issues
<ide><path>rc/main/java/com/plivo/api/util/Utils.java <ide> import java.util.Map; <ide> import java.util.Map.Entry; <ide> import java.util.Objects; <add>import java.util.Set; <add>import java.util.SortedSet; <ide> import java.util.regex.Pattern; <ide> import java.util.stream.Collectors; <ide> import java.util.stream.Stream; <del>import org.apache.commons.lang.StringUtils; <ide> <ide> import javax.crypto.Mac; <ide> import javax.crypto.spec.SecretKeySpec; <ide> return computeSignature(url, nonce, authToken).equals(signature); <ide> } <ide> <del> public static String generateUrl(String url, String method, HashMap<String, String> params){ <add> public static String generateUrl(String url, String method, HashMap<String, String> params) throws MalformedURLException { <ide> URL parsedURL = new URL(url); <del> paramString = ""; <del> if method == "GET"{ <del> keys = params.keySet(); <del> for(String key : keys){ <del> paramString += key + "=" + params[key] + "&"; <del> } <del> Strip(paramString, "&"); <del> if parsedURL.getQuery(){ <add> String paramString = ""; <add> List<String> keys = new ArrayList<String>(params.keySet()); <add> if(method == "GET"){ <add> for (String key : keys) { <add> paramString += key + "=" + params.get(key) + "&"; <add> } <add> paramString = paramString.substring(0, paramString.length() - 1); <add> try{ <add> parsedURL.getQuery().length(); <add> url += "&" + paramString; <add> } catch (Exception e) { <ide> url += "/?" + paramString; <ide> } <del> else{ <del> url += "&" + paramString; <del> } <ide> } <ide> else{ <del> keys = Arrays.sort(params.keySet()); <del> for(String key : keys){ <del> paramString += key + params[key]; <add> for (String key : keys) { <add> paramString += key + params.get(key); <ide> } <ide> url += "." + paramString; <ide> } <ide> <ide> public static boolean validateSignatureV3(String url, String nonce, String signature, String authToken, String method, HashMap<String, String> params) <ide> throws NoSuchAlgorithmException, InvalidKeyException, MalformedURLException, UnsupportedEncodingException { <del> String[] splitSignature = signature.split(","); <add> List<String> splitSignature = Arrays.asList(signature.split(",")); <ide> return splitSignature.contains(computeSignatureV3(url, nonce, authToken, method, params)); <ide> } <ide> <ide> System.out.println(language); <ide> if (voiceParts.length != 2 || !voiceParts[0].equals("Polly")) { <ide> throw new PlivoXmlException("XML Validation Error: Invalid language. Voice " + voice + " is not valid. " + <del> "Refer <https://www.plivo.com/docs/voice/getting-started/advanced/getting-started-with-ssml/#ssml-voices> for the list of supported voices."); <add> "Refer <https://www.plivo.com/docs/voice/getting-started/advanced/getting-started-with-ssml/#ssml-voices> for the list of supported voices."); <ide> } <ide> <ide> Map<String, List<String>> languageVoices = getLanguageVoices(); <ide> } <ide> String transformedVoiceName = transformString(voiceParts[1]); <ide> <del> if (!voiceParts[1].equals("*") && !availableLanguageVoices.contains(transformedVoiceName) ){ <add> if (!voiceParts[1].equals("*") && !availableLanguageVoices.contains(transformedVoiceName)) { <ide> throw new PlivoXmlException("XML Validation Error: <Speak> voice '" + voice + <del> "' is not valid. Refer <https://www.plivo.com/docs/voice/getting-started/advanced/getting-started-with-ssml/#ssml-voices> for list of supported voices."); <add> "' is not valid. Refer <https://www.plivo.com/docs/voice/getting-started/advanced/getting-started-with-ssml/#ssml-voices> for list of supported voices."); <ide> } <ide> } <ide> <ide> .collect(Collectors.joining("_")); <ide> return transformedString; <ide> } <del> <del> <ide> }
JavaScript
mit
86987c715725592f30e286e5740bce77ec0c6666
0
he7d3r/mw-gadget-rtrc,Krinkle/mw-gadget-rtrc
/** * Real-Time Recent Changes * https://github.com/Krinkle/mw-gadget-rtrc * * @license http://krinkle.mit-license.org/ * @author Timo Tijhof, 2010–2013 */ /*global alert */ (function ($, mw) { 'use strict'; /** * Configuration * ------------------------------------------------- */ var appVersion = 'v0.9.8', apiUrl = mw.util.wikiScript('api'), conf = mw.config.get([ 'skin', 'wgAction', 'wgCanonicalSpecialPageName', 'wgPageName', 'wgServer', 'wgTitle', 'wgUserLanguage', 'wgDBname' ]), cvnApiUrl = '//cvn.wmflabs.org/api.php', intuitionLoadUrl = '//tools.wmflabs.org/intuition/load.php?env=mw', docUrl = '//meta.wikimedia.org/wiki/User:Krinkle/Tools/Real-Time_Recent_Changes?uselang=' + conf.wgUserLanguage, // 32x32px ajaxLoaderUrl = '//upload.wikimedia.org/wikipedia/commons/d/de/Ajax-loader.gif', patrolCacheSize = 20, /** * Info from the wiki * ------------------------------------------------- */ userHasPatrolRight = false, userPatrolTokenCache = false, rcTags = [], wikiTimeOffset, /** * State * ------------------------------------------------- */ updateFeedTimeout, rcPrevDayHeading, skippedRCIDs = [], patrolledRCIDs = [], monthNames, prevFeedHtml, isUpdating = false, /** * Feed options * ------------------------------------------------- */ defOpt = { rc: { // Timestamp start: undefined, // Timestamp end: undefined, // Direction "older" (descending) or "newer" (ascending) dir: 'older', // Array of namespace ids namespace: undefined, // User name user: undefined, // Tag ID tag: undefined, // Show filters: exclude, include, filter showAnonOnly: false, showUnpatrolledOnly: false, limit: 25, // Type filters are "show matches only" typeEdit: false, typeNew: false }, app: { refresh: 3, cvnDB: false, massPatrol: false, autoDiff: false } }, opt = $(true, {}, defOpt), timeUtil, message, msg, navCollapsed, navSupported = conf.skin === 'vector' && !!window.localStorage, nextFrame = window.requestAnimationFrame || setTimeout, currentDiff, currentDiffRcid, $wrapper, $body, $feed, $RCOptions_submit; /** * Utility functions * ------------------------------------------------- */ if (!String.prototype.ucFirst) { String.prototype.ucFirst = function () { // http://jsperf.com/ucfirst/4 // http://jsperf.com/ucfirst-replace-vs-substr/3 // str.charAt(0).toUpperCase() + str.substr(1); // str[0].toUpperCase() + str.slice(1); // str.charAt(0).toUpperCase() + str.substring(1); // str.substr(0, 1).toUpperCase() + str.substr(1, this.length); return this.charAt(0).toUpperCase() + this.substring(1); }; } // Prepends a leading zero if value is under 10 function leadingZero(i) { if (i < 10) { i = '0' + i; } return i; } timeUtil = { // Create new Date instance from MediaWiki API timestamp string newDateFromApi: function (s) { // Possible number/integer to string var t = Date.UTC( // "2010-04-25T23:24:02Z" => 2010, 3, 25, 23, 24, 2 parseInt(s.slice(0, 4), 10), // Year parseInt(s.slice(5, 7), 10) - 1, // Month parseInt(s.slice(8, 10), 10), // Day parseInt(s.slice(11, 13), 10), // Hour parseInt(s.slice(14, 16), 10), // Minutes parseInt(s.slice(17, 19), 10) // Seconds ); return new Date(t); }, /** * Apply user offset. * * Only use this if you're extracting individual values * from the object (e.g. getUTCDay or getUTCMinutes). * The full timestamp will incorrectly claim "GMT". */ applyUserOffset: function (d) { var offset = mw.user.options.get('timecorrection'); // This preference has no default value, it is null for users that don't // override the site's default timeoffset. if (offset) { offset = Number(offset.split('|')[1]); } else { offset = wikiTimeOffset; } // There is no way to set a timezone in javascript, so we instead pretend the real unix // time is different and then get the values from that. d.setTime(d.getTime() + (offset * 60 * 1000)); return d; }, // Get clocktime string adjusted to timezone of wiki // from MediaWiki timestamp string getClocktimeFromApi: function (s) { var d = timeUtil.applyUserOffset(timeUtil.newDateFromApi(s)); // Return clocktime with leading zeros return leadingZero(d.getUTCHours()) + ':' + leadingZero(d.getUTCMinutes()); } }; /** * Main functions * ------------------------------------------------- */ function buildRcDayHead(time) { var current = time.getDate(); if (current === rcPrevDayHeading) { return ''; } rcPrevDayHeading = current; return '<div class="mw-rtrc-heading"><div><strong>' + time.getDate() + ' ' + monthNames[time.getMonth()] + '</strong></div></div>'; } /** * @param {Object} rc Recent change object from API * @return {string} HTML */ function buildRcItem(rc) { var diffsize, isUnpatrolled, isAnon, typeSymbol, itemClass, diffLink, commentHtml, el, item; // Get size difference (can be negative, zero or positive) diffsize = rc.newlen - rc.oldlen; // Convert undefined/empty-string values from API into booleans isUnpatrolled = rc.unpatrolled !== undefined; isAnon = rc.anon !== undefined; // typeSymbol, diffLink & itemClass typeSymbol = '&nbsp;'; itemClass = ''; if (rc.type === 'new') { typeSymbol += '<span class="newpage">N</span>'; } if ((rc.type === 'edit' || rc.type === 'new') && userHasPatrolRight && isUnpatrolled) { typeSymbol += '<span class="unpatrolled">!</span>'; } commentHtml = rc.parsedcomment; // Check if edit summary is an AES if (commentHtml.indexOf('<a href="/wiki/Commons:AES" class="mw-redirect" title="Commons:AES">\u2190</a>') === 0) { // TODO: This is specific to commons.wikimedia.org itemClass += ' mw-rtrc-item-aes'; } // Anon-attribute if (isAnon) { itemClass = ' mw-rtrc-item-anon'; } else { itemClass = ' mw-rtrc-item-liu'; } /* Example: <div class="mw-rtrc-item mw-rtrc-item-patrolled" data-diff="0" data-rcid="0" user="Abc"> <div diff>(<a class="diff" href="//">diff</a>)</div> <div type><span class="unpatrolled">!</span></div> <div timetitle>00:00 <a href="//?rcid=0" target="_blank">Abc</a></div> <div user><a class="user" href="//User:Abc">Abc</a></div> <div other><a href="//User talk:Abc">talk</a> / <a href="//Special:Contributions/Abc">contribs</a>&nbsp;<span class="comment">Abc</span></div> <div size><span class="mw-plusminus-null">(0)</span></div> </div> */ // build & return item item = buildRcDayHead(timeUtil.newDateFromApi(rc.timestamp)); item += '<div class="mw-rtrc-item ' + itemClass + '" data-diff="' + rc.revid + '" data-rcid="' + rc.rcid + '" user="' + rc.user + '">'; if (rc.type === 'edit') { diffLink = '<a class="rcitemlink diff" href="' + mw.util.wikiScript() + '?diff=' + rc.revid + '&oldif=' + rc.old_revid + '&rcid=' + rc.rcid + '">' + mw.message('diff').escaped() + '</a>'; } else if (rc.type === 'new') { diffLink = '<a class="rcitemlink newPage">new</a>'; } else { diffLink = mw.message('diff').escaped(); } item += '<div first>(' + diffLink + ') ' + typeSymbol + ' '; item += timeUtil.getClocktimeFromApi(rc.timestamp) + ' <a class="page" href="' + mw.util.getUrl(rc.title) + '?rcid=' + rc.rcid + '" target="_blank">' + rc.title + '</a></div>'; item += '<div user>&nbsp;<small>&middot;&nbsp;<a href="' + mw.util.getUrl('User talk:' + rc.user) + '" target="_blank">T</a> &middot; <a href="' + mw.util.getUrl('Special:Contributions/' + rc.user) + '" target="_blank">C</a>&nbsp;</small>&middot;&nbsp;<a class="user" href="' + mw.util.getUrl((mw.util.isIPv4Address(rc.user) || mw.util.isIPv6Address(rc.user) ? 'Special:Contributions/' : 'User:') + rc.user) + '" target="_blank">' + rc.user + '</a></div>'; item += '<div other>&nbsp;<span class="comment">' + commentHtml + '</span></div>'; if (diffsize > 0) { el = diffsize > 399 ? 'strong' : 'span'; item += '<div size><' + el + ' class="mw-plusminus-pos">(' + diffsize + ')</' + el + '></div>'; } else if (diffsize === 0) { item += '<div size><span class="mw-plusminus-null">(0)</span></div>'; } else { el = diffsize < -399 ? 'strong' : 'span'; item += '<div size><' + el + ' class="mw-plusminus-neg">(' + diffsize + ')</' + el + '></div>'; } item += '</div>'; return item; } /** * @param {Object} newOpt * @param {string} [mode=normal] One of 'quiet' or 'normal' * @return {boolean} True if no changes were made, false otherwise */ function normaliseSettings(newOpt, mode) { var mod = false; // MassPatrol requires a filter to be active if (newOpt.app.massPatrol && !newOpt.rc.user) { newOpt.app.massPatrol = false; mod = true; if (mode !== 'quiet') { alert(msg('masspatrol-requires-userfilter')); } } // MassPatrol requires AutoDiff if (newOpt.app.massPatrol && !newOpt.app.autoDiff) { newOpt.app.autoDiff = true; mod = true; } return !mod; } function readSettingsForm() { // jQuery#serializeArray is nice, but doesn't include "value: false" for unchecked // checkboxes that are not disabled. Using raw .elements instead and filtering // out <fieldset>. var $settings = $($wrapper.find('.mw-rtrc-settings')[0].elements).filter(':input'); opt = $.extend(true, {}, defOpt); $settings.each(function (i, el) { var name = el.name; switch (name) { // RC case 'limit': opt.rc[name] = Number(el.value); break; case 'namespace': // Can be "0". // Value "" (all) is represented by undefined. // TODO: Turn this into a multi-select, the API supports it. opt.rc[name] = el.value.length ? Number(el.value) : undefined; break; case 'user': case 'start': case 'end': case 'tag': opt.rc[name] = el.value || undefined; break; case 'showAnonOnly': case 'showUnpatrolledOnly': case 'typeEdit': case 'typeNew': opt.rc[name] = el.checked; break; case 'dir': // There's more than 1 radio button with this name in this loop, // use the value of the first (and only) checked one. if (el.checked) { opt.rc[name] = el.value; } break; // APP case 'cvnDB': case 'massPatrol': case 'autoDiff': opt.app[name] = el.checked; break; case 'refresh': opt.app[name] = Number(el.value); break; } }); if (!normaliseSettings(opt)) { // TODO: Optimise this, no need to repopulate the entire settings form // if only 1 thing changed. fillSettingsForm(opt); } } function fillSettingsForm(newOpt) { var $settings = $($wrapper.find('.mw-rtrc-settings')[0].elements).filter(':input'); if (newOpt.rc) { $.each(newOpt.rc, function (key, value) { var $setting = $settings.filter(function () { return this.name === key; }), setting = $setting[0]; if (!setting) { return; } switch (key) { case 'limit': setting.value = value; break; case 'namespace': if (value === undefined) { // Value "" (all) is represented by undefined. $setting.find('option').eq(0).prop('selected', true); } else { $setting.val(value); } break; case 'user': case 'start': case 'end': case 'tag': setting.value = value || ''; break; case 'showAnonOnly': case 'showUnpatrolledOnly': case 'typeEdit': case 'typeNew': setting.checked = value; break; case 'dir': if (setting.value === value) { setting.checked = true; } break; } }); } if (newOpt.app) { $.each(newOpt.app, function (key, value) { var $setting = $settings.filter(function () { return this.name === key; }), setting = $setting[0]; if (!setting) { setting = document.getElementById('rc-options-' + key); $setting = $(setting); } if (!setting) { return; } switch (key) { case 'cvnDB': case 'massPatrol': case 'autoDiff': setting.checked = value; break; case 'refresh': setting.value = value; break; } }); } } function getPermalink() { var uri = new mw.Uri(mw.util.getUrl(conf.wgPageName)), reducedOpt = {}; $.each(opt.rc, function (key, value) { if (defOpt.rc[key] !== value) { if (!reducedOpt.rc) { reducedOpt.rc = {}; } reducedOpt.rc[key] = value; } }); $.each(opt.app, function (key, value) { if (defOpt.app[key] !== value) { if (!reducedOpt.app) { reducedOpt.app = {}; } reducedOpt.app[key] = value; } }); reducedOpt = $.toJSON(reducedOpt); uri.extend({ opt: reducedOpt === '{}' ? undefined : reducedOpt, kickstart: 1 }); return uri.toString(); } // Read permalink into the program and reflect into settings form. // TODO: Refactor into init, as this does more than read permalink. // It also inits the settings form and handles kickstart function readPermalink() { var url = new mw.Uri(), newOpt = url.query.opt, kickstart = url.query.kickstart; newOpt = newOpt ? $.parseJSON(newOpt): {}; newOpt = $.extend(true, {}, defOpt, newOpt); normaliseSettings(newOpt, 'quiet'); fillSettingsForm(newOpt); opt = newOpt; if (kickstart === '1') { updateFeedNow(); if ($wrapper[0].scrollIntoView) { $wrapper[0].scrollIntoView(); } } } function getApiRcParams(rc) { var rcprop = [ 'flags', 'timestamp', 'user', 'title', 'parsedcomment', 'sizes', 'ids' ], rcshow = ['!bot'], rctype = [], params = {}; params.rcdir = rc.dir; if (rc.dir === 'older') { if (rc.end !== undefined) { params.rcstart = rc.end; } if (rc.start !== undefined) { params.rcend = rc.start; } } else if (rc.dir === 'newer') { if (rc.start !== undefined) { params.rcstart = rc.start; } if (rc.end !== undefined) { params.rcend = rc.end; } } if (rc.namespace !== undefined) { params.rcnamespace = rc.namespace; } if (rc.user !== undefined) { params.rcuser = rc.user; } // params.titles: Title filter option (rctitles) is no longer supported by MediaWiki, // see https://bugzilla.wikimedia.org/show_bug.cgi?id=12394#c5. if (rc.tag !== undefined) { params.rctag = rc.tag; } if (userHasPatrolRight) { rcprop.push('patrolled'); } params.rcprop = rcprop.join('|'); if (rc.showAnonOnly) { rcshow.push('anon'); } if (rc.showUnpatrolledOnly) { rcshow.push('!patrolled'); } params.rcshow = rcshow.join('|'); params.rclimit = rc.limit; if (rc.typeEdit) { rctype.push('edit'); } if (rc.typeNew) { rctype.push('new'); } params.rctype = rctype.length ? rctype.join('|') : 'edit|new'; return params; } // Called when the feed is regenerated before being inserted in the document function applyRtrcAnnotations($feedContent) { // Re-apply item classes $feedContent.filter('.mw-rtrc-item').each(function () { var $el = $(this), rcid = Number($el.data('rcid')); // Mark skipped and patrolled items as such if ($.inArray(rcid, skippedRCIDs) !== -1) { $el.addClass('mw-rtrc-item-skipped'); } else if ($.inArray(rcid, patrolledRCIDs) !== -1) { $el.addClass('mw-rtrc-item-patrolled'); } else if (rcid === currentDiffRcid) { $el.addClass('mw-rtrc-item-current'); } }); } /** * @param {Object} update * @param {jQuery} update.$feedContent * @param {string} update.rawHtml */ function pushFeedContent(update) { // TODO: Only do once $body.removeClass('placeholder'); $feed.find('.mw-rtrc-feed-update').html( message('lastupdate-rc', new Date().toLocaleString()).escaped() + ' | <a href="' + getPermalink() + '">' + message('permalink').escaped() + '</a>' ); if (update.rawHtml !== prevFeedHtml) { prevFeedHtml = update.rawHtml; applyRtrcAnnotations(update.$feedContent); $feed.find('.mw-rtrc-feed-content').empty().append(update.$feedContent); } // Schedule next update updateFeedTimeout = setTimeout(updateFeed, opt.app.refresh * 1000); $('#krRTRC_loader').hide(); } function applyCvnAnnotations($feedContent, callback) { var users; // Find all user names inside the feed users = []; $feedContent.filter('.mw-rtrc-item').each(function () { var user = $(this).attr('user'); if (user) { users.push(user); } }); if (!users.length) { callback(); return; } $.ajax({ url: cvnApiUrl, data: { users: users.join('|'), }, dataType: 'jsonp' }) .fail(function () { callback(); }) .done(function (data) { var d; if (!data.users) { callback(); return; } // Loop through all users $.each(data.users, function (name, user) { var tooltip; // Only if blacklisted, otherwise dont highlight if (user.type === 'blacklist') { tooltip = ''; if (user.comment) { tooltip += msg('cvn-reason') + ': ' + user.comment + '. '; } else { tooltip += msg('cvn-reason') + ': ' + msg('cvn-reason-empty'); } if (user.adder) { tooltip += msg('cvn-adder') + ': ' + user.adder; } else { tooltip += msg('cvn-adder') + ': ' + msg('cvn-adder-empty'); } // Apply blacklisted-class, and insert icon with tooltip $feedContent .filter('.mw-rtrc-item') .filter(function () { return $(this).attr('user') === name; }) .find('.user') .addClass('blacklisted') .attr('title', tooltip); } }); // Either way, push the feed to the frontend callback(); d = new Date(); d.setTime(data.lastUpdate * 1000); $feed.find('.mw-rtrc-feed-cvninfo').text('CVN DB ' + msg('lastupdate-cvn', d.toUTCString())); }); } function updateFeedNow() { $('#rc-options-pause').prop('checked', false); clearTimeout(updateFeedTimeout); updateFeed(); } function updateFeed() { var rcparams; if (!isUpdating) { // Indicate updating $('#krRTRC_loader').show(); isUpdating = true; // Download recent changes rcparams = getApiRcParams(opt.rc); rcparams.format = 'json'; rcparams.action = 'query'; rcparams.list = 'recentchanges'; $.ajax({ url: apiUrl, dataType: 'json', data: rcparams }).fail(function () { var feedContentHTML = '<h3>Downloading recent changes failed</h3>'; pushFeedContent({ $feedContent: $(feedContentHTML), rawHtml: feedContentHTML }); isUpdating = false; $RCOptions_submit.prop('disabled', false).css('opacity', '1.0'); }).done(function (data) { var recentchanges, $feedContent, feedContentHTML = ''; if (data.error) { $body.removeClass('placeholder'); // Account doesn't have patrol flag if (data.error.code === 'rcpermissiondenied') { feedContentHTML += '<h3>Downloading recent changes failed</h3><p>Please untick the "Unpatrolled only"-checkbox or request the Patroller-right.</a>'; // Other error } else { feedContentHTML += '<h3>Downloading recent changes failed</h3><p>Please check the settings above and try again. If you believe this is a bug, please <a href="//meta.wikimedia.org/w/index.php?title=User_talk:Krinkle/Tools&action=edit&section=new&preload=User_talk:Krinkle/Tools/Preload" target="_blank"><strong>let me know</strong></a>.'; } } else { recentchanges = data.query.recentchanges; if (recentchanges.length) { $.each(recentchanges, function (i, rc) { feedContentHTML += buildRcItem(rc); }); } else { // Everything is OK - no results feedContentHTML += '<strong><em>' + message('nomatches').escaped() + '</em></strong>'; } // Reset day rcPrevDayHeading = undefined; } $feedContent = $($.parseHTML(feedContentHTML)); if (opt.app.cvnDB) { applyCvnAnnotations($feedContent, function () { pushFeedContent({ $feedContent: $feedContent, rawHtml: feedContentHTML }); isUpdating = false; }); } else { pushFeedContent({ $feedContent: $feedContent, rawHtml: feedContentHTML }); isUpdating = false; } $RCOptions_submit.prop('disabled', false).css('opacity', '1.0'); }); } } function krRTRC_NextDiff() { var $lis = $feed.find('.mw-rtrc-item:not(.mw-rtrc-item-current, .mw-rtrc-item-patrolled, .mw-rtrc-item-skipped)'); $lis.eq(0).find('a.rcitemlink').click(); } function krRTRC_ToggleMassPatrol(b) { if (b === true) { if (!currentDiff) { krRTRC_NextDiff(); } else { $('.patrollink a').click(); } } } function navToggle() { navCollapsed = String(navCollapsed !== 'true'); $('html').toggleClass('mw-rtrc-navtoggle-collapsed'); localStorage.setItem('mw-rtrc-navtoggle-collapsed', navCollapsed); } // Build the main interface function buildInterface() { var namespaceOptionsHtml, tagOptionsHtml, key, fmNs = mw.config.get('wgFormattedNamespaces'); namespaceOptionsHtml = '<option value>' + mw.message('namespacesall').escaped() + '</option>'; namespaceOptionsHtml += '<option value="0">' + mw.message('blanknamespace').escaped() + '</option>'; for (key in fmNs) { if (key > 0) { namespaceOptionsHtml += '<option value="' + key + '">' + fmNs[key] + '</option>'; } } tagOptionsHtml = '<option value selected>' + message('select-placeholder-none').escaped() + '</option>'; for (key = 0; key < rcTags.length; key++) { tagOptionsHtml += '<option value="' + mw.html.escape(rcTags[key]) + '">' + mw.html.escape(rcTags[key]) + '</option>'; } $wrapper = $($.parseHTML( '<div class="mw-rtrc-wrapper">' + '<div class="mw-rtrc-head">' + 'Real-Time Recent Changes <small>(' + appVersion + ')</small>' + '<div class="mw-rtrc-head-links">' + (!mw.user.isAnon() ? ( '<a target="_blank" href="' + mw.util.getUrl('Special:Log/patrol') + '?user=' + encodeURIComponent(mw.user.name()) + '">' + message('mypatrollog').escaped().ucFirst() + '</a>') : '' ) + '<a id="mw-rtrc-toggleHelp">Help</a>' + '</div>' + '</div>' + '<form id="krRTRC_RCOptions" class="mw-rtrc-settings mw-rtrc-nohelp make-switch"><fieldset>' + '<div class="panel-group">' + '<div class="panel">' + '<label for="mw-rtrc-settings-limit" class="head">' + message('limit').escaped() + '</label>' + '<select id="mw-rtrc-settings-limit" name="limit">' + '<option value="10">10</option>' + '<option value="25" selected>25</option>' + '<option value="50">50</option>' + '<option value="75">75</option>' + '<option value="100">100</option>' + '</select>' + '</div>' + '<div class="panel">' + '<label class="head">' + message('filter').escaped() + '</label>' + '<div style="text-align: left;">' + '<label>' + '<input type="checkbox" name="showAnonOnly" />' + ' ' + message('showAnonOnly').escaped() + '</label>' + '<br />' + '<label>' + '<input type="checkbox" name="showUnpatrolledOnly" />' + ' ' + message('showUnpatrolledOnly').escaped() + '</label>' + '</div>' + '</div>' + '<div class="panel">' + '<label for="mw-rtrc-settings-user" class="head">' + message('userfilter').escaped() + '<span section="Userfilter" class="helpicon"></span>' + '</label>' + '<div style="text-align: center;">' + '<input type="text" size="16" id="mw-rtrc-settings-user" name="user" />' + '<br />' + '<input class="button button-small" type="button" id="mw-rtrc-settings-user-clr" value="' + message('clear').escaped() + '" />' + '</div>' + '</div>' + '<div class="panel">' + '<label class="head">' + message('type').escaped() + '</label>' + '<div style="text-align: left;">' + '<label>' + '<input type="checkbox" name="typeEdit" checked />' + ' ' + message('typeEdit').escaped() + '</label>' + '<br />' + '<label>' + '<input type="checkbox" name="typeNew" checked />' + ' ' + message('typeNew').escaped() + '</label>' + '</div>' + '</div>' + '<div class="panel">' + '<label class="head">' + message('timeframe').escaped() + '<span section="Timeframe" class="helpicon"></span>' + '</label>' + '<div style="text-align: right;">' + '<label>' + message('time-from').escaped() + ': ' + '<input type="text" size="18" name="start" />' + '</label>' + '<br />' + '<label>' + message('time-untill').escaped() + ': ' + '<input type="text" size="18" name="end" />' + '</label>' + '</div>' + '</div>' + '<div class="panel">' + '<label class="head">' + mw.message('namespaces').escaped() + ' <br />' + '<select class="mw-rtrc-setting-select" name="namespace">' + namespaceOptionsHtml + '</select>' + '</label>' + '</div>' + '<div class="panel">' + '<label class="head">' + message('order').escaped() + ' <br />' + '<span section="Order" class="helpicon"></span>' + '</label>' + '<div style="text-align: left;">' + '<label>' + '<input type="radio" name="dir" value="newer" />' + ' ' + message('asc').escaped() + '</label>' + '<br />' + '<label>' + '<input type="radio" name="dir" value="older" checked />' + ' ' + message('desc').escaped() + '</label>' + '</div>' + '</div>' + '<div class="panel">' + '<label for="mw-rtrc-settings-refresh" class="head">' + 'R<br />' + '<span section="Reload_Interval" class="helpicon"></span>' + '</label>' + '<input type="number" value="3" min="0" max="99" size="2" id="mw-rtrc-settings-refresh" name="refresh" />' + '</div>' + '<div class="panel">' + '<label class="head">' + 'CVN DB<br />' + '<span section="IRC_Blacklist" class="helpicon"></span>' + '<input type="checkbox" class="switch" name="cvnDB" />' + '</label>' + '</div>' + '<div class="panel panel-last">' + '<input class="button" type="button" id="RCOptions_submit" value="' + message('apply').escaped() + '" />' + '</div>' + '</div>' + '<div class="panel-group panel-group-mini">' + '<div class="panel">' + '<label class="head">' + message('tag').escaped() + ' <select class="mw-rtrc-setting-select" name="tag">' + tagOptionsHtml + '</select>' + '</label>' + '</div>' + '<div class="panel">' + '<label class="head">' + 'MassPatrol' + '<span section="MassPatrol" class="helpicon"></span>' + '<input type="checkbox" class="switch" name="massPatrol" />' + '</label>' + '</div>' + '<div class="panel">' + '<label class="head">' + 'AutoDiff' + '<span section="AutoDiff" class="helpicon"></span>' + '<input type="checkbox" class="switch" name="autoDiff" />' + '</label>' + '</div>' + '<div class="panel">' + '<label class="head">' + 'Pause' + '<input class="switch" type="checkbox" id="rc-options-pause" />' + '</label>' + '</div>' + '</div>' + '</fieldset></form>' + '<a name="krRTRC_DiffTop" />' + '<div class="mw-rtrc-diff" id="krRTRC_DiffFrame" style="display: none;"></div>' + '<div class="mw-rtrc-body placeholder">' + '<div class="mw-rtrc-feed">' + '<div class="mw-rtrc-feed-update"></div>' + '<div class="mw-rtrc-feed-content"></div>' + '<small class="mw-rtrc-feed-cvninfo"></small>' + '</div>' + '<img src="' + ajaxLoaderUrl + '" id="krRTRC_loader" style="display: none;" />' + '<div class="mw-rtrc-legend">' + 'Colors: <div class="mw-rtrc-item mw-rtrc-item-patrolled inline-block">&nbsp;' + mw.message('markedaspatrolled').escaped() + '&nbsp;</div>, <div class="mw-rtrc-item mw-rtrc-item-current inline-block">&nbsp;' + message('currentedit').escaped() + '&nbsp;</div>, ' + '<div class="mw-rtrc-item mw-rtrc-item-skipped inline-block">&nbsp;' + message('skippededit').escaped() + '&nbsp;</div>, ' + '<div class="mw-rtrc-item mw-rtrc-item-aes inline-block">&nbsp;Edit with an Automatic Edit Summary&nbsp;</div>' + '<br />Abbreviations: T - ' + mw.message('talkpagelinktext').escaped() + ', C - ' + mw.message('contributions', mw.user).escaped() + '</div>' + '</div>' + '<div style="clear: both;"></div>' + '<div class="mw-rtrc-foot">' + '<div class="plainlinks" style="text-align: right;">' + 'Real-Time Recent Changes by ' + '<a href="//meta.wikimedia.org/wiki/User:Krinkle" class="external text" rel="nofollow">Krinkle</a>' + ' | <a href="//meta.wikimedia.org/wiki/User:Krinkle/Tools/Real-Time_Recent_Changes" class="external text" rel="nofollow">' + message('documentation').escaped() + '</a>' + ' | <a href="https://github.com/Krinkle/mw-gadget-rtrc/releases" class="external text" rel="nofollow">' + message('changelog').escaped() + '</a>' + ' | <a href="https://github.com/Krinkle/mw-gadget-rtrc/issues" class="external text" rel="nofollow">Feedback</a>' + ' | <a href="http://krinkle.mit-license.org" class="external text" rel="nofollow">License</a>' + '</div>' + '</div>' + '</div>' )); // Add helper element for switch checkboxes $wrapper.find('input.switch').after('<div class="switched"></div>'); // All links within the diffframe should open in a new window $wrapper.find('#krRTRC_DiffFrame').on('click', 'table.diff a', function () { var $el = $(this); if ($el.is('[href^="http://"], [href^="https://"], [href^="//"]')) { $el.attr('target', '_blank'); } }); $('#content').empty().append($wrapper); nextFrame(function () { $('html').addClass('mw-rtrc-ready'); }); $body = $wrapper.find('.mw-rtrc-body'); $feed = $body.find('.mw-rtrc-feed'); } // Bind event hanlders in the user interface function bindInterface() { $RCOptions_submit = $('#RCOptions_submit'); // Apply button $RCOptions_submit.click(function () { $RCOptions_submit.prop('disabled', true).css('opacity', '0.5'); readSettingsForm(); krRTRC_ToggleMassPatrol(opt.app.massPatrol); updateFeedNow(); return false; }); // Close Diff $('#diffClose').live('click', function () { $('#krRTRC_DiffFrame').fadeOut('fast'); currentDiff = currentDiffRcid = false; }); // Load diffview on (diff)-link click $('a.diff').live('click', function (e) { var $item = $(this).closest('.mw-rtrc-item').addClass('mw-rtrc-item-current'), title = $item.find('.page').text(), href = $(this).attr('href'), $frame = $('#krRTRC_DiffFrame'); $feed.find('.mw-rtrc-item-current').not($item).removeClass('mw-rtrc-item-current'); currentDiff = Number($item.data('diff')); currentDiffRcid = Number($item.data('rcid')); // Reset style="max-height: 400;" from a.newPage below $frame.fadeOut().removeAttr('style'); $.ajax({ url: mw.util.wikiScript(), dataType: 'html', data: { action: 'render', diff: currentDiff, diffonly: '1', uselang: conf.wgUserLanguage } }).fail(function (jqXhr) { $frame .stop(true, true) .append(jqXhr.responseText || 'Loading diff failed.') .fadeIn(); }).done(function (data) { var skipButtonHtml; if ($.inArray(currentDiffRcid, skippedRCIDs) !== -1) { skipButtonHtml = '<span class="tab"><a id="diffUnskip">Unskip</a></span>'; } else { skipButtonHtml = '<span class="tab"><a id="diffSkip">Skip</a></span>'; } $frame .stop(true, true) .html(data) .prepend( '<h3>' + mw.html.escape(title) + '</h3>' + '<div class="mw-rtrc-diff-tools">' + '<span class="tab"><a id="diffClose">X</a></span>' + '<span class="tab"><a href="' + href + '" target="_blank" id="diffNewWindow">Open in Wiki</a></span>' + (userPatrolTokenCache ? '<span class="tab"><a onclick="(function(){ if($(\'.patrollink a\').length){ $(\'.patrollink a\').click(); } else { $(\'#diffSkip\').click(); } })();">[mark]</a></span>' : '' ) + '<span class="tab"><a id="diffNext">' + mw.message('next').escaped().ucFirst() + ' &raquo;</a></span>' + skipButtonHtml + '</div>' ) .fadeIn(); if (opt.app.massPatrol) { $frame.find('.patrollink a').click(); } }); e.preventDefault(); }); $('a.newPage').live('click', function (e) { var $item = $(this).closest('.mw-rtrc-item').addClass('mw-rtrc-item-current'), title = $item.find('.page').text(), href = $item.find('.page').attr('href'), $frame = $('#krRTRC_DiffFrame'); $feed.find('.mw-rtrc-item-current').not($item).removeClass('mw-rtrc-item-current'); currentDiffRcid = Number($item.data('rcid')); $frame.fadeOut().css('max-height', '400px'); $.ajax({ url: href, dataType: 'html', data: { action: 'render', uselang: conf.wgUserLanguage } }).fail(function (jqXhr) { $frame .stop(true, true) .append(jqXhr.responseText || 'Loading diff failed.') .fadeIn(); }).done(function (data) { var skipButtonHtml; if ($.inArray(currentDiffRcid, skippedRCIDs) !== -1) { skipButtonHtml = '<span class="tab"><a id="diffUnskip">Unskip</a></span>'; } else { skipButtonHtml = '<span class="tab"><a id="diffSkip">Skip</a></span>'; } $frame .stop(true, true) .html(data) .prepend( '<h3>' + title + '</h3>' + '<div class="mw-rtrc-diff-tools">' + '<span class="tab"><a id="diffClose">X</a></span>' + '<span class="tab"><a href="' + href + '" target="_blank" id="diffNewWindow">Open in Wiki</a></span>' + '<span class="tab"><a onclick="$(\'.patrollink a\').click()">[mark]</a></span>' + '<span class="tab"><a id="diffNext">' + mw.message('next').escaped().ucFirst() + ' &raquo;</a></span>' + skipButtonHtml + '</div>' ) .fadeIn(); if (opt.app.massPatrol) { $frame.find('.patrollink a').click(); } }); e.preventDefault(); }); // Mark as patrolled $('.patrollink').live('click', function () { var $el = $(this); $el.find('a').text(mw.msg('markaspatrolleddiff') + '...'); $.ajax({ type: 'POST', url: apiUrl, dataType: 'json', data: { action: 'patrol', format: 'json', list: 'recentchanges', rcid: currentDiffRcid, token: userPatrolTokenCache } }).done(function (data) { if (!data || data.error) { $el.empty().append( $('<span style="color: red;"></span>').text(mw.msg('markedaspatrollederror')) ); mw.log('Patrol error:', data); } else { $el.empty().append( $('<span style="color: green;"></span>').text(mw.msg('markedaspatrolled')) ); $feed.find('.mw-rtrc-item[data-rcid="' + currentDiffRcid + '"]').addClass('mw-rtrc-item-patrolled'); // Patrolling/Refreshing sometimes overlap eachother causing patrolled edits to show up in an 'unpatrolled only' feed. // Make sure that any patrolled edits stay marked as such to prevent AutoDiff from picking a patrolled edit patrolledRCIDs.push(currentDiffRcid); while (patrolledRCIDs.length > patrolCacheSize) { patrolledRCIDs.shift(); } if (opt.app.autoDiff) { krRTRC_NextDiff(); } } }).fail(function () { $el.empty().append( $('<span style="color: red;"></span>').text(mw.msg('markedaspatrollederror')) ); }); return false; }); // Trigger NextDiff $('#diffNext').live('click', function () { krRTRC_NextDiff(); }); // SkipDiff $('#diffSkip').live('click', function () { $feed.find('.mw-rtrc-item[data-rcid="' + currentDiffRcid + '"]').addClass('mw-rtrc-item-skipped'); // Add to array, to re-add class after refresh skippedRCIDs.push(currentDiffRcid); krRTRC_NextDiff(); }); // UnskipDiff $('#diffUnskip').live('click', function () { $feed.find('.mw-rtrc-item[data-rcid="' + currentDiffRcid + '"]').removeClass('mw-rtrc-item-skipped'); // Remove from array, to no longer re-add class after refresh skippedRCIDs.splice(skippedRCIDs.indexOf(currentDiffRcid), 1); }); // Show helpicons $('#mw-rtrc-toggleHelp').click(function (e) { e.preventDefault(); $('#krRTRC_RCOptions').toggleClass('mw-rtrc-nohelp mw-rtrc-help'); }); // Link helpicons $('.mw-rtrc-settings .helpicon') .attr('title', msg('helpicon-tooltip')) .click(function (e) { e.preventDefault(); window.open(docUrl + '#' + $(this).attr('section'), '_blank'); }); // Clear rcuser-field // If MassPatrol is active, warn that clearing rcuser will automatically disable MassPatrol f $('#mw-rtrc-settings-user-clr').click(function () { $('#mw-rtrc-settings-user').val(''); }); // Mark as patrolled when rollbacking // Note: As of MediaWiki r(unknown) rollbacking does already automatically patrol all reverted revisions. // But by doing it anyway it saves a click for the AutoDiff-users $('.mw-rollback-link a').live('click', function () { $('.patrollink a').click(); }); // Button: Pause $('#rc-options-pause').click(function () { if (this.checked) { clearTimeout(updateFeedTimeout); return; } updateFeedNow(); }); } function showUnsupported() { $('#content').empty().append( $('<p>').addClass('errorbox').text( 'This program requires functionality not supported in this browser.' ) ); } function showFail() { $('#content').empty().append( $('<p>').addClass('errorbox').text('An unexpected error occurred.') ); } /** * Init functions * ------------------------------------------------- */ /** * Fetches all external data we need. * * This runs in parallel with loading of modules and i18n. * * @return {jQuery.Promise} */ function initData() { var dRights = $.Deferred(), promises = [ dRights.promise() ]; // Get userrights mw.loader.using('mediawiki.user', function () { mw.user.getRights(function (rights) { if ($.inArray('patrol', rights) !== -1) { userHasPatrolRight = true; } dRights.resolve(); }); }); // Get a patroltoken promises.push($.ajax({ url: apiUrl, dataType: 'json', data: { format: 'json', action: 'query', list: 'recentchanges', rctoken: 'patrol', rclimit: 1, // Using rctype=new because some wikis only have patrolling of newpages enabled. // If querying all changes returns an edit in that case, it won't have a token on it. // This workaround works as long as there are no wikis with RC-patrol but no NP-patrol. rctype: 'new' } }).done(function (data) { userPatrolTokenCache = data.query.recentchanges[0].patroltoken; })); // Get MediaWiki interface messages promises.push($.ajax({ url: apiUrl, dataType: 'json', data: { action: 'query', format: 'json', meta: 'allmessages', amlang: conf.wgUserLanguage, ammessages: ([ 'ascending abbrev', 'blanknamespace', 'contributions', 'descending abbrev', 'diff', 'hide', 'markaspatrolleddiff', 'markedaspatrolled', 'markedaspatrollederror', 'namespaces', 'namespacesall', 'next', 'recentchanges-label-bot', 'recentchanges-label-minor', 'recentchanges-label-newpage', 'recentchanges-label-unpatrolled', 'show', 'talkpagelinktext' ].join('|')) } }).done(function (data) { data = data.query.allmessages; for (var i = 0; i < data.length; i ++) { mw.messages.set(data[i].name, data[i]['*']); } })); promises.push($.ajax({ url: apiUrl, dataType: 'json', data: { format: 'json', action: 'query', list: 'tags', tgprop: 'displayname' } }).done(function (data) { var tags = data.query && data.query.tags; if (tags) { rcTags = $.map(tags, function (tag) { return tag.name; }); } })); promises.push($.ajax({ url: apiUrl, dataType: 'json', data: { format: 'json', action: 'query', meta: 'siteinfo' } }).done(function (data) { wikiTimeOffset = (data.query && data.query.general.timeoffset) || 0; })); return $.when.apply(null, promises); } /** * @return {jQuery.Promise} */ function init() { var dModules, dI18N, featureTest; // Transform title and navigation tabs document.title = 'RTRC: ' + conf.wgDBname; $(function () { $('#p-namespaces ul') .find('li.selected') .removeClass('new') .find('a') .text('RTRC'); }); featureTest = !!( // For timeUtil Date.UTC && // For CSS :before and :before $.support.modernizr4rtrc.generatedcontent ); if (!featureTest) { $(showUnsupported); return; } // These selectors from vector-hd conflict with mw-rtrc-available $('.vector-animateLayout').removeClass('vector-animateLayout'); $('html').addClass('mw-rtrc-available'); if (navSupported) { // Apply stored setting navCollapsed = localStorage.getItem('mw-rtrc-navtoggle-collapsed') || 'true'; if (navCollapsed === 'true') { $('html').toggleClass('mw-rtrc-navtoggle-collapsed'); } } dModules = $.Deferred(); mw.loader.using( [ 'jquery.json', 'mediawiki.action.history.diff', 'mediawiki.jqueryMsg', 'mediawiki.Uri', 'mediawiki.user', 'mediawiki.util' ], dModules.resolve, dModules.reject ); if (!mw.libs.getIntuition) { mw.libs.getIntuition = $.ajax({ url: intuitionLoadUrl, dataType: 'script', cache: true }); } dI18N = mw.libs.getIntuition .then(function () { return mw.libs.intuition.load('rtrc'); }) .done(function () { message = $.proxy(mw.libs.intuition.message, null, 'rtrc'); msg = $.proxy(mw.libs.intuition.msg, null, 'rtrc'); }); $.when(initData(), dModules, dI18N, $.ready).fail(showFail).done(function () { // Set up DOM for navtoggle if (navSupported) { // Needs i18n and $.ready $('body').append( $('#p-logo') .clone() .removeAttr('id') .addClass('mw-rtrc-navtoggle-logo'), $('<div>') .addClass('mw-rtrc-navtoggle') .attr('title', msg('navtoggle-tooltip')) .on('click', navToggle) ); } // Map over months monthNames = msg('months').split(','); buildInterface(); readPermalink(); bindInterface(); }); } /** * Execution * ------------------------------------------------- */ // On every page $(function () { if (!$('#t-rtrc').length) { mw.util.addPortletLink( 'p-tb', mw.util.getUrl('Special:BlankPage/RTRC'), 'RTRC', 't-rtrc', 'Monitor and patrol recent changes in real-time', null, '#t-specialpages' ); } }); /** * Modernizr 2.6.2 (Custom Build) | MIT & BSD * Build: http://modernizr.com/download/#-generatedcontent-teststyles * * Customized further for inclusion in mw-gadget-rtrc: * - Remove unused utilities. * - Export to jQuery.support.modernizr4rtrc instead of window.Modernizr. */ (function () { var docElement = document.documentElement, mod = 'modernizr', smile = ':)'; function injectElementWithStyles(rule, callback, nodes, testnames) { var style, ret, node, docOverflow, div = document.createElement('div'), body = document.body, fakeBody = body || document.createElement('body'); if (parseInt(nodes, 10)) { while (nodes--) { node = document.createElement('div'); node.id = testnames ? testnames[nodes] : mod + (nodes + 1); div.appendChild(node); } } style = ['&#173;', '<style id="s', mod, '">', rule, '</style>'].join(''); div.id = mod; (body ? div : fakeBody).innerHTML += style; fakeBody.appendChild(div); if (!body) { fakeBody.style.background = ''; fakeBody.style.overflow = 'hidden'; docOverflow = docElement.style.overflow; docElement.style.overflow = 'hidden'; docElement.appendChild(fakeBody); } ret = callback(div, rule); if (!body) { fakeBody.parentNode.removeChild(fakeBody); docElement.style.overflow = docOverflow; } else { div.parentNode.removeChild(div); } return !!ret; } $.support.modernizr4rtrc = { generatedcontent: (function () { return injectElementWithStyles(['#', mod, '{font:0/0 a}#', mod, ':after{content:"', smile, '";visibility:hidden;font:3px/1 a}'].join(''), function (node) { return node.offsetHeight >= 3; }); }()) }; })(); // Initialise if in the right context if ( (conf.wgTitle === 'Krinkle/RTRC' && conf.wgAction === 'view') || (conf.wgCanonicalSpecialPageName === 'Blankpage' && conf.wgTitle.split('/', 2)[1] === 'RTRC') ) { init(); } }(jQuery, mediaWiki));
src/rtrc.js
/** * Real-Time Recent Changes * https://github.com/Krinkle/mw-gadget-rtrc * * @license http://krinkle.mit-license.org/ * @author Timo Tijhof, 2010–2013 */ /*global alert */ (function ($, mw) { 'use strict'; /** * Configuration * ------------------------------------------------- */ var appVersion = 'v0.9.8', apiUrl = mw.util.wikiScript('api'), conf = mw.config.get([ 'skin', 'wgAction', 'wgCanonicalSpecialPageName', 'wgPageName', 'wgServer', 'wgTitle', 'wgUserLanguage', 'wgDBname' ]), cvnApiUrl = '//cvn.wmflabs.org/api.php', intuitionLoadUrl = '//tools.wmflabs.org/intuition/load.php?env=mw', docUrl = '//meta.wikimedia.org/wiki/User:Krinkle/Tools/Real-Time_Recent_Changes?uselang=' + conf.wgUserLanguage, // 32x32px ajaxLoaderUrl = '//upload.wikimedia.org/wikipedia/commons/d/de/Ajax-loader.gif', patrolCacheSize = 20, /** * Info from the wiki * ------------------------------------------------- */ userHasPatrolRight = false, userPatrolTokenCache = false, rcTags = [], wikiTimeOffset, /** * State * ------------------------------------------------- */ updateFeedTimeout, rcPrevDayHeading, skippedRCIDs = [], patrolledRCIDs = [], monthNames, prevFeedHtml, isUpdating = false, /** * Feed options * ------------------------------------------------- */ defOpt = { rc: { // Timestamp start: undefined, // Timestamp end: undefined, // Direction "older" (descending) or "newer" (ascending) dir: 'older', // Array of namespace ids namespace: undefined, // User name user: undefined, // Tag ID tag: undefined, // Show filters: exclude, include, filter showAnonOnly: false, showUnpatrolledOnly: false, limit: 25, // Type filters are "show matches only" typeEdit: false, typeNew: false }, app: { refresh: 3, cvnDB: false, massPatrol: false, autoDiff: false } }, opt = $(true, {}, defOpt), timeUtil, message, msg, navCollapsed, navSupported = conf.skin === 'vector' && !!window.localStorage, nextFrame = window.requestAnimationFrame || setTimeout, currentDiff, currentDiffRcid, $wrapper, $body, $feed, $RCOptions_submit; /** * Utility functions * ------------------------------------------------- */ if (!String.prototype.ucFirst) { String.prototype.ucFirst = function () { // http://jsperf.com/ucfirst/4 // http://jsperf.com/ucfirst-replace-vs-substr/3 // str.charAt(0).toUpperCase() + str.substr(1); // str[0].toUpperCase() + str.slice(1); // str.charAt(0).toUpperCase() + str.substring(1); // str.substr(0, 1).toUpperCase() + str.substr(1, this.length); return this.charAt(0).toUpperCase() + this.substring(1); }; } // Prepends a leading zero if value is under 10 function leadingZero(i) { if (i < 10) { i = '0' + i; } return i; } timeUtil = { // Create new Date instance from MediaWiki API timestamp string newDateFromApi: function (s) { // Possible number/integer to string var t = Date.UTC( // "2010-04-25T23:24:02Z" => 2010, 3, 25, 23, 24, 2 parseInt(s.slice(0, 4), 10), // Year parseInt(s.slice(5, 7), 10) - 1, // Month parseInt(s.slice(8, 10), 10), // Day parseInt(s.slice(11, 13), 10), // Hour parseInt(s.slice(14, 16), 10), // Minutes parseInt(s.slice(17, 19), 10) // Seconds ); return new Date(t); }, /** * Apply user offset. * * Only use this if you're extracting individual values * from the object (e.g. getUTCDay or getUTCMinutes). * The full timestamp will incorrectly claim "GMT". */ applyUserOffset: function (d) { var offset = mw.user.options.get('timecorrection'); // This preference has no default value, it is null for users that don't // override the site's default timeoffset. if (offset) { offset = Number(offset.split('|')[1]); } else { offset = wikiTimeOffset; } // There is no way to set a timezone in javascript, so we instead pretend the real unix // time is different and then get the values from that. d.setTime(d.getTime() + (offset * 60 * 1000)); return d; }, // Get clocktime string adjusted to timezone of wiki // from MediaWiki timestamp string getClocktimeFromApi: function (s) { var d = timeUtil.applyUserOffset(timeUtil.newDateFromApi(s)); // Return clocktime with leading zeros return leadingZero(d.getUTCHours()) + ':' + leadingZero(d.getUTCMinutes()); } }; /** * Main functions * ------------------------------------------------- */ function buildRcDayHead(time) { var current = time.getDate(); if (current === rcPrevDayHeading) { return ''; } rcPrevDayHeading = current; return '<div class="mw-rtrc-heading"><div><strong>' + time.getDate() + ' ' + monthNames[time.getMonth()] + '</strong></div></div>'; } /** * @param {Object} rc Recent change object from API * @return {string} HTML */ function buildRcItem(rc) { var diffsize, isPatrolled, isAnon, typeSymbol, itemClass, diffLink, commentHtml, el, item; // Get size difference (can be negative, zero or positive) diffsize = rc.newlen - rc.oldlen; // Convert undefined/empty-string values from API into booleans isPatrolled = rc.patrolled !== undefined; isAnon = rc.anon !== undefined; // typeSymbol, diffLink & itemClass typeSymbol = '&nbsp;'; itemClass = ''; if (rc.type === 'new') { typeSymbol += '<span class="newpage">N</span>'; } if ((rc.type === 'edit' || rc.type === 'new') && userHasPatrolRight && !isPatrolled) { typeSymbol += '<span class="unpatrolled">!</span>'; } commentHtml = rc.parsedcomment; // Check if edit summary is an AES if (commentHtml.indexOf('<a href="/wiki/Commons:AES" class="mw-redirect" title="Commons:AES">\u2190</a>') === 0) { // TODO: This is specific to commons.wikimedia.org itemClass += ' mw-rtrc-item-aes'; } // Anon-attribute if (isAnon) { itemClass = ' mw-rtrc-item-anon'; } else { itemClass = ' mw-rtrc-item-liu'; } /* Example: <div class="mw-rtrc-item mw-rtrc-item-patrolled" data-diff="0" data-rcid="0" user="Abc"> <div diff>(<a class="diff" href="//">diff</a>)</div> <div type><span class="unpatrolled">!</span></div> <div timetitle>00:00 <a href="//?rcid=0" target="_blank">Abc</a></div> <div user><a class="user" href="//User:Abc">Abc</a></div> <div other><a href="//User talk:Abc">talk</a> / <a href="//Special:Contributions/Abc">contribs</a>&nbsp;<span class="comment">Abc</span></div> <div size><span class="mw-plusminus-null">(0)</span></div> </div> */ // build & return item item = buildRcDayHead(timeUtil.newDateFromApi(rc.timestamp)); item += '<div class="mw-rtrc-item ' + itemClass + '" data-diff="' + rc.revid + '" data-rcid="' + rc.rcid + '" user="' + rc.user + '">'; if (rc.type === 'edit') { diffLink = '<a class="rcitemlink diff" href="' + mw.util.wikiScript() + '?diff=' + rc.revid + '&oldif=' + rc.old_revid + '&rcid=' + rc.rcid + '">' + mw.message('diff').escaped() + '</a>'; } else if (rc.type === 'new') { diffLink = '<a class="rcitemlink newPage">new</a>'; } else { diffLink = mw.message('diff').escaped(); } item += '<div first>(' + diffLink + ') ' + typeSymbol + ' '; item += timeUtil.getClocktimeFromApi(rc.timestamp) + ' <a class="page" href="' + mw.util.getUrl(rc.title) + '?rcid=' + rc.rcid + '" target="_blank">' + rc.title + '</a></div>'; item += '<div user>&nbsp;<small>&middot;&nbsp;<a href="' + mw.util.getUrl('User talk:' + rc.user) + '" target="_blank">T</a> &middot; <a href="' + mw.util.getUrl('Special:Contributions/' + rc.user) + '" target="_blank">C</a>&nbsp;</small>&middot;&nbsp;<a class="user" href="' + mw.util.getUrl((mw.util.isIPv4Address(rc.user) || mw.util.isIPv6Address(rc.user) ? 'Special:Contributions/' : 'User:') + rc.user) + '" target="_blank">' + rc.user + '</a></div>'; item += '<div other>&nbsp;<span class="comment">' + commentHtml + '</span></div>'; if (diffsize > 0) { el = diffsize > 399 ? 'strong' : 'span'; item += '<div size><' + el + ' class="mw-plusminus-pos">(' + diffsize + ')</' + el + '></div>'; } else if (diffsize === 0) { item += '<div size><span class="mw-plusminus-null">(0)</span></div>'; } else { el = diffsize < -399 ? 'strong' : 'span'; item += '<div size><' + el + ' class="mw-plusminus-neg">(' + diffsize + ')</' + el + '></div>'; } item += '</div>'; return item; } /** * @param {Object} newOpt * @param {string} [mode=normal] One of 'quiet' or 'normal' * @return {boolean} True if no changes were made, false otherwise */ function normaliseSettings(newOpt, mode) { var mod = false; // MassPatrol requires a filter to be active if (newOpt.app.massPatrol && !newOpt.rc.user) { newOpt.app.massPatrol = false; mod = true; if (mode !== 'quiet') { alert(msg('masspatrol-requires-userfilter')); } } // MassPatrol requires AutoDiff if (newOpt.app.massPatrol && !newOpt.app.autoDiff) { newOpt.app.autoDiff = true; mod = true; } return !mod; } function readSettingsForm() { // jQuery#serializeArray is nice, but doesn't include "value: false" for unchecked // checkboxes that are not disabled. Using raw .elements instead and filtering // out <fieldset>. var $settings = $($wrapper.find('.mw-rtrc-settings')[0].elements).filter(':input'); opt = $.extend(true, {}, defOpt); $settings.each(function (i, el) { var name = el.name; switch (name) { // RC case 'limit': opt.rc[name] = Number(el.value); break; case 'namespace': // Can be "0". // Value "" (all) is represented by undefined. // TODO: Turn this into a multi-select, the API supports it. opt.rc[name] = el.value.length ? Number(el.value) : undefined; break; case 'user': case 'start': case 'end': case 'tag': opt.rc[name] = el.value || undefined; break; case 'showAnonOnly': case 'showUnpatrolledOnly': case 'typeEdit': case 'typeNew': opt.rc[name] = el.checked; break; case 'dir': // There's more than 1 radio button with this name in this loop, // use the value of the first (and only) checked one. if (el.checked) { opt.rc[name] = el.value; } break; // APP case 'cvnDB': case 'massPatrol': case 'autoDiff': opt.app[name] = el.checked; break; case 'refresh': opt.app[name] = Number(el.value); break; } }); if (!normaliseSettings(opt)) { // TODO: Optimise this, no need to repopulate the entire settings form // if only 1 thing changed. fillSettingsForm(opt); } } function fillSettingsForm(newOpt) { var $settings = $($wrapper.find('.mw-rtrc-settings')[0].elements).filter(':input'); if (newOpt.rc) { $.each(newOpt.rc, function (key, value) { var $setting = $settings.filter(function () { return this.name === key; }), setting = $setting[0]; if (!setting) { return; } switch (key) { case 'limit': setting.value = value; break; case 'namespace': if (value === undefined) { // Value "" (all) is represented by undefined. $setting.find('option').eq(0).prop('selected', true); } else { $setting.val(value); } break; case 'user': case 'start': case 'end': case 'tag': setting.value = value || ''; break; case 'showAnonOnly': case 'showUnpatrolledOnly': case 'typeEdit': case 'typeNew': setting.checked = value; break; case 'dir': if (setting.value === value) { setting.checked = true; } break; } }); } if (newOpt.app) { $.each(newOpt.app, function (key, value) { var $setting = $settings.filter(function () { return this.name === key; }), setting = $setting[0]; if (!setting) { setting = document.getElementById('rc-options-' + key); $setting = $(setting); } if (!setting) { return; } switch (key) { case 'cvnDB': case 'massPatrol': case 'autoDiff': setting.checked = value; break; case 'refresh': setting.value = value; break; } }); } } function getPermalink() { var uri = new mw.Uri(mw.util.getUrl(conf.wgPageName)), reducedOpt = {}; $.each(opt.rc, function (key, value) { if (defOpt.rc[key] !== value) { if (!reducedOpt.rc) { reducedOpt.rc = {}; } reducedOpt.rc[key] = value; } }); $.each(opt.app, function (key, value) { if (defOpt.app[key] !== value) { if (!reducedOpt.app) { reducedOpt.app = {}; } reducedOpt.app[key] = value; } }); reducedOpt = $.toJSON(reducedOpt); uri.extend({ opt: reducedOpt === '{}' ? undefined : reducedOpt, kickstart: 1 }); return uri.toString(); } // Read permalink into the program and reflect into settings form. // TODO: Refactor into init, as this does more than read permalink. // It also inits the settings form and handles kickstart function readPermalink() { var url = new mw.Uri(), newOpt = url.query.opt, kickstart = url.query.kickstart; newOpt = newOpt ? $.parseJSON(newOpt): {}; newOpt = $.extend(true, {}, defOpt, newOpt); normaliseSettings(newOpt, 'quiet'); fillSettingsForm(newOpt); opt = newOpt; if (kickstart === '1') { updateFeedNow(); if ($wrapper[0].scrollIntoView) { $wrapper[0].scrollIntoView(); } } } function getApiRcParams(rc) { var rcprop = [ 'flags', 'timestamp', 'user', 'title', 'parsedcomment', 'sizes', 'ids' ], rcshow = ['!bot'], rctype = [], params = {}; params.rcdir = rc.dir; if (rc.dir === 'older') { if (rc.end !== undefined) { params.rcstart = rc.end; } if (rc.start !== undefined) { params.rcend = rc.start; } } else if (rc.dir === 'newer') { if (rc.start !== undefined) { params.rcstart = rc.start; } if (rc.end !== undefined) { params.rcend = rc.end; } } if (rc.namespace !== undefined) { params.rcnamespace = rc.namespace; } if (rc.user !== undefined) { params.rcuser = rc.user; } // params.titles: Title filter option (rctitles) is no longer supported by MediaWiki, // see https://bugzilla.wikimedia.org/show_bug.cgi?id=12394#c5. if (rc.tag !== undefined) { params.rctag = rc.tag; } if (userHasPatrolRight) { rcprop.push('patrolled'); } params.rcprop = rcprop.join('|'); if (rc.showAnonOnly) { rcshow.push('anon'); } if (rc.showUnpatrolledOnly) { rcshow.push('!patrolled'); } params.rcshow = rcshow.join('|'); params.rclimit = rc.limit; if (rc.typeEdit) { rctype.push('edit'); } if (rc.typeNew) { rctype.push('new'); } params.rctype = rctype.length ? rctype.join('|') : 'edit|new'; return params; } // Called when the feed is regenerated before being inserted in the document function applyRtrcAnnotations($feedContent) { // Re-apply item classes $feedContent.filter('.mw-rtrc-item').each(function () { var $el = $(this), rcid = Number($el.data('rcid')); // Mark skipped and patrolled items as such if ($.inArray(rcid, skippedRCIDs) !== -1) { $el.addClass('mw-rtrc-item-skipped'); } else if ($.inArray(rcid, patrolledRCIDs) !== -1) { $el.addClass('mw-rtrc-item-patrolled'); } else if (rcid === currentDiffRcid) { $el.addClass('mw-rtrc-item-current'); } }); } /** * @param {Object} update * @param {jQuery} update.$feedContent * @param {string} update.rawHtml */ function pushFeedContent(update) { // TODO: Only do once $body.removeClass('placeholder'); $feed.find('.mw-rtrc-feed-update').html( message('lastupdate-rc', new Date().toLocaleString()).escaped() + ' | <a href="' + getPermalink() + '">' + message('permalink').escaped() + '</a>' ); if (update.rawHtml !== prevFeedHtml) { prevFeedHtml = update.rawHtml; applyRtrcAnnotations(update.$feedContent); $feed.find('.mw-rtrc-feed-content').empty().append(update.$feedContent); } // Schedule next update updateFeedTimeout = setTimeout(updateFeed, opt.app.refresh * 1000); $('#krRTRC_loader').hide(); } function applyCvnAnnotations($feedContent, callback) { var users; // Find all user names inside the feed users = []; $feedContent.filter('.mw-rtrc-item').each(function () { var user = $(this).attr('user'); if (user) { users.push(user); } }); if (!users.length) { callback(); return; } $.ajax({ url: cvnApiUrl, data: { users: users.join('|'), }, dataType: 'jsonp' }) .fail(function () { callback(); }) .done(function (data) { var d; if (!data.users) { callback(); return; } // Loop through all users $.each(data.users, function (name, user) { var tooltip; // Only if blacklisted, otherwise dont highlight if (user.type === 'blacklist') { tooltip = ''; if (user.comment) { tooltip += msg('cvn-reason') + ': ' + user.comment + '. '; } else { tooltip += msg('cvn-reason') + ': ' + msg('cvn-reason-empty'); } if (user.adder) { tooltip += msg('cvn-adder') + ': ' + user.adder; } else { tooltip += msg('cvn-adder') + ': ' + msg('cvn-adder-empty'); } // Apply blacklisted-class, and insert icon with tooltip $feedContent .filter('.mw-rtrc-item') .filter(function () { return $(this).attr('user') === name; }) .find('.user') .addClass('blacklisted') .attr('title', tooltip); } }); // Either way, push the feed to the frontend callback(); d = new Date(); d.setTime(data.lastUpdate * 1000); $feed.find('.mw-rtrc-feed-cvninfo').text('CVN DB ' + msg('lastupdate-cvn', d.toUTCString())); }); } function updateFeedNow() { $('#rc-options-pause').prop('checked', false); clearTimeout(updateFeedTimeout); updateFeed(); } function updateFeed() { var rcparams; if (!isUpdating) { // Indicate updating $('#krRTRC_loader').show(); isUpdating = true; // Download recent changes rcparams = getApiRcParams(opt.rc); rcparams.format = 'json'; rcparams.action = 'query'; rcparams.list = 'recentchanges'; $.ajax({ url: apiUrl, dataType: 'json', data: rcparams }).fail(function () { var feedContentHTML = '<h3>Downloading recent changes failed</h3>'; pushFeedContent({ $feedContent: $(feedContentHTML), rawHtml: feedContentHTML }); isUpdating = false; $RCOptions_submit.prop('disabled', false).css('opacity', '1.0'); }).done(function (data) { var recentchanges, $feedContent, feedContentHTML = ''; if (data.error) { $body.removeClass('placeholder'); // Account doesn't have patrol flag if (data.error.code === 'rcpermissiondenied') { feedContentHTML += '<h3>Downloading recent changes failed</h3><p>Please untick the "Unpatrolled only"-checkbox or request the Patroller-right.</a>'; // Other error } else { feedContentHTML += '<h3>Downloading recent changes failed</h3><p>Please check the settings above and try again. If you believe this is a bug, please <a href="//meta.wikimedia.org/w/index.php?title=User_talk:Krinkle/Tools&action=edit&section=new&preload=User_talk:Krinkle/Tools/Preload" target="_blank"><strong>let me know</strong></a>.'; } } else { recentchanges = data.query.recentchanges; if (recentchanges.length) { $.each(recentchanges, function (i, rc) { feedContentHTML += buildRcItem(rc); }); } else { // Everything is OK - no results feedContentHTML += '<strong><em>' + message('nomatches').escaped() + '</em></strong>'; } // Reset day rcPrevDayHeading = undefined; } $feedContent = $($.parseHTML(feedContentHTML)); if (opt.app.cvnDB) { applyCvnAnnotations($feedContent, function () { pushFeedContent({ $feedContent: $feedContent, rawHtml: feedContentHTML }); isUpdating = false; }); } else { pushFeedContent({ $feedContent: $feedContent, rawHtml: feedContentHTML }); isUpdating = false; } $RCOptions_submit.prop('disabled', false).css('opacity', '1.0'); }); } } function krRTRC_NextDiff() { var $lis = $feed.find('.mw-rtrc-item:not(.mw-rtrc-item-current, .mw-rtrc-item-patrolled, .mw-rtrc-item-skipped)'); $lis.eq(0).find('a.rcitemlink').click(); } function krRTRC_ToggleMassPatrol(b) { if (b === true) { if (!currentDiff) { krRTRC_NextDiff(); } else { $('.patrollink a').click(); } } } function navToggle() { navCollapsed = String(navCollapsed !== 'true'); $('html').toggleClass('mw-rtrc-navtoggle-collapsed'); localStorage.setItem('mw-rtrc-navtoggle-collapsed', navCollapsed); } // Build the main interface function buildInterface() { var namespaceOptionsHtml, tagOptionsHtml, key, fmNs = mw.config.get('wgFormattedNamespaces'); namespaceOptionsHtml = '<option value>' + mw.message('namespacesall').escaped() + '</option>'; namespaceOptionsHtml += '<option value="0">' + mw.message('blanknamespace').escaped() + '</option>'; for (key in fmNs) { if (key > 0) { namespaceOptionsHtml += '<option value="' + key + '">' + fmNs[key] + '</option>'; } } tagOptionsHtml = '<option value selected>' + message('select-placeholder-none').escaped() + '</option>'; for (key = 0; key < rcTags.length; key++) { tagOptionsHtml += '<option value="' + mw.html.escape(rcTags[key]) + '">' + mw.html.escape(rcTags[key]) + '</option>'; } $wrapper = $($.parseHTML( '<div class="mw-rtrc-wrapper">' + '<div class="mw-rtrc-head">' + 'Real-Time Recent Changes <small>(' + appVersion + ')</small>' + '<div class="mw-rtrc-head-links">' + (!mw.user.isAnon() ? ( '<a target="_blank" href="' + mw.util.getUrl('Special:Log/patrol') + '?user=' + encodeURIComponent(mw.user.name()) + '">' + message('mypatrollog').escaped().ucFirst() + '</a>') : '' ) + '<a id="mw-rtrc-toggleHelp">Help</a>' + '</div>' + '</div>' + '<form id="krRTRC_RCOptions" class="mw-rtrc-settings mw-rtrc-nohelp make-switch"><fieldset>' + '<div class="panel-group">' + '<div class="panel">' + '<label for="mw-rtrc-settings-limit" class="head">' + message('limit').escaped() + '</label>' + '<select id="mw-rtrc-settings-limit" name="limit">' + '<option value="10">10</option>' + '<option value="25" selected>25</option>' + '<option value="50">50</option>' + '<option value="75">75</option>' + '<option value="100">100</option>' + '</select>' + '</div>' + '<div class="panel">' + '<label class="head">' + message('filter').escaped() + '</label>' + '<div style="text-align: left;">' + '<label>' + '<input type="checkbox" name="showAnonOnly" />' + ' ' + message('showAnonOnly').escaped() + '</label>' + '<br />' + '<label>' + '<input type="checkbox" name="showUnpatrolledOnly" />' + ' ' + message('showUnpatrolledOnly').escaped() + '</label>' + '</div>' + '</div>' + '<div class="panel">' + '<label for="mw-rtrc-settings-user" class="head">' + message('userfilter').escaped() + '<span section="Userfilter" class="helpicon"></span>' + '</label>' + '<div style="text-align: center;">' + '<input type="text" size="16" id="mw-rtrc-settings-user" name="user" />' + '<br />' + '<input class="button button-small" type="button" id="mw-rtrc-settings-user-clr" value="' + message('clear').escaped() + '" />' + '</div>' + '</div>' + '<div class="panel">' + '<label class="head">' + message('type').escaped() + '</label>' + '<div style="text-align: left;">' + '<label>' + '<input type="checkbox" name="typeEdit" checked />' + ' ' + message('typeEdit').escaped() + '</label>' + '<br />' + '<label>' + '<input type="checkbox" name="typeNew" checked />' + ' ' + message('typeNew').escaped() + '</label>' + '</div>' + '</div>' + '<div class="panel">' + '<label class="head">' + message('timeframe').escaped() + '<span section="Timeframe" class="helpicon"></span>' + '</label>' + '<div style="text-align: right;">' + '<label>' + message('time-from').escaped() + ': ' + '<input type="text" size="18" name="start" />' + '</label>' + '<br />' + '<label>' + message('time-untill').escaped() + ': ' + '<input type="text" size="18" name="end" />' + '</label>' + '</div>' + '</div>' + '<div class="panel">' + '<label class="head">' + mw.message('namespaces').escaped() + ' <br />' + '<select class="mw-rtrc-setting-select" name="namespace">' + namespaceOptionsHtml + '</select>' + '</label>' + '</div>' + '<div class="panel">' + '<label class="head">' + message('order').escaped() + ' <br />' + '<span section="Order" class="helpicon"></span>' + '</label>' + '<div style="text-align: left;">' + '<label>' + '<input type="radio" name="dir" value="newer" />' + ' ' + message('asc').escaped() + '</label>' + '<br />' + '<label>' + '<input type="radio" name="dir" value="older" checked />' + ' ' + message('desc').escaped() + '</label>' + '</div>' + '</div>' + '<div class="panel">' + '<label for="mw-rtrc-settings-refresh" class="head">' + 'R<br />' + '<span section="Reload_Interval" class="helpicon"></span>' + '</label>' + '<input type="number" value="3" min="0" max="99" size="2" id="mw-rtrc-settings-refresh" name="refresh" />' + '</div>' + '<div class="panel">' + '<label class="head">' + 'CVN DB<br />' + '<span section="IRC_Blacklist" class="helpicon"></span>' + '<input type="checkbox" class="switch" name="cvnDB" />' + '</label>' + '</div>' + '<div class="panel panel-last">' + '<input class="button" type="button" id="RCOptions_submit" value="' + message('apply').escaped() + '" />' + '</div>' + '</div>' + '<div class="panel-group panel-group-mini">' + '<div class="panel">' + '<label class="head">' + message('tag').escaped() + ' <select class="mw-rtrc-setting-select" name="tag">' + tagOptionsHtml + '</select>' + '</label>' + '</div>' + '<div class="panel">' + '<label class="head">' + 'MassPatrol' + '<span section="MassPatrol" class="helpicon"></span>' + '<input type="checkbox" class="switch" name="massPatrol" />' + '</label>' + '</div>' + '<div class="panel">' + '<label class="head">' + 'AutoDiff' + '<span section="AutoDiff" class="helpicon"></span>' + '<input type="checkbox" class="switch" name="autoDiff" />' + '</label>' + '</div>' + '<div class="panel">' + '<label class="head">' + 'Pause' + '<input class="switch" type="checkbox" id="rc-options-pause" />' + '</label>' + '</div>' + '</div>' + '</fieldset></form>' + '<a name="krRTRC_DiffTop" />' + '<div class="mw-rtrc-diff" id="krRTRC_DiffFrame" style="display: none;"></div>' + '<div class="mw-rtrc-body placeholder">' + '<div class="mw-rtrc-feed">' + '<div class="mw-rtrc-feed-update"></div>' + '<div class="mw-rtrc-feed-content"></div>' + '<small class="mw-rtrc-feed-cvninfo"></small>' + '</div>' + '<img src="' + ajaxLoaderUrl + '" id="krRTRC_loader" style="display: none;" />' + '<div class="mw-rtrc-legend">' + 'Colors: <div class="mw-rtrc-item mw-rtrc-item-patrolled inline-block">&nbsp;' + mw.message('markedaspatrolled').escaped() + '&nbsp;</div>, <div class="mw-rtrc-item mw-rtrc-item-current inline-block">&nbsp;' + message('currentedit').escaped() + '&nbsp;</div>, ' + '<div class="mw-rtrc-item mw-rtrc-item-skipped inline-block">&nbsp;' + message('skippededit').escaped() + '&nbsp;</div>, ' + '<div class="mw-rtrc-item mw-rtrc-item-aes inline-block">&nbsp;Edit with an Automatic Edit Summary&nbsp;</div>' + '<br />Abbreviations: T - ' + mw.message('talkpagelinktext').escaped() + ', C - ' + mw.message('contributions', mw.user).escaped() + '</div>' + '</div>' + '<div style="clear: both;"></div>' + '<div class="mw-rtrc-foot">' + '<div class="plainlinks" style="text-align: right;">' + 'Real-Time Recent Changes by ' + '<a href="//meta.wikimedia.org/wiki/User:Krinkle" class="external text" rel="nofollow">Krinkle</a>' + ' | <a href="//meta.wikimedia.org/wiki/User:Krinkle/Tools/Real-Time_Recent_Changes" class="external text" rel="nofollow">' + message('documentation').escaped() + '</a>' + ' | <a href="https://github.com/Krinkle/mw-gadget-rtrc/releases" class="external text" rel="nofollow">' + message('changelog').escaped() + '</a>' + ' | <a href="https://github.com/Krinkle/mw-gadget-rtrc/issues" class="external text" rel="nofollow">Feedback</a>' + ' | <a href="http://krinkle.mit-license.org" class="external text" rel="nofollow">License</a>' + '</div>' + '</div>' + '</div>' )); // Add helper element for switch checkboxes $wrapper.find('input.switch').after('<div class="switched"></div>'); // All links within the diffframe should open in a new window $wrapper.find('#krRTRC_DiffFrame').on('click', 'table.diff a', function () { var $el = $(this); if ($el.is('[href^="http://"], [href^="https://"], [href^="//"]')) { $el.attr('target', '_blank'); } }); $('#content').empty().append($wrapper); nextFrame(function () { $('html').addClass('mw-rtrc-ready'); }); $body = $wrapper.find('.mw-rtrc-body'); $feed = $body.find('.mw-rtrc-feed'); } // Bind event hanlders in the user interface function bindInterface() { $RCOptions_submit = $('#RCOptions_submit'); // Apply button $RCOptions_submit.click(function () { $RCOptions_submit.prop('disabled', true).css('opacity', '0.5'); readSettingsForm(); krRTRC_ToggleMassPatrol(opt.app.massPatrol); updateFeedNow(); return false; }); // Close Diff $('#diffClose').live('click', function () { $('#krRTRC_DiffFrame').fadeOut('fast'); currentDiff = currentDiffRcid = false; }); // Load diffview on (diff)-link click $('a.diff').live('click', function (e) { var $item = $(this).closest('.mw-rtrc-item').addClass('mw-rtrc-item-current'), title = $item.find('.page').text(), href = $(this).attr('href'), $frame = $('#krRTRC_DiffFrame'); $feed.find('.mw-rtrc-item-current').not($item).removeClass('mw-rtrc-item-current'); currentDiff = Number($item.data('diff')); currentDiffRcid = Number($item.data('rcid')); // Reset style="max-height: 400;" from a.newPage below $frame.fadeOut().removeAttr('style'); $.ajax({ url: mw.util.wikiScript(), dataType: 'html', data: { action: 'render', diff: currentDiff, diffonly: '1', uselang: conf.wgUserLanguage } }).fail(function (jqXhr) { $frame .stop(true, true) .append(jqXhr.responseText || 'Loading diff failed.') .fadeIn(); }).done(function (data) { var skipButtonHtml; if ($.inArray(currentDiffRcid, skippedRCIDs) !== -1) { skipButtonHtml = '<span class="tab"><a id="diffUnskip">Unskip</a></span>'; } else { skipButtonHtml = '<span class="tab"><a id="diffSkip">Skip</a></span>'; } $frame .stop(true, true) .html(data) .prepend( '<h3>' + mw.html.escape(title) + '</h3>' + '<div class="mw-rtrc-diff-tools">' + '<span class="tab"><a id="diffClose">X</a></span>' + '<span class="tab"><a href="' + href + '" target="_blank" id="diffNewWindow">Open in Wiki</a></span>' + (userPatrolTokenCache ? '<span class="tab"><a onclick="(function(){ if($(\'.patrollink a\').length){ $(\'.patrollink a\').click(); } else { $(\'#diffSkip\').click(); } })();">[mark]</a></span>' : '' ) + '<span class="tab"><a id="diffNext">' + mw.message('next').escaped().ucFirst() + ' &raquo;</a></span>' + skipButtonHtml + '</div>' ) .fadeIn(); if (opt.app.massPatrol) { $frame.find('.patrollink a').click(); } }); e.preventDefault(); }); $('a.newPage').live('click', function (e) { var $item = $(this).closest('.mw-rtrc-item').addClass('mw-rtrc-item-current'), title = $item.find('.page').text(), href = $item.find('.page').attr('href'), $frame = $('#krRTRC_DiffFrame'); $feed.find('.mw-rtrc-item-current').not($item).removeClass('mw-rtrc-item-current'); currentDiffRcid = Number($item.data('rcid')); $frame.fadeOut().css('max-height', '400px'); $.ajax({ url: href, dataType: 'html', data: { action: 'render', uselang: conf.wgUserLanguage } }).fail(function (jqXhr) { $frame .stop(true, true) .append(jqXhr.responseText || 'Loading diff failed.') .fadeIn(); }).done(function (data) { var skipButtonHtml; if ($.inArray(currentDiffRcid, skippedRCIDs) !== -1) { skipButtonHtml = '<span class="tab"><a id="diffUnskip">Unskip</a></span>'; } else { skipButtonHtml = '<span class="tab"><a id="diffSkip">Skip</a></span>'; } $frame .stop(true, true) .html(data) .prepend( '<h3>' + title + '</h3>' + '<div class="mw-rtrc-diff-tools">' + '<span class="tab"><a id="diffClose">X</a></span>' + '<span class="tab"><a href="' + href + '" target="_blank" id="diffNewWindow">Open in Wiki</a></span>' + '<span class="tab"><a onclick="$(\'.patrollink a\').click()">[mark]</a></span>' + '<span class="tab"><a id="diffNext">' + mw.message('next').escaped().ucFirst() + ' &raquo;</a></span>' + skipButtonHtml + '</div>' ) .fadeIn(); if (opt.app.massPatrol) { $frame.find('.patrollink a').click(); } }); e.preventDefault(); }); // Mark as patrolled $('.patrollink').live('click', function () { var $el = $(this); $el.find('a').text(mw.msg('markaspatrolleddiff') + '...'); $.ajax({ type: 'POST', url: apiUrl, dataType: 'json', data: { action: 'patrol', format: 'json', list: 'recentchanges', rcid: currentDiffRcid, token: userPatrolTokenCache } }).done(function (data) { if (!data || data.error) { $el.empty().append( $('<span style="color: red;"></span>').text(mw.msg('markedaspatrollederror')) ); mw.log('Patrol error:', data); } else { $el.empty().append( $('<span style="color: green;"></span>').text(mw.msg('markedaspatrolled')) ); $feed.find('.mw-rtrc-item[data-rcid="' + currentDiffRcid + '"]').addClass('mw-rtrc-item-patrolled'); // Patrolling/Refreshing sometimes overlap eachother causing patrolled edits to show up in an 'unpatrolled only' feed. // Make sure that any patrolled edits stay marked as such to prevent AutoDiff from picking a patrolled edit patrolledRCIDs.push(currentDiffRcid); while (patrolledRCIDs.length > patrolCacheSize) { patrolledRCIDs.shift(); } if (opt.app.autoDiff) { krRTRC_NextDiff(); } } }).fail(function () { $el.empty().append( $('<span style="color: red;"></span>').text(mw.msg('markedaspatrollederror')) ); }); return false; }); // Trigger NextDiff $('#diffNext').live('click', function () { krRTRC_NextDiff(); }); // SkipDiff $('#diffSkip').live('click', function () { $feed.find('.mw-rtrc-item[data-rcid="' + currentDiffRcid + '"]').addClass('mw-rtrc-item-skipped'); // Add to array, to re-add class after refresh skippedRCIDs.push(currentDiffRcid); krRTRC_NextDiff(); }); // UnskipDiff $('#diffUnskip').live('click', function () { $feed.find('.mw-rtrc-item[data-rcid="' + currentDiffRcid + '"]').removeClass('mw-rtrc-item-skipped'); // Remove from array, to no longer re-add class after refresh skippedRCIDs.splice(skippedRCIDs.indexOf(currentDiffRcid), 1); }); // Show helpicons $('#mw-rtrc-toggleHelp').click(function (e) { e.preventDefault(); $('#krRTRC_RCOptions').toggleClass('mw-rtrc-nohelp mw-rtrc-help'); }); // Link helpicons $('.mw-rtrc-settings .helpicon') .attr('title', msg('helpicon-tooltip')) .click(function (e) { e.preventDefault(); window.open(docUrl + '#' + $(this).attr('section'), '_blank'); }); // Clear rcuser-field // If MassPatrol is active, warn that clearing rcuser will automatically disable MassPatrol f $('#mw-rtrc-settings-user-clr').click(function () { $('#mw-rtrc-settings-user').val(''); }); // Mark as patrolled when rollbacking // Note: As of MediaWiki r(unknown) rollbacking does already automatically patrol all reverted revisions. // But by doing it anyway it saves a click for the AutoDiff-users $('.mw-rollback-link a').live('click', function () { $('.patrollink a').click(); }); // Button: Pause $('#rc-options-pause').click(function () { if (this.checked) { clearTimeout(updateFeedTimeout); return; } updateFeedNow(); }); } function showUnsupported() { $('#content').empty().append( $('<p>').addClass('errorbox').text( 'This program requires functionality not supported in this browser.' ) ); } function showFail() { $('#content').empty().append( $('<p>').addClass('errorbox').text('An unexpected error occurred.') ); } /** * Init functions * ------------------------------------------------- */ /** * Fetches all external data we need. * * This runs in parallel with loading of modules and i18n. * * @return {jQuery.Promise} */ function initData() { var dRights = $.Deferred(), promises = [ dRights.promise() ]; // Get userrights mw.loader.using('mediawiki.user', function () { mw.user.getRights(function (rights) { if ($.inArray('patrol', rights) !== -1) { userHasPatrolRight = true; } dRights.resolve(); }); }); // Get a patroltoken promises.push($.ajax({ url: apiUrl, dataType: 'json', data: { format: 'json', action: 'query', list: 'recentchanges', rctoken: 'patrol', rclimit: 1, // Using rctype=new because some wikis only have patrolling of newpages enabled. // If querying all changes returns an edit in that case, it won't have a token on it. // This workaround works as long as there are no wikis with RC-patrol but no NP-patrol. rctype: 'new' } }).done(function (data) { userPatrolTokenCache = data.query.recentchanges[0].patroltoken; })); // Get MediaWiki interface messages promises.push($.ajax({ url: apiUrl, dataType: 'json', data: { action: 'query', format: 'json', meta: 'allmessages', amlang: conf.wgUserLanguage, ammessages: ([ 'ascending abbrev', 'blanknamespace', 'contributions', 'descending abbrev', 'diff', 'hide', 'markaspatrolleddiff', 'markedaspatrolled', 'markedaspatrollederror', 'namespaces', 'namespacesall', 'next', 'recentchanges-label-bot', 'recentchanges-label-minor', 'recentchanges-label-newpage', 'recentchanges-label-unpatrolled', 'show', 'talkpagelinktext' ].join('|')) } }).done(function (data) { data = data.query.allmessages; for (var i = 0; i < data.length; i ++) { mw.messages.set(data[i].name, data[i]['*']); } })); promises.push($.ajax({ url: apiUrl, dataType: 'json', data: { format: 'json', action: 'query', list: 'tags', tgprop: 'displayname' } }).done(function (data) { var tags = data.query && data.query.tags; if (tags) { rcTags = $.map(tags, function (tag) { return tag.name; }); } })); promises.push($.ajax({ url: apiUrl, dataType: 'json', data: { format: 'json', action: 'query', meta: 'siteinfo' } }).done(function (data) { wikiTimeOffset = (data.query && data.query.general.timeoffset) || 0; })); return $.when.apply(null, promises); } /** * @return {jQuery.Promise} */ function init() { var dModules, dI18N, featureTest; // Transform title and navigation tabs document.title = 'RTRC: ' + conf.wgDBname; $(function () { $('#p-namespaces ul') .find('li.selected') .removeClass('new') .find('a') .text('RTRC'); }); featureTest = !!( // For timeUtil Date.UTC && // For CSS :before and :before $.support.modernizr4rtrc.generatedcontent ); if (!featureTest) { $(showUnsupported); return; } // These selectors from vector-hd conflict with mw-rtrc-available $('.vector-animateLayout').removeClass('vector-animateLayout'); $('html').addClass('mw-rtrc-available'); if (navSupported) { // Apply stored setting navCollapsed = localStorage.getItem('mw-rtrc-navtoggle-collapsed') || 'true'; if (navCollapsed === 'true') { $('html').toggleClass('mw-rtrc-navtoggle-collapsed'); } } dModules = $.Deferred(); mw.loader.using( [ 'jquery.json', 'mediawiki.action.history.diff', 'mediawiki.jqueryMsg', 'mediawiki.Uri', 'mediawiki.user', 'mediawiki.util' ], dModules.resolve, dModules.reject ); if (!mw.libs.getIntuition) { mw.libs.getIntuition = $.ajax({ url: intuitionLoadUrl, dataType: 'script', cache: true }); } dI18N = mw.libs.getIntuition .then(function () { return mw.libs.intuition.load('rtrc'); }) .done(function () { message = $.proxy(mw.libs.intuition.message, null, 'rtrc'); msg = $.proxy(mw.libs.intuition.msg, null, 'rtrc'); }); $.when(initData(), dModules, dI18N, $.ready).fail(showFail).done(function () { // Set up DOM for navtoggle if (navSupported) { // Needs i18n and $.ready $('body').append( $('#p-logo') .clone() .removeAttr('id') .addClass('mw-rtrc-navtoggle-logo'), $('<div>') .addClass('mw-rtrc-navtoggle') .attr('title', msg('navtoggle-tooltip')) .on('click', navToggle) ); } // Map over months monthNames = msg('months').split(','); buildInterface(); readPermalink(); bindInterface(); }); } /** * Execution * ------------------------------------------------- */ // On every page $(function () { if (!$('#t-rtrc').length) { mw.util.addPortletLink( 'p-tb', mw.util.getUrl('Special:BlankPage/RTRC'), 'RTRC', 't-rtrc', 'Monitor and patrol recent changes in real-time', null, '#t-specialpages' ); } }); /** * Modernizr 2.6.2 (Custom Build) | MIT & BSD * Build: http://modernizr.com/download/#-generatedcontent-teststyles * * Customized further for inclusion in mw-gadget-rtrc: * - Remove unused utilities. * - Export to jQuery.support.modernizr4rtrc instead of window.Modernizr. */ (function () { var docElement = document.documentElement, mod = 'modernizr', smile = ':)'; function injectElementWithStyles(rule, callback, nodes, testnames) { var style, ret, node, docOverflow, div = document.createElement('div'), body = document.body, fakeBody = body || document.createElement('body'); if (parseInt(nodes, 10)) { while (nodes--) { node = document.createElement('div'); node.id = testnames ? testnames[nodes] : mod + (nodes + 1); div.appendChild(node); } } style = ['&#173;', '<style id="s', mod, '">', rule, '</style>'].join(''); div.id = mod; (body ? div : fakeBody).innerHTML += style; fakeBody.appendChild(div); if (!body) { fakeBody.style.background = ''; fakeBody.style.overflow = 'hidden'; docOverflow = docElement.style.overflow; docElement.style.overflow = 'hidden'; docElement.appendChild(fakeBody); } ret = callback(div, rule); if (!body) { fakeBody.parentNode.removeChild(fakeBody); docElement.style.overflow = docOverflow; } else { div.parentNode.removeChild(div); } return !!ret; } $.support.modernizr4rtrc = { generatedcontent: (function () { return injectElementWithStyles(['#', mod, '{font:0/0 a}#', mod, ':after{content:"', smile, '";visibility:hidden;font:3px/1 a}'].join(''), function (node) { return node.offsetHeight >= 3; }); }()) }; })(); // Initialise if in the right context if ( (conf.wgTitle === 'Krinkle/RTRC' && conf.wgAction === 'view') || (conf.wgCanonicalSpecialPageName === 'Blankpage' && conf.wgTitle.split('/', 2)[1] === 'RTRC') ) { init(); } }(jQuery, mediaWiki));
Use rc.unpatrolled property in recentchanges API This has been introduced recently (MediaWiki 1.23alpha) and is more accurate for our purpose, since something not being patrolled doesn't always mean it is patrollable (e.g. on wikis with newpage patrol enabled but edit patrol disabled, or for rc entries for log events).
src/rtrc.js
Use rc.unpatrolled property in recentchanges API
<ide><path>rc/rtrc.js <ide> * @return {string} HTML <ide> */ <ide> function buildRcItem(rc) { <del> var diffsize, isPatrolled, isAnon, <add> var diffsize, isUnpatrolled, isAnon, <ide> typeSymbol, itemClass, diffLink, <ide> commentHtml, el, item; <ide> <ide> diffsize = rc.newlen - rc.oldlen; <ide> <ide> // Convert undefined/empty-string values from API into booleans <del> isPatrolled = rc.patrolled !== undefined; <add> isUnpatrolled = rc.unpatrolled !== undefined; <ide> isAnon = rc.anon !== undefined; <ide> <ide> // typeSymbol, diffLink & itemClass <ide> typeSymbol += '<span class="newpage">N</span>'; <ide> } <ide> <del> if ((rc.type === 'edit' || rc.type === 'new') && userHasPatrolRight && !isPatrolled) { <add> if ((rc.type === 'edit' || rc.type === 'new') && userHasPatrolRight && isUnpatrolled) { <ide> typeSymbol += '<span class="unpatrolled">!</span>'; <ide> } <ide>
Java
agpl-3.0
119882bb9c11bd54cc3a24e8af69cac3e917c30c
0
oncokb/oncokb,oncokb/oncokb,zhx828/oncokb,zhx828/oncokb,zhx828/oncokb,oncokb/oncokb
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.mskcc.cbio.oncokb.importer; import org.apache.commons.lang3.StringUtils; import org.json.JSONArray; import org.json.JSONObject; import org.mskcc.cbio.oncokb.bo.AlterationBo; import org.mskcc.cbio.oncokb.bo.PortalAlterationBo; import org.mskcc.cbio.oncokb.model.Alteration; import org.mskcc.cbio.oncokb.model.Gene; import org.mskcc.cbio.oncokb.model.PortalAlteration; import org.mskcc.cbio.oncokb.util.AlterationUtils; import org.mskcc.cbio.oncokb.util.ApplicationContextSingleton; import org.mskcc.cbio.oncokb.util.FileUtils; import org.mskcc.cbio.oncokb.util.GeneUtils; import java.io.IOException; import java.text.DecimalFormat; import java.util.*; /** * @author jiaojiao April/14/2016 Import alteration data from portal database */ public class PortalAlterationImporter { private static List<Alteration> findAlterationList(Gene gene, String proteinChange, String mutation_type, Integer proteinStartPosition, Integer proteinEndPosition) { List<Alteration> alterations = new ArrayList<>(); List<Alteration> alterationsSet = new ArrayList<>(); HashMap<String, String[]> mapper = new HashMap<>(); mapper.put("Targeted_Region", new String[]{"inframe_deletion", "inframe_insertion"}); mapper.put("COMPLEX_INDEL", new String[]{"inframe_deletion", "inframe_insertion"}); mapper.put("Indel", new String[]{"frameshift_variant", "inframe_deletion", "inframe_insertion"}); mapper.put("In_Frame_Del", new String[]{"inframe_deletion", "feature_truncation"}); mapper.put("3'Flank", new String[]{"any"}); mapper.put("5'Flank", new String[]{"any"}); mapper.put("ESSENTIAL_SPLICE_SITE", new String[]{"feature_truncation"}); mapper.put("Exon skipping", new String[]{"inframe_deletion"}); mapper.put("Frameshift deletion", new String[]{"frameshift_variant"}); mapper.put("Frameshift insertion", new String[]{"frameshift_variant"}); mapper.put("FRAMESHIFT_CODING", new String[]{"frameshift_variant"}); mapper.put("Frame_Shift_Del", new String[]{"frameshift_variant"}); mapper.put("Frame_Shift_Ins", new String[]{"frameshift_variant"}); mapper.put("Fusion", new String[]{"fusion"}); mapper.put("In_Frame_Ins", new String[]{"inframe_insertion"}); mapper.put("Missense", new String[]{"missense_variant"}); mapper.put("Missense_Mutation", new String[]{"missense_variant"}); mapper.put("Nonsense_Mutation", new String[]{"stop_gained"}); mapper.put("Nonstop_Mutation", new String[]{"stop_lost"}); mapper.put("Splice_Site", new String[]{"splice_region_variant"}); mapper.put("Splice_Site_Del", new String[]{"splice_region_variant"}); mapper.put("Splice_Site_SNP", new String[]{"splice_region_variant"}); mapper.put("splicing", new String[]{"splice_region_variant"}); mapper.put("Splice_Region", new String[]{"splice_region_variant"}); mapper.put("Translation_Start_Site", new String[]{"start_lost"}); mapper.put("vIII deletion", new String[]{"any"}); mapper.put("exon14skip", new String[]{"inframe_deletion"}); mapper.put("frameshift", new String[]{"frameshift_variant"}); mapper.put("nonframeshift insertion", new String[]{"frameshift_variant", "inframe_deletion", "inframe_insertion"}); mapper.put("nonframeshift_deletion", new String[]{"frameshift_variant", "inframe_deletion", "inframe_insertion"}); mapper.put("nonframeshift_insertion", new String[]{"frameshift_variant", "inframe_deletion", "inframe_insertion"}); mapper.put("Nonsense", new String[]{"stop_gained"}); mapper.put("splice", new String[]{"splice_region_variant"}); mapper.put("Splice_Site_Indel", new String[]{"splice_region_variant"}); String[] consequences = mapper.get(mutation_type); if (consequences == null) { System.out.println("No mutation type mapping for " + mutation_type); } else { for (String consequence : consequences) { Alteration alt = AlterationUtils.getAlteration(gene == null ? null : gene.getHugoSymbol(), proteinChange, null, consequence, proteinStartPosition, proteinEndPosition); AlterationUtils.annotateAlteration(alt, alt.getAlteration()); alterations.addAll(AlterationUtils.getRelevantAlterations(alt)); } alterationsSet = AlterationUtils.excludeVUS(alterations); } return alterationsSet; } public static void main(String[] args) throws IOException { JSONObject jObject = null; PortalAlteration portalAlteration = null; String geneUrl = "http://oncokb.org/legacy-api/gene.json"; String geneResult = FileUtils.readRemote(geneUrl); JSONArray geneJSONResult = new JSONArray(geneResult); String genes[] = new String[geneJSONResult.length()]; for (int i = 0; i < geneJSONResult.length(); i++) { jObject = geneJSONResult.getJSONObject(i); genes[i] = jObject.get("hugoSymbol").toString(); } String joinedGenes = StringUtils.join(genes, ","); String studies[] = {"blca_tcga_pub", "brca_tcga_pub2015", "cesc_tcga", "coadread_tcga_pub", "hnsc_tcga_pub", "kich_tcga_pub", "kirc_tcga_pub", "kirp_tcga", "lihc_tcga", "luad_tcga_pub", "lusc_tcga_pub", "lgggbm_tcga_pub", "ov_tcga_pub", "thca_tcga_pub", "prad_tcga_pub", "sarc_tcga", "skcm_tcga", "stad_tcga_pub", "tgct_tcga", "ucec_tcga_pub"}; String joinedStudies = StringUtils.join(studies, ","); String studyUrl = "http://www.cbioportal.org/api-legacy/studies?study_ids=" + joinedStudies; String studyResult = FileUtils.readRemote(studyUrl); JSONArray studyJSONResult = new JSONArray(studyResult); PortalAlterationBo portalAlterationBo = ApplicationContextSingleton.getPortalAlterationBo(); for (int j = 0; j < studyJSONResult.length(); j++) { jObject = studyJSONResult.getJSONObject(j); if (jObject.has("id") && jObject.has("type_of_cancer")) { String cancerStudy = jObject.get("id").toString(); String cancerType = jObject.get("type_of_cancer").toString(); System.out.println("*****************************************************************************"); System.out.println("Importing portal alteration data for " + jObject.get("name").toString()); //get sequenced sample list for one study String sequencedSamplesUrl = "http://www.cbioportal.org/api-legacy/samplelists?sample_list_ids=" + cancerStudy + "_sequenced"; String sequencedSamplesResult = FileUtils.readRemote(sequencedSamplesUrl); JSONArray sequencedSamplesJSONResult = new JSONArray(sequencedSamplesResult); if (sequencedSamplesJSONResult != null && sequencedSamplesJSONResult.length() > 0) { JSONArray sequencedSamples = (JSONArray) sequencedSamplesJSONResult.getJSONObject(0).get("sample_ids"); String genetic_profile_id = cancerStudy + "_mutations"; String sample_list_id = cancerStudy + "_sequenced"; String profileDataUrl = "http://www.cbioportal.org/api-legacy/geneticprofiledata?genetic_profile_ids=" + genetic_profile_id + "&genes=" + joinedGenes + "&sample_list_id=" + sample_list_id; String alterationResult = FileUtils.readRemote(profileDataUrl); JSONArray alterationJSONResult = new JSONArray(alterationResult); for (int m = 0; m < alterationJSONResult.length(); m++) { jObject = alterationJSONResult.getJSONObject(m); String proteinChange = jObject.getString("amino_acid_change"); Integer proteinStartPosition = jObject.getInt("protein_start_position"); Integer proteinEndPosition = jObject.getInt("protein_end_position"); String mutation_type = jObject.getString("mutation_type"); String hugo_gene_symbol = jObject.getString("hugo_gene_symbol"); Integer entrez_gene_id = jObject.getInt("entrez_gene_id"); String sampleId = jObject.getString("sample_id"); Gene gene = GeneUtils.getGene(entrez_gene_id, hugo_gene_symbol); portalAlteration = new PortalAlteration(cancerType, cancerStudy, sampleId, gene, proteinChange, proteinStartPosition, proteinEndPosition, mutation_type); portalAlterationBo.save(portalAlteration); Set<PortalAlteration> portalAlterations = new HashSet<>(); List<Alteration> oncoKBAlterations = findAlterationList(gene, proteinChange, mutation_type, proteinStartPosition, proteinEndPosition); for (Alteration oncoKBAlteration : oncoKBAlterations) { portalAlterations = oncoKBAlteration.getPortalAlterations(); portalAlterations.add(portalAlteration); AlterationBo alterationBo = ApplicationContextSingleton.getAlterationBo(); oncoKBAlteration.setPortalAlterations(portalAlterations); alterationBo.update(oncoKBAlteration); } //remove saved sample from sequenced sample list for (int n = 0; n < sequencedSamples.length(); n++) { if (sequencedSamples.get(n).equals(sampleId)) { sequencedSamples.remove(n); break; } } } //save samples that don't have mutations if (sequencedSamples.length() > 0) { for (int p = 0; p < sequencedSamples.length(); p++) { portalAlteration = new PortalAlteration(cancerType, cancerStudy, sequencedSamples.getString(p), null, null, null, null, null); portalAlterationBo.save(portalAlteration); } } } else { System.out.println("\tThe study doesnot have any sequenced samples."); } DecimalFormat myFormatter = new DecimalFormat("##.##"); String output = myFormatter.format(100 * (j + 1) / studyJSONResult.length()); System.out.println("Importing " + output + "% done."); } } } }
core/src/main/java/org/mskcc/cbio/oncokb/importer/PortalAlterationImporter.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.mskcc.cbio.oncokb.importer; import org.apache.commons.lang3.StringUtils; import org.json.JSONArray; import org.json.JSONObject; import org.mskcc.cbio.oncokb.bo.AlterationBo; import org.mskcc.cbio.oncokb.bo.PortalAlterationBo; import org.mskcc.cbio.oncokb.model.Alteration; import org.mskcc.cbio.oncokb.model.Gene; import org.mskcc.cbio.oncokb.model.PortalAlteration; import org.mskcc.cbio.oncokb.util.AlterationUtils; import org.mskcc.cbio.oncokb.util.ApplicationContextSingleton; import org.mskcc.cbio.oncokb.util.FileUtils; import org.mskcc.cbio.oncokb.util.GeneUtils; import java.io.IOException; import java.text.DecimalFormat; import java.util.*; /** * @author jiaojiao April/14/2016 Import alteration data from portal database */ public class PortalAlterationImporter { private static List<Alteration> findAlterationList(Gene gene, String proteinChange, String mutation_type, Integer proteinStartPosition, Integer proteinEndPosition) { List<Alteration> alterations = new ArrayList<>(); List<Alteration> alterationsSet = new ArrayList<>(); HashMap<String, String[]> mapper = new HashMap<>(); mapper.put("Targeted_Region", new String[]{"inframe_deletion", "inframe_insertion"}); mapper.put("COMPLEX_INDEL", new String[]{"inframe_deletion", "inframe_insertion"}); mapper.put("Indel", new String[]{"frameshift_variant", "inframe_deletion", "inframe_insertion"}); mapper.put("In_Frame_Del", new String[]{"inframe_deletion", "feature_truncation"}); mapper.put("3'Flank", new String[]{"any"}); mapper.put("5'Flank", new String[]{"any"}); mapper.put("ESSENTIAL_SPLICE_SITE", new String[]{"feature_truncation"}); mapper.put("Exon skipping", new String[]{"inframe_deletion"}); mapper.put("Frameshift deletion", new String[]{"frameshift_variant"}); mapper.put("Frameshift insertion", new String[]{"frameshift_variant"}); mapper.put("FRAMESHIFT_CODING", new String[]{"frameshift_variant"}); mapper.put("Frame_Shift_Del", new String[]{"frameshift_variant"}); mapper.put("Frame_Shift_Ins", new String[]{"frameshift_variant"}); mapper.put("Fusion", new String[]{"fusion"}); mapper.put("In_Frame_Ins", new String[]{"inframe_insertion"}); mapper.put("Missense", new String[]{"missense_variant"}); mapper.put("Missense_Mutation", new String[]{"missense_variant"}); mapper.put("Nonsense_Mutation", new String[]{"stop_gained"}); mapper.put("Nonstop_Mutation", new String[]{"stop_lost"}); mapper.put("Splice_Site", new String[]{"splice_region_variant"}); mapper.put("Splice_Site_Del", new String[]{"splice_region_variant"}); mapper.put("Splice_Site_SNP", new String[]{"splice_region_variant"}); mapper.put("splicing", new String[]{"splice_region_variant"}); mapper.put("Splice_Region", new String[]{"splice_region_variant"}); mapper.put("Translation_Start_Site", new String[]{"start_lost"}); mapper.put("vIII deletion", new String[]{"any"}); mapper.put("exon14skip", new String[]{"inframe_deletion"}); mapper.put("frameshift", new String[]{"frameshift_variant"}); mapper.put("nonframeshift insertion", new String[]{"frameshift_variant", "inframe_deletion", "inframe_insertion"}); mapper.put("nonframeshift_deletion", new String[]{"frameshift_variant", "inframe_deletion", "inframe_insertion"}); mapper.put("nonframeshift_insertion", new String[]{"frameshift_variant", "inframe_deletion", "inframe_insertion"}); mapper.put("Nonsense", new String[]{"stop_gained"}); mapper.put("splice", new String[]{"splice_region_variant"}); mapper.put("Splice_Site_Indel", new String[]{"splice_region_variant"}); String[] consequences = mapper.get(mutation_type); if (consequences == null) { System.out.println("No mutation type mapping for " + mutation_type); } else { for (String consequence : consequences) { Alteration alt = AlterationUtils.getAlteration(gene == null ? null : gene.getHugoSymbol(), proteinChange, null, consequence, proteinStartPosition, proteinEndPosition); AlterationUtils.annotateAlteration(alt, alt.getAlteration()); alterations.addAll(AlterationUtils.getRelevantAlterations(alt)); } alterationsSet = AlterationUtils.excludeVUS(alterations); } return alterationsSet; } public static void main(String[] args) throws IOException { JSONObject jObject = null; PortalAlteration portalAlteration = null; String geneUrl = "http://oncokb.org/legacy-api/gene.json"; String geneResult = FileUtils.readRemote(geneUrl); JSONArray geneJSONResult = new JSONArray(geneResult); String genes[] = new String[geneJSONResult.length()]; for (int i = 0; i < geneJSONResult.length(); i++) { jObject = geneJSONResult.getJSONObject(i); genes[i] = jObject.get("hugoSymbol").toString(); } String joinedGenes = StringUtils.join(genes, ","); String studies[] = {"blca_tcga_pub", "brca_tcga_pub2015", "cesc_tcga", "coadread_tcga_pub", "hnsc_tcga_pub", "kich_tcga_pub", "kirc_tcga_pub", "kirp_tcga", "lihc_tcga", "luad_tcga_pub", "lusc_tcga_pub", "lgggbm_tcga_pub", "ov_tcga_pub", "thca_tcga_pub", "prad_tcga_pub", "sarc_tcga", "skcm_tcga", "stad_tcga_pub", "tgct_tcga", "ucec_tcga_pub", "msk_impact_2017"}; String joinedStudies = StringUtils.join(studies, ","); String studyUrl = "http://www.cbioportal.org/api-legacy/studies?study_ids=" + joinedStudies; String studyResult = FileUtils.readRemote(studyUrl); JSONArray studyJSONResult = new JSONArray(studyResult); PortalAlterationBo portalAlterationBo = ApplicationContextSingleton.getPortalAlterationBo(); for (int j = 0; j < studyJSONResult.length(); j++) { jObject = studyJSONResult.getJSONObject(j); if (jObject.has("id") && jObject.has("type_of_cancer")) { String cancerStudy = jObject.get("id").toString(); String cancerType = jObject.get("type_of_cancer").toString(); System.out.println("*****************************************************************************"); System.out.println("Importing portal alteration data for " + jObject.get("name").toString()); //get sequenced sample list for one study String sequencedSamplesUrl = "http://www.cbioportal.org/api-legacy/samplelists?sample_list_ids=" + cancerStudy + "_sequenced"; String sequencedSamplesResult = FileUtils.readRemote(sequencedSamplesUrl); JSONArray sequencedSamplesJSONResult = new JSONArray(sequencedSamplesResult); if (sequencedSamplesJSONResult != null && sequencedSamplesJSONResult.length() > 0) { JSONArray sequencedSamples = (JSONArray) sequencedSamplesJSONResult.getJSONObject(0).get("sample_ids"); String genetic_profile_id = cancerStudy + "_mutations"; String sample_list_id = cancerStudy + "_sequenced"; String profileDataUrl = "http://www.cbioportal.org/api-legacy/geneticprofiledata?genetic_profile_ids=" + genetic_profile_id + "&genes=" + joinedGenes + "&sample_list_id=" + sample_list_id; String alterationResult = FileUtils.readRemote(profileDataUrl); JSONArray alterationJSONResult = new JSONArray(alterationResult); for (int m = 0; m < alterationJSONResult.length(); m++) { jObject = alterationJSONResult.getJSONObject(m); String proteinChange = jObject.getString("amino_acid_change"); Integer proteinStartPosition = jObject.getInt("protein_start_position"); Integer proteinEndPosition = jObject.getInt("protein_end_position"); String mutation_type = jObject.getString("mutation_type"); String hugo_gene_symbol = jObject.getString("hugo_gene_symbol"); Integer entrez_gene_id = jObject.getInt("entrez_gene_id"); String sampleId = jObject.getString("sample_id"); Gene gene = GeneUtils.getGene(entrez_gene_id, hugo_gene_symbol); portalAlteration = new PortalAlteration(cancerType, cancerStudy, sampleId, gene, proteinChange, proteinStartPosition, proteinEndPosition, mutation_type); portalAlterationBo.save(portalAlteration); Set<PortalAlteration> portalAlterations = new HashSet<>(); List<Alteration> oncoKBAlterations = findAlterationList(gene, proteinChange, mutation_type, proteinStartPosition, proteinEndPosition); for (Alteration oncoKBAlteration : oncoKBAlterations) { portalAlterations = oncoKBAlteration.getPortalAlterations(); portalAlterations.add(portalAlteration); AlterationBo alterationBo = ApplicationContextSingleton.getAlterationBo(); oncoKBAlteration.setPortalAlterations(portalAlterations); alterationBo.update(oncoKBAlteration); } //remove saved sample from sequenced sample list for (int n = 0; n < sequencedSamples.length(); n++) { if (sequencedSamples.get(n).equals(sampleId)) { sequencedSamples.remove(n); break; } } } //save samples that don't have mutations if (sequencedSamples.length() > 0) { for (int p = 0; p < sequencedSamples.length(); p++) { portalAlteration = new PortalAlteration(cancerType, cancerStudy, sequencedSamples.getString(p), null, null, null, null, null); portalAlterationBo.save(portalAlteration); } } } else { System.out.println("\tThe study doesnot have any sequenced samples."); } DecimalFormat myFormatter = new DecimalFormat("##.##"); String output = myFormatter.format(100 * (j + 1) / studyJSONResult.length()); System.out.println("Importing " + output + "% done."); } } } }
Remove msk_impact_2017 study
core/src/main/java/org/mskcc/cbio/oncokb/importer/PortalAlterationImporter.java
Remove msk_impact_2017 study
<ide><path>ore/src/main/java/org/mskcc/cbio/oncokb/importer/PortalAlterationImporter.java <ide> genes[i] = jObject.get("hugoSymbol").toString(); <ide> } <ide> String joinedGenes = StringUtils.join(genes, ","); <del> String studies[] = {"blca_tcga_pub", "brca_tcga_pub2015", "cesc_tcga", "coadread_tcga_pub", "hnsc_tcga_pub", "kich_tcga_pub", "kirc_tcga_pub", "kirp_tcga", "lihc_tcga", "luad_tcga_pub", "lusc_tcga_pub", "lgggbm_tcga_pub", "ov_tcga_pub", "thca_tcga_pub", "prad_tcga_pub", "sarc_tcga", "skcm_tcga", "stad_tcga_pub", "tgct_tcga", "ucec_tcga_pub", "msk_impact_2017"}; <add> String studies[] = {"blca_tcga_pub", "brca_tcga_pub2015", "cesc_tcga", "coadread_tcga_pub", "hnsc_tcga_pub", "kich_tcga_pub", "kirc_tcga_pub", "kirp_tcga", "lihc_tcga", "luad_tcga_pub", "lusc_tcga_pub", "lgggbm_tcga_pub", "ov_tcga_pub", "thca_tcga_pub", "prad_tcga_pub", "sarc_tcga", "skcm_tcga", "stad_tcga_pub", "tgct_tcga", "ucec_tcga_pub"}; <ide> String joinedStudies = StringUtils.join(studies, ","); <ide> String studyUrl = "http://www.cbioportal.org/api-legacy/studies?study_ids=" + joinedStudies; <ide> String studyResult = FileUtils.readRemote(studyUrl);
Java
apache-2.0
93f62d12d4c1f2fb9c677bf48fba1b834590ce5e
0
jenkinsci/fortify-cloudscan-plugin,jenkinsci/fortify-cloudscan-plugin,jenkinsci/fortify-cloudscan-plugin
/* * This file is part of Fortify CloudScan Jenkins plugin. * * 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.jenkinsci.plugins.fortifycloudscan; import hudson.model.BuildListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Serializable; /** * This class is called by FortifyCloudScanBuilder (the Jenkins build-step plugin). * Performs the external execution of the cloudscan command line interface. * * @author Steve Springett ([email protected]) */ public class FortifyCloudScanExecutor implements Serializable { private static final long serialVersionUID = 3595913479313812273L; private String[] command; private BuildListener listener; /** * Constructs a new FortifyCloudScanExecutor object. * * @param command A String array of the command and options to use * @param listener BuildListener object to interact with the current build */ public FortifyCloudScanExecutor(String[] command, BuildListener listener) { this.command = command; this.listener = listener; } /** * Executes cloudscan with configured arguments * * @return a boolean value indicating if the command was executed successfully or not. */ public boolean perform() { String[] versionCommand = {command[0], "-version"}; execute(versionCommand); logCommand(); return execute(command); } /** * Executes the external cloudscan process sending stderr and stdout to the logger */ private boolean execute(String[] command) { Process process; try { // Java exec requires that commands containing spaces be in an array process = Runtime.getRuntime().exec(command); // Redirect error and output to console StreamLogger erroutLogger = new StreamLogger(process.getErrorStream()); StreamLogger stdoutLogger = new StreamLogger(process.getInputStream()); erroutLogger.start(); stdoutLogger.start(); int exitCode = process.waitFor(); return exitCode == 0; } catch (InterruptedException e) { log(Messages.Executor_Failure() + ": " + e.getMessage()); } catch (IOException e) { log(Messages.Executor_Failure() + ": " + e.getMessage()); } return false; } /** * Log messages to the builds console. * @param message The message to log */ protected void log(String message) { final String outtag = "[" + FortifyCloudScanPlugin.PLUGIN_NAME + "] "; listener.getLogger().println(outtag + message.replaceAll("\\n", "\n" + outtag)); } private void logCommand() { String cmd = Messages.Executor_Display_Options() + ": "; for (String param : command) { cmd = cmd + param + " "; } log(cmd); } private class StreamLogger extends Thread { InputStream is; private StreamLogger(InputStream is) { this.is = is; } @Override public void run() { try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { log(line); } } catch (IOException ioe) { ioe.printStackTrace(); } } } }
src/main/java/org/jenkinsci/plugins/fortifycloudscan/FortifyCloudScanExecutor.java
/* * This file is part of Fortify CloudScan Jenkins plugin. * * 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.jenkinsci.plugins.fortifycloudscan; import hudson.model.BuildListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Serializable; /** * This class is called by FortifyCloudScanBuilder (the Jenkins build-step plugin). * Performs the external execution of the cloudscan command line interface. * * @author Steve Springett ([email protected]) */ public class FortifyCloudScanExecutor implements Serializable { private static final long serialVersionUID = 3595913479313812273L; private String[] command; private BuildListener listener; /** * Constructs a new FortifyCloudScanExecutor object. * * @param command A String array of the command and options to use * @param listener BuildListener object to interact with the current build */ public FortifyCloudScanExecutor(String[] command, BuildListener listener) { this.command = command; this.listener = listener; } /** * Executes cloudscan with configured arguments * * @return a boolean value indicating if the command was executed successfully or not. */ public boolean perform() { String[] versionCommand = {command[0], "-version"}; execute(versionCommand); logCommand(); return execute(command); } /** * Executes the external cloudscan process sending stderr and stdout to the logger */ private boolean execute(String[] command) { Process process; try { // Java exec requires that commands containing spaces be in an array process = Runtime.getRuntime().exec(command); // Redirect error and output to console StreamLogger erroutLogger = new StreamLogger(process.getErrorStream()); StreamLogger stdoutLogger = new StreamLogger(process.getInputStream()); erroutLogger.start(); stdoutLogger.start(); int exitCode = process.waitFor(); if (exitCode != 0) { return false; } } catch (InterruptedException e) { log(Messages.Executor_Failure() + ": " + e.getMessage()); } catch (IOException e) { log(Messages.Executor_Failure() + ": " + e.getMessage()); } return true; } /** * Log messages to the builds console. * @param message The message to log */ protected void log(String message) { final String outtag = "[" + FortifyCloudScanPlugin.PLUGIN_NAME + "] "; listener.getLogger().println(outtag + message.replaceAll("\\n", "\n" + outtag)); } private void logCommand() { String cmd = Messages.Executor_Display_Options() + ": "; for (String param : command) { cmd = cmd + param + " "; } log(cmd); } private class StreamLogger extends Thread { InputStream is; private StreamLogger(InputStream is) { this.is = is; } @Override public void run() { try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { log(line); } } catch (IOException ioe) { ioe.printStackTrace(); } } } }
Fixing execution logic to report accurate build status
src/main/java/org/jenkinsci/plugins/fortifycloudscan/FortifyCloudScanExecutor.java
Fixing execution logic to report accurate build status
<ide><path>rc/main/java/org/jenkinsci/plugins/fortifycloudscan/FortifyCloudScanExecutor.java <ide> stdoutLogger.start(); <ide> <ide> int exitCode = process.waitFor(); <del> if (exitCode != 0) { <del> return false; <del> } <add> return exitCode == 0; <ide> } catch (InterruptedException e) { <ide> log(Messages.Executor_Failure() + ": " + e.getMessage()); <ide> } catch (IOException e) { <ide> log(Messages.Executor_Failure() + ": " + e.getMessage()); <ide> } <del> return true; <add> return false; <ide> } <ide> <ide> /**
Java
epl-1.0
1338b3431232c4544cbabeb295645dc7d94f33ca
0
theanuradha/debrief,theanuradha/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,theanuradha/debrief,debrief/debrief,debrief/debrief,debrief/debrief,debrief/debrief,theanuradha/debrief
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2016, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package org.mwc.debrief.dis.ui.views; import java.lang.reflect.Field; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.DropTargetAdapter; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.PreferencesUtil; import org.eclipse.ui.part.ResourceTransfer; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.xy.XYDataset; import org.jfree.experimental.chart.swt.ChartComposite; import org.jfree.ui.RectangleEdge; import org.mwc.cmap.core.CorePlugin; import org.mwc.cmap.core.DataTypes.Temporal.ControllableTime; import org.mwc.cmap.core.ui_support.PartMonitor; import org.mwc.debrief.dis.DisActivator; import org.mwc.debrief.dis.core.DISModule; import org.mwc.debrief.dis.core.IDISModule; import org.mwc.debrief.dis.listeners.IDISGeneralPDUListener; import org.mwc.debrief.dis.listeners.IDISStartResumeListener; import org.mwc.debrief.dis.listeners.IDISStopListener; import org.mwc.debrief.dis.listeners.impl.DISContext; import org.mwc.debrief.dis.listeners.impl.DebriefCollisionListener; import org.mwc.debrief.dis.listeners.impl.DebriefDetonationListener; import org.mwc.debrief.dis.listeners.impl.DebriefEventListener; import org.mwc.debrief.dis.listeners.impl.DebriefFireListener; import org.mwc.debrief.dis.listeners.impl.DebriefFixListener; import org.mwc.debrief.dis.listeners.impl.IDISContext; import org.mwc.debrief.dis.providers.DISFilters; import org.mwc.debrief.dis.providers.IPDUProvider; import org.mwc.debrief.dis.providers.network.IDISController; import org.mwc.debrief.dis.providers.network.IDISNetworkPrefs; import org.mwc.debrief.dis.providers.network.NetworkDISProvider; import org.mwc.debrief.dis.runner.SimulationRunner; import org.mwc.debrief.dis.ui.preferences.DebriefDISNetPrefs; import org.mwc.debrief.dis.ui.preferences.DebriefDISSimulatorPrefs; import org.mwc.debrief.dis.ui.preferences.DisPrefs; import MWC.GUI.CanvasType; import MWC.GenericData.HiResDate; import edu.nps.moves.dis.EntityID; import edu.nps.moves.dis.Pdu; public class DisListenerView extends ViewPart { public static final String HELP_CONTEXT = "org.mwc.debrief.help.DISSupport"; private Button connectButton; private Button playButton; private Button pauseButton; private Button stopButton; // private Button resumeButton; private Button launchButton; private ChartComposite chartComposite; private Text pathText; private Button newPlotButton; private Button liveUpdatesButton; private Action fitToDataAction; private IDISModule _disModule; private IPDUProvider _netProvider; protected Thread _simThread; protected Job _simJob; /** * flag for if time is already being updated * */ boolean updatePending = false; /** * our context * */ private IDISContext _context; /** * we need to access the setting of live updates from outside the UI thread, so store it here. */ private boolean _doLiveUpdates = true; /** * we need to access the setting of new plots from outside the UI thread, so store it here. */ private boolean _newPlotPerReplication = false; /** * we need to access the setting of fit to data from outside the UI thread, so store it here. */ private boolean _fitToDataValue = false; private DebriefDISSimulatorPrefs _simPrefs; protected SimulationRunner _simulationRunner; private PerformanceGraph _perfGraph; private PartMonitor _myPartMonitor; private Group controlButtons; final String LAUNCH_STRING = "Launch"; final String LISTEN_STRING = "Listen"; private IDISController _disController; private EntityID _ourID; private void initModule() { _simPrefs = new DebriefDISSimulatorPrefs(); // get the debrief prefs IDISNetworkPrefs netPrefs = new DebriefDISNetPrefs(); // get the network data source NetworkDISProvider prov = new NetworkDISProvider(netPrefs); _netProvider = prov; _disController = prov; _disModule = new DISModule(); _disModule.setProvider(_netProvider); _perfGraph = new PerformanceGraph(chartComposite); _disModule.addGeneralPDUListener(_perfGraph); // _disModule.addScenarioListener(_perfGraph); _simulationRunner = new SimulationRunner(_simPrefs); // sort out the part listneer. Note - we have to do this before we can setup the DIS listeners // (below) _myPartMonitor = new PartMonitor(getSite().getWorkbenchWindow().getPartService()); _context = new DISContext(_myPartMonitor) { ControllableTime ct = null; @Override public boolean getLiveUpdates() { return _doLiveUpdates; } @Override public boolean getUseNewPlot() { return _newPlotPerReplication; } @Override public boolean getFitToData() { return _fitToDataValue; } @Override public void setNewTime(long time) { if (_doLiveUpdates) { // tell the plot editor about the newtime if (ct == null) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { final IWorkbench wb = PlatformUI.getWorkbench(); final IWorkbenchWindow win = wb.getActiveWorkbenchWindow(); if (win != null) { final IWorkbenchPage page = win.getActivePage(); final IEditorPart editor = page.getActiveEditor(); if (editor != null) { ct = (ControllableTime) editor .getAdapter(ControllableTime.class); } } } }); } if (ct != null) { ct.setTime(this, new HiResDate(time), true); } else { System.err.println("ct was null"); } } } @Override public void screenUpdated() { _perfGraph.screenUpdate(); } @Override public void zoomToFit() { Runnable doUpdate = new Runnable() { @Override public void run() { final IWorkbench wb = PlatformUI.getWorkbench(); final IWorkbenchWindow win = wb.getActiveWorkbenchWindow(); if (win != null) { final IWorkbenchPage page = win.getActivePage(); final IEditorPart editor = page.getActiveEditor(); if (editor != null) { CanvasType canvas = (CanvasType) editor.getAdapter(CanvasType.class); canvas.rescale(); } } } }; // check we're in the UI thread if (Display.getCurrent() != null && Thread.currentThread().equals(Display.getCurrent().getThread())) { doUpdate.run(); } else { Display.getCurrent().asyncExec(doUpdate); } } }; setupListeners(_disModule); } private void handleStopMessage(long time, final int appId, short eid, final short reason) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { // check it wasn't us that send the message if (appId == NetworkDISProvider.APPLICATION_ID) { // ignore - it's us sending it return; } // hey, check the reason switch (reason) { case IDISStopListener.PDU_FREEZE: System.err.println("PAUSE"); pauseReceived(); break; case IDISStopListener.PDU_STOP: System.err.println("STOP"); // update the UI stopReceived(); // check it wasn't from us short ourAppId = (short) DisActivator.getDefault().getPreferenceStore().getInt( DisActivator.APP_ID); if (appId != ourAppId) { // ok, popup message MessageBox dialog = new MessageBox(PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(), SWT.OK); dialog.setText("DIS Interface"); dialog.setMessage("The simulation has completed, with reason: " + reason); // open dialog dialog.open(); } break; default: CorePlugin.logError(Status.WARNING, "Unknown DIS stop reason received:" + reason, null); } } }); } private void setupListeners(final IDISModule module) { // listen for stop, so we can update the UI module.addStopListener(new IDISStopListener() { @Override public void stop(long time, int appId, short eid, short reason) { handleStopMessage(time, appId, eid, reason); } }); // handle the time updates module.addGeneralPDUListener(new IDISGeneralPDUListener() { final long TIME_UNSET = module.convertTime(-1); long time = TIME_UNSET; long lastTime = TIME_UNSET; @Override public void logPDU(Pdu pdu) { long newTime = module.convertTime(pdu.getTimestamp()); if (newTime != time && time != TIME_UNSET) { // are we already updating? if (!updatePending) { // nope, go for it. updatePending = true; Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (_doLiveUpdates) { // first the data model _context.fireUpdate(null, null); // now the time if (time > lastTime) { _context.setNewTime(time); // hey, should we fit to window? if (_fitToDataValue) { _context.zoomToFit(); } lastTime = time; } } updatePending = false; } }); } } time = newTime; } @Override public void complete(String reason) { // reset the time counter time = TIME_UNSET; } }); // ok, Debrief fix listener module.addFixListener(new DebriefFixListener(_context)); module.addDetonationListener(new DebriefDetonationListener(_context)); module.addEventListener(new DebriefEventListener(_context)); module.addFireListener(new DebriefFireListener(_context)); module.addStartResumeListener(new IDISStartResumeListener() { @Override public void add(long time, short eid, long replication) { playHeard(); // also, tell the context about the new replication id _context.setReplicationId(replication); } }); module.addCollisionListener(new DebriefCollisionListener(_context)); } @Override public void createPartControl(Composite parent) { // height of the DIS icon, and the Listen button final int col1Width = 80; Composite composite = new Composite(parent, SWT.NONE); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false); composite.setLayoutData(gd); GridLayout layout = new GridLayout(1, false); layout.marginWidth = 0; layout.marginHeight = 0; composite.setLayout(layout); Composite topRow = new Composite(composite, SWT.NONE); gd = new GridData(SWT.FILL, SWT.FILL, true, false); topRow.setLayoutData(gd); layout = new GridLayout(2, false); layout.marginWidth = 5; layout.marginHeight = 5; topRow.setLayout(layout); Label iconLbl = new Label(topRow, SWT.CENTER); iconLbl.setImage(AbstractUIPlugin.imageDescriptorFromPlugin( "org.mwc.debrief.dis", "icons/50px/dis_icon.png").createImage()); GridData gd3 = new GridData(SWT.CENTER, SWT.CENTER, false, false); gd3.widthHint = col1Width; iconLbl.setLayoutData(gd3); Group localGroup = new Group(topRow, SWT.NONE); localGroup.setText("Local simulator"); gd = new GridData(SWT.FILL, SWT.FILL, true, false); localGroup.setLayoutData(gd); layout = new GridLayout(5, false); layout.marginWidth = 5; layout.marginHeight = 5; localGroup.setLayout(layout); launchButton = new Button(localGroup, SWT.NONE); gd = new GridData(SWT.FILL, SWT.FILL, false, false); gd.widthHint = col1Width; launchButton.setText(LAUNCH_STRING); launchButton.setLayoutData(gd); launchButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doLaunch(); } }); Label label = new Label(localGroup, SWT.NONE); gd = new GridData(GridData.HORIZONTAL_ALIGN_END, GridData.VERTICAL_ALIGN_CENTER, false, true); gd.verticalIndent = 6; label.setLayoutData(gd); label.setText("Control file:"); pathText = new Text(localGroup, SWT.SINGLE | SWT.BORDER); gd = new GridData(SWT.FILL, SWT.FILL, true, false); gd.horizontalSpan = 2; gd.widthHint = 150; pathText.setLayoutData(gd); pathText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { String newText = pathText.getText(); if (newText != null) { IPreferenceStore store = DisActivator.getDefault().getPreferenceStore(); store.setValue(DisActivator.PATH_TO_INPUT_FILE, pathText.getText()); } } }); IPreferenceStore store = DisActivator.getDefault().getPreferenceStore(); pathText.setText(store.getString(DisActivator.PATH_TO_INPUT_FILE)); final Button browseButton = new Button(localGroup, SWT.PUSH); gd = new GridData(SWT.FILL, SWT.FILL, false, false); browseButton.setToolTipText("Browse for control file"); browseButton.setLayoutData(gd); browseButton.setText("..."); browseButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(getSite().getShell(), SWT.SINGLE); String value = pathText.getText(); if (value.trim().length() == 0) { value = Platform.getLocation().toOSString(); } dialog.setFilterPath(value); String result = dialog.open(); if (result == null || result.trim().length() == 0) { return; } pathText.setText(result); } }); // ///////////////////////// // Control // ///////////////////////// Composite controlHolder = new Composite(composite, SWT.NONE); gd = new GridData(SWT.FILL, SWT.FILL, true, false); controlHolder.setLayoutData(gd); layout = new GridLayout(2, false); layout.marginWidth = 5; layout.marginHeight = 5; controlHolder.setLayout(layout); connectButton = new Button(controlHolder, SWT.TOGGLE); connectButton.setText(LISTEN_STRING); gd = new GridData(SWT.FILL, SWT.FILL, false, false); gd.widthHint = col1Width; connectButton.setLayoutData(gd); connectButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (connectButton.getSelection()) { doConnect(); } else { doDisconnect(); } } }); controlButtons = new Group(controlHolder, SWT.NONE); controlButtons.setText("Control"); gd = new GridData(SWT.FILL, SWT.FILL, true, false); controlButtons.setLayoutData(gd); layout = new GridLayout(3, false); layout.marginWidth = 5; layout.marginHeight = 5; controlButtons.setLayout(layout); playButton = new Button(controlButtons, SWT.NONE); playButton.setText("Play"); gd = new GridData(SWT.FILL, SWT.FILL, true, false); playButton.setLayoutData(gd); playButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { sendPlay(); // doPlay(); } }); pauseButton = new Button(controlButtons, SWT.NONE); pauseButton.setText("Pause"); gd = new GridData(SWT.FILL, SWT.FILL, true, false); pauseButton.setLayoutData(gd); pauseButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { _disController.sendPause(); // doPause(); } }); stopButton = new Button(controlButtons, SWT.NONE); stopButton.setText("Stop"); gd = new GridData(SWT.FILL, SWT.FILL, true, false); stopButton.setLayoutData(gd); stopButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { _disController.sendStop(); // doStop(); } }); playButton.setEnabled(false); pauseButton.setEnabled(false); stopButton.setEnabled(false); // ///////////////////////// // SETTINGS // ///////////////////////// Group settingsPanel = new Group(composite, SWT.NONE); settingsPanel.setText("Settings"); gd = new GridData(SWT.FILL, SWT.FILL, true, false); settingsPanel.setLayoutData(gd); layout = new GridLayout(3, false); layout.marginWidth = 5; layout.marginHeight = 5; settingsPanel.setLayout(layout); newPlotButton = new Button(settingsPanel, SWT.CHECK); gd = new GridData(SWT.FILL, SWT.FILL, true, false); newPlotButton.setLayoutData(gd); newPlotButton.setText("New plot per replication"); newPlotButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { _newPlotPerReplication = newPlotButton.getSelection(); } }); newPlotButton.setSelection(_newPlotPerReplication); liveUpdatesButton = new Button(settingsPanel, SWT.CHECK); gd = new GridData(SWT.FILL, SWT.FILL, true, false); liveUpdatesButton.setLayoutData(gd); liveUpdatesButton.setText("Live updates"); liveUpdatesButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { _doLiveUpdates = liveUpdatesButton.getSelection(); // if it's being unselected, do a refresh all if (liveUpdatesButton.getSelection()) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { _context.fireUpdate(null, null); } }); } } }); liveUpdatesButton.setSelection(_doLiveUpdates); final Link link = new Link(settingsPanel, SWT.NONE); gd = new GridData(SWT.END, SWT.FILL, false, false); gd.horizontalSpan = 1; link.setLayoutData(gd); link.setText("<a href=\"id\">Server Prefs</a>"); link.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(link.getShell(), DisPrefs.ID, null, null); dialog.open(); } }); link.setToolTipText("Dis Preferences"); // ///////////////////////// // CHART // ///////////////////////// Composite chartPanel = new Composite(composite, SWT.BORDER); gd = new GridData(SWT.FILL, SWT.FILL, true, true); chartPanel.setLayoutData(gd); layout = new GridLayout(1, false); chartPanel.setLayout(layout); XYDataset dataset = new TimeSeriesCollection(); JFreeChart theChart = ChartFactory.createTimeSeriesChart("Line Chart", "Time", "Hertz", dataset); chartComposite = new ChartComposite(chartPanel, SWT.NONE, theChart, 400, 600, 300, 200, 1800, 1800, true, true, true, true, true, true) { @Override public void mouseUp(MouseEvent event) { super.mouseUp(event); JFreeChart c = getChart(); if (c != null) { c.setNotify(true); // force redraw } } }; fixChartComposite(); gd = new GridData(SWT.FILL, SWT.FILL, true, true); chartComposite.setLayoutData(gd); layout = new GridLayout(1, false); chartComposite.setLayout(layout); theChart.getLegend().setVisible(true); theChart.getLegend().setPosition(RectangleEdge.TOP); theChart.getTitle().setVisible(false); // create our unique originating ID createEntityID(); // ok, and the location commands contributeToActionBars(); // ok, we can go for it initModule(); // ok, sort out the help PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, HELP_CONTEXT); addDropSupport(); } private void addDropSupport() { int operations = DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK | DND.DROP_DEFAULT; DropTarget target = new DropTarget(pathText, operations); Transfer[] types = new Transfer[] {ResourceTransfer.getInstance()}; target.setTransfer(types); target.addDropListener(new DropTargetAdapter() { @Override public void drop(DropTargetEvent event) { super.drop(event); Object data = event.data; IResource resource = null; if (data.getClass().isArray() && ((Object[]) data).length > 0) { resource = (IResource) ((Object[]) data)[0]; } else if (data instanceof IResource) { resource = (IResource) data; } if (resource != null) { String fileExtension = resource.getFileExtension(); if (fileExtension.equals("inp")) { pathText.setText(resource.getLocation().toOSString()); } } event.detail = 1; } }); } private void createEntityID() { _ourID = new EntityID(); _ourID.setApplication((short) DisActivator.getDefault() .getPreferenceStore().getInt(DisActivator.APP_ID)); _ourID.setSite((short) DisActivator.getDefault().getPreferenceStore() .getInt(DisActivator.SITE_ID)); } private void fixChartComposite() { Class<ChartComposite> clazz = ChartComposite.class; try { Field field = clazz.getDeclaredField("canvas"); field.setAccessible(true); Object object = field.get(chartComposite); if (object instanceof Canvas) { Canvas canvas = (Canvas) object; GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); canvas.setLayoutData(gd); GridLayout layout = new GridLayout(1, false); canvas.setLayout(layout); } } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e1) { DisActivator.log(e1); } } private void contributeToActionBars() { fitToDataAction = new org.eclipse.jface.action.Action() { public void run() { _fitToDataValue = fitToDataAction.isChecked(); } }; fitToDataAction.setChecked(_fitToDataValue); fitToDataAction.setText("Fit to data"); fitToDataAction .setToolTipText("Zoom the selected plot out to show the full data"); fitToDataAction.setImageDescriptor(CorePlugin .getImageDescriptor("icons/16/fit_to_win.png")); final IActionBars bars = getViewSite().getActionBars(); fillLocalPullDown(bars.getMenuManager()); bars.getToolBarManager().add(fitToDataAction); bars.getToolBarManager().add( CorePlugin.createOpenHelpAction(HELP_CONTEXT, null, this)); } private void fillLocalPullDown(final IMenuManager manager) { manager.add(new Separator()); manager.add(CorePlugin.createOpenHelpAction(HELP_CONTEXT, null, this)); } @Override public void setFocus() { launchButton.setFocus(); } // private void doKill() // { // _simulationRunner.stop(); // // doDisconnect(); // // // tell the perf graph that we've finished // _perfGraph.complete("Stop button"); // // launchButton.setText(LAUNCH_STRING); // // } /** * run the simulator, passing it the specified input file * * @param inputPath */ public void doLaunch(String inputPath) { // ok, start with a "connect", if we have to if (!connectButton.getSelection()) { connectButton.setSelection(true); doConnect(); // doPlay(); } _simulationRunner.run(inputPath); } private void doLaunch() { IPreferenceStore store = DisActivator.getDefault().getPreferenceStore(); String pText = store.getString(DisActivator.PATH_TO_INPUT_FILE); doLaunch(pText); } private void doPlay() { playButton.setEnabled(false); pauseButton.setEnabled(true); stopButton.setEnabled(true); } private void doPause() { playButton.setEnabled(true); pauseButton.setEnabled(false); stopButton.setEnabled(true); } private void doStop() { playButton.setEnabled(true); pauseButton.setEnabled(false); stopButton.setEnabled(false); // tell the perf graph that we've finished _perfGraph.complete("Stop button"); // tell the context that it's complete _context.scenarioComplete(); _perfGraph.complete("Stopped"); } protected void stopReceived() { doStop(); // no, don't disconnect, since we may get another replication // doDisconnect(); // no, don't jump to launch - we may still be running // launchButton.setFocus(); } protected void pauseReceived() { doPause(); } private void doConnect() { // collate the prefs final String app = DisActivator.getDefault().getPreferenceStore().getString( DisActivator.APP_FILTER); final String site = DisActivator.getDefault().getPreferenceStore().getString( DisActivator.SITE_FILTER); final String ex = DisActivator.getDefault().getPreferenceStore().getString( DisActivator.EXERCISE_FILTER); final DISFilters filter = new DISFilters(app, site, ex); _netProvider.attach(filter, _ourID); playButton.setEnabled(true); pauseButton.setEnabled(false); stopButton.setEnabled(false); connectButton.setText("Listening"); } private void doDisconnect() { _netProvider.detach(); playButton.setEnabled(false); pauseButton.setEnabled(false); stopButton.setEnabled(false); connectButton.setSelection(false); connectButton.setText(LISTEN_STRING); // also, stop the graph updating _perfGraph.complete("Disconnected"); } private void playHeard() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { // ok, it's running - update the UI doPlay(); } }); } private void sendPlay() { _disController.sendPlay(); } }
org.mwc.debrief.dis/src/org/mwc/debrief/dis/ui/views/DisListenerView.java
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2016, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package org.mwc.debrief.dis.ui.views; import java.lang.reflect.Field; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.PreferencesUtil; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.xy.XYDataset; import org.jfree.experimental.chart.swt.ChartComposite; import org.jfree.ui.RectangleEdge; import org.mwc.cmap.core.CorePlugin; import org.mwc.cmap.core.DataTypes.Temporal.ControllableTime; import org.mwc.cmap.core.ui_support.PartMonitor; import org.mwc.debrief.dis.DisActivator; import org.mwc.debrief.dis.core.DISModule; import org.mwc.debrief.dis.core.IDISModule; import org.mwc.debrief.dis.listeners.IDISGeneralPDUListener; import org.mwc.debrief.dis.listeners.IDISStartResumeListener; import org.mwc.debrief.dis.listeners.IDISStopListener; import org.mwc.debrief.dis.listeners.impl.DISContext; import org.mwc.debrief.dis.listeners.impl.DebriefCollisionListener; import org.mwc.debrief.dis.listeners.impl.DebriefDetonationListener; import org.mwc.debrief.dis.listeners.impl.DebriefEventListener; import org.mwc.debrief.dis.listeners.impl.DebriefFireListener; import org.mwc.debrief.dis.listeners.impl.DebriefFixListener; import org.mwc.debrief.dis.listeners.impl.IDISContext; import org.mwc.debrief.dis.providers.DISFilters; import org.mwc.debrief.dis.providers.IPDUProvider; import org.mwc.debrief.dis.providers.network.IDISController; import org.mwc.debrief.dis.providers.network.IDISNetworkPrefs; import org.mwc.debrief.dis.providers.network.NetworkDISProvider; import org.mwc.debrief.dis.runner.SimulationRunner; import org.mwc.debrief.dis.ui.preferences.DebriefDISNetPrefs; import org.mwc.debrief.dis.ui.preferences.DebriefDISSimulatorPrefs; import org.mwc.debrief.dis.ui.preferences.DisPrefs; import MWC.GUI.CanvasType; import MWC.GenericData.HiResDate; import edu.nps.moves.dis.EntityID; import edu.nps.moves.dis.Pdu; public class DisListenerView extends ViewPart { public static final String HELP_CONTEXT = "org.mwc.debrief.help.DISSupport"; private Button connectButton; private Button playButton; private Button pauseButton; private Button stopButton; // private Button resumeButton; private Button launchButton; private ChartComposite chartComposite; private Text pathText; private Button newPlotButton; private Button liveUpdatesButton; private Action fitToDataAction; private IDISModule _disModule; private IPDUProvider _netProvider; protected Thread _simThread; protected Job _simJob; /** * flag for if time is already being updated * */ boolean updatePending = false; /** * our context * */ private IDISContext _context; /** * we need to access the setting of live updates from outside the UI thread, so store it here. */ private boolean _doLiveUpdates = true; /** * we need to access the setting of new plots from outside the UI thread, so store it here. */ private boolean _newPlotPerReplication = false; /** * we need to access the setting of fit to data from outside the UI thread, so store it here. */ private boolean _fitToDataValue = false; private DebriefDISSimulatorPrefs _simPrefs; protected SimulationRunner _simulationRunner; private PerformanceGraph _perfGraph; private PartMonitor _myPartMonitor; private Group controlButtons; final String LAUNCH_STRING = "Launch"; final String LISTEN_STRING = "Listen"; private IDISController _disController; private EntityID _ourID; private void initModule() { _simPrefs = new DebriefDISSimulatorPrefs(); // get the debrief prefs IDISNetworkPrefs netPrefs = new DebriefDISNetPrefs(); // get the network data source NetworkDISProvider prov = new NetworkDISProvider(netPrefs); _netProvider = prov; _disController = prov; _disModule = new DISModule(); _disModule.setProvider(_netProvider); _perfGraph = new PerformanceGraph(chartComposite); _disModule.addGeneralPDUListener(_perfGraph); // _disModule.addScenarioListener(_perfGraph); _simulationRunner = new SimulationRunner(_simPrefs); // sort out the part listneer. Note - we have to do this before we can setup the DIS listeners // (below) _myPartMonitor = new PartMonitor(getSite().getWorkbenchWindow().getPartService()); _context = new DISContext(_myPartMonitor) { ControllableTime ct = null; @Override public boolean getLiveUpdates() { return _doLiveUpdates; } @Override public boolean getUseNewPlot() { return _newPlotPerReplication; } @Override public boolean getFitToData() { return _fitToDataValue; } @Override public void setNewTime(long time) { if (_doLiveUpdates) { // tell the plot editor about the newtime if (ct == null) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { final IWorkbench wb = PlatformUI.getWorkbench(); final IWorkbenchWindow win = wb.getActiveWorkbenchWindow(); if (win != null) { final IWorkbenchPage page = win.getActivePage(); final IEditorPart editor = page.getActiveEditor(); if (editor != null) { ct = (ControllableTime) editor .getAdapter(ControllableTime.class); } } } }); } if (ct != null) { ct.setTime(this, new HiResDate(time), true); } else { System.err.println("ct was null"); } } } @Override public void screenUpdated() { _perfGraph.screenUpdate(); } @Override public void zoomToFit() { Runnable doUpdate = new Runnable() { @Override public void run() { final IWorkbench wb = PlatformUI.getWorkbench(); final IWorkbenchWindow win = wb.getActiveWorkbenchWindow(); if (win != null) { final IWorkbenchPage page = win.getActivePage(); final IEditorPart editor = page.getActiveEditor(); if (editor != null) { CanvasType canvas = (CanvasType) editor.getAdapter(CanvasType.class); canvas.rescale(); } } } }; // check we're in the UI thread if (Display.getCurrent() != null && Thread.currentThread().equals(Display.getCurrent().getThread())) { doUpdate.run(); } else { Display.getCurrent().asyncExec(doUpdate); } } }; setupListeners(_disModule); } private void handleStopMessage(long time, final int appId, short eid, final short reason) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { // check it wasn't us that send the message if (appId == NetworkDISProvider.APPLICATION_ID) { // ignore - it's us sending it return; } // hey, check the reason switch (reason) { case IDISStopListener.PDU_FREEZE: System.err.println("PAUSE"); pauseReceived(); break; case IDISStopListener.PDU_STOP: System.err.println("STOP"); // update the UI stopReceived(); // check it wasn't from us short ourAppId = (short) DisActivator.getDefault().getPreferenceStore().getInt( DisActivator.APP_ID); if (appId != ourAppId) { // ok, popup message MessageBox dialog = new MessageBox(PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(), SWT.OK); dialog.setText("DIS Interface"); dialog.setMessage("The simulation has completed, with reason: " + reason); // open dialog dialog.open(); } break; default: CorePlugin.logError(Status.WARNING, "Unknown DIS stop reason received:" + reason, null); } } }); } private void setupListeners(final IDISModule module) { // listen for stop, so we can update the UI module.addStopListener(new IDISStopListener() { @Override public void stop(long time, int appId, short eid, short reason) { handleStopMessage(time, appId, eid, reason); } }); // handle the time updates module.addGeneralPDUListener(new IDISGeneralPDUListener() { final long TIME_UNSET = module.convertTime(-1); long time = TIME_UNSET; long lastTime = TIME_UNSET; @Override public void logPDU(Pdu pdu) { long newTime = module.convertTime(pdu.getTimestamp()); if (newTime != time && time != TIME_UNSET) { // are we already updating? if (!updatePending) { // nope, go for it. updatePending = true; Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (_doLiveUpdates) { // first the data model _context.fireUpdate(null, null); // now the time if (time > lastTime) { _context.setNewTime(time); // hey, should we fit to window? if (_fitToDataValue) { _context.zoomToFit(); } lastTime = time; } } updatePending = false; } }); } } time = newTime; } @Override public void complete(String reason) { // reset the time counter time = TIME_UNSET; } }); // ok, Debrief fix listener module.addFixListener(new DebriefFixListener(_context)); module.addDetonationListener(new DebriefDetonationListener(_context)); module.addEventListener(new DebriefEventListener(_context)); module.addFireListener(new DebriefFireListener(_context)); module.addStartResumeListener(new IDISStartResumeListener() { @Override public void add(long time, short eid, long replication) { playHeard(); // also, tell the context about the new replication id _context.setReplicationId(replication); } }); module.addCollisionListener(new DebriefCollisionListener(_context)); } @Override public void createPartControl(Composite parent) { // height of the DIS icon, and the Listen button final int col1Width = 80; Composite composite = new Composite(parent, SWT.NONE); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false); composite.setLayoutData(gd); GridLayout layout = new GridLayout(1, false); layout.marginWidth = 0; layout.marginHeight = 0; composite.setLayout(layout); Composite topRow = new Composite(composite, SWT.NONE); gd = new GridData(SWT.FILL, SWT.FILL, true, false); topRow.setLayoutData(gd); layout = new GridLayout(2, false); layout.marginWidth = 5; layout.marginHeight = 5; topRow.setLayout(layout); Label iconLbl = new Label(topRow, SWT.CENTER); iconLbl.setImage(AbstractUIPlugin.imageDescriptorFromPlugin( "org.mwc.debrief.dis", "icons/50px/dis_icon.png").createImage()); GridData gd3 = new GridData(SWT.CENTER, SWT.CENTER, false, false); gd3.widthHint = col1Width; iconLbl.setLayoutData(gd3); Group localGroup = new Group(topRow, SWT.NONE); localGroup.setText("Local simulator"); gd = new GridData(SWT.FILL, SWT.FILL, true, false); localGroup.setLayoutData(gd); layout = new GridLayout(5, false); layout.marginWidth = 5; layout.marginHeight = 5; localGroup.setLayout(layout); launchButton = new Button(localGroup, SWT.NONE); gd = new GridData(SWT.FILL, SWT.FILL, false, false); gd.widthHint = col1Width; launchButton.setText(LAUNCH_STRING); launchButton.setLayoutData(gd); launchButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doLaunch(); } }); Label label = new Label(localGroup, SWT.NONE); gd = new GridData(GridData.HORIZONTAL_ALIGN_END, GridData.VERTICAL_ALIGN_CENTER, false, true); gd.verticalIndent = 6; label.setLayoutData(gd); label.setText("Control file:"); pathText = new Text(localGroup, SWT.SINGLE | SWT.BORDER); gd = new GridData(SWT.FILL, SWT.FILL, true, false); gd.horizontalSpan = 2; gd.widthHint = 150; pathText.setLayoutData(gd); pathText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { String newText = pathText.getText(); if (newText != null) { IPreferenceStore store = DisActivator.getDefault().getPreferenceStore(); store.setValue(DisActivator.PATH_TO_INPUT_FILE, pathText.getText()); } } }); IPreferenceStore store = DisActivator.getDefault().getPreferenceStore(); pathText.setText(store.getString(DisActivator.PATH_TO_INPUT_FILE)); final Button browseButton = new Button(localGroup, SWT.PUSH); gd = new GridData(SWT.FILL, SWT.FILL, false, false); browseButton.setToolTipText("Browse for control file"); browseButton.setLayoutData(gd); browseButton.setText("..."); browseButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(getSite().getShell(), SWT.SINGLE); String value = pathText.getText(); if (value.trim().length() == 0) { value = Platform.getLocation().toOSString(); } dialog.setFilterPath(value); String result = dialog.open(); if (result == null || result.trim().length() == 0) { return; } pathText.setText(result); } }); // ///////////////////////// // Control // ///////////////////////// Composite controlHolder = new Composite(composite, SWT.NONE); gd = new GridData(SWT.FILL, SWT.FILL, true, false); controlHolder.setLayoutData(gd); layout = new GridLayout(2, false); layout.marginWidth = 5; layout.marginHeight = 5; controlHolder.setLayout(layout); connectButton = new Button(controlHolder, SWT.TOGGLE); connectButton.setText(LISTEN_STRING); gd = new GridData(SWT.FILL, SWT.FILL, false, false); gd.widthHint = col1Width; connectButton.setLayoutData(gd); connectButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (connectButton.getSelection()) { doConnect(); } else { doDisconnect(); } } }); controlButtons = new Group(controlHolder, SWT.NONE); controlButtons.setText("Control"); gd = new GridData(SWT.FILL, SWT.FILL, true, false); controlButtons.setLayoutData(gd); layout = new GridLayout(3, false); layout.marginWidth = 5; layout.marginHeight = 5; controlButtons.setLayout(layout); playButton = new Button(controlButtons, SWT.NONE); playButton.setText("Play"); gd = new GridData(SWT.FILL, SWT.FILL, true, false); playButton.setLayoutData(gd); playButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { sendPlay(); // doPlay(); } }); pauseButton = new Button(controlButtons, SWT.NONE); pauseButton.setText("Pause"); gd = new GridData(SWT.FILL, SWT.FILL, true, false); pauseButton.setLayoutData(gd); pauseButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { _disController.sendPause(); // doPause(); } }); stopButton = new Button(controlButtons, SWT.NONE); stopButton.setText("Stop"); gd = new GridData(SWT.FILL, SWT.FILL, true, false); stopButton.setLayoutData(gd); stopButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { _disController.sendStop(); // doStop(); } }); playButton.setEnabled(false); pauseButton.setEnabled(false); stopButton.setEnabled(false); // ///////////////////////// // SETTINGS // ///////////////////////// Group settingsPanel = new Group(composite, SWT.NONE); settingsPanel.setText("Settings"); gd = new GridData(SWT.FILL, SWT.FILL, true, false); settingsPanel.setLayoutData(gd); layout = new GridLayout(3, false); layout.marginWidth = 5; layout.marginHeight = 5; settingsPanel.setLayout(layout); newPlotButton = new Button(settingsPanel, SWT.CHECK); gd = new GridData(SWT.FILL, SWT.FILL, true, false); newPlotButton.setLayoutData(gd); newPlotButton.setText("New plot per replication"); newPlotButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { _newPlotPerReplication = newPlotButton.getSelection(); } }); newPlotButton.setSelection(_newPlotPerReplication); liveUpdatesButton = new Button(settingsPanel, SWT.CHECK); gd = new GridData(SWT.FILL, SWT.FILL, true, false); liveUpdatesButton.setLayoutData(gd); liveUpdatesButton.setText("Live updates"); liveUpdatesButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { _doLiveUpdates = liveUpdatesButton.getSelection(); // if it's being unselected, do a refresh all if (liveUpdatesButton.getSelection()) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { _context.fireUpdate(null, null); } }); } } }); liveUpdatesButton.setSelection(_doLiveUpdates); final Link link = new Link(settingsPanel, SWT.NONE); gd = new GridData(SWT.END, SWT.FILL, false, false); gd.horizontalSpan = 1; link.setLayoutData(gd); link.setText("<a href=\"id\">Server Prefs</a>"); link.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(link.getShell(), DisPrefs.ID, null, null); dialog.open(); } }); link.setToolTipText("Dis Preferences"); // ///////////////////////// // CHART // ///////////////////////// Composite chartPanel = new Composite(composite, SWT.BORDER); gd = new GridData(SWT.FILL, SWT.FILL, true, true); chartPanel.setLayoutData(gd); layout = new GridLayout(1, false); chartPanel.setLayout(layout); XYDataset dataset = new TimeSeriesCollection(); JFreeChart theChart = ChartFactory.createTimeSeriesChart("Line Chart", "Time", "Hertz", dataset); chartComposite = new ChartComposite(chartPanel, SWT.NONE, theChart, 400, 600, 300, 200, 1800, 1800, true, true, true, true, true, true) { @Override public void mouseUp(MouseEvent event) { super.mouseUp(event); JFreeChart c = getChart(); if (c != null) { c.setNotify(true); // force redraw } } }; fixChartComposite(); gd = new GridData(SWT.FILL, SWT.FILL, true, true); chartComposite.setLayoutData(gd); layout = new GridLayout(1, false); chartComposite.setLayout(layout); theChart.getLegend().setVisible(true); theChart.getLegend().setPosition(RectangleEdge.TOP); theChart.getTitle().setVisible(false); // create our unique originating ID createEntityID(); // ok, and the location commands contributeToActionBars(); // ok, we can go for it initModule(); // ok, sort out the help PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, HELP_CONTEXT); } private void createEntityID() { _ourID = new EntityID(); _ourID.setApplication((short) DisActivator.getDefault() .getPreferenceStore().getInt(DisActivator.APP_ID)); _ourID.setSite((short) DisActivator.getDefault().getPreferenceStore() .getInt(DisActivator.SITE_ID)); } private void fixChartComposite() { Class<ChartComposite> clazz = ChartComposite.class; try { Field field = clazz.getDeclaredField("canvas"); field.setAccessible(true); Object object = field.get(chartComposite); if (object instanceof Canvas) { Canvas canvas = (Canvas) object; GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); canvas.setLayoutData(gd); GridLayout layout = new GridLayout(1, false); canvas.setLayout(layout); } } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e1) { DisActivator.log(e1); } } private void contributeToActionBars() { fitToDataAction = new org.eclipse.jface.action.Action() { public void run() { _fitToDataValue = fitToDataAction.isChecked(); } }; fitToDataAction.setChecked(_fitToDataValue); fitToDataAction.setText("Fit to data"); fitToDataAction .setToolTipText("Zoom the selected plot out to show the full data"); fitToDataAction.setImageDescriptor(CorePlugin .getImageDescriptor("icons/16/fit_to_win.png")); final IActionBars bars = getViewSite().getActionBars(); fillLocalPullDown(bars.getMenuManager()); bars.getToolBarManager().add(fitToDataAction); bars.getToolBarManager().add( CorePlugin.createOpenHelpAction(HELP_CONTEXT, null, this)); } private void fillLocalPullDown(final IMenuManager manager) { manager.add(new Separator()); manager.add(CorePlugin.createOpenHelpAction(HELP_CONTEXT, null, this)); } @Override public void setFocus() { launchButton.setFocus(); } // private void doKill() // { // _simulationRunner.stop(); // // doDisconnect(); // // // tell the perf graph that we've finished // _perfGraph.complete("Stop button"); // // launchButton.setText(LAUNCH_STRING); // // } /** * run the simulator, passing it the specified input file * * @param inputPath */ public void doLaunch(String inputPath) { // ok, start with a "connect", if we have to if (!connectButton.getSelection()) { connectButton.setSelection(true); doConnect(); // doPlay(); } _simulationRunner.run(inputPath); } private void doLaunch() { IPreferenceStore store = DisActivator.getDefault().getPreferenceStore(); String pText = store.getString(DisActivator.PATH_TO_INPUT_FILE); doLaunch(pText); } private void doPlay() { playButton.setEnabled(false); pauseButton.setEnabled(true); stopButton.setEnabled(true); } private void doPause() { playButton.setEnabled(true); pauseButton.setEnabled(false); stopButton.setEnabled(true); } private void doStop() { playButton.setEnabled(true); pauseButton.setEnabled(false); stopButton.setEnabled(false); // tell the perf graph that we've finished _perfGraph.complete("Stop button"); // tell the context that it's complete _context.scenarioComplete(); _perfGraph.complete("Stopped"); } protected void stopReceived() { doStop(); // no, don't disconnect, since we may get another replication // doDisconnect(); // no, don't jump to launch - we may still be running // launchButton.setFocus(); } protected void pauseReceived() { doPause(); } private void doConnect() { // collate the prefs final String app = DisActivator.getDefault().getPreferenceStore().getString( DisActivator.APP_FILTER); final String site = DisActivator.getDefault().getPreferenceStore().getString( DisActivator.SITE_FILTER); final String ex = DisActivator.getDefault().getPreferenceStore().getString( DisActivator.EXERCISE_FILTER); final DISFilters filter = new DISFilters(app, site, ex); _netProvider.attach(filter, _ourID); playButton.setEnabled(true); pauseButton.setEnabled(false); stopButton.setEnabled(false); connectButton.setText("Listening"); } private void doDisconnect() { _netProvider.detach(); playButton.setEnabled(false); pauseButton.setEnabled(false); stopButton.setEnabled(false); connectButton.setSelection(false); connectButton.setText(LISTEN_STRING); // also, stop the graph updating _perfGraph.complete("Disconnected"); } private void playHeard() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { // ok, it's running - update the UI doPlay(); } }); } private void sendPlay() { _disController.sendPlay(); } }
add drop handler for target file
org.mwc.debrief.dis/src/org/mwc/debrief/dis/ui/views/DisListenerView.java
add drop handler for target file
<ide><path>rg.mwc.debrief.dis/src/org/mwc/debrief/dis/ui/views/DisListenerView.java <ide> <ide> import java.lang.reflect.Field; <ide> <add>import org.eclipse.core.resources.IResource; <ide> import org.eclipse.core.runtime.Platform; <ide> import org.eclipse.core.runtime.Status; <ide> import org.eclipse.core.runtime.jobs.Job; <ide> import org.eclipse.jface.preference.IPreferenceStore; <ide> import org.eclipse.jface.preference.PreferenceDialog; <ide> import org.eclipse.swt.SWT; <add>import org.eclipse.swt.dnd.DND; <add>import org.eclipse.swt.dnd.DropTarget; <add>import org.eclipse.swt.dnd.DropTargetAdapter; <add>import org.eclipse.swt.dnd.DropTargetEvent; <add>import org.eclipse.swt.dnd.Transfer; <ide> import org.eclipse.swt.events.ModifyEvent; <ide> import org.eclipse.swt.events.ModifyListener; <ide> import org.eclipse.swt.events.MouseEvent; <ide> import org.eclipse.ui.IWorkbenchWindow; <ide> import org.eclipse.ui.PlatformUI; <ide> import org.eclipse.ui.dialogs.PreferencesUtil; <add>import org.eclipse.ui.part.ResourceTransfer; <ide> import org.eclipse.ui.part.ViewPart; <ide> import org.eclipse.ui.plugin.AbstractUIPlugin; <ide> import org.jfree.chart.ChartFactory; <ide> { <ide> <ide> public static final String HELP_CONTEXT = "org.mwc.debrief.help.DISSupport"; <add> <ide> private Button connectButton; <ide> private Button playButton; <ide> private Button pauseButton; <ide> <ide> // ok, sort out the help <ide> PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, HELP_CONTEXT); <add> <add> addDropSupport(); <add> } <add> <add> private void addDropSupport() <add> { <add> int operations = <add> DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK | DND.DROP_DEFAULT; <add> DropTarget target = new DropTarget(pathText, operations); <add> <add> Transfer[] types = new Transfer[] <add> {ResourceTransfer.getInstance()}; <add> target.setTransfer(types); <add> target.addDropListener(new DropTargetAdapter() <add> { <add> @Override <add> public void drop(DropTargetEvent event) <add> { <add> super.drop(event); <add> Object data = event.data; <add> IResource resource = null; <add> if (data.getClass().isArray() && ((Object[]) data).length > 0) <add> { <add> resource = (IResource) ((Object[]) data)[0]; <add> } <add> else if (data instanceof IResource) <add> { <add> resource = (IResource) data; <add> } <add> <add> if (resource != null) <add> { <add> String fileExtension = resource.getFileExtension(); <add> if (fileExtension.equals("inp")) <add> { <add> pathText.setText(resource.getLocation().toOSString()); <add> } <add> } <add> event.detail = 1; <add> } <add> }); <ide> } <ide> <ide> private void createEntityID()
Java
apache-2.0
d42ae4310354875d86486067d7a6250b7d914c6c
0
apache/clerezza,apache/clerezza
/* * 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.clerezza.platform.language; import java.io.IOException; import java.lang.ref.SoftReference; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.locks.Lock; import org.apache.clerezza.platform.Constants; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.clerezza.rdf.core.BNode; import org.apache.clerezza.rdf.core.Graph; import org.apache.clerezza.rdf.core.Language; import org.osgi.service.component.ComponentContext; import org.apache.clerezza.rdf.core.NonLiteral; import org.apache.clerezza.rdf.core.PlainLiteral; import org.apache.clerezza.rdf.core.Resource; import org.apache.clerezza.rdf.core.Triple; import org.apache.clerezza.rdf.core.UriRef; import org.apache.clerezza.rdf.core.access.LockableMGraph; import org.apache.clerezza.rdf.core.access.TcManager; import org.apache.clerezza.rdf.core.impl.TripleImpl; import org.apache.clerezza.rdf.core.serializedform.ParsingProvider; import org.apache.clerezza.rdf.core.serializedform.SupportedFormat; import org.apache.clerezza.rdf.ontologies.LINGVOJ; import org.apache.clerezza.rdf.ontologies.PLATFORM; import org.apache.clerezza.rdf.ontologies.RDF; import org.apache.clerezza.rdf.ontologies.RDFS; import org.apache.clerezza.rdf.utils.GraphNode; import org.apache.clerezza.rdf.utils.RdfList; /** * This class provides a OSGi service for managing languages in the Clerezza * platform. * * @author mir */ @Component(immediate=true, enabled= true) @Service(LanguageService.class) public class LanguageService { @Reference private TcManager tcManager; /** * this is linked to the system-graph, accessing requires respective * permission */ private List<Resource> languageList; /** * no permission on the system graph required to access this */ private List<Resource> languageListCache; private static final String PARSER_FILTER = "(supportedFormat=" + SupportedFormat.RDF_XML +")"; @Reference(target=PARSER_FILTER) private ParsingProvider parser; private SoftReference<Graph> softLingvojGraph = new SoftReference<Graph>(null); private LockableMGraph getSystemGraph() { return tcManager.getMGraph(Constants.SYSTEM_GRAPH_URI); } private LockableMGraph getConfigGraph() { return tcManager.getMGraph(Constants.CONFIG_GRAPH_URI); } /** * Returns a <code>List</code> of <code>LanguageDescription</code>s which * describe the languages which are supported by the platform. The first * entry describes the default language af the platform. * @return a list containing all language descriptions. */ public List<LanguageDescription> getLanguages() { List<LanguageDescription> langList = new ArrayList<LanguageDescription>(); Iterator<Resource> languages = languageListCache.iterator(); while (languages.hasNext()) { UriRef language = (UriRef) languages.next(); langList.add( new LanguageDescription(new GraphNode(language, getConfigGraph()))); } return langList; } /** * Returns the <code>LanguageDescription</code> of the default language * of the platform. * @return the language description of the default language. */ public LanguageDescription getDefaultLanguage() { return new LanguageDescription( new GraphNode(languageListCache.get(0), getConfigGraph())); } /** * Returns a set containg all language uris which are in the * <http://www.lingvoj.org/lingvoj> graph which is included in this bundle. * @return a set containing all language uris. This uris can be used to * add the language to Clerezza over the addLanguage()-method in this class. */ public Set<UriRef> getAllLanguages() { Set<UriRef> result = new HashSet<UriRef>(); Graph lingvojGraph = getLingvojGraph(); Iterator<Triple> languages = lingvojGraph.filter(null, RDFS.isDefinedBy, null); while (languages.hasNext()) { UriRef languageUri = (UriRef) languages.next().getSubject(); result.add(languageUri); } return result; } /** * Returns a language uri of a language which has a label containing the * specified languageName. The label itself is in the language specified through * inLanguage. If inLanguage is null, then all labels of a language of searched. * If no language was found in the <http://www.lingvoj.org/lingvoj> * graph, then null is returned. The returned uri can be used to * add the language to Clerezza over the addLanguage()-method in this class. * @return a language uris */ public UriRef getLanguage(String languageName, Language inLanguage) { Graph lingvojGraph = getLingvojGraph(); Iterator<Triple> languages = lingvojGraph.filter(null, RDFS.isDefinedBy, null); while (languages.hasNext()) { GraphNode languageNode = new GraphNode((UriRef) languages.next().getSubject(), lingvojGraph); Iterator<Resource> labels = languageNode.getObjects(RDFS.label); while (labels.hasNext()) { PlainLiteral label = (PlainLiteral) labels.next(); if (label.getLanguage().equals(inLanguage) || inLanguage == null) { if (label.getLexicalForm().contains(languageName)) { return (UriRef) languageNode.getNode(); } } } } return null; } /** * Adds the language specified through languageUri to the Clerezza * platform. The languageUri has to be a <http://www.lingvoj.org/ontology#Lingvo> * according to the graph <http://www.lingvoj.org/lingvoj> included in this * bundle., e.g. "http://www.lingvoj.org/lang/de" adds German. * The uri is added to the system graph and its context to the conent graph. * The context added is the context provided by lingvoj.rdf. * @param languageUri The language uri which specifies the language to be * added to the platform. */ public void addLanguage(UriRef languageUri) { if (!languageListCache.contains(languageUri)) { if(languageList.add(languageUri)) { addToConfigGraph(languageUri); } languageListCache.add(languageUri); } } private void synchronizeContentGraph() { for (Resource resource : languageListCache) { addToConfigGraph((UriRef)resource); } } /** * Adds the langugae information for the specified language to the content * graph, if the content-graph contains no LINGVOJ.iso1 property for that suject. * * @param languageUri */ private void addToConfigGraph(NonLiteral languageUri) { LockableMGraph configGraph = getConfigGraph(); Lock writeLock = configGraph.getLock().writeLock(); writeLock.lock(); try { if (!configGraph.filter(languageUri, LINGVOJ.iso1, null).hasNext()) { configGraph.addAll(getLanguageContext(languageUri)); } } finally { writeLock.unlock(); } } private Graph getLanguageContext(NonLiteral langUri) { Graph lingvojRdf = getLingvojGraph(); GraphNode languageNode = new GraphNode(langUri, lingvojRdf); return languageNode.getNodeContext(); } private Graph getLingvojGraph() { Graph lingvojGraph = softLingvojGraph.get(); if (lingvojGraph != null) { return lingvojGraph; } URL config = getClass().getResource("lingvoj.rdf"); if (config == null) { throw new RuntimeException("no file found"); } try { lingvojGraph = parser.parse(config.openStream(), SupportedFormat.RDF_XML, null); softLingvojGraph = new SoftReference<Graph>(lingvojGraph); return lingvojGraph; } catch (IOException ex) { throw new RuntimeException(ex); } } /** * The activate method is called when SCR activates the component configuration. * * @param componentContext */ protected void activate(ComponentContext componentContext) { final RdfList rdfList = new RdfList(getListNode(), getSystemGraph()); languageList = Collections.synchronizedList(rdfList); //access to languages should not require access to system graph, //so copying the resources to an ArrayList languageListCache = Collections.synchronizedList( new ArrayList<Resource>(rdfList)); if (languageListCache.size() == 0) { addLanguage(new UriRef("http://www.lingvoj.org/lang/en")); } //this is to make sure the content graph contains the relevant data synchronizeContentGraph(); } private NonLiteral getListNode() { NonLiteral instance = null; LockableMGraph systemGraph = getSystemGraph(); Lock readLock = systemGraph.getLock().readLock(); readLock.lock(); try { Iterator<Triple> instances = systemGraph.filter(null, RDF.type, PLATFORM.Instance); if (!instances.hasNext()) { throw new RuntimeException("No Platform:Instance in system graph."); } instance = instances.next().getSubject(); Iterator<Triple> langListIter = systemGraph.filter(instance, PLATFORM.languages, null); if (langListIter.hasNext()) { return (NonLiteral) langListIter.next().getObject(); } } finally { readLock.unlock(); } BNode listNode = new BNode(); systemGraph.add(new TripleImpl(instance, PLATFORM.languages, listNode)); return listNode; } }
org.apache.clerezza.parent/org.apache.clerezza.platform.language/org.apache.clerezza.platform.language.core/src/main/java/org/apache/clerezza/platform/language/LanguageService.java
/* * 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.clerezza.platform.language; import java.io.IOException; import java.lang.ref.SoftReference; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.locks.Lock; import org.apache.clerezza.platform.Constants; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.clerezza.rdf.core.BNode; import org.apache.clerezza.rdf.core.Graph; import org.apache.clerezza.rdf.core.Language; import org.osgi.service.component.ComponentContext; import org.apache.clerezza.rdf.core.NonLiteral; import org.apache.clerezza.rdf.core.PlainLiteral; import org.apache.clerezza.rdf.core.Resource; import org.apache.clerezza.rdf.core.Triple; import org.apache.clerezza.rdf.core.UriRef; import org.apache.clerezza.rdf.core.access.LockableMGraph; import org.apache.clerezza.rdf.core.access.TcManager; import org.apache.clerezza.rdf.core.impl.TripleImpl; import org.apache.clerezza.rdf.core.serializedform.ParsingProvider; import org.apache.clerezza.rdf.core.serializedform.SupportedFormat; import org.apache.clerezza.rdf.ontologies.LINGVOJ; import org.apache.clerezza.rdf.ontologies.PLATFORM; import org.apache.clerezza.rdf.ontologies.RDF; import org.apache.clerezza.rdf.ontologies.RDFS; import org.apache.clerezza.rdf.utils.GraphNode; import org.apache.clerezza.rdf.utils.RdfList; /** * This class provides a OSGi service for managing languages in the Clerezza * platform. * * @author mir */ @Component(immediate=true, enabled= true) @Service(LanguageService.class) public class LanguageService { @Reference private TcManager tcManager; /** * this is linked to the system-graph, accessing requires respective * permission */ private List<Resource> languageList; /** * no permission on the system graph required to access this */ private List<Resource> languageListCache; private static final String PARSER_FILTER = "(supportedFormat=" + SupportedFormat.RDF_XML +")"; @Reference(target=PARSER_FILTER) private ParsingProvider parser; private SoftReference<Graph> softLingvojGraph = new SoftReference<Graph>(null); private LockableMGraph getSystemGraph() { return tcManager.getMGraph(Constants.SYSTEM_GRAPH_URI); } private LockableMGraph getConfigGraph() { return tcManager.getMGraph(Constants.CONFIG_GRAPH_URI); } /** * Returns a <code>List</code> of <code>LanguageDescription</code>s which * describe the languages which are supported by the platform. The first * entry describes the default language af the platform. * @return a list containing all language descriptions. */ public List<LanguageDescription> getLanguages() { List<LanguageDescription> langList = new ArrayList<LanguageDescription>(); Iterator<Resource> languages = languageListCache.iterator(); while (languages.hasNext()) { UriRef language = (UriRef) languages.next(); langList.add( new LanguageDescription(new GraphNode(language, getConfigGraph()))); } return langList; } /** * Returns the <code>LanguageDescription</code> of the default language * of the platform. * @return the language description of the default language. */ public LanguageDescription getDefaultLanguage() { return new LanguageDescription( new GraphNode(languageListCache.get(0), getConfigGraph())); } /** * Returns a set containg all language uris which are in the * <http://www.lingvoj.org/lingvoj> graph which is included in this bundle. * @return a set containing all language uris. This uris can be used to * add the language to Clerezza over the addLanguage()-method in this class. */ public Set<UriRef> getAllLanguages() { Set<UriRef> result = new HashSet<UriRef>(); Graph lingvojGraph = getLingvojGraph(); Iterator<Triple> languages = lingvojGraph.filter(null, RDFS.isDefinedBy, null); while (languages.hasNext()) { UriRef languageUri = (UriRef) languages.next().getSubject(); result.add(languageUri); } return result; } /** * Returns a language uri of a language which has a label containing the * specified languageName. The label itself is in the language specified through * inLanguage. If inLanguage is null, then all labels of a language of searched. * If no language was found in the <http://www.lingvoj.org/lingvoj> * graph, then null is returned. The returned uri can be used to * add the language to Clerezza over the addLanguage()-method in this class. * @return a language uris */ public UriRef getLanguage(String languageName, Language inLanguage) { Graph lingvojGraph = getLingvojGraph(); Iterator<Triple> languages = lingvojGraph.filter(null, RDFS.isDefinedBy, null); while (languages.hasNext()) { GraphNode languageNode = new GraphNode((UriRef) languages.next().getSubject(), lingvojGraph); Iterator<Resource> labels = languageNode.getObjects(RDFS.label); while (labels.hasNext()) { PlainLiteral label = (PlainLiteral) labels.next(); if (label.getLanguage().equals(inLanguage) || inLanguage == null) { if (label.getLexicalForm().contains(languageName)) { return (UriRef) languageNode.getNode(); } } } } return null; } /** * Adds the language specified through languageUri to the Clerezza * platform. The languageUri has to be a <http://www.lingvoj.org/ontology#Lingvo> * according to the graph <http://www.lingvoj.org/lingvoj> included in this * bundle., e.g. "http://www.lingvoj.org/lang/de" adds German. * The uri is added to the system graph and its context to the conent graph. * The context added is the context provided by lingvoj.rdf. * @param languageUri The language uri which specifies the language to be * added to the platform. */ public void addLanguage(UriRef languageUri) { if (!languageListCache.contains(languageUri)) { if(languageList.add(languageUri)) { addToConfigGraph(languageUri); } languageListCache.add(languageUri); } } private void synchronizeContentGraph() { for (Resource resource : languageListCache) { addToConfigGraph((UriRef)resource); } } /** * Adds the langugae information for the specified language to the content * graph, if the content-graph contains no LINGVOJ.iso1 property for that suject. * * @param languageUri */ private void addToConfigGraph(NonLiteral languageUri) { LockableMGraph configGraph = getConfigGraph(); Lock writeLock = configGraph.getLock().writeLock(); writeLock.lock(); try { if (!configGraph.filter(languageUri, LINGVOJ.iso1, null).hasNext()) { configGraph.addAll(getLanguageContext(languageUri)); } } finally { writeLock.unlock(); } } private Graph getLanguageContext(NonLiteral langUri) { Graph lingvojRdf = getLingvojGraph(); GraphNode languageNode = new GraphNode(langUri, lingvojRdf); return languageNode.getNodeContext(); } private Graph getLingvojGraph() { Graph lingvojGraph = softLingvojGraph.get(); if (lingvojGraph != null) { return lingvojGraph; } URL config = getClass().getResource("lingvoj.rdf"); if (config == null) { throw new RuntimeException("no file found"); } try { lingvojGraph = parser.parse(config.openStream(), SupportedFormat.RDF_XML, null); softLingvojGraph = new SoftReference<Graph>(lingvojGraph); return lingvojGraph; } catch (IOException ex) { throw new RuntimeException(ex); } } /** * The activate method is called when SCR activates the component configuration. * * @param componentContext */ protected void activate(ComponentContext componentContext) { final RdfList rdfList = new RdfList(getListNode(), getSystemGraph()); languageList = Collections.synchronizedList(rdfList); //access to languages should not require access to system graph, //so copying the resources to an ArrayList languageListCache = Collections.synchronizedList( new ArrayList<Resource>(rdfList)); if (languageListCache.size() == 0) { addLanguage(new UriRef("http://www.lingvoj.org/lang/en")); } //this is to make sure the content graph contains the relevant data synchronizeContentGraph(); } private NonLiteral getListNode() { NonLiteral instance = null; LockableMGraph systemGraph = getSystemGraph(); Lock readLock = systemGraph.getLock().readLock(); readLock.lock(); try { Iterator<Triple> instances = systemGraph.filter(null, RDF.type, PLATFORM.Instance); if (!instances.hasNext()) { throw new RuntimeException("No Platform:Instance in system graph."); } instance = instances.next().getSubject(); Iterator<Triple> langListIter = systemGraph.filter(instance, PLATFORM.languages, null); if (langListIter.hasNext()) { return (NonLiteral) langListIter.next().getObject(); } } finally { readLock.unlock(); } BNode listNode = new BNode(); Lock writeLock = systemGraph.getLock().writeLock(); writeLock.lock(); try { systemGraph.add(new TripleImpl(instance, PLATFORM.languages, listNode)); } finally { writeLock.unlock(); } return listNode; } }
CLEREZZA-316: removed superfluous write lock git-svn-id: 38b6077511a9281ad6e07629729fbb76b9a63fb8@1005074 13f79535-47bb-0310-9956-ffa450edef68
org.apache.clerezza.parent/org.apache.clerezza.platform.language/org.apache.clerezza.platform.language.core/src/main/java/org/apache/clerezza/platform/language/LanguageService.java
CLEREZZA-316: removed superfluous write lock
<ide><path>rg.apache.clerezza.parent/org.apache.clerezza.platform.language/org.apache.clerezza.platform.language.core/src/main/java/org/apache/clerezza/platform/language/LanguageService.java <ide> readLock.unlock(); <ide> } <ide> BNode listNode = new BNode(); <del> Lock writeLock = systemGraph.getLock().writeLock(); <del> writeLock.lock(); <del> try { <del> systemGraph.add(new TripleImpl(instance, PLATFORM.languages, listNode)); <del> } finally { <del> writeLock.unlock(); <del> } <add> systemGraph.add(new TripleImpl(instance, PLATFORM.languages, listNode)); <ide> return listNode; <ide> } <ide> }
JavaScript
cc0-1.0
e6d836ea69e30dfe11fc6c50d2b04ea1f6658cf2
0
awolfe76/hmda-viz-prototype,cfpb/hmda-viz-prototype,Kibrael/hmda-viz-prototype,Kibrael/hmda-viz-prototype,awolfe76/hmda-viz-prototype,cfpb/hmda-viz-prototype,Kibrael/hmda-viz-prototype
/* get data for each select input call the corresponding mustache template and fill the input set the first option as selected */ function getUIData() { 'use strict'; $('select').each(function() { var selectID = this.id; // get <select> data $.get(selectID + '.json', function(data) { // get template $.get('/hmda-viz-prototype/templates/selects.html', function(templates) { var template = $(templates).filter('#' + selectID).html(); var html = Mustache.to_html(template, data); $('#' + selectID).html(html); // set first option as selected $('#' + selectID + ' option:first').attr('selected', 'selected'); }); }); }); } /* get data for the table call the corresponding mustache template and fill the input set the first option as selected */ function getTableData(table) { 'use strict'; // get <table> data $.get(table + '.json', function(data) { // get template $.get('/hmda-viz-prototype/templates/' + table + '.html', function(templates) { var template = $(templates).filter('#' + table).html(); var html = Mustache.to_html(template, data); $('#' + table).html(html); }); }); } /* update the button link on the form pages */ function setLink() { 'use strict'; var newURL = ''; // needed on first page, year and state make the url $('select').each(function() { newURL += $(this).val().replace(' ', '-').toLowerCase() + '/'; }); $('.js-btn').attr('href', newURL); } $( document ).ready(function() { 'use strict'; jQuery.ajaxSetup({async:false}); // no async! var urlPath = window.location.pathname.split('/'); var path = urlPath[urlPath.length-2]; if (urlPath.length === 8) { getTableData(path); } else { // fill the select inputs getUIData(); // initial set link setLink(); // call setlink when new choice is made $('select').click(function() { setLink(); }); } });
src/static/js/app.js
// get data for each select input // call the corresponding mustache template and fill the input // set the first option as selected function getUIData() { 'use strict'; $('select').each(function() { var selectID = this.id; $.get(selectID + '.json', function(data) { $.get('/hmda-viz-prototype/templates/selects.html', function(templates) { var template = $(templates).filter('#' + selectID).html(); var html = Mustache.to_html(template, data); $('#' + selectID).html(html); $('#' + selectID + ' option:first').attr('selected', 'selected'); }); }); }); } function getTableData(table) { 'use strict'; $.get(table + '.json', function(data) { $.get('/hmda-viz-prototype/templates/' + table + '.html', function(templates) { var template = $(templates).filter('#' + table).html(); var html = Mustache.to_html(template, data); $('#' + table).html(html); }); }); } // update the button link function setLink() { 'use strict'; var newURL = ''; // needed on first page, year and state make the url $('select').each(function() { newURL += $(this).val().replace(' ', '-').toLowerCase() + '/'; }); $('.js-btn').attr('href', newURL); } $( document ).ready(function() { 'use strict'; jQuery.ajaxSetup({async:false}); // no async! var urlPath = window.location.pathname.split('/'); var path = urlPath[urlPath.length-2]; if (urlPath.length === 8) { getTableData(path); } else { // fill the select inputs getUIData(); // initial set link setLink(); // call setlink when new choice is made $('select').click(function() { setLink(); }); } });
comments
src/static/js/app.js
comments
<ide><path>rc/static/js/app.js <del>// get data for each select input <del>// call the corresponding mustache template and fill the input <del>// set the first option as selected <add>/* <add>get data for each select input <add>call the corresponding mustache template and fill the input <add>set the first option as selected <add>*/ <ide> function getUIData() { <ide> 'use strict'; <ide> $('select').each(function() { <ide> var selectID = this.id; <add> // get <select> data <ide> $.get(selectID + '.json', function(data) { <add> // get template <ide> $.get('/hmda-viz-prototype/templates/selects.html', function(templates) { <ide> var template = $(templates).filter('#' + selectID).html(); <ide> var html = Mustache.to_html(template, data); <ide> $('#' + selectID).html(html); <add> // set first option as selected <ide> $('#' + selectID + ' option:first').attr('selected', 'selected'); <ide> }); <ide> }); <ide> }); <ide> } <ide> <add>/* <add>get data for the table <add>call the corresponding mustache template and fill the input <add>set the first option as selected <add>*/ <ide> function getTableData(table) { <ide> 'use strict'; <add> // get <table> data <ide> $.get(table + '.json', function(data) { <add> // get template <ide> $.get('/hmda-viz-prototype/templates/' + table + '.html', function(templates) { <ide> var template = $(templates).filter('#' + table).html(); <ide> var html = Mustache.to_html(template, data); <ide> }); <ide> } <ide> <del>// update the button link <add>/* <add>update the button link on the form pages <add>*/ <ide> function setLink() { <ide> 'use strict'; <ide> var newURL = ''; // needed on first page, year and state make the url
Java
mpl-2.0
9892cfc57ce078c38b5036fb50c2c0a777062d36
0
GUBotDev/XBeeJavaLibrary,brucetsao/XBeeJavaLibrary,digidotcom/XBeeJavaLibrary
/** * Copyright (c) 2014 Digi International Inc., * All rights not expressly granted are reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. * * Digi International Inc. 11001 Bren Road East, Minnetonka, MN 55343 * ======================================================================= */ package com.digi.xbee.api.connection; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.digi.xbee.api.exceptions.InvalidPacketException; import com.digi.xbee.api.listeners.IPacketReceiveListener; import com.digi.xbee.api.listeners.ISerialDataReceiveListener; import com.digi.xbee.api.models.SpecialByte; import com.digi.xbee.api.models.OperatingMode; import com.digi.xbee.api.packet.XBeeAPIPacket; import com.digi.xbee.api.packet.APIFrameType; import com.digi.xbee.api.packet.XBeePacket; import com.digi.xbee.api.packet.XBeePacketParser; import com.digi.xbee.api.packet.common.ReceivePacket; import com.digi.xbee.api.packet.raw.RX16Packet; import com.digi.xbee.api.packet.raw.RX64Packet; import com.digi.xbee.api.utils.ByteUtils; import com.digi.xbee.api.utils.HexUtils; /** * Thread that constantly reads data from the input stream. * * Depending on the working mode, read data is notified as is * to the subscribed listeners or is parsed to a packet using the * packet parser and then notified to subscribed listeners. */ public class DataReader extends Thread { // Constants private final static int ALL_FRAME_IDS = 99999; private final static int MAXIMUM_PARALLEL_LISTENER_THREADS = 20; // Variables private boolean running = false; private IConnectionInterface connectionInterface; private volatile OperatingMode mode; private ArrayList<ISerialDataReceiveListener> serialDataReceiveListeners = new ArrayList<ISerialDataReceiveListener>(); // The packetReceiveListeners requires to be a HashMap with an associated integer. The integer is used to determine // the frame ID of the packet that should be received. When it is 99999 (ALL_FRAME_IDS), all the packets will be handled. private HashMap<IPacketReceiveListener, Integer> packetReceiveListeners = new HashMap<IPacketReceiveListener, Integer>(); private Logger logger; /** * Class constructor. Instances a new DataReader object for the given interface. * * @param connectionInterface Connection interface to read from. * @param mode XBee operating mode. * * @throws NullPointerException if {@code connectionInterface == null} or * {@code mode == null}. */ public DataReader(IConnectionInterface connectionInterface, OperatingMode mode) { if (connectionInterface == null) throw new NullPointerException("Connection interface cannot be null."); if (mode == null) throw new NullPointerException("Operating mode cannot be null."); this.connectionInterface = connectionInterface; this.mode = mode; this.logger = LoggerFactory.getLogger(DataReader.class); } /** * Sets the mode of the reader. * * @param mode XBee mode * * @throws NullPointerException if {@code mode == null}. */ public void setXBeeReaderMode(OperatingMode mode) { if (mode == null) throw new NullPointerException("Operating mode cannot be null."); this.mode = mode; } /** * Adds the given serial data receive listener to the list of listeners to be notified when * serial data is received. * * @param listener Listener to be notified when new serial data is received. */ public void addSerialDatatReceiveListener(ISerialDataReceiveListener listener) { synchronized (serialDataReceiveListeners) { if (!serialDataReceiveListeners.contains(listener)) serialDataReceiveListeners.add(listener); } } /** * Removes the given serial data receive listener from the list of serial data * receive listeners. * * @param listener Serial data receive listener to remove. */ public void removeSerialDataReceiveListener(ISerialDataReceiveListener listener) { synchronized (serialDataReceiveListeners) { if (serialDataReceiveListeners.contains(listener)) serialDataReceiveListeners.remove(listener); } } /** * Adds the given packet receive listener to the list of listeners to be notified when a * packet is received. * * @param listener Listener to be notified when a packet is received. */ public void addPacketReceiveListener(IPacketReceiveListener listener) { addPacketReceiveListener(listener, ALL_FRAME_IDS); } /** * Adds the given packet receive listener to the list of listeners to be notified when a * packet is received. * * @param listener Listener to be notified when a packet is received. * @param frameID Frame ID for which this listener should be notified and removed after. * Using {@link #ALL_FRAME_IDS} this listener will be notified always and * will be removed only by user request. */ public void addPacketReceiveListener(IPacketReceiveListener listener, int frameID) { synchronized (packetReceiveListeners) { if (!packetReceiveListeners.containsKey(listener)) packetReceiveListeners.put(listener, frameID); } } /** * Removes the given packet receive listener from the list of XBee packet * receive listeners. * * @param listener Packet receive listener to remove. */ public void removePacketReceiveListener(IPacketReceiveListener listener) { synchronized (packetReceiveListeners) { if (packetReceiveListeners.containsKey(listener)) packetReceiveListeners.remove(listener); } } /* * (non-Javadoc) * @see java.lang.Thread#run() */ public void run() { logger.debug(connectionInterface.toString() + "Data reader started."); running = true; try { synchronized (connectionInterface) { connectionInterface.wait(); } while (running) { if (!running) break; if (connectionInterface.getInputStream() != null) { switch (mode) { case AT: break; case API: case API_ESCAPE: int headerByte = connectionInterface.getInputStream().read(); // If it is packet header parse the packet, if not discard this byte and continue. if (headerByte == SpecialByte.HEADER_BYTE.getValue()) { XBeePacketParser parser = new XBeePacketParser(connectionInterface.getInputStream(), mode); try { XBeePacket packet = parser.parsePacket(); packetReceived(packet); } catch (InvalidPacketException e) { logger.error("Error parsing the API packet.", e); } } break; default: break; } } else if (connectionInterface.getInputStream() == null) break; if (connectionInterface.getInputStream() == null) break; else if (connectionInterface.getInputStream().available() > 0) continue; synchronized (connectionInterface) { connectionInterface.wait(); } } } catch (IOException e) { logger.error("Error reading from input stream.", e); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } catch (IllegalStateException e) { logger.error(e.getMessage(), e); } finally { if (running) { running = false; if (connectionInterface != null && connectionInterface.isOpen()) connectionInterface.close(); } } } /** * A packet was received, dispatch it to the corresponding listener(s). * * @param packet The received packet. */ private void packetReceived(XBeePacket packet) { // Notify that a packet has been received to the corresponding listeners. notifyPacketReceived(packet); // Check if the packet is an API packet. if (!(packet instanceof XBeeAPIPacket)) return; // Get the API packet type. XBeeAPIPacket apiPacket = (XBeeAPIPacket)packet; APIFrameType apiType = apiPacket.getFrameType(); if (apiType == null) return; String address = null; byte[] data = null; boolean isBroadcastData = false; switch(apiType) { case RECEIVE_PACKET: address = ((ReceivePacket)apiPacket).get64bitAddress().toString(); data = ((ReceivePacket)apiPacket).getReceivedData(); isBroadcastData = ByteUtils.isBitEnabled(((ReceivePacket)apiPacket).getReceiveOptions(), 1); break; case RX_64: address = ((RX64Packet)apiPacket).getSourceAddress().toString(); data = ((RX64Packet)apiPacket).getReceivedData(); if (ByteUtils.isBitEnabled(((RX64Packet)apiPacket).getReceiveOptions(), 1) || ByteUtils.isBitEnabled(((RX64Packet)apiPacket).getReceiveOptions(), 2)) isBroadcastData = true; break; case RX_16: address = ((RX16Packet)apiPacket).getSourceAddress().toString(); data = ((RX16Packet)apiPacket).getReceivedData(); if (ByteUtils.isBitEnabled(((RX16Packet)apiPacket).getReceiveOptions(), 1) || ByteUtils.isBitEnabled(((RX16Packet)apiPacket).getReceiveOptions(), 2)) isBroadcastData = true; break; default: break; } // Notify that serial data was received to the corresponding listeners. if (address != null && data != null) notifySerialDataReceived(address, data, isBroadcastData); } /** * Notifies subscribed serial data receive listeners that serial data has been received. * * @param address The address of the node that sent the data. * @param data The received data. * @param isBroadcastData Indicates whether or not the data was sent via broadcast to execute * the corresponding broadcast callback. */ private void notifySerialDataReceived(final String address, final byte[] data, final boolean isBroadcastData) { if (isBroadcastData) logger.info(connectionInterface.toString() + "Broadcast serial data received from {} >> {}.", address, HexUtils.prettyHexString(data)); else logger.info(connectionInterface.toString() + "Serial data received from {} >> {}.", address, HexUtils.prettyHexString(data)); try { synchronized (serialDataReceiveListeners) { ScheduledExecutorService executor = Executors.newScheduledThreadPool(Math.min(MAXIMUM_PARALLEL_LISTENER_THREADS, serialDataReceiveListeners.size())); for (final ISerialDataReceiveListener listener:serialDataReceiveListeners) { executor.execute(new Runnable() { public void run() { /* Synchronize the listener so it is not called twice. That is, let the listener to finish its job. By synchronizing the listener also unicast and broadcast data reception are synchronized, that is, while unicast data is being processed, broadcast data is waiting till it finishes, and the other way around. */ synchronized (listener) { if (isBroadcastData) listener.broadcastSerialDataReceived(address, data); else listener.serialDataReceived(address, data); } } }); } executor.shutdown(); } } catch (Exception e) { logger.error(e.getMessage(), e); } } /** * Notifies subscribed packet listeners that a packet has been received. * * @param packet The received packet. */ private void notifyPacketReceived(final XBeePacket packet) { logger.debug(connectionInterface.toString() + "Packet received: \n{}", packet.toPrettyString()); try { synchronized (packetReceiveListeners) { final ArrayList<IPacketReceiveListener> removeListeners = new ArrayList<IPacketReceiveListener>(); ScheduledExecutorService executor = Executors.newScheduledThreadPool(Math.min(MAXIMUM_PARALLEL_LISTENER_THREADS, packetReceiveListeners.size())); for (final IPacketReceiveListener listener:packetReceiveListeners.keySet()) { executor.execute(new Runnable() { public void run() { if (packetReceiveListeners.get(listener) == ALL_FRAME_IDS) listener.packetReceived(packet); else if (((XBeeAPIPacket)packet).needsAPIFrameID() && ((XBeeAPIPacket)packet).getFrameID() == packetReceiveListeners.get(listener)) { listener.packetReceived(packet); removeListeners.add(listener); } } }); } executor.shutdown(); // Remove required listeners. for (IPacketReceiveListener listener:removeListeners) packetReceiveListeners.remove(listener); } } catch (Exception e) { logger.error(e.getMessage(), e); } } /** * Returns whether the Data reader is running or not. * * @return True if the Data reader is running, false otherwise. */ public boolean isRunning() { return running; } /** * Stops the Data reader thread. */ public void stopReader() { running = false; synchronized (connectionInterface) { connectionInterface.notify(); } logger.debug(connectionInterface.toString() + "Data reader stopped."); } }
src/com/digi/xbee/api/connection/DataReader.java
/** * Copyright (c) 2014 Digi International Inc., * All rights not expressly granted are reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. * * Digi International Inc. 11001 Bren Road East, Minnetonka, MN 55343 * ======================================================================= */ package com.digi.xbee.api.connection; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.digi.xbee.api.exceptions.InvalidPacketException; import com.digi.xbee.api.listeners.IPacketReceiveListener; import com.digi.xbee.api.listeners.ISerialDataReceiveListener; import com.digi.xbee.api.models.SpecialByte; import com.digi.xbee.api.models.OperatingMode; import com.digi.xbee.api.packet.XBeeAPIPacket; import com.digi.xbee.api.packet.APIFrameType; import com.digi.xbee.api.packet.XBeePacket; import com.digi.xbee.api.packet.XBeePacketParser; import com.digi.xbee.api.packet.common.ReceivePacket; import com.digi.xbee.api.packet.raw.RX16Packet; import com.digi.xbee.api.packet.raw.RX64Packet; import com.digi.xbee.api.utils.ByteUtils; import com.digi.xbee.api.utils.HexUtils; /** * Thread that constantly reads data from the input stream. * * Depending on the working mode, read data is notified as is * to the subscribed listeners or is parsed to a packet using the * packet parser and then notified to subscribed listeners. */ public class DataReader extends Thread { // Constants private final static int ALL_FRAME_IDS = 99999; private final static int MAXIMUM_PARALLEL_LISTENER_THREADS = 20; // Variables private boolean running = false; private IConnectionInterface connectionInterface; private volatile OperatingMode mode; private ArrayList<ISerialDataReceiveListener> serialDataReceiveListeners = new ArrayList<ISerialDataReceiveListener>(); // The packetReceiveListeners requires to be a HashMap with an associated integer. The integer is used to determine // the frame ID of the packet that should be received. When it is 99999 (ALL_FRAME_IDS), all the packets will be handled. private HashMap<IPacketReceiveListener, Integer> packetReceiveListeners = new HashMap<IPacketReceiveListener, Integer>(); private Logger logger; /** * Class constructor. Instances a new DataReader object for the given interface. * * @param connectionInterface Connection interface to read from. * @param mode XBee operating mode. * * @throws NullPointerException if {@code connectionInterface == null} or * {@code mode == null}. */ public DataReader(IConnectionInterface connectionInterface, OperatingMode mode) { if (connectionInterface == null) throw new NullPointerException("Connection interface cannot be null."); if (mode == null) throw new NullPointerException("Operating mode cannot be null."); this.connectionInterface = connectionInterface; this.mode = mode; this.logger = LoggerFactory.getLogger(DataReader.class); } /** * Sets the mode of the reader. * * @param mode XBee mode * * @throws NullPointerException if {@code mode == null}. */ public void setXBeeReaderMode(OperatingMode mode) { if (mode == null) throw new NullPointerException("Operating mode cannot be null."); this.mode = mode; } /** * Adds the given serial data receive listener to the list of listeners to be notified when * serial data is received. * * @param listener Listener to be notified when new serial data is received. */ public void addSerialDatatReceiveListener(ISerialDataReceiveListener listener) { synchronized (serialDataReceiveListeners) { if (!serialDataReceiveListeners.contains(listener)) serialDataReceiveListeners.add(listener); } } /** * Removes the given serial data receive listener from the list of serial data * receive listeners. * * @param listener Serial data receive listener to remove. */ public void removeSerialDataReceiveListener(ISerialDataReceiveListener listener) { synchronized (serialDataReceiveListeners) { if (serialDataReceiveListeners.contains(listener)) serialDataReceiveListeners.remove(listener); } } /** * Adds the given packet receive listener to the list of listeners to be notified when a * packet is received. * * @param listener Listener to be notified when a packet is received. */ public void addPacketReceiveListener(IPacketReceiveListener listener) { addPacketReceiveListener(listener, ALL_FRAME_IDS); } /** * Adds the given packet receive listener to the list of listeners to be notified when a * packet is received. * * @param listener Listener to be notified when a packet is received. * @param frameID Frame ID for which this listener should be notified and removed after. * Using {@link #ALL_FRAME_IDS} this listener will be notified always and * will be removed only by user request. */ public void addPacketReceiveListener(IPacketReceiveListener listener, int frameID) { synchronized (packetReceiveListeners) { if (!packetReceiveListeners.containsKey(listener)) packetReceiveListeners.put(listener, frameID); } } /** * Removes the given packet receive listener from the list of XBee packet * receive listeners. * * @param listener Packet receive listener to remove. */ public void removePacketReceiveListener(IPacketReceiveListener listener) { synchronized (packetReceiveListeners) { if (packetReceiveListeners.containsKey(listener)) packetReceiveListeners.remove(listener); } } /* * (non-Javadoc) * @see java.lang.Thread#run() */ public void run() { logger.debug(connectionInterface.toString() + "Data reader started."); running = true; try { synchronized (connectionInterface) { connectionInterface.wait(); } while (running) { if (!running) break; if (connectionInterface.getInputStream() != null) { switch (mode) { case AT: break; case API: case API_ESCAPE: int headerByte = connectionInterface.getInputStream().read(); // If it is packet header parse the packet, if not discard this byte and continue. if (headerByte == SpecialByte.HEADER_BYTE.getValue()) { XBeePacketParser parser = new XBeePacketParser(connectionInterface.getInputStream(), mode); try { XBeePacket packet = parser.parsePacket(); packetReceived(packet); } catch (InvalidPacketException e) { logger.error("Error parsing the API packet.", e); } } break; default: break; } } else if (connectionInterface.getInputStream() == null) break; if (connectionInterface.getInputStream() == null) break; else if (connectionInterface.getInputStream().available() > 0) continue; synchronized (connectionInterface) { connectionInterface.wait(); } } } catch (IOException e) { logger.error("Error reading from input stream.", e); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } catch (IllegalStateException e) { logger.error(e.getMessage(), e); } finally { if (running) { running = false; if (connectionInterface != null && connectionInterface.isOpen()) connectionInterface.close(); } } } /** * A packet was received, dispatch it to the corresponding listener(s). * * @param packet The received packet. */ private void packetReceived(XBeePacket packet) { // Notify that a packet has been received to the corresponding listeners. notifyPacketReceived(packet); // Check if the packet is an API packet. if (!(packet instanceof XBeeAPIPacket)) return; // Get the API packet type. XBeeAPIPacket apiPacket = (XBeeAPIPacket)packet; APIFrameType apiType = apiPacket.getFrameType(); if (apiType == null) return; String address = null; byte[] data = null; boolean isBroadcastData = false; switch(apiType) { case RECEIVE_PACKET: address = ((ReceivePacket)apiPacket).get64bitAddress().toString(); data = ((ReceivePacket)apiPacket).getReceivedData(); isBroadcastData = ByteUtils.isBitEnabled(((ReceivePacket)apiPacket).getReceiveOptions(), 1); break; case RX_64: address = ((RX64Packet)apiPacket).getSourceAddress().toString(); data = ((RX64Packet)apiPacket).getReceivedData(); if (ByteUtils.isBitEnabled(((RX64Packet)apiPacket).getReceiveOptions(), 1) || ByteUtils.isBitEnabled(((RX64Packet)apiPacket).getReceiveOptions(), 2)) isBroadcastData = true; break; case RX_16: address = ((RX16Packet)apiPacket).getSourceAddress().toString(); data = ((RX16Packet)apiPacket).getReceivedData(); if (ByteUtils.isBitEnabled(((RX16Packet)apiPacket).getReceiveOptions(), 1) || ByteUtils.isBitEnabled(((RX16Packet)apiPacket).getReceiveOptions(), 2)) isBroadcastData = true; break; default: break; } // Notify that serial data was received to the corresponding listeners. if (address != null && data != null) notifySerialDataReceived(address, data, isBroadcastData); } /** * Notifies subscribed serial data receive listeners that serial data has been received. * * @param address The address of the node that sent the data. * @param data The received data. * @param isBroadcastData Indicates whether or not the data was sent via broadcast to execute * the corresponding broadcast callback. */ private void notifySerialDataReceived(final String address, final byte[] data, final boolean isBroadcastData) { if (isBroadcastData) logger.info(connectionInterface.toString() + "Broadcast serial data received from {} >> {}.", address, HexUtils.prettyHexString(data)); else logger.info(connectionInterface.toString() + "Serial data received from {} >> {}.", address, HexUtils.prettyHexString(data)); try { synchronized (serialDataReceiveListeners) { ScheduledExecutorService executor = Executors.newScheduledThreadPool(Math.min(MAXIMUM_PARALLEL_LISTENER_THREADS, serialDataReceiveListeners.size())); for (final ISerialDataReceiveListener listener:serialDataReceiveListeners) { executor.execute(new Runnable() { public void run() { if (isBroadcastData) listener.broadcastSerialDataReceived(address, data); else listener.serialDataReceived(address, data); } }); } executor.shutdown(); } } catch (Exception e) { logger.error(e.getMessage(), e); } } /** * Notifies subscribed packet listeners that a packet has been received. * * @param packet The received packet. */ private void notifyPacketReceived(final XBeePacket packet) { logger.debug(connectionInterface.toString() + "Packet received: \n{}", packet.toPrettyString()); try { synchronized (packetReceiveListeners) { final ArrayList<IPacketReceiveListener> removeListeners = new ArrayList<IPacketReceiveListener>(); ScheduledExecutorService executor = Executors.newScheduledThreadPool(Math.min(MAXIMUM_PARALLEL_LISTENER_THREADS, packetReceiveListeners.size())); for (final IPacketReceiveListener listener:packetReceiveListeners.keySet()) { executor.execute(new Runnable() { public void run() { if (packetReceiveListeners.get(listener) == ALL_FRAME_IDS) listener.packetReceived(packet); else if (((XBeeAPIPacket)packet).needsAPIFrameID() && ((XBeeAPIPacket)packet).getFrameID() == packetReceiveListeners.get(listener)) { listener.packetReceived(packet); removeListeners.add(listener); } } }); } executor.shutdown(); // Remove required listeners. for (IPacketReceiveListener listener:removeListeners) packetReceiveListeners.remove(listener); } } catch (Exception e) { logger.error(e.getMessage(), e); } } /** * Returns whether the Data reader is running or not. * * @return True if the Data reader is running, false otherwise. */ public boolean isRunning() { return running; } /** * Stops the Data reader thread. */ public void stopReader() { running = false; synchronized (connectionInterface) { connectionInterface.notify(); } logger.debug(connectionInterface.toString() + "Data reader stopped."); } }
[XBJAPI-143] Synchronized serial data reception listeners so they are not called twice. By synchronizing the listener also unicast and broadcast data reception are synchronized, that is, while unicast data is being processed, broadcast data is waiting till it finishes, and the other way around. https://jira.digi.com/browse/XBJAPI-143 Signed-off-by: Tatiana Leon <[email protected]>
src/com/digi/xbee/api/connection/DataReader.java
[XBJAPI-143] Synchronized serial data reception listeners so they are not called twice.
<ide><path>rc/com/digi/xbee/api/connection/DataReader.java <ide> for (final ISerialDataReceiveListener listener:serialDataReceiveListeners) { <ide> executor.execute(new Runnable() { <ide> public void run() { <del> if (isBroadcastData) <del> listener.broadcastSerialDataReceived(address, data); <del> else <del> listener.serialDataReceived(address, data); <add> /* Synchronize the listener so it is not called <add> twice. That is, let the listener to finish its job. <add> <add> By synchronizing the listener also unicast and <add> broadcast data reception are synchronized, that is, <add> while unicast data is being processed, broadcast <add> data is waiting till it finishes, and the other <add> way around. */ <add> synchronized (listener) { <add> if (isBroadcastData) <add> listener.broadcastSerialDataReceived(address, data); <add> else <add> listener.serialDataReceived(address, data); <add> } <ide> } <ide> }); <ide> }
Java
mit
32a57f99208bcc013c993a1f6639d7fb095be521
0
elBukkit/MagicPlugin,elBukkit/MagicLib,elBukkit/MagicPlugin,elBukkit/MagicPlugin
package com.elmakers.mine.bukkit.action; import com.elmakers.mine.bukkit.api.block.MaterialBrush; import com.elmakers.mine.bukkit.api.effect.EffectPlay; import com.elmakers.mine.bukkit.api.effect.EffectPlayer; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.api.spell.MageSpell; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.api.block.UndoList; import com.elmakers.mine.bukkit.api.spell.SpellResult; import com.elmakers.mine.bukkit.api.spell.TargetType; import com.elmakers.mine.bukkit.api.wand.Wand; import com.elmakers.mine.bukkit.spell.BaseSpell; import com.elmakers.mine.bukkit.spell.BlockSpell; import com.elmakers.mine.bukkit.spell.BrushSpell; import com.elmakers.mine.bukkit.spell.TargetingSpell; import com.elmakers.mine.bukkit.spell.UndoableSpell; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.util.Vector; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.UUID; import java.util.logging.Logger; public class CastContext implements com.elmakers.mine.bukkit.api.action.CastContext { protected static Random random; private final Location location; private final Entity entity; private Location targetLocation; private Location targetSourceLocation; private Location targetCenterLocation; private Entity targetEntity; private UndoList undoList; private String targetName = null; private SpellResult result = SpellResult.NO_ACTION; private SpellResult initialResult = SpellResult.CAST; private Vector direction = null; private Set<UUID> targetMessagesSent = new HashSet<UUID>(); private Collection<EffectPlay> currentEffects = new ArrayList<EffectPlay>(); private Spell spell; private BaseSpell baseSpell; private BlockSpell blockSpell; private MageSpell mageSpell; private BrushSpell brushSpell; private TargetingSpell targetingSpell; private UndoableSpell undoSpell; private MaterialBrush brush; private CastContext base; private Wand wand; // Base Context private int workAllowed = 500; private int actionsPerformed; private boolean finished = false; public CastContext() { this.location = null; this.entity = null; this.base = this; this.result = SpellResult.NO_ACTION; targetMessagesSent = new HashSet<UUID>(); currentEffects = new ArrayList<EffectPlay>(); } public CastContext(com.elmakers.mine.bukkit.api.action.CastContext copy) { this(copy, copy.getEntity(), copy instanceof CastContext ? ((CastContext) copy).location : null); } public CastContext(com.elmakers.mine.bukkit.api.action.CastContext copy, Entity sourceEntity) { this(copy, sourceEntity, null); } public CastContext(com.elmakers.mine.bukkit.api.action.CastContext copy, Location sourceLocation) { this(copy, null, sourceLocation); } public CastContext(com.elmakers.mine.bukkit.api.action.CastContext copy, Entity sourceEntity, Location sourceLocation) { this.location = sourceLocation; this.entity = sourceEntity; this.setSpell(copy.getSpell()); this.targetEntity = copy.getTargetEntity(); this.targetLocation = copy.getTargetLocation(); this.undoList = copy.getUndoList(); this.targetName = copy.getTargetName(); this.brush = copy.getBrush(); this.targetMessagesSent = copy.getTargetMessagesSent(); this.currentEffects = copy.getCurrentEffects(); this.result = copy.getResult(); this.wand = copy.getWand(); Location centerLocation = copy.getTargetCenterLocation(); if (centerLocation != null) { targetCenterLocation = centerLocation; } if (copy instanceof CastContext) { this.base = ((CastContext)copy).base; this.initialResult = ((CastContext)copy).initialResult; this.direction = ((CastContext)copy).direction; } else { this.base = this; } } public void setSpell(Spell spell) { this.spell = spell; if (spell instanceof BaseSpell) { this.baseSpell = (BaseSpell)spell; } if (spell instanceof MageSpell) { this.mageSpell = (MageSpell)spell; this.wand = this.mageSpell.getMage().getActiveWand(); } if (spell instanceof UndoableSpell) { this.undoSpell = (UndoableSpell)spell; undoList = this.undoSpell.getUndoList(); } if (spell instanceof TargetingSpell) { this.targetingSpell = (TargetingSpell)spell; } if (spell instanceof BlockSpell) { this.blockSpell = (BlockSpell)spell; } if (spell instanceof BrushSpell) { this.brushSpell = (BrushSpell)spell; } } @Override public Location getWandLocation() { if (location != null) { return location; } Location wandLocation = this.baseSpell != null ? baseSpell.getWandLocation() : getEyeLocation(); if (wandLocation != null && direction != null) { wandLocation.setDirection(direction); } return wandLocation; } @Override public Location getEyeLocation() { if (location != null) { return location; } if (entity != null) { if (entity instanceof LivingEntity) { return ((LivingEntity) entity).getEyeLocation(); } return entity.getLocation(); } return spell.getEyeLocation(); } @Override public Entity getEntity() { if (entity != null) { return entity; } return spell.getEntity(); } @Override public LivingEntity getLivingEntity() { Entity entity = getEntity(); return entity instanceof LivingEntity ? (LivingEntity)entity : null; } @Override public Location getLocation() { if (location != null) { return location; } if (entity != null) { return entity.getLocation(); } return spell.getLocation(); } @Override public Location getTargetLocation() { return targetLocation; } @Override public Location getTargetSourceLocation() { return targetSourceLocation == null ? targetLocation : targetSourceLocation; } @Override public Block getTargetBlock() { return targetLocation == null ? null : targetLocation.getBlock(); } @Override public Entity getTargetEntity() { return targetEntity; } @Override public Vector getDirection() { if (direction != null) { return direction.clone(); } return getLocation().getDirection(); } @Override public void setDirection(Vector direction) { this.direction = direction; } @Override public World getWorld() { Location location = getLocation(); return location == null ? null : location.getWorld(); } @Override public void setTargetEntity(Entity targetEntity) { this.targetEntity = targetEntity; } @Override public void setTargetLocation(Location targetLocation) { this.targetLocation = targetLocation; } @Override public void setTargetSourceLocation(Location targetLocation) { targetSourceLocation = targetLocation; } @Override public Spell getSpell() { return spell; } @Override public Mage getMage() { return this.mageSpell == null ? null : this.mageSpell.getMage(); } @Override public Wand getWand() { return wand; } @Override public MageController getController() { Mage mage = getMage(); return mage == null ? null : mage.getController(); } @Override public void registerForUndo(Runnable runnable) { addWork(1); if (undoList != null) { undoList.add(runnable); } } @Override public void registerModified(Entity entity) { addWork(5); if (undoList != null) { undoList.modify(entity); } } @Override public void registerDamaged(Entity entity) { addWork(5); if (undoList != null) { undoList.damage(entity); } } @Override public void registerForUndo(Entity entity) { addWork(5); if (undoList != null) { undoList.add(entity); } } @Override public void registerForUndo(Block block) { addWork(10); if (undoList != null) { undoList.add(block); } } @Override public void updateBlock(Block block) { MageController controller = getController(); if (controller != null) { controller.updateBlock(block); } } @Override public void registerVelocity(Entity entity) { addWork(5); if (undoList != null) { undoList.modifyVelocity(entity); } } @Override public void registerMoved(Entity entity) { addWork(5); if (undoList != null) { undoList.move(entity); } } @Override public void registerPotionEffects(Entity entity) { addWork(5); if (undoList != null) { undoList.addPotionEffects(entity); } } @Override public Block getPreviousBlock() { return targetingSpell != null ? targetingSpell.getPreviousBlock() : null; } @Override public boolean isIndestructible(Block block) { return blockSpell != null ? blockSpell.isIndestructible(block) : true; } @Override public boolean hasBuildPermission(Block block) { return baseSpell != null ? baseSpell.hasBuildPermission(block) : false; } @Override public boolean hasBreakPermission(Block block) { return baseSpell != null ? baseSpell.hasBreakPermission(block) : false; } @Override public boolean hasEffects(String key) { return baseSpell != null ? baseSpell.hasEffects(key) : false; } @Override public void playEffects(String key) { playEffects(key, 1.0f); } @Override public Collection<EffectPlayer> getEffects(String effectKey) { Collection<EffectPlayer> effects = spell.getEffects(effectKey); if (effects.size() == 0) return effects; // Create parameter map Map<String, String> parameterMap = null; ConfigurationSection workingParameters = spell != null ? spell.getWorkingParameters() : null; if (workingParameters != null) { Collection<String> keys = workingParameters.getKeys(false); parameterMap = new HashMap<String, String>(); for (String key : keys) { parameterMap.put("$" + key, workingParameters.getString(key)); } } for (EffectPlayer player : effects) { // Track effect plays for cancelling player.setEffectPlayList(currentEffects); // Set material and color player.setMaterial(spell.getEffectMaterial()); player.setColor(spell.getEffectColor()); String overrideParticle = spell.getEffectParticle(); player.setParticleOverride(overrideParticle); // Set parameters player.setParameterMap(parameterMap); } return effects; } @Override public void playEffects(String effectName, float scale) { playEffects(effectName, scale, null, getEntity(), null, getTargetEntity()); } public void playEffects(String effectName, float scale, Block sourceBlock) { playEffects(effectName, scale, null, getEntity(), null, getTargetEntity(), sourceBlock); } @Override public void playEffects(String effectName, float scale, Location sourceLocation, Entity sourceEntity, Location targetLocation, Entity targetEntity) { playEffects(effectName, scale, sourceLocation, sourceEntity, targetLocation, targetEntity, null); } @Override public void playEffects(String effectName, float scale, Location sourceLocation, Entity sourceEntity, Location targetLocation, Entity targetEntity, Block sourceBlock) { Collection<EffectPlayer> effects = getEffects(effectName); if (effects.size() > 0) { Location wand = null; Location eyeLocation = getEyeLocation(); Location location = getLocation(); Collection<Entity> targeted = getTargetedEntities(); for (EffectPlayer player : effects) { // Set scale player.setScale(scale); Mage mage = getMage(); Location source = sourceLocation; if (source == null) { boolean useWand = mage != null && mage.getEntity() == sourceEntity && player.shouldUseWandLocation(); source = player.shouldUseEyeLocation() ? eyeLocation : location; if (useWand) { if (wand == null) { wand = getWandLocation(); } source = wand; } } Location target = targetLocation; if (target == null) { target = getTargetLocation(); if (player.shouldUseBlockLocation()) { target = target.getBlock().getLocation(); } else if (!player.shouldUseHitLocation() && targetEntity != null) { if (targetEntity instanceof LivingEntity) { target = ((LivingEntity)targetEntity).getEyeLocation(); } else { target = targetEntity.getLocation(); } } } if (sourceBlock != null) { player.setMaterial(sourceBlock); } player.start(source, sourceEntity, target, targetEntity, targeted); } } } @Override public void cancelEffects() { for (EffectPlay player : currentEffects) { player.cancel(); } currentEffects.clear(); } @Override public String getMessage(String key) { return getMessage(key, ""); } @Override public String getMessage(String key, String def) { return baseSpell != null ? baseSpell.getMessage(key, def) : def; } @Override public Location findPlaceToStand(Location target, int verticalSearchDistance, boolean goUp) { return baseSpell != null ? baseSpell.findPlaceToStand(target, goUp, verticalSearchDistance) : location; } public Location findPlaceToStand(Location targetLoc, int verticalSearchDistance) { return baseSpell != null ? baseSpell.findPlaceToStand(targetLoc, verticalSearchDistance, verticalSearchDistance) : location; } @Override public int getVerticalSearchDistance() { return baseSpell != null ? baseSpell.getVerticalSearchDistance() : 4; } @Override public boolean isOkToStandIn(Material material) { return baseSpell != null ? baseSpell.isOkToStandIn(material) : true; } @Override public boolean isWater(Material mat) { return (mat == Material.WATER || mat == Material.STATIONARY_WATER); } @Override public boolean isOkToStandOn(Material material) { return (material != Material.AIR && material != Material.LAVA && material != Material.STATIONARY_LAVA); } @Override public boolean allowPassThrough(Material material) { return baseSpell != null ? baseSpell.allowPassThrough(material) : true; } @Override public void castMessageKey(String key) { if (baseSpell != null) { baseSpell.castMessage(getMessage(key)); } } @Override public void sendMessageKey(String key) { if (baseSpell != null) { baseSpell.sendMessage(getMessage(key)); } } @Override public void showMessage(String key, String def) { Mage mage = getMage(); if (mage != null) { mage.sendMessage(getMessage(key, def)); } } @Override public void showMessage(String message) { Mage mage = getMage(); if (mage != null) { mage.sendMessage(message); } } @Override public void castMessage(String message) { if (baseSpell != null) { baseSpell.castMessage(message); } } @Override public void sendMessage(String message) { if (baseSpell != null) { baseSpell.sendMessage(message); } } @Override public void setTargetedLocation(Location location) { if (targetingSpell != null) { targetingSpell.setTarget(location); } } @Override public Block findBlockUnder(Block block) { if (targetingSpell != null) { block = targetingSpell.findBlockUnder(block); } return block; } @Override public Block findSpaceAbove(Block block) { if (targetingSpell != null) { block = targetingSpell.findSpaceAbove(block); } return block; } @Override public boolean isTransparent(Material material) { if (targetingSpell != null) { return targetingSpell.isTransparent(material); } return material.isTransparent(); } @Override public boolean isPassthrough(Material material) { if (baseSpell != null) { return baseSpell.isPassthrough(material); } return material.isTransparent(); } @Override public boolean isDestructible(Block block) { if (blockSpell != null) { return blockSpell.isDestructible(block); } return true; } @Override public boolean areAnyDestructible(Block block) { if (blockSpell != null) { return blockSpell.areAnyDestructible(block); } return true; } @Override public boolean isTargetable(Block block) { if (targetingSpell != null) { return targetingSpell.isTargetable(this, block); } return true; } @Override public TargetType getTargetType() { TargetType targetType = TargetType.NONE; if (targetingSpell != null) { targetType = targetingSpell.getTargetType(); } return targetType; } @Override public boolean getTargetsCaster() { if (baseSpell != null) { return baseSpell.getTargetsCaster(); } return false; } @Override public boolean isConsumeFree() { if (baseSpell != null) { return baseSpell.getConsumeReduction() >= 1; } return false; } @Override public void setTargetsCaster(boolean target) { if (baseSpell != null) { baseSpell.setTargetsCaster(target); } } @Override public boolean canTarget(Entity entity) { return targetingSpell == null ? true : targetingSpell.canTarget(entity); } @Override public MaterialBrush getBrush() { if (brush != null) { return brush; } return brushSpell == null ? null : brushSpell.getBrush(); } @Override public void setBrush(MaterialBrush brush) { this.brush = brush; } @Override public Collection<Entity> getTargetedEntities() { if (undoList == null) { return new ArrayList<Entity>(); } return undoList.getAllEntities(); } @Override public void messageTargets(String messageKey) { Mage mage = getMage(); if (mage.isStealth()) return; Collection<Entity> targets = getTargetedEntities(); if (targets == null || targets.isEmpty()) return; MageController controller = getController(); LivingEntity sourceEntity = mage == null ? null : mage.getLivingEntity(); String playerMessage = getMessage(messageKey); if (playerMessage.length() > 0) { for (Entity target : targets) { UUID targetUUID = target.getUniqueId(); if (target instanceof Player && target != sourceEntity && !targetMessagesSent.contains(targetUUID)) { targetMessagesSent.add(targetUUID); playerMessage = playerMessage.replace("$spell", spell.getName()); Mage targetMage = controller.getMage(target); targetMage.sendMessage(playerMessage); } } } } @Override public Block getInteractBlock() { Location location = getEyeLocation(); if (location == null) return null; Block playerBlock = location.getBlock(); if (isTargetable(playerBlock)) return playerBlock; Vector direction = location.getDirection().normalize(); return location.add(direction).getBlock(); } @Override public Random getRandom() { if (random == null) { random = new Random(); } return random; } @Override public UndoList getUndoList() { return undoList; } @Override public String getTargetName() { return targetName; } @Override public void setTargetName(String name) { targetName = name; } @Override public Logger getLogger() { return getController().getLogger(); } @Override public int getWorkAllowed() { return this.base.workAllowed; } @Override public void setWorkAllowed(int work) { this.base.workAllowed = work; } @Override public void addWork(int work) { this.base.workAllowed -= work; } @Override public void performedActions(int count) { this.base.actionsPerformed += count; } @Override public int getActionsPerformed() { return base.actionsPerformed; } @Override public void finish() { if (finished) return; finished = true; Mage mage = getMage(); if (undoSpell != null && undoSpell.isUndoable()) { if (!undoList.isScheduled()) { getController().update(undoList); } mage.registerForUndo(undoList); } result = result.max(initialResult); if (spell != null) { mage.sendDebugMessage(ChatColor.WHITE + "Finish " + ChatColor.GOLD + spell.getName() + ChatColor.WHITE + ": " + ChatColor.AQUA + result.name().toLowerCase(), 2); spell.finish(this); } String resultName = result.name().toLowerCase(); castMessageKey(resultName + "_finish"); playEffects(resultName + "_finish"); } @Override public void retarget(int range, double fov, double closeRange, double closeFOV, boolean useHitbox) { if (targetingSpell != null) { targetingSpell.retarget(range, fov, closeRange, closeFOV, useHitbox); setTargetEntity(targetingSpell.getTargetEntity()); setTargetLocation(targetingSpell.getTargetLocation()); } } @Override public void retarget(int range, double fov, double closeRange, double closeFOV, boolean useHitbox, int yOffset, boolean targetSpaceRequired, int targetMinOffset) { if (targetingSpell != null) { targetingSpell.retarget(range, fov, closeRange, closeFOV, useHitbox, yOffset, targetSpaceRequired, targetMinOffset); setTargetEntity(targetingSpell.getTargetEntity()); setTargetLocation(targetingSpell.getTargetLocation()); } } @Override public com.elmakers.mine.bukkit.api.action.CastContext getBaseContext() { return base; } @Override public Location getTargetCenterLocation() { return targetCenterLocation == null ? targetLocation : targetCenterLocation; } @Override public Set<UUID> getTargetMessagesSent() { return targetMessagesSent; } @Override public Collection<EffectPlay> getCurrentEffects() { return currentEffects; } @Override public Plugin getPlugin() { MageController controller = getController(); return controller == null ? null : controller.getPlugin(); } @Override public boolean teleport(final Entity entity, final Location location, final int verticalSearchDistance, boolean preventFall) { return teleport(entity, location, verticalSearchDistance, preventFall, true); } @Override public boolean teleport(final Entity entity, final Location location, final int verticalSearchDistance, boolean preventFall, boolean safe) { Chunk chunk = location.getBlock().getChunk(); if (!chunk.isLoaded()) { chunk.load(true); } Location targetLocation = findPlaceToStand(location, verticalSearchDistance); if (targetLocation == null && !preventFall) { Block block = location.getBlock(); Block blockOneUp = block.getRelative(BlockFace.UP); if (!safe || (isOkToStandIn(blockOneUp.getType()) && isOkToStandIn(block.getType()))) { targetLocation = location; } } if (targetLocation != null) { targetLocation.setX(location.getX() - location.getBlockX() + targetLocation.getBlockX()); targetLocation.setZ(location.getZ() - location.getBlockZ() + targetLocation.getBlockZ()); registerMoved(entity); // Hacky double-teleport to work-around vanilla suffocation checks boolean isWorldChange = !targetLocation.getWorld().equals(entity.getWorld()); entity.teleport(targetLocation); if (isWorldChange) { entity.teleport(targetLocation); } setTargetLocation(targetLocation); sendMessageKey("teleport"); playEffects("teleport"); } else { sendMessageKey("teleport_failed"); playEffects("teleport_failed"); return false; } return true; } @Override public boolean teleport(final Entity entity, final Location location, final int verticalSearchDistance) { return teleport(entity, location, verticalSearchDistance, true); } @Override public void setSpellParameters(ConfigurationSection parameters) { if (baseSpell != null) { baseSpell.processParameters(parameters); } } @Override public Set<Material> getMaterialSet(String key) { return getController().getMaterialSet(key); } @Override public SpellResult getResult() { return this.result; } @Override public void setResult(SpellResult result) { this.result = result; } @Override public void addResult(SpellResult result) { if (result != SpellResult.PENDING) { this.result = this.result.min(result); } } public void setInitialResult(SpellResult result) { initialResult = result; } @Override public boolean canCast(Location location) { if (baseSpell != null) { return baseSpell.canCast(location); } return true; } @Override public boolean isBreakable(Block block) { return com.elmakers.mine.bukkit.block.UndoList.isBreakable(block); } @Override public Double getBreakable(Block block) { return com.elmakers.mine.bukkit.block.UndoList.getBreakable(block); } @Override public void clearBreakable(Block block) { com.elmakers.mine.bukkit.block.UndoList.unregisterBreakable(block); } @Override public void clearReflective(Block block) { com.elmakers.mine.bukkit.block.UndoList.unregisterReflective(block); } @Override public boolean isReflective(Block block) { if (block == null) return false; if (targetingSpell != null && targetingSpell.isReflective(block.getType())) { return true; } return com.elmakers.mine.bukkit.block.UndoList.isReflective(block); } @Override public Double getReflective(Block block) { if (block == null) return null; if (block == null) return null; if (targetingSpell != null && targetingSpell.isReflective(block.getType())) { return 1.0; } return com.elmakers.mine.bukkit.block.UndoList.getReflective(block); } @Override public void registerBreakable(Block block, double breakable) { com.elmakers.mine.bukkit.block.UndoList.registerBreakable(block, breakable); undoList.setUndoBreakable(true); } @Override public void registerReflective(Block block, double reflectivity) { com.elmakers.mine.bukkit.block.UndoList.registerReflective(block, reflectivity); undoList.setUndoReflective(true); } @Override public String parameterize(String command) { Location location = getLocation(); Mage mage = getMage(); MageController controller = getController(); command = command .replace("@_", " ") .replace("@spell", getSpell().getName()) .replace("@pd", mage.getDisplayName()) .replace("@pn", mage.getName()) .replace("@uuid", mage.getId()) .replace("@p", mage.getName()); if (location != null) { command = command .replace("@world", location.getWorld().getName()) .replace("@x", Double.toString(location.getX())) .replace("@y", Double.toString(location.getY())) .replace("@z", Double.toString(location.getZ())); } Location targetLocation = getTargetLocation(); if (targetLocation != null) { command = command .replace("@tworld", targetLocation.getWorld().getName()) .replace("@tx", Double.toString(targetLocation.getX())) .replace("@ty", Double.toString(targetLocation.getY())) .replace("@tz", Double.toString(targetLocation.getZ())); } Entity targetEntity = getTargetEntity(); if (targetEntity != null) { if (controller.isMage(targetEntity)) { Mage targetMage = controller.getMage(targetEntity); command = command .replace("@td", targetMage.getDisplayName()) .replace("@tn", targetMage.getName()) .replace("@tuuid", targetMage.getId()) .replace("@t", targetMage.getName()); } else { command = command .replace("@td", controller.getEntityDisplayName(targetEntity)) .replace("@tn", controller.getEntityName(targetEntity)) .replace("@tuuid", targetEntity.getUniqueId().toString()) .replace("@t", controller.getEntityName(targetEntity)); } } return ChatColor.translateAlternateColorCodes('&', command); } }
src/main/java/com/elmakers/mine/bukkit/action/CastContext.java
package com.elmakers.mine.bukkit.action; import com.elmakers.mine.bukkit.api.block.MaterialBrush; import com.elmakers.mine.bukkit.api.effect.EffectPlay; import com.elmakers.mine.bukkit.api.effect.EffectPlayer; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.api.spell.MageSpell; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.api.block.UndoList; import com.elmakers.mine.bukkit.api.spell.SpellResult; import com.elmakers.mine.bukkit.api.spell.TargetType; import com.elmakers.mine.bukkit.api.wand.Wand; import com.elmakers.mine.bukkit.spell.BaseSpell; import com.elmakers.mine.bukkit.spell.BlockSpell; import com.elmakers.mine.bukkit.spell.BrushSpell; import com.elmakers.mine.bukkit.spell.TargetingSpell; import com.elmakers.mine.bukkit.spell.UndoableSpell; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.util.Vector; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.UUID; import java.util.logging.Logger; public class CastContext implements com.elmakers.mine.bukkit.api.action.CastContext { protected static Random random; private final Location location; private final Entity entity; private Location targetLocation; private Location targetSourceLocation; private Location targetCenterLocation; private Entity targetEntity; private UndoList undoList; private String targetName = null; private SpellResult result = SpellResult.NO_ACTION; private SpellResult initialResult = SpellResult.CAST; private Vector direction = null; private Set<UUID> targetMessagesSent = new HashSet<UUID>(); private Collection<EffectPlay> currentEffects = new ArrayList<EffectPlay>(); private Spell spell; private BaseSpell baseSpell; private BlockSpell blockSpell; private MageSpell mageSpell; private BrushSpell brushSpell; private TargetingSpell targetingSpell; private UndoableSpell undoSpell; private MaterialBrush brush; private CastContext base; private Wand wand; // Base Context private int workAllowed = 500; private int actionsPerformed; private boolean finished = false; public CastContext() { this.location = null; this.entity = null; this.base = this; this.result = SpellResult.NO_ACTION; targetMessagesSent = new HashSet<UUID>(); currentEffects = new ArrayList<EffectPlay>(); } public CastContext(com.elmakers.mine.bukkit.api.action.CastContext copy) { this(copy, copy.getEntity(), copy instanceof CastContext ? ((CastContext) copy).location : null); } public CastContext(com.elmakers.mine.bukkit.api.action.CastContext copy, Entity sourceEntity) { this(copy, sourceEntity, null); } public CastContext(com.elmakers.mine.bukkit.api.action.CastContext copy, Location sourceLocation) { this(copy, null, sourceLocation); } public CastContext(com.elmakers.mine.bukkit.api.action.CastContext copy, Entity sourceEntity, Location sourceLocation) { this.location = sourceLocation; this.entity = sourceEntity; this.setSpell(copy.getSpell()); this.targetEntity = copy.getTargetEntity(); this.targetLocation = copy.getTargetLocation(); this.undoList = copy.getUndoList(); this.targetName = copy.getTargetName(); this.brush = copy.getBrush(); this.targetMessagesSent = copy.getTargetMessagesSent(); this.currentEffects = copy.getCurrentEffects(); this.result = copy.getResult(); this.wand = copy.getWand(); Location centerLocation = copy.getTargetCenterLocation(); if (centerLocation != null) { targetCenterLocation = centerLocation; } if (copy instanceof CastContext) { this.base = ((CastContext)copy).base; this.initialResult = ((CastContext)copy).initialResult; this.direction = ((CastContext)copy).direction; } else { this.base = this; } } public void setSpell(Spell spell) { this.spell = spell; if (spell instanceof BaseSpell) { this.baseSpell = (BaseSpell)spell; } if (spell instanceof MageSpell) { this.mageSpell = (MageSpell)spell; this.wand = this.mageSpell.getMage().getActiveWand(); } if (spell instanceof UndoableSpell) { this.undoSpell = (UndoableSpell)spell; undoList = this.undoSpell.getUndoList(); } if (spell instanceof TargetingSpell) { this.targetingSpell = (TargetingSpell)spell; } if (spell instanceof BlockSpell) { this.blockSpell = (BlockSpell)spell; } if (spell instanceof BrushSpell) { this.brushSpell = (BrushSpell)spell; } } @Override public Location getWandLocation() { if (location != null) { return location; } Location wandLocation = this.baseSpell != null ? baseSpell.getWandLocation() : getEyeLocation(); if (wandLocation != null && direction != null) { wandLocation.setDirection(direction); } return wandLocation; } @Override public Location getEyeLocation() { if (location != null) { return location; } if (entity != null) { if (entity instanceof LivingEntity) { return ((LivingEntity) entity).getEyeLocation(); } return entity.getLocation(); } return spell.getEyeLocation(); } @Override public Entity getEntity() { if (entity != null) { return entity; } return spell.getEntity(); } @Override public LivingEntity getLivingEntity() { Entity entity = getEntity(); return entity instanceof LivingEntity ? (LivingEntity)entity : null; } @Override public Location getLocation() { if (location != null) { return location; } if (entity != null) { return entity.getLocation(); } return spell.getLocation(); } @Override public Location getTargetLocation() { return targetLocation; } @Override public Location getTargetSourceLocation() { return targetSourceLocation == null ? targetLocation : targetSourceLocation; } @Override public Block getTargetBlock() { return targetLocation == null ? null : targetLocation.getBlock(); } @Override public Entity getTargetEntity() { return targetEntity; } @Override public Vector getDirection() { if (direction != null) { return direction.clone(); } return getLocation().getDirection(); } @Override public void setDirection(Vector direction) { this.direction = direction; } @Override public World getWorld() { Location location = getLocation(); return location == null ? null : location.getWorld(); } @Override public void setTargetEntity(Entity targetEntity) { this.targetEntity = targetEntity; } @Override public void setTargetLocation(Location targetLocation) { this.targetLocation = targetLocation; } @Override public void setTargetSourceLocation(Location targetLocation) { targetSourceLocation = targetLocation; } @Override public Spell getSpell() { return spell; } @Override public Mage getMage() { return this.mageSpell == null ? null : this.mageSpell.getMage(); } @Override public Wand getWand() { return wand; } @Override public MageController getController() { Mage mage = getMage(); return mage == null ? null : mage.getController(); } @Override public void registerForUndo(Runnable runnable) { addWork(1); if (undoList != null) { undoList.add(runnable); } } @Override public void registerModified(Entity entity) { addWork(5); if (undoList != null) { undoList.modify(entity); } } @Override public void registerDamaged(Entity entity) { addWork(5); if (undoList != null) { undoList.damage(entity); } } @Override public void registerForUndo(Entity entity) { addWork(5); if (undoList != null) { undoList.add(entity); } } @Override public void registerForUndo(Block block) { addWork(10); if (undoList != null) { undoList.add(block); } } @Override public void updateBlock(Block block) { MageController controller = getController(); if (controller != null) { controller.updateBlock(block); } } @Override public void registerVelocity(Entity entity) { addWork(5); if (undoList != null) { undoList.modifyVelocity(entity); } } @Override public void registerMoved(Entity entity) { addWork(5); if (undoList != null) { undoList.move(entity); } } @Override public void registerPotionEffects(Entity entity) { addWork(5); if (undoList != null) { undoList.addPotionEffects(entity); } } @Override public Block getPreviousBlock() { return targetingSpell != null ? targetingSpell.getPreviousBlock() : null; } @Override public boolean isIndestructible(Block block) { return blockSpell != null ? blockSpell.isIndestructible(block) : true; } @Override public boolean hasBuildPermission(Block block) { return baseSpell != null ? baseSpell.hasBuildPermission(block) : false; } @Override public boolean hasBreakPermission(Block block) { return baseSpell != null ? baseSpell.hasBreakPermission(block) : false; } @Override public boolean hasEffects(String key) { return baseSpell != null ? baseSpell.hasEffects(key) : false; } @Override public void playEffects(String key) { playEffects(key, 1.0f); } @Override public Collection<EffectPlayer> getEffects(String effectKey) { Collection<EffectPlayer> effects = spell.getEffects(effectKey); if (effects.size() == 0) return effects; // Create parameter map Map<String, String> parameterMap = null; ConfigurationSection workingParameters = spell != null ? spell.getWorkingParameters() : null; if (workingParameters != null) { Collection<String> keys = workingParameters.getKeys(false); parameterMap = new HashMap<String, String>(); for (String key : keys) { parameterMap.put("$" + key, workingParameters.getString(key)); } } for (EffectPlayer player : effects) { // Track effect plays for cancelling player.setEffectPlayList(currentEffects); // Set material and color player.setMaterial(spell.getEffectMaterial()); player.setColor(spell.getEffectColor()); String overrideParticle = spell.getEffectParticle(); player.setParticleOverride(overrideParticle); // Set parameters player.setParameterMap(parameterMap); } return effects; } @Override public void playEffects(String effectName, float scale) { playEffects(effectName, scale, null, getEntity(), null, getTargetEntity()); } public void playEffects(String effectName, float scale, Block sourceBlock) { playEffects(effectName, scale, null, getEntity(), null, getTargetEntity(), sourceBlock); } @Override public void playEffects(String effectName, float scale, Location sourceLocation, Entity sourceEntity, Location targetLocation, Entity targetEntity) { playEffects(effectName, scale, sourceLocation, sourceEntity, targetLocation, targetEntity, null); } @Override public void playEffects(String effectName, float scale, Location sourceLocation, Entity sourceEntity, Location targetLocation, Entity targetEntity, Block sourceBlock) { Collection<EffectPlayer> effects = getEffects(effectName); if (effects.size() > 0) { Location wand = null; Location eyeLocation = getEyeLocation(); Location location = getLocation(); Collection<Entity> targeted = getTargetedEntities(); for (EffectPlayer player : effects) { // Set scale player.setScale(scale); Mage mage = getMage(); Location source = sourceLocation; if (source == null) { boolean useWand = mage != null && mage.getEntity() == sourceEntity && player.shouldUseWandLocation(); source = player.shouldUseEyeLocation() ? eyeLocation : location; if (useWand) { if (wand == null) { wand = getWandLocation(); } source = wand; } } Location target = targetLocation; if (target == null) { target = getTargetLocation(); if (player.shouldUseBlockLocation()) { target = target.getBlock().getLocation(); } else if (!player.shouldUseHitLocation() && targetEntity != null) { if (targetEntity instanceof LivingEntity) { target = ((LivingEntity)targetEntity).getEyeLocation(); } else { target = targetEntity.getLocation(); } } } if (sourceBlock != null) { player.setMaterial(sourceBlock); } player.start(source, sourceEntity, target, targetEntity, targeted); } } } @Override public void cancelEffects() { for (EffectPlay player : currentEffects) { player.cancel(); } currentEffects.clear(); } @Override public String getMessage(String key) { return getMessage(key, ""); } @Override public String getMessage(String key, String def) { return baseSpell != null ? baseSpell.getMessage(key, def) : def; } @Override public Location findPlaceToStand(Location target, int verticalSearchDistance, boolean goUp) { return baseSpell != null ? baseSpell.findPlaceToStand(target, goUp, verticalSearchDistance) : location; } public Location findPlaceToStand(Location targetLoc, int verticalSearchDistance) { return baseSpell != null ? baseSpell.findPlaceToStand(targetLoc, verticalSearchDistance, verticalSearchDistance) : location; } @Override public int getVerticalSearchDistance() { return baseSpell != null ? baseSpell.getVerticalSearchDistance() : 4; } @Override public boolean isOkToStandIn(Material material) { return baseSpell != null ? baseSpell.isOkToStandIn(material) : true; } @Override public boolean isWater(Material mat) { return (mat == Material.WATER || mat == Material.STATIONARY_WATER); } @Override public boolean isOkToStandOn(Material material) { return (material != Material.AIR && material != Material.LAVA && material != Material.STATIONARY_LAVA); } @Override public boolean allowPassThrough(Material material) { return baseSpell != null ? baseSpell.allowPassThrough(material) : true; } @Override public void castMessageKey(String key) { if (baseSpell != null) { baseSpell.castMessage(getMessage(key)); } } @Override public void sendMessageKey(String key) { if (baseSpell != null) { baseSpell.sendMessage(getMessage(key)); } } @Override public void showMessage(String key, String def) { Mage mage = getMage(); if (mage != null) { mage.sendMessage(getMessage(key, def)); } } @Override public void showMessage(String message) { Mage mage = getMage(); if (mage != null) { mage.sendMessage(message); } } @Override public void castMessage(String message) { if (baseSpell != null) { baseSpell.castMessage(message); } } @Override public void sendMessage(String message) { if (baseSpell != null) { baseSpell.sendMessage(message); } } @Override public void setTargetedLocation(Location location) { if (targetingSpell != null) { targetingSpell.setTarget(location); } } @Override public Block findBlockUnder(Block block) { if (targetingSpell != null) { block = targetingSpell.findBlockUnder(block); } return block; } @Override public Block findSpaceAbove(Block block) { if (targetingSpell != null) { block = targetingSpell.findSpaceAbove(block); } return block; } @Override public boolean isTransparent(Material material) { if (targetingSpell != null) { return targetingSpell.isTransparent(material); } return material.isTransparent(); } @Override public boolean isPassthrough(Material material) { if (baseSpell != null) { return baseSpell.isPassthrough(material); } return material.isTransparent(); } @Override public boolean isDestructible(Block block) { if (blockSpell != null) { return blockSpell.isDestructible(block); } return true; } @Override public boolean areAnyDestructible(Block block) { if (blockSpell != null) { return blockSpell.areAnyDestructible(block); } return true; } @Override public boolean isTargetable(Block block) { if (targetingSpell != null) { return targetingSpell.isTargetable(this, block); } return true; } @Override public TargetType getTargetType() { TargetType targetType = TargetType.NONE; if (targetingSpell != null) { targetType = targetingSpell.getTargetType(); } return targetType; } @Override public boolean getTargetsCaster() { if (baseSpell != null) { return baseSpell.getTargetsCaster(); } return false; } @Override public boolean isConsumeFree() { if (baseSpell != null) { return baseSpell.getConsumeReduction() >= 1; } return false; } @Override public void setTargetsCaster(boolean target) { if (baseSpell != null) { baseSpell.setTargetsCaster(target); } } @Override public boolean canTarget(Entity entity) { return targetingSpell == null ? true : targetingSpell.canTarget(entity); } @Override public MaterialBrush getBrush() { if (brush != null) { return brush; } return brushSpell == null ? null : brushSpell.getBrush(); } @Override public void setBrush(MaterialBrush brush) { this.brush = brush; } @Override public Collection<Entity> getTargetedEntities() { if (undoList == null) { return new ArrayList<Entity>(); } return undoList.getAllEntities(); } @Override public void messageTargets(String messageKey) { Mage mage = getMage(); if (mage.isStealth()) return; Collection<Entity> targets = getTargetedEntities(); if (targets == null || targets.isEmpty()) return; MageController controller = getController(); LivingEntity sourceEntity = mage == null ? null : mage.getLivingEntity(); String playerMessage = getMessage(messageKey); if (playerMessage.length() > 0) { for (Entity target : targets) { UUID targetUUID = target.getUniqueId(); if (target instanceof Player && target != sourceEntity && !targetMessagesSent.contains(targetUUID)) { targetMessagesSent.add(targetUUID); playerMessage = playerMessage.replace("$spell", spell.getName()); Mage targetMage = controller.getMage(target); targetMage.sendMessage(playerMessage); } } } } @Override public Block getInteractBlock() { Location location = getEyeLocation(); if (location == null) return null; Block playerBlock = location.getBlock(); if (isTargetable(playerBlock)) return playerBlock; Vector direction = location.getDirection().normalize(); return location.add(direction).getBlock(); } @Override public Random getRandom() { if (random == null) { random = new Random(); } return random; } @Override public UndoList getUndoList() { return undoList; } @Override public String getTargetName() { return targetName; } @Override public void setTargetName(String name) { targetName = name; } @Override public Logger getLogger() { return getController().getLogger(); } @Override public int getWorkAllowed() { return this.base.workAllowed; } @Override public void setWorkAllowed(int work) { this.base.workAllowed = work; } @Override public void addWork(int work) { this.base.workAllowed -= work; } @Override public void performedActions(int count) { this.base.actionsPerformed += count; } @Override public int getActionsPerformed() { return base.actionsPerformed; } @Override public void finish() { if (finished) return; finished = true; Mage mage = getMage(); if (undoSpell != null && undoSpell.isUndoable()) { if (!undoList.isScheduled()) { getController().update(undoList); } mage.registerForUndo(undoList); } result = result.max(initialResult); if (spell != null) { mage.sendDebugMessage(ChatColor.WHITE + "Finish " + ChatColor.GOLD + spell.getName() + ChatColor.WHITE + ": " + ChatColor.AQUA + result.name().toLowerCase(), 2); spell.finish(this); } String resultName = result.name().toLowerCase(); castMessageKey(resultName + "_finish"); playEffects(resultName + "_finish"); } @Override public void retarget(int range, double fov, double closeRange, double closeFOV, boolean useHitbox) { if (targetingSpell != null) { targetingSpell.retarget(range, fov, closeRange, closeFOV, useHitbox); setTargetEntity(targetingSpell.getTargetEntity()); setTargetLocation(targetingSpell.getTargetLocation()); } } @Override public void retarget(int range, double fov, double closeRange, double closeFOV, boolean useHitbox, int yOffset, boolean targetSpaceRequired, int targetMinOffset) { if (targetingSpell != null) { targetingSpell.retarget(range, fov, closeRange, closeFOV, useHitbox, yOffset, targetSpaceRequired, targetMinOffset); setTargetEntity(targetingSpell.getTargetEntity()); setTargetLocation(targetingSpell.getTargetLocation()); } } @Override public com.elmakers.mine.bukkit.api.action.CastContext getBaseContext() { return base; } @Override public Location getTargetCenterLocation() { return targetCenterLocation == null ? targetLocation : targetCenterLocation; } @Override public Set<UUID> getTargetMessagesSent() { return targetMessagesSent; } @Override public Collection<EffectPlay> getCurrentEffects() { return currentEffects; } @Override public Plugin getPlugin() { MageController controller = getController(); return controller == null ? null : controller.getPlugin(); } @Override public boolean teleport(final Entity entity, final Location location, final int verticalSearchDistance, boolean preventFall) { return teleport(entity, location, verticalSearchDistance, preventFall, true); } @Override public boolean teleport(final Entity entity, final Location location, final int verticalSearchDistance, boolean preventFall, boolean safe) { Chunk chunk = location.getBlock().getChunk(); if (!chunk.isLoaded()) { chunk.load(true); } Location targetLocation = findPlaceToStand(location, verticalSearchDistance); org.bukkit.Bukkit.getLogger().info("Found " + targetLocation + " from " + location + " search: " + verticalSearchDistance); if (targetLocation == null && !preventFall) { Block block = location.getBlock(); Block blockOneUp = block.getRelative(BlockFace.UP); if (!safe || (isOkToStandIn(blockOneUp.getType()) && isOkToStandIn(block.getType()))) { targetLocation = location; } } if (targetLocation != null) { targetLocation.setX(location.getX() - location.getBlockX() + targetLocation.getBlockX()); targetLocation.setZ(location.getZ() - location.getBlockZ() + targetLocation.getBlockZ()); registerMoved(entity); // Hacky double-teleport to work-around vanilla suffocation checks boolean isWorldChange = !targetLocation.getWorld().equals(entity.getWorld()); entity.teleport(targetLocation); if (isWorldChange) { entity.teleport(targetLocation); } setTargetLocation(targetLocation); sendMessageKey("teleport"); playEffects("teleport"); } else { sendMessageKey("teleport_failed"); playEffects("teleport_failed"); return false; } return true; } @Override public boolean teleport(final Entity entity, final Location location, final int verticalSearchDistance) { return teleport(entity, location, verticalSearchDistance, true); } @Override public void setSpellParameters(ConfigurationSection parameters) { if (baseSpell != null) { baseSpell.processParameters(parameters); } } @Override public Set<Material> getMaterialSet(String key) { return getController().getMaterialSet(key); } @Override public SpellResult getResult() { return this.result; } @Override public void setResult(SpellResult result) { this.result = result; } @Override public void addResult(SpellResult result) { if (result != SpellResult.PENDING) { this.result = this.result.min(result); } } public void setInitialResult(SpellResult result) { initialResult = result; } @Override public boolean canCast(Location location) { if (baseSpell != null) { return baseSpell.canCast(location); } return true; } @Override public boolean isBreakable(Block block) { return com.elmakers.mine.bukkit.block.UndoList.isBreakable(block); } @Override public Double getBreakable(Block block) { return com.elmakers.mine.bukkit.block.UndoList.getBreakable(block); } @Override public void clearBreakable(Block block) { com.elmakers.mine.bukkit.block.UndoList.unregisterBreakable(block); } @Override public void clearReflective(Block block) { com.elmakers.mine.bukkit.block.UndoList.unregisterReflective(block); } @Override public boolean isReflective(Block block) { if (block == null) return false; if (targetingSpell != null && targetingSpell.isReflective(block.getType())) { return true; } return com.elmakers.mine.bukkit.block.UndoList.isReflective(block); } @Override public Double getReflective(Block block) { if (block == null) return null; if (block == null) return null; if (targetingSpell != null && targetingSpell.isReflective(block.getType())) { return 1.0; } return com.elmakers.mine.bukkit.block.UndoList.getReflective(block); } @Override public void registerBreakable(Block block, double breakable) { com.elmakers.mine.bukkit.block.UndoList.registerBreakable(block, breakable); undoList.setUndoBreakable(true); } @Override public void registerReflective(Block block, double reflectivity) { com.elmakers.mine.bukkit.block.UndoList.registerReflective(block, reflectivity); undoList.setUndoReflective(true); } @Override public String parameterize(String command) { Location location = getLocation(); Mage mage = getMage(); MageController controller = getController(); command = command .replace("@_", " ") .replace("@spell", getSpell().getName()) .replace("@pd", mage.getDisplayName()) .replace("@pn", mage.getName()) .replace("@uuid", mage.getId()) .replace("@p", mage.getName()); if (location != null) { command = command .replace("@world", location.getWorld().getName()) .replace("@x", Double.toString(location.getX())) .replace("@y", Double.toString(location.getY())) .replace("@z", Double.toString(location.getZ())); } Location targetLocation = getTargetLocation(); if (targetLocation != null) { command = command .replace("@tworld", targetLocation.getWorld().getName()) .replace("@tx", Double.toString(targetLocation.getX())) .replace("@ty", Double.toString(targetLocation.getY())) .replace("@tz", Double.toString(targetLocation.getZ())); } Entity targetEntity = getTargetEntity(); if (targetEntity != null) { if (controller.isMage(targetEntity)) { Mage targetMage = controller.getMage(targetEntity); command = command .replace("@td", targetMage.getDisplayName()) .replace("@tn", targetMage.getName()) .replace("@tuuid", targetMage.getId()) .replace("@t", targetMage.getName()); } else { command = command .replace("@td", controller.getEntityDisplayName(targetEntity)) .replace("@tn", controller.getEntityName(targetEntity)) .replace("@tuuid", targetEntity.getUniqueId().toString()) .replace("@t", controller.getEntityName(targetEntity)); } } return ChatColor.translateAlternateColorCodes('&', command); } }
Remove debug print
src/main/java/com/elmakers/mine/bukkit/action/CastContext.java
Remove debug print
<ide><path>rc/main/java/com/elmakers/mine/bukkit/action/CastContext.java <ide> } <ide> <ide> Location targetLocation = findPlaceToStand(location, verticalSearchDistance); <del> <del> org.bukkit.Bukkit.getLogger().info("Found " + targetLocation + " from " + location + " search: " + verticalSearchDistance); <del> <ide> if (targetLocation == null && !preventFall) { <ide> Block block = location.getBlock(); <ide> Block blockOneUp = block.getRelative(BlockFace.UP);
Java
apache-2.0
cc2be7cfea878aba3ff5ef577b9b3df5ecbb72b2
0
AmeBel/relex,rodsol/relex-temp,leungmanhin/relex,ainishdave/relex,williampma/relex,opencog/relex,williampma/relex,ainishdave/relex,anitzkin/relex,ainishdave/relex,opencog/relex,AmeBel/relex,linas/relex,rodsol/relex-temp,virneo/relex,ainishdave/relex,williampma/relex,rodsol/relex,williampma/relex,opencog/relex,rodsol/relex,rodsol/relex-temp,anitzkin/relex,linas/relex,anitzkin/relex,rodsol/relex,linas/relex,virneo/relex,anitzkin/relex,AmeBel/relex,rodsol/relex-temp,rodsol/relex,anitzkin/relex,rodsol/relex-temp,virneo/relex,virneo/relex,leungmanhin/relex,leungmanhin/relex
/* * Copyright 2008 Novamente LLC * * 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 relex.feature; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import relex.output.PrologList; /** * FeatureNodes may store either a set of key-value pairs, where the * values are other FeatureNodes, or they may store a single string. * * XXX FIXME: The FeatureNode class is nothing more than a home-grown * version of a standard key-value aka frame-slot class. It should * be replaced by, or, at least, inherit from, some standard java * class library implementing these functions. * * This class also needs to be refactored: by attempting to store * either a string value or set of keyed nodes, it has to check * for bad access and throw exceptions when this occurs. It would * have been more effective to either run-time up-cast, and to * implement LISP-like cons, pair, car and cdr primitves to avoid * this confusion. */ public class FeatureNode extends Atom { private static final long serialVersionUID = -1498736655984934453L; // Width of output of toString(), before it is truncated with "..." private static int PRINT_LIMIT = 300; private static FeatureNameFilter DEFAULT_FEATURE_NAME_FILTER = new FeatureNameFilter(); public static FeatureNameFilter defaultFilter() { return DEFAULT_FEATURE_NAME_FILTER; } /** * The set of all FeatureNodes which have features pointing to this one. * This is used to properly implement mergeWith(other: FeatureNode) In this * case, the other is destroyed, and the parents must be notified in order * to reset their features to point to the new FeatureNode. */ private HashSet<FeatureNode> parents; /** * FeatureNodes may store either a set of key-value pairs, where the * values are other FeatureNodes, or they may store a single string. * Most access routines to this class will throw an exception if * the wrong one of these two different things is requested. */ private HashMap<String,FeatureNode> kv_pairs; private String value; /** * By default, feature structures have no string value */ public FeatureNode() { parents = new HashSet<FeatureNode>(); kv_pairs = new HashMap<String,FeatureNode>(); value = null; } /** */ public FeatureNode(String str) { this(); // If str can be interpreted as a FeatureAction, it is. // Otherwise, str is interpreted as the value of this FeatureNode. // // But this is used only during development of new relex rules; // do not do this in ordinary production code. In particular, // this code will mis-identify any lingering HTML markup, and // crash the system! (We shouldn't feed relex any HTML, but // sometimes some slips through ..) // //if (str.length() > 0 && str.charAt(0) == '<') { // String[] lines = str.split("\\n"); // for (int i = 0; i < lines.length; i++) { // FeatureAction act = new FeatureAction(lines[i]); // act.doAction(this); // } //} else { // forceValue(str); //} forceValue(str); } protected Iterator<FeatureNode> getParents() { return parents.iterator(); } /** * @return true if the node value is simply a string. */ public boolean isValued() { return kv_pairs == null; } /** * Force node to store a hash of key-value pairs */ public void forceFeatures() { if (value != null) throw new RuntimeException( "Must set value to null before forcing features."); if (kv_pairs == null) kv_pairs = new HashMap<String,FeatureNode>(); } /** * Force node to store a single string value. */ public void forceValue(String val) { if (kv_pairs != null) { if (getFeatureNames().size() > 0) throw new RuntimeException( "Must clear features before forcing value."); } kv_pairs = null; setValue(val); } /** * @return true if this feature structure has no values or features */ public boolean isEmpty() { if (isValued()) return value == null; return kv_pairs.size() == 0; } /** * Sets the value of this feature node. Method will fail if this FeatureNode * is not valued, by throwing RuntimeException. * * @param value * the value of this feature node */ public void setValue(String value) { if (!isValued()) throw new RuntimeException( "Cannot set the value of a non-valued FeatureNode"); if (value == null) throw new RuntimeException("Cannot set to null value"); this.value = new String(value); } /** * @return the value of this FeatureNode, or null if it has none */ public String getValue() { if (!isValued()) throw new RuntimeException("non-valued FeatureNodes have no string value"); return value; } /** * Perform a key-value lookup. * @param key * the name of a feature to be looked up. * @return the string value associated with the key, else * null, if the thing associated with the key is * a non-string-valued FeatureNode. */ public String featureValue(String key) { FeatureNode f = get(key); if (f == null) return null; return f.getValue(); } /** * Convenience method to create a feature node and add it to this one. * Throws RuntimeException if this FeatureNode is string-valued. * @param key * @return the new FeatureNode */ public FeatureNode add(String key) { if (isValued()) throw new RuntimeException( "Cannot add a key for a string-valued FeatureNode"); FeatureNode f = new FeatureNode(); set(key, f); return f; } public void add(String key, String value) { FeatureNode fn = add(key); fn.forceValue(value); } /** * Substitutes oldF with newF in any of the feature targets of this node. */ public void substitute(FeatureNode oldF, FeatureNode newF) { if (oldF == newF) return; Iterator<String> i = getFeatureNames().iterator(); while (i.hasNext()) { String name = i.next(); if (get(name).equiv(oldF)) set(name, newF); } } /** * Merges other into this, throwing an exception if they are not unifiable. * If "this" isEmpty, then it is replaced with other, which means that after * calling this method, "this" is not guaranteed to be a legitimate part of * the entire feature structure you were dealing with. * * XXX -- this is somewhat strangely named, it doesn't really * merge, per-se, since if both featurenodes have features * in them, then it throws an exeption if the features aren't * identical. So really, a "merge" occurs only when one of the * featurenodes is empty. * * What's even crazier, the SentenceAlgorithm.java silently * eats the exceptions thrown here. So its all pretty pointless... * * So basically, this is just kind of crazy, I think. This * makes sense only if the algs files are cleanly built... * * Returns the merged node. */ public FeatureNode mergeWith(FeatureNode other) { if (other == this) return this; if (other.isEmpty()) { other.replaceSelfWith(this); return other; } if (isEmpty()) { replaceSelfWith(other); return this; } // Throw execeptions if the two FeatureNodes are non-unifiable if (isValued()) { if ((!other.isValued()) || (!other.getValue().equals(getValue()))) { throw new RuntimeException( "Cannot merge a nonvalued node or a node with a different value into a non-empty valued node"); } } else { // this has features if (other.isValued()) { // other has value throw new RuntimeException( "Cannot merge a non-empty valued node into a non-empty normal feature node"); } // other has features for (String fName : other.getFeatureNames()) { FeatureNode otherf = other.get(fName); FeatureNode thisf = this.get(fName); if (otherf != thisf) { throw new RuntimeException( "Cannot merge two non-valued feature nodes with inconsistent features.\n" + "\tSuggest using += instead of = in algs file. fName = " + fName); } } } return this; } public FeatureNode copyInto(FeatureNode other) { if (other == this) return this; // Throw execeptions if the two FeatureNodes are non-unifiable if (isValued()) { if (!other.isValued()) { throw new RuntimeException( "Cannot merge a nonvalued node into a non-empty valued node"); } } else { // this has features if (other.isValued()) { // other has value throw new RuntimeException( "Cannot merge a non-empty valued node into a non-empty normal feature node"); } } // After checking for inconsistencies above, we can safely execute the // code below if (!isValued()) { for (String fName : other.getFeatureNames()) { set(fName, other.get(fName)); } } return this; } public void replaceSelfWith(FeatureNode other) { if (other == this) return; // Create a new hashset to avoid ConcurrentModificationException. // That is, we will be modifying parents as we iterate through its // *copy*. Iterator<FeatureNode> i = new HashSet<FeatureNode>(parents).iterator(); while (i.hasNext()) { FeatureNode p = i.next(); p.substitute(this, other); } if (!parents.isEmpty()) throw new RuntimeException("replace self failed"); } /** * Associates key to the target FeatureNode. Drops references to the * existing target associated with this key, if any. An exiting target * is notified that it must update it's parent set. Setting to null * removes the feature from this FeatureNode. If this FeatureNode is * string-valued, the method will fail and throw RuntimeException. * * @param key * the key that will reference the target. * @param target * the FeatureNode to set it to. */ public void set(String key, FeatureNode target) { if (isValued()) throw new RuntimeException("Cannot set key-value pair for a string-valued FeatureNode"); if (key == null) throw new RuntimeException("key must be non-null"); FeatureNode oldTarget = get(key); if (target == null) { kv_pairs.remove(key); } else { target.parents.add(this); kv_pairs.put(key, target); } if (oldTarget != null) { // If there are no other features pointing to the old target, // remove this from the list of oldTarget's parents. if (!kv_pairs.containsValue(oldTarget)) oldTarget.parents.remove(this); } } /** * Returns a feature's value, i.e. the node associated with * the name "key". If this node is string-valued, NULL is returned. * * @param key * @return the value of the feature, or null if it has no value */ public FeatureNode get(String key) { if (isValued()) throw new RuntimeException("String-valued FeatureNodes have no keys."); if (key == null) throw new RuntimeException("Key was null"); return kv_pairs.get(key); } // Like "get" but makes the feature node if it doesn't exist. public FeatureNode getOrMake(String key) { FeatureNode ret = get(key); if (ret == null) { ret = new FeatureNode(); set(key, ret); } return ret; } /** * Returns the set of keys in this FeatureNode * * @return the set of feature names */ public Set<String> getFeatureNames() { if (isValued()) throw new RuntimeException("valued FeatureNodes have no features"); return kv_pairs.keySet(); } /** * Recursive function implements toString, keeping track of how far to * indent each level, and appending values to a StringBuffer. * * The use of an "already visited" hashset lowers performance * dramatically, but makes this routine thread-safe in principle. * * @param indents * the number of double spaces to indent the output * @param sb * the string buffer to output to * @param indices * a map from FeatureNodes to indices * @param alreadyVisited * the set of FeatureNodes which have already been visited * @param filter * a filter that controls which features are printed, and their * order */ protected void _toString(int indents, StringBuffer sb, HashMap<FeatureNode,Integer> indices, HashSet<FeatureNode> alreadyVisited, FeatureNameFilter filter) { // Get index and return if its already been printed. Integer index = (Integer) indices.get(this); int indexIndents = 0; if (index != null) { sb.append("$").append(index.toString()); if (alreadyVisited.contains(this) && !isValued()) return; indexIndents = (index.intValue() > 9 ? 3 : 2); } // else alreadyVisited.add(this); // Don't print too deep into a feature structure. if (indents > PRINT_LIMIT) { sb.append("..."); return; } // For string-valued feature nodes, print value and return. if (isValued()) { sb.append(toString()); return; } // Print current node. sb.append("["); // Set the number of spaces to indent features in this node. StringBuffer spaces = new StringBuffer(); for (int j = 0; j < indents + indexIndents + 1; j++) spaces.append(" "); boolean firstLoop = true; // For each key, recurse. Iterator<String> i = features(filter); while (i.hasNext()) { if (firstLoop) firstLoop = false; else sb.append("\n").append(spaces); String featName = i.next(); int newindents = indents + indexIndents + 2 + featName.length(); sb.append(featName).append(" "); get(featName)._toString(newindents, sb, indices, alreadyVisited, filter); } sb.append("]"); } /* * Creates a map from FeatureNodes that appear more than once, * to integers. Used by toString() to print indices only once * when FeatureNodes appear more than once. */ private HashMap<FeatureNode,Integer> makeIndices(HashMap<FeatureNode,Integer> indices, HashSet<FeatureNode> alreadyVisited, FeatureNameFilter filter) { if (alreadyVisited.contains(this)) { if (!indices.keySet().contains(this)) indices.put(this, indices.size()); return indices; } alreadyVisited.add(this); if (!isValued()) { Iterator<String> i = features(filter); while (i.hasNext()) { String s = i.next(); get(s).makeIndices(indices, alreadyVisited, filter); } } return indices; } /** * Returns a pretty-printed, multi-line indented string representing * the contents of this FeatureNode. The filter is used to determine * which nodes are printed. * * @return */ public String toString(FeatureNameFilter filter) { if (isValued()) return "<<" + getValue() + ">>"; StringBuffer sb = new StringBuffer(); _toString(0, sb, makeIndices(new HashMap<FeatureNode,Integer>(), new HashSet<FeatureNode>(), filter), new HashSet<FeatureNode>(), filter); return sb.toString(); } public String toString() { return toString(DEFAULT_FEATURE_NAME_FILTER); } /** * Export feature structures as Prolog lists. * XXX deprecated -- caller should use the PrologList class directly * @deprecated */ public String toPrologList(FeatureNameFilter filter, boolean indent) { PrologList pl = new PrologList(); return pl.toPrologList(this, filter, indent); } /** * pathTarget() -- find the feature node at the end of the path * @return feature or null if not in path * * This routine walks the indicated chain of keys, looking * up each in turn. If any key in the path is not found, * null is returned. If particular, if the very first * path element is not found, null is returned. If the * navigation was successful, then the FeatureNode at * the end of the path is returned. * * Example usage: * pathTarget(new FeaturePath("<ref noun_number>")); */ public FeatureNode pathTarget(FeaturePath path) { FeatureNode cur = this; Iterator<String> feats = path.iterator(); while (feats.hasNext() && cur != null) { if (cur.isValued()) return null; cur = cur.get(feats.next()); } return cur; } public FeatureNode pathTarget(String str) { return pathTarget(new FeaturePath(str)); } /** * pathValue() -- * Returns the value of the path target -- or null if the path does not exist. */ public String pathValue(FeaturePath path) { FeatureNode target = pathTarget(path); if (target == null) return null; return target.getValue(); } public String pathValue(String str) { FeaturePath path = new FeaturePath(str); FeatureNode target = pathTarget(path); if (target == null) return null; if (!target.isValued()) return null; return target.getValue(); } /** * Like pathTarget(), but creates the path if it doesn't already exist. * setting its target to the passed target. If forceTarget is false, then an * error will be thrown if the path does not unify with this FeatureNode. */ public void makePath(FeaturePath path, FeatureNode target, boolean forceTarget) { FeatureNode cur = this; Iterator<String> feats = path.iterator(); while (feats.hasNext()) { FeatureNode last = cur; String name = feats.next(); cur = cur.get(name); if (cur == null) { if (feats.hasNext()) { cur = new FeatureNode(); } else { cur = target; if ((!forceTarget) && last.get(name) != null) throw new RuntimeException("Path already exists"); } last.set(name, cur); } } } public void makePath(FeaturePath path, FeatureNode target) { makePath(path, target, false); } /** * equiv() -- returns true if two references point to the same object. * @return true if equivalent, else false * @param other pointer to the object being compared to * * The standard comp-sci name for this is "equiv", and not "equals". * The method "equals" will return true if two objects contain the * same data; whereas this method return true only if its one and the * same object. * * This routine is used to handle the case where two features are set * to each other even though they have no value. In this case, we * might have something like: <a b c> = <d e f>. The target of both * these paths will be the same object: an empty FeatureNode. * */ public final boolean equiv(Object other) { // MUST BE == return other == this; } /* * features() -- returns a list of the features minus those specified by a filter * @return an iterator to an ArrayList containing those features of this FeatureNode not in the filter's ignore list * @param filter the FeatureNameFilter * This routine returns the feature node's features without * the features specified by the filter pa */ public Iterator<String> features(FeatureNameFilter filter) { ArrayList<String> output = new ArrayList<String>(); HashSet<String> featureNamesCopy = new HashSet<String>(getFeatureNames()); ArrayList<String> ignored = new ArrayList<String>(); for(String aFilter: filter.getIgnoreSet()){ filter.transferMultiNames(ignored, featureNamesCopy, aFilter); } filter.transfer(output, featureNamesCopy); return output.iterator(); } /** * Debugging function -- return string containing key names. */ public String _prt_keys() { if (isValued()) return ""; String ret = ""; Iterator<String> j = getFeatureNames().iterator(); while (j.hasNext()) { String stuff = j.next(); ret += stuff + " "; } ret += "\n"; return ret; } /** * Debugging function -- return list of key-value pairs. */ public String _prt_vals() { if (isValued()) return "this=" + value; String ret = ""; Iterator<String> j = getFeatureNames().iterator(); while (j.hasNext()) { String stuff = j.next(); ret += stuff + "="; String v = pathValue("<" + stuff + ">"); if (v == null) ret += "@"; else ret += v; ret += "\n"; } return ret; } // Test method static public void main(String[] args) { FeatureNode three = new FeatureNode("3"); FeatureNode root = new FeatureNode(); root.add("a").add("b").add("c").set("d", three); root.get("a").set("c", new FeatureNode("4")); root.add("a0").add("b0").set("c0", root.get("a").get("b").get("c")); System.out.println(root); } } // =========================== End of File ===============================
src/java/relex/feature/FeatureNode.java
/* * Copyright 2008 Novamente LLC * * 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 relex.feature; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import relex.output.PrologList; /** * FeatureNodes may store either a set of key-value pairs, where the * values are other FeatureNodes, or they may store a single string. * * XXX FIXME: The FeatureNode class is nothing more than a home-grown * version of a standard key-value aka frame-slot class. It should * be replaced by, or, at least, inherit from, some standard java * class library implementing these functions. * * This class also needs to be refactored: by attempting to store * either a string value or set of keyed nodes, it has to check * for bad access and throw exceptions when this occurs. It would * have been more effective to either run-time up-cast, and to * implement LISP-like cons, pair, car and cdr primitves to avoid * this confusion. */ public class FeatureNode extends Atom { private static final long serialVersionUID = -1498736655984934453L; // Width of output of toString(), before it is truncated with "..." private static int PRINT_LIMIT = 300; private static FeatureNameFilter DEFAULT_FEATURE_NAME_FILTER = new FeatureNameFilter(); public static FeatureNameFilter defaultFilter() { return DEFAULT_FEATURE_NAME_FILTER; } /** * The set of all FeatureNodes which have features pointing to this one. * This is used to properly implement mergeWith(other: FeatureNode) In this * case, the other is destroyed, and the parents must be notified in order * to reset their features to point to the new FeatureNode. */ private HashSet<FeatureNode> parents; /** * FeatureNodes may store either a set of key-value pairs, where the * values are other FeatureNodes, or they may store a single string. * Most access routines to this class will throw an exception if * the wrong one of these two different things is requested. */ private HashMap<String,FeatureNode> kv_pairs; private String value; /** * By default, feature structures have no string value */ public FeatureNode() { parents = new HashSet<FeatureNode>(); kv_pairs = new HashMap<String,FeatureNode>(); value = null; } /** */ public FeatureNode(String str) { this(); // If str can be interpreted as a FeatureAction, it is. // Otherwise, str is interpreted as the value of this FeatureNode. // // But this is used only during development of new relex rules; // do not do this in ordinary production code. In particular, // this code will mis-identify any lingering HTML markup, and // crash the system! (We shouldn't feed relex any HTML, but // sometimes some slips through ..) // //if (str.length() > 0 && str.charAt(0) == '<') { // String[] lines = str.split("\\n"); // for (int i = 0; i < lines.length; i++) { // FeatureAction act = new FeatureAction(lines[i]); // act.doAction(this); // } //} else { // forceValue(str); //} forceValue(str); } protected Iterator<FeatureNode> getParents() { return parents.iterator(); } /** * @return true if the node value is simply a string. */ public boolean isValued() { return kv_pairs == null; } /** * Force node to store a hash of key-value pairs */ public void forceFeatures() { if (value != null) throw new RuntimeException( "Must set value to null before forcing features."); if (kv_pairs == null) kv_pairs = new HashMap<String,FeatureNode>(); } /** * Force node to store a single string value. */ public void forceValue(String val) { if (kv_pairs != null) { if (getFeatureNames().size() > 0) throw new RuntimeException( "Must clear features before forcing value."); } kv_pairs = null; setValue(val); } /** * @return true if this feature structure has no values or features */ public boolean isEmpty() { if (isValued()) return value == null; return kv_pairs.size() == 0; } /** * Sets the value of this feature node. Method will fail if this FeatureNode * is not valued, by throwing RuntimeException. * * @param value * the value of this feature node */ public void setValue(String value) { if (!isValued()) throw new RuntimeException( "Cannot set the value of a non-valued FeatureNode"); if (value == null) throw new RuntimeException("Cannot set to null value"); this.value = new String(value); } /** * @return the value of this FeatureNode, or null if it has none */ public String getValue() { if (!isValued()) throw new RuntimeException("non-valued FeatureNodes have no string value"); return value; } /** * Perform a key-value lookup. * @param key * the name of a feature to be looked up. * @return the string value associated with the key, else * null, if the thing associated with the key is * a non-string-valued FeatureNode. */ public String featureValue(String key) { FeatureNode f = get(key); if (f == null) return null; return f.getValue(); } /** * Convenience method to create a feature node and add it to this one. * Throws RuntimeException if this FeatureNode is string-valued. * @param key * @return the new FeatureNode */ public FeatureNode add(String key) { if (isValued()) throw new RuntimeException( "Cannot add a key for a string-valued FeatureNode"); FeatureNode f = new FeatureNode(); set(key, f); return f; } public void add(String key, String value) { FeatureNode fn = add(key); fn.forceValue(value); } /** * Substitutes oldF with newF in any of the feature targets of this node. */ public void substitute(FeatureNode oldF, FeatureNode newF) { if (oldF == newF) return; Iterator<String> i = getFeatureNames().iterator(); while (i.hasNext()) { String name = i.next(); if (get(name).equiv(oldF)) set(name, newF); } } /** * Merges other into this, throwing an exception if they are not unifiable. * If "this" isEmpty, then it is replaced with other, which means that after * calling this method, "this" is not guaranteed to be a legitimate part of * the entire feature structure you were dealing with. * * XXX -- this is somewhat strangely named, it doesn't really * merge, per-se, since if both featurenodes have features * in them, then it throws an exeption if the features aren't * identical. So really, a "merge" occurs only when one of the * featurenodes is empty. * * What's even crazier, the SentenceAlgorithm.java silently * eats the exceptions thrown here. So its all pretty pointless... * * So basically, this is just kind of crazy, I think. This * makes sense only if the algs files are cleanly built... * * Returns the merged node. */ public FeatureNode mergeWith(FeatureNode other) { if (other == this) return this; if (other.isEmpty()) { other.replaceSelfWith(this); return other; } if (isEmpty()) { replaceSelfWith(other); return this; } // Throw execeptions if the two FeatureNodes are non-unifiable if (isValued()) { if ((!other.isValued()) || (!other.getValue().equals(getValue()))) { throw new RuntimeException( "Cannot merge a nonvalued node or a node with a different value into a non-empty valued node"); } } else { // this has features if (other.isValued()) { // other has value throw new RuntimeException( "Cannot merge a non-empty valued node into a non-empty normal feature node"); } // other has features for (String fName : other.getFeatureNames()) { FeatureNode otherf = other.get(fName); FeatureNode thisf = this.get(fName); if (otherf != thisf) { throw new RuntimeException( "Cannot merge two non-valued feature nodes with inconsistent features. fName = " + fName); } } } return this; } public FeatureNode copyInto(FeatureNode other) { if (other == this) return this; // Throw execeptions if the two FeatureNodes are non-unifiable if (isValued()) { if (!other.isValued()) { throw new RuntimeException( "Cannot merge a nonvalued node into a non-empty valued node"); } } else { // this has features if (other.isValued()) { // other has value throw new RuntimeException( "Cannot merge a non-empty valued node into a non-empty normal feature node"); } } // After checking for inconsistencies above, we can safely execute the // code below if (!isValued()) { for (String fName : other.getFeatureNames()) { set(fName, other.get(fName)); } } return this; } public void replaceSelfWith(FeatureNode other) { if (other == this) return; // Create a new hashset to avoid ConcurrentModificationException. // That is, we will be modifying parents as we iterate through its // *copy*. Iterator<FeatureNode> i = new HashSet<FeatureNode>(parents).iterator(); while (i.hasNext()) { FeatureNode p = i.next(); p.substitute(this, other); } if (!parents.isEmpty()) throw new RuntimeException("replace self failed"); } /** * Associates key to the target FeatureNode. Drops references to the * existing target associated with this key, if any. An exiting target * is notified that it must update it's parent set. Setting to null * removes the feature from this FeatureNode. If this FeatureNode is * string-valued, the method will fail and throw RuntimeException. * * @param key * the key that will reference the target. * @param target * the FeatureNode to set it to. */ public void set(String key, FeatureNode target) { if (isValued()) throw new RuntimeException("Cannot set key-value pair for a string-valued FeatureNode"); if (key == null) throw new RuntimeException("key must be non-null"); FeatureNode oldTarget = get(key); if (target == null) { kv_pairs.remove(key); } else { target.parents.add(this); kv_pairs.put(key, target); } if (oldTarget != null) { // If there are no other features pointing to the old target, // remove this from the list of oldTarget's parents. if (!kv_pairs.containsValue(oldTarget)) oldTarget.parents.remove(this); } } /** * Returns a feature's value, i.e. the node associated with * the name "key". If this node is string-valued, NULL is returned. * * @param key * @return the value of the feature, or null if it has no value */ public FeatureNode get(String key) { if (isValued()) throw new RuntimeException("String-valued FeatureNodes have no keys."); if (key == null) throw new RuntimeException("Key was null"); return kv_pairs.get(key); } // Like "get" but makes the feature node if it doesn't exist. public FeatureNode getOrMake(String key) { FeatureNode ret = get(key); if (ret == null) { ret = new FeatureNode(); set(key, ret); } return ret; } /** * Returns the set of keys in this FeatureNode * * @return the set of feature names */ public Set<String> getFeatureNames() { if (isValued()) throw new RuntimeException("valued FeatureNodes have no features"); return kv_pairs.keySet(); } /** * Recursive function implements toString, keeping track of how far to * indent each level, and appending values to a StringBuffer. * * The use of an "already visited" hashset lowers performance * dramatically, but makes this routine thread-safe in principle. * * @param indents * the number of double spaces to indent the output * @param sb * the string buffer to output to * @param indices * a map from FeatureNodes to indices * @param alreadyVisited * the set of FeatureNodes which have already been visited * @param filter * a filter that controls which features are printed, and their * order */ protected void _toString(int indents, StringBuffer sb, HashMap<FeatureNode,Integer> indices, HashSet<FeatureNode> alreadyVisited, FeatureNameFilter filter) { // Get index and return if its already been printed. Integer index = (Integer) indices.get(this); int indexIndents = 0; if (index != null) { sb.append("$").append(index.toString()); if (alreadyVisited.contains(this) && !isValued()) return; indexIndents = (index.intValue() > 9 ? 3 : 2); } // else alreadyVisited.add(this); // Don't print too deep into a feature structure. if (indents > PRINT_LIMIT) { sb.append("..."); return; } // For string-valued feature nodes, print value and return. if (isValued()) { sb.append(toString()); return; } // Print current node. sb.append("["); // Set the number of spaces to indent features in this node. StringBuffer spaces = new StringBuffer(); for (int j = 0; j < indents + indexIndents + 1; j++) spaces.append(" "); boolean firstLoop = true; // For each key, recurse. Iterator<String> i = features(filter); while (i.hasNext()) { if (firstLoop) firstLoop = false; else sb.append("\n").append(spaces); String featName = i.next(); int newindents = indents + indexIndents + 2 + featName.length(); sb.append(featName).append(" "); get(featName)._toString(newindents, sb, indices, alreadyVisited, filter); } sb.append("]"); } /* * Creates a map from FeatureNodes that appear more than once, * to integers. Used by toString() to print indices only once * when FeatureNodes appear more than once. */ private HashMap<FeatureNode,Integer> makeIndices(HashMap<FeatureNode,Integer> indices, HashSet<FeatureNode> alreadyVisited, FeatureNameFilter filter) { if (alreadyVisited.contains(this)) { if (!indices.keySet().contains(this)) indices.put(this, indices.size()); return indices; } alreadyVisited.add(this); if (!isValued()) { Iterator<String> i = features(filter); while (i.hasNext()) { String s = i.next(); get(s).makeIndices(indices, alreadyVisited, filter); } } return indices; } /** * Returns a pretty-printed, multi-line indented string representing * the contents of this FeatureNode. The filter is used to determine * which nodes are printed. * * @return */ public String toString(FeatureNameFilter filter) { if (isValued()) return "<<" + getValue() + ">>"; StringBuffer sb = new StringBuffer(); _toString(0, sb, makeIndices(new HashMap<FeatureNode,Integer>(), new HashSet<FeatureNode>(), filter), new HashSet<FeatureNode>(), filter); return sb.toString(); } public String toString() { return toString(DEFAULT_FEATURE_NAME_FILTER); } /** * Export feature structures as Prolog lists. * XXX deprecated -- caller should use the PrologList class directly * @deprecated */ public String toPrologList(FeatureNameFilter filter, boolean indent) { PrologList pl = new PrologList(); return pl.toPrologList(this, filter, indent); } /** * pathTarget() -- find the feature node at the end of the path * @return feature or null if not in path * * This routine walks the indicated chain of keys, looking * up each in turn. If any key in the path is not found, * null is returned. If particular, if the very first * path element is not found, null is returned. If the * navigation was successful, then the FeatureNode at * the end of the path is returned. * * Example usage: * pathTarget(new FeaturePath("<ref noun_number>")); */ public FeatureNode pathTarget(FeaturePath path) { FeatureNode cur = this; Iterator<String> feats = path.iterator(); while (feats.hasNext() && cur != null) { if (cur.isValued()) return null; cur = cur.get(feats.next()); } return cur; } public FeatureNode pathTarget(String str) { return pathTarget(new FeaturePath(str)); } /** * pathValue() -- * Returns the value of the path target -- or null if the path does not exist. */ public String pathValue(FeaturePath path) { FeatureNode target = pathTarget(path); if (target == null) return null; return target.getValue(); } public String pathValue(String str) { FeaturePath path = new FeaturePath(str); FeatureNode target = pathTarget(path); if (target == null) return null; if (!target.isValued()) return null; return target.getValue(); } /** * Like pathTarget(), but creates the path if it doesn't already exist. * setting its target to the passed target. If forceTarget is false, then an * error will be thrown if the path does not unify with this FeatureNode. */ public void makePath(FeaturePath path, FeatureNode target, boolean forceTarget) { FeatureNode cur = this; Iterator<String> feats = path.iterator(); while (feats.hasNext()) { FeatureNode last = cur; String name = feats.next(); cur = cur.get(name); if (cur == null) { if (feats.hasNext()) { cur = new FeatureNode(); } else { cur = target; if ((!forceTarget) && last.get(name) != null) throw new RuntimeException("Path already exists"); } last.set(name, cur); } } } public void makePath(FeaturePath path, FeatureNode target) { makePath(path, target, false); } /** * equiv() -- returns true if two references point to the same object. * @return true if equivalent, else false * @param other pointer to the object being compared to * * The standard comp-sci name for this is "equiv", and not "equals". * The method "equals" will return true if two objects contain the * same data; whereas this method return true only if its one and the * same object. * * This routine is used to handle the case where two features are set * to each other even though they have no value. In this case, we * might have something like: <a b c> = <d e f>. The target of both * these paths will be the same object: an empty FeatureNode. * */ public final boolean equiv(Object other) { // MUST BE == return other == this; } /* * features() -- returns a list of the features minus those specified by a filter * @return an iterator to an ArrayList containing those features of this FeatureNode not in the filter's ignore list * @param filter the FeatureNameFilter * This routine returns the feature node's features without * the features specified by the filter pa */ public Iterator<String> features(FeatureNameFilter filter) { ArrayList<String> output = new ArrayList<String>(); HashSet<String> featureNamesCopy = new HashSet<String>(getFeatureNames()); ArrayList<String> ignored = new ArrayList<String>(); for(String aFilter: filter.getIgnoreSet()){ filter.transferMultiNames(ignored, featureNamesCopy, aFilter); } filter.transfer(output, featureNamesCopy); return output.iterator(); } /** * Debugging function -- return string containing key names. */ public String _prt_keys() { if (isValued()) return ""; String ret = ""; Iterator<String> j = getFeatureNames().iterator(); while (j.hasNext()) { String stuff = j.next(); ret += stuff + " "; } ret += "\n"; return ret; } /** * Debugging function -- return list of key-value pairs. */ public String _prt_vals() { if (isValued()) return "this=" + value; String ret = ""; Iterator<String> j = getFeatureNames().iterator(); while (j.hasNext()) { String stuff = j.next(); ret += stuff + "="; String v = pathValue("<" + stuff + ">"); if (v == null) ret += "@"; else ret += v; ret += "\n"; } return ret; } // Test method static public void main(String[] args) { FeatureNode three = new FeatureNode("3"); FeatureNode root = new FeatureNode(); root.add("a").add("b").add("c").set("d", three); root.get("a").set("c", new FeatureNode("4")); root.add("a0").add("b0").set("c0", root.get("a").get("b").get("c")); System.out.println(root); } } // =========================== End of File ===============================
change error message to be more helpful.
src/java/relex/feature/FeatureNode.java
change error message to be more helpful.
<ide><path>rc/java/relex/feature/FeatureNode.java <ide> if (otherf != thisf) <ide> { <ide> throw new RuntimeException( <del> "Cannot merge two non-valued feature nodes with inconsistent features. fName = " + fName); <add> "Cannot merge two non-valued feature nodes with inconsistent features.\n" + <add> "\tSuggest using += instead of = in algs file. fName = " + fName); <ide> } <ide> } <ide> }
Java
apache-2.0
270c6cc91fb99f41e3066144a0558c47102feb10
0
GideonLeGrange/panstamp-java
package me.legrange.panstamp.impl; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.logging.Level; import java.util.logging.Logger; import me.legrange.panstamp.Endpoint; import me.legrange.panstamp.EndpointEvent; import me.legrange.panstamp.EndpointListener; import me.legrange.panstamp.GatewayException; import me.legrange.panstamp.PanStamp; import me.legrange.panstamp.PanStampEvent; import me.legrange.panstamp.PanStampEvent.Type; import me.legrange.panstamp.PanStampListener; import me.legrange.panstamp.Register; import me.legrange.panstamp.RegisterEvent; import me.legrange.panstamp.RegisterListener; import me.legrange.panstamp.def.Device; import me.legrange.panstamp.def.EndpointDef; import me.legrange.panstamp.def.RegisterDef; import me.legrange.swap.Registers; import me.legrange.swap.SwapMessage; /** * An implementation of a panStamp abstraction. Instances of this class * represent instances of panStamp devices connected to the network behind the * gateway. * * @author gideon */ public class PanStampImpl implements PanStamp { /** * @return address of this mote */ @Override public int getAddress() { return address; } /** * @return the register for the given id * @param id Register to read */ @Override public Register getRegister(int id) { RegisterImpl reg; synchronized (registers) { reg = registers.get(id); if (reg == null) { reg = new RegisterImpl(this, id); registers.put(id, reg); } } return reg; } @Override public List<Register> getRegisters() throws GatewayException { List<Register> all = new ArrayList<>(); all.addAll(registers.values()); Collections.sort(all, new Comparator() { @Override public int compare(Object o1, Object o2) { return ((Register) o1).getId() - ((Register) o2).getId(); } }); return all; } @Override public boolean hasRegister(int id) throws GatewayException { return registers.get(id) != null; } @Override public void addListener(PanStampListener l) { listeners.add(l); } @Override public void removeListener(PanStampListener l) { listeners.remove(l); } /** * send a query message to the remote node */ void sendQueryMessage(int id) throws ModemException { gw.sendQueryMessage(this, id); } /** * send a command message to the remote node * * @param value Value to send */ void sendCommandMessage(int id, byte[] value) throws ModemException { gw.sendCommandMessage(this, id, value); } /** * Receive a status message from the remote node. */ void statusMessageReceived(SwapMessage msg) { RegisterImpl reg = (RegisterImpl) getRegister(msg.getRegisterID()); boolean isNew = !reg.hasValue(); reg.valueReceived(msg.getRegisterValue()); if (isNew) { fireEvent(Type.REGISTER_DETECTED, reg); } } private void fireEvent(final PanStampEvent.Type type) { fireEvent(type, null); } private void fireEvent(final PanStampEvent.Type type, final Register reg) { PanStampEvent ev = new PanStampEvent() { @Override public Type getType() { return type; } @Override public PanStamp getDevice() { return PanStampImpl.this; } @Override public Register getRegister() { return reg; } }; for (PanStampListener l : listeners) { pool.submit(new UpdateTask(ev, l)); } } /** * create a new mote for the given address in the given network */ PanStampImpl(SerialGateway gw, int address) throws GatewayException { this.gw = gw; this.address = address; for (Registers.Register reg : Registers.Register.values()) { RegisterImpl impl = new RegisterImpl(this, reg); registers.put(reg.position(), impl); switch (reg) { case PRODUCT_CODE: impl.addListener(productCodeListener()); break; case SYSTEM_STATE: { Endpoint<Integer> ep = impl.getEndpoint(StandardEndpoint.SYSTEM_STATE.getName()); ep.addListener(systemStateListener()); break; } } } } private EndpointListener systemStateListener() { return new EndpointListener<Integer>() { @Override public void endpointUpdated(EndpointEvent<Integer> ev) { switch (ev.getType()) { case VALUE_RECEIVED: try { int state = ev.getEndpoint().getValue(); if (state != syncState) { syncState = state; fireEvent(Type.SYNC_STATE_CHANGE); } } catch (GatewayException ex) { Logger.getLogger(PanStampImpl.class.getName()).log(Level.SEVERE, null, ex); } break; } } }; } private RegisterListener productCodeListener() { return new RegisterListener() { @Override public void registerUpdated(RegisterEvent ev) { try { switch (ev.getType()) { case VALUE_RECEIVED: Register reg = ev.getRegister(); int mfId = getManufacturerId(reg); int pdId = getProductId(reg); if ((mfId != manufacturerId) || (pdId != productId)) { manufacturerId = mfId; productId = pdId; loadEndpoints(); } fireEvent(Type.PRODUCT_CODE_UPDATE); break; } } catch (GatewayException ex) { Logger.getLogger(PanStampImpl.class.getName()).log(Level.SEVERE, null, ex); } } }; } /** * load all endpoints */ private void loadEndpoints() throws GatewayException { Device def = getDeviceDefinition(); List<RegisterDef> rpDefs = def.getRegisters(); for (RegisterDef rpDef : rpDefs) { RegisterImpl reg = (RegisterImpl) getRegister(rpDef.getId()); for (EndpointDef epDef : rpDef.getEndpoints()) { reg.addEndpoint(epDef); } } } /** * get the device definition for this panStamp */ private Device getDeviceDefinition() throws GatewayException { return gw.getDeviceDefinition(manufacturerId, productId); } /** * get the manufacturer id for this panStamp */ private int getManufacturerId(Register reg) throws GatewayException { byte val[] = reg.getValue(); return val[0] << 24 | val[1] << 16 | val[2] << 8 | val[3]; } /** * get the product id for this panStamp */ private int getProductId(Register reg) throws GatewayException { byte val[] = reg.getValue(); return val[4] << 24 | val[5] << 16 | val[6] << 8 | val[7]; } private final int address; private final SerialGateway gw; private int manufacturerId; private int productId; private int syncState; private final Map<Integer, RegisterImpl> registers = new HashMap<>(); private final List<PanStampListener> listeners = new LinkedList<>(); private final ExecutorService pool = Executors.newCachedThreadPool(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, "PanStamp Event Task"); t.setDaemon(true); return t; } }); private static class UpdateTask implements Runnable { private UpdateTask(PanStampEvent ev, PanStampListener l) { this.l = l; this.ev = ev; } @Override public void run() { try { l.deviceUpdated(ev); } catch (Throwable e) { Logger.getLogger(SerialGateway.class.getName()).log(Level.SEVERE, null, e); } } private final PanStampListener l; private final PanStampEvent ev; } }
src/main/java/me/legrange/panstamp/impl/PanStampImpl.java
package me.legrange.panstamp.impl; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.logging.Level; import java.util.logging.Logger; import me.legrange.panstamp.Endpoint; import me.legrange.panstamp.EndpointEvent; import me.legrange.panstamp.EndpointListener; import me.legrange.panstamp.GatewayException; import me.legrange.panstamp.PanStamp; import me.legrange.panstamp.PanStampEvent; import me.legrange.panstamp.PanStampEvent.Type; import me.legrange.panstamp.PanStampListener; import me.legrange.panstamp.Register; import me.legrange.panstamp.RegisterEvent; import me.legrange.panstamp.RegisterListener; import me.legrange.panstamp.def.Device; import me.legrange.panstamp.def.EndpointDef; import me.legrange.panstamp.def.RegisterDef; import me.legrange.swap.Registers; import me.legrange.swap.SwapMessage; /** * An implementation of a panStamp abstraction. Instances of this class * represent instances of panStamp devices connected to the network behind the * gateway. * * @author gideon */ public class PanStampImpl implements PanStamp { /** * @return address of this mote */ @Override public int getAddress() { return address; } /** * @return the register for the given id * @param id Register to read */ @Override public Register getRegister(int id) { RegisterImpl reg; synchronized (registers) { reg = registers.get(id); if (reg == null) { reg = new RegisterImpl(this, id); registers.put(id, reg); } } return reg; } @Override public List<Register> getRegisters() throws GatewayException { List<Register> all = new ArrayList<>(); all.addAll(registers.values()); Collections.sort(all, new Comparator() { @Override public int compare(Object o1, Object o2) { return ((Register) o1).getId() - ((Register) o2).getId(); } }); return all; } @Override public boolean hasRegister(int id) throws GatewayException { return registers.get(id) != null; } @Override public void addListener(PanStampListener l) { listeners.add(l); } @Override public void removeListener(PanStampListener l) { listeners.remove(l); } /** * send a query message to the remote node */ void sendQueryMessage(int id) throws ModemException { gw.sendQueryMessage(this, id); } /** * send a command message to the remote node * * @param value Value to send */ void sendCommandMessage(int id, byte[] value) throws ModemException { gw.sendCommandMessage(this, id, value); } /** * Receive a status message from the remote node. */ void statusMessageReceived(SwapMessage msg) { RegisterImpl reg = (RegisterImpl) getRegister(msg.getRegisterID()); boolean isNew = reg.hasValue(); reg.valueReceived(msg.getRegisterValue()); if (isNew) { fireEvent(Type.REGISTER_DETECTED, reg); } } private void fireEvent(final PanStampEvent.Type type) { fireEvent(type, null); } private void fireEvent(final PanStampEvent.Type type, final Register reg) { PanStampEvent ev = new PanStampEvent() { @Override public Type getType() { return type; } @Override public PanStamp getDevice() { return PanStampImpl.this; } @Override public Register getRegister() { return reg; } }; for (PanStampListener l : listeners) { pool.submit(new UpdateTask(ev, l)); } } /** * create a new mote for the given address in the given network */ PanStampImpl(SerialGateway gw, int address) throws GatewayException { this.gw = gw; this.address = address; for (Registers.Register reg : Registers.Register.values()) { RegisterImpl impl = new RegisterImpl(this, reg); registers.put(reg.position(), impl); switch (reg) { case PRODUCT_CODE: impl.addListener(productCodeListener()); break; case SYSTEM_STATE: { Endpoint<Integer> ep = impl.getEndpoint(StandardEndpoint.SYSTEM_STATE.getName()); ep.addListener(systemStateListener()); } } } } private EndpointListener systemStateListener() { return new EndpointListener<Integer>() { @Override public void endpointUpdated(EndpointEvent<Integer> ev) { switch (ev.getType()) { case VALUE_RECEIVED : try { int state = ev.getEndpoint().getValue(); if (state != syncState) { syncState = state; fireEvent(Type.SYNC_STATE_CHANGE); } } catch (GatewayException ex) { Logger.getLogger(PanStampImpl.class.getName()).log(Level.SEVERE, null, ex); } } } }; } private RegisterListener productCodeListener() { return new RegisterListener() { @Override public void registerUpdated(RegisterEvent ev) { try { switch (ev.getType()) { case VALUE_RECEIVED: Register reg = ev.getRegister(); int mfId = getManufacturerId(reg); int pdId = getProductId(reg); if ((mfId != manufacturerId) || (pdId != productId)) { manufacturerId = mfId; productId = pdId; loadEndpoints(); } fireEvent(Type.PRODUCT_CODE_UPDATE); break; } } catch (GatewayException ex) { Logger.getLogger(PanStampImpl.class.getName()).log(Level.SEVERE, null, ex); } } }; } /** * load all endpoints */ private void loadEndpoints() throws GatewayException { Device def = getDeviceDefinition(); List<RegisterDef> rpDefs = def.getRegisters(); for (RegisterDef rpDef : rpDefs) { RegisterImpl reg = (RegisterImpl) getRegister(rpDef.getId()); for (EndpointDef epDef : rpDef.getEndpoints()) { reg.addEndpoint(epDef); } } } /** * get the device definition for this panStamp */ private Device getDeviceDefinition() throws GatewayException { return gw.getDeviceDefinition(manufacturerId, productId); } /** * get the manufacturer id for this panStamp */ private int getManufacturerId(Register reg) throws GatewayException { byte val[] = reg.getValue(); return val[0] << 24 | val[1] << 16 | val[2] << 8 | val[3]; } /** * get the product id for this panStamp */ private int getProductId(Register reg) throws GatewayException { byte val[] = reg.getValue(); return val[4] << 24 | val[5] << 16 | val[6] << 8 | val[7]; } private final int address; private final SerialGateway gw; private int manufacturerId; private int productId; private int syncState; private final Map<Integer, RegisterImpl> registers = new HashMap<>(); private final List<PanStampListener> listeners = new LinkedList<>(); private final ExecutorService pool = Executors.newCachedThreadPool(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, "PanStamp Event Task"); t.setDaemon(true); return t; } }); private static class UpdateTask implements Runnable { private UpdateTask(PanStampEvent ev, PanStampListener l) { this.l = l; this.ev = ev; } @Override public void run() { try { l.deviceUpdated(ev); } catch (Throwable e) { Logger.getLogger(SerialGateway.class.getName()).log(Level.SEVERE, null, e); } } private final PanStampListener l; private final PanStampEvent ev; } }
Fixed bug. Register was considered new on each update
src/main/java/me/legrange/panstamp/impl/PanStampImpl.java
Fixed bug. Register was considered new on each update
<ide><path>rc/main/java/me/legrange/panstamp/impl/PanStampImpl.java <ide> * Receive a status message from the remote node. <ide> */ <ide> void statusMessageReceived(SwapMessage msg) { <del> RegisterImpl reg = (RegisterImpl) getRegister(msg.getRegisterID()); <del> boolean isNew = reg.hasValue(); <del> reg.valueReceived(msg.getRegisterValue()); <del> if (isNew) { <del> fireEvent(Type.REGISTER_DETECTED, reg); <del> } <add> RegisterImpl reg = (RegisterImpl) getRegister(msg.getRegisterID()); <add> boolean isNew = !reg.hasValue(); <add> reg.valueReceived(msg.getRegisterValue()); <add> if (isNew) { <add> fireEvent(Type.REGISTER_DETECTED, reg); <add> } <ide> } <ide> <ide> private void fireEvent(final PanStampEvent.Type type) { <ide> fireEvent(type, null); <ide> } <del> <add> <ide> private void fireEvent(final PanStampEvent.Type type, final Register reg) { <ide> PanStampEvent ev = new PanStampEvent() { <ide> <ide> public Register getRegister() { <ide> return reg; <ide> } <del> <del> <add> <ide> }; <ide> for (PanStampListener l : listeners) { <ide> pool.submit(new UpdateTask(ev, l)); <ide> case SYSTEM_STATE: { <ide> Endpoint<Integer> ep = impl.getEndpoint(StandardEndpoint.SYSTEM_STATE.getName()); <ide> ep.addListener(systemStateListener()); <add> break; <ide> } <ide> } <ide> } <ide> } <ide> <del> private EndpointListener systemStateListener() { <add> private EndpointListener systemStateListener() { <ide> return new EndpointListener<Integer>() { <ide> <ide> @Override <ide> public void endpointUpdated(EndpointEvent<Integer> ev) { <ide> switch (ev.getType()) { <del> case VALUE_RECEIVED : <del> try { <del> int state = ev.getEndpoint().getValue(); <del> if (state != syncState) { <del> syncState = state; <del> fireEvent(Type.SYNC_STATE_CHANGE); <del> } <del> } catch (GatewayException ex) { <del> Logger.getLogger(PanStampImpl.class.getName()).log(Level.SEVERE, null, ex); <add> case VALUE_RECEIVED: <add> try { <add> int state = ev.getEndpoint().getValue(); <add> if (state != syncState) { <add> syncState = state; <add> fireEvent(Type.SYNC_STATE_CHANGE); <add> } <add> } catch (GatewayException ex) { <add> Logger.getLogger(PanStampImpl.class.getName()).log(Level.SEVERE, null, ex); <add> } <add> break; <ide> } <del> } <ide> } <ide> }; <ide> } <add> <ide> private RegisterListener productCodeListener() { <ide> return new RegisterListener() { <ide> @Override
Java
mpl-2.0
69348b0db571e31f3d9fa0d0587684d799ce0f83
0
GreenDelta/olca-modules,GreenDelta/olca-modules,GreenDelta/olca-modules
package org.openlca.util; import java.io.File; import java.io.IOException; import java.nio.file.AccessDeniedException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; /** * A simple utility class for directory operations. */ public final class Dirs { /** * Returns true if and only if the given file is an empty folder. */ public static boolean isEmpty(File file) { if (file == null) return false; return isEmpty(file.toPath()); } /** * Returns true if and only if the given path points to an empty folder. */ public static boolean isEmpty(Path path) { if (path == null) return false; if (!Files.isDirectory(path) || !Files.exists(path)) return false; try (var stream = Files.newDirectoryStream(path)) { return !stream.iterator().hasNext(); } catch (IOException e) { throw new RuntimeException(e); } } /** * Creates a directory if it not yet exists. */ public static void make(String path) { make(Paths.get(path)); } /** * Creates a directory if it not yet exists. */ public static void make(Path dir) { if (dir == null) return; try { Files.createDirectories(dir); } catch (IOException e) { throw new RuntimeException("failed to create directories " + dir, e); } } /** * Deletes the content from the given directory but not the directory * itself. */ public static void clean(Path dir) { if (dir == null) return; try { Files.newDirectoryStream(dir).forEach(p -> { if (Files.isDirectory(p)) delete(p); else { try { Files.delete(p); } catch (IOException e) { throw new RuntimeException("failed to delete " + p, e); } } }); } catch (IOException e) { throw new RuntimeException("failed to clean " + dir, e); } } /** * Copies a directory recursively. */ public static void copy(Path from, Path to) { if (from == null || to == null || !Files.exists(from)) return; try { Files.walkFileTree(from, new Copy(from, to)); } catch (IOException e) { throw new RuntimeException("failed to copy " + from + " to " + to, e); } } public static void delete(File dir) { if (dir == null || !dir.exists()) return; delete(dir.toPath()); } /** * Deletes a directory recursively. */ public static void delete(String path) { delete(Paths.get(path)); } /** * Deletes a directory recursively. */ public static void delete(Path dir) { if (dir == null || !Files.exists(dir)) return; try { Files.walkFileTree(dir, new Delete()); } catch (IOException e) { throw new RuntimeException("failed to delete " + dir, e); } } /** * Moves the given directory to the new location. */ public static void move(Path from, Path to) { copy(from, to); delete(from); } /** * Determines the size of the content of a directory recursively. */ public static long size(Path dir) { if (dir == null || !Files.exists(dir)) return 0; try { Size size = new Size(); Files.walkFileTree(dir, size); return size.size; } catch (IOException e) { throw new RuntimeException("failed to determine size of directory " + dir, e); } } private static class Size extends SimpleFileVisitor<Path> { private long size; @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { size += attrs.size(); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { return FileVisitResult.CONTINUE; } } private static class Copy extends SimpleFileVisitor<Path> { private final Path from; private final Path to; public Copy(Path from, Path to) { this.from = from; this.to = to; } @Override public FileVisitResult preVisitDirectory(Path fromDir, BasicFileAttributes attrs) throws IOException { Path toDir = to.resolve(from.relativize(fromDir)); if (!Files.exists(toDir)) Files.createDirectory(toDir); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.copy(file, to.resolve(from.relativize(file)), StandardCopyOption.REPLACE_EXISTING); return FileVisitResult.CONTINUE; } } private static class Delete extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes atts) throws IOException { try { Files.delete(file); } catch (AccessDeniedException e) { // files on windows can be marked as read-only var f = file.toFile(); if (!f.canWrite()) { f.setWritable(true); Files.delete(file); } } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc != null) throw exc; Files.delete(dir); return FileVisitResult.CONTINUE; } } }
olca-core/src/main/java/org/openlca/util/Dirs.java
package org.openlca.util; import java.io.File; import java.io.IOException; import java.nio.file.AccessDeniedException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; /** * A simple utility class for directory operations. */ public final class Dirs { /** * Returns true if and only if the given file is an empty folder. */ public static boolean isEmpty(File file) { if (file == null) return false; return isEmpty(file.toPath()); } /** * Returns true if and only if the given path points to an empty folder. */ public static boolean isEmpty(Path path) { if (path == null) return false; if (!Files.isDirectory(path) || !Files.exists(path)) return false; try (var stream = Files.newDirectoryStream(path)) { return !stream.iterator().hasNext(); } catch (IOException e) { throw new RuntimeException(e); } } /** * Creates a directory if it not yet exists. */ public static void make(String path) { make(Paths.get(path)); } /** * Creates a directory if it not yet exists. */ public static void make(Path dir) { if (dir == null) return; try { Files.createDirectories(dir); } catch (IOException e) { throw new RuntimeException("failed to create directories " + dir, e); } } /** * Deletes the content from the given directory but not the directory * itself. */ public static void clean(Path dir) { if (dir == null) return; try { Files.newDirectoryStream(dir).forEach(p -> { if (Files.isDirectory(p)) delete(p); else { try { Files.delete(p); } catch (IOException e) { throw new RuntimeException("failed to delete " + p, e); } } }); } catch (IOException e) { throw new RuntimeException("failed to clean " + dir, e); } } /** * Copies a directory recursively. */ public static void copy(Path from, Path to) { if (from == null || to == null || !Files.exists(from)) return; try { Files.walkFileTree(from, new Copy(from, to)); } catch (IOException e) { throw new RuntimeException("failed to copy " + from + " to " + to, e); } } public static void delete(File dir) { if (dir == null || !dir.exists()) return; if (!dir.isDirectory()) { if (!dir.delete()) { dir.deleteOnExit(); } } delete(dir.toPath()); } /** * Deletes a directory recursively. */ public static void delete(String path) { delete(Paths.get(path)); } /** * Deletes a directory recursively. */ public static void delete(Path dir) { if (dir == null || !Files.exists(dir)) return; try { Files.walkFileTree(dir, new Delete()); } catch (IOException e) { throw new RuntimeException("failed to delete " + dir, e); } } /** * Moves the given directory to the new location. */ public static void move(Path from, Path to) { copy(from, to); delete(from); } public static void main(String[] args) { var p = new File( "C:\\Users\\Sebastian\\openLCA-data-1.4\\repositories\\test\\objects\\pack\\pack-66969c7f5c49dc76095a2f6ba1dbd30660d13b49.idx") .toPath(); delete(p); } /** * Determines the size of the content of a directory recursively. */ public static long size(Path dir) { if (dir == null || !Files.exists(dir)) return 0; try { Size size = new Size(); Files.walkFileTree(dir, size); return size.size; } catch (IOException e) { throw new RuntimeException("failed to determine size of directory " + dir, e); } } private static class Size extends SimpleFileVisitor<Path> { private long size; @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { size += attrs.size(); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { return FileVisitResult.CONTINUE; } } private static class Copy extends SimpleFileVisitor<Path> { private final Path from; private final Path to; public Copy(Path from, Path to) { this.from = from; this.to = to; } @Override public FileVisitResult preVisitDirectory(Path fromDir, BasicFileAttributes attrs) throws IOException { Path toDir = to.resolve(from.relativize(fromDir)); if (!Files.exists(toDir)) Files.createDirectory(toDir); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.copy(file, to.resolve(from.relativize(file)), StandardCopyOption.REPLACE_EXISTING); return FileVisitResult.CONTINUE; } } private static class Delete extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes atts) throws IOException { try { Files.delete(file); } catch (AccessDeniedException e) { // files on windows can be marked as read-only var f = file.toFile(); if (!f.canWrite()) { f.setWritable(true); Files.delete(file); } } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc != null) throw exc; Files.delete(dir); return FileVisitResult.CONTINUE; } } }
Using FileVisitor to delete File.isFile()
olca-core/src/main/java/org/openlca/util/Dirs.java
Using FileVisitor to delete File.isFile()
<ide><path>lca-core/src/main/java/org/openlca/util/Dirs.java <ide> public static void delete(File dir) { <ide> if (dir == null || !dir.exists()) <ide> return; <del> if (!dir.isDirectory()) { <del> if (!dir.delete()) { <del> dir.deleteOnExit(); <del> } <del> } <ide> delete(dir.toPath()); <ide> } <ide> <ide> public static void move(Path from, Path to) { <ide> copy(from, to); <ide> delete(from); <del> } <del> <del> public static void main(String[] args) { <del> var p = new File( <del> "C:\\Users\\Sebastian\\openLCA-data-1.4\\repositories\\test\\objects\\pack\\pack-66969c7f5c49dc76095a2f6ba1dbd30660d13b49.idx") <del> .toPath(); <del> delete(p); <ide> } <ide> <ide> /**
JavaScript
agpl-3.0
1ae9f6c1aab65fd204c96c388fe1eec066e1d958
0
dataunity/ggjs
var ggjs = ggjs || {}; // ------------------ // Utilities // ------------------ ggjs.util = (function () { var isUndefined = function (val) { return typeof val === 'undefined'; }, isNullOrUndefined = function (val) { return isUndefined(val) || val == null; }, objKeys = function (obj) { var keys = [], key; for (key in obj) { if (obj.hasOwnProperty(key)) keys.push(key); } return keys; }, countObjKeys = function (obj) { return objKeys(obj).length; }, deepCopy = function (obj) { return JSON.parse(JSON.stringify(obj)); }, toBoolean = function(obj){ var str; if (obj === null || isUndefined(obj)) { return false; } str = String(obj).trim().toLowerCase(); switch(str){ case "true": case "yes": case "1": return true; case "false": case "no": case "0": return false; default: return Boolean(str); } }; return { isUndefined: isUndefined, isNullOrUndefined: isNullOrUndefined, objKeys: objKeys, countObjKeys: countObjKeys, deepCopy: deepCopy, toBoolean: toBoolean } })(); ggjs.util.array = (function () { var indexOf = function(arr, item) { // Finds the index of item in array var index = -1, i; for(i = 0; i < arr.length; i++) { if(arr[i] === item) { index = i; break; } } return index; }, contains = function (arr, item) { return indexOf(arr, item) !== -1; }; return { indexOf: indexOf, contains: contains } })(); // ------------------ // Datasets // ------------------ ggjs.Dataset = (function() { var dataset = function(spec) { spec = spec || {}; if (ggjs.util.isUndefined(spec.name)) throw "The dataset name must be defined"; this.dataset = { name: spec.name, values: spec.values || null, url: spec.url || null, contentType: spec.contentType || null, dataTypes: spec.dataTypes || {} }; //if (s) ggjs.extend(this.dataset, s); }; var prototype = dataset.prototype; prototype.name = function (val) { if (!arguments.length) return this.dataset.name; this.dataset.name = val; return this; }; prototype.values = function(val) { // Note: values should be JSON style data, e.g: // [{"a": 1, "b": 1}, {"a": 2, "b": 2}] if (!arguments.length) return this.dataset.values; this.dataset.values = val; return this; }; prototype.url = function (val) { if (!arguments.length) return this.dataset.url; this.dataset.url = val; return this; }; prototype.contentType = function (val) { if (!arguments.length) return this.dataset.contentType; this.dataset.contentType = val; return this; }; prototype.dataTypes = function (val) { if (!arguments.length) return this.dataset.dataTypes; this.dataset.dataTypes = val; return this; }; prototype.applyDataTypesToValues = function (dataTypes, values) { // Applies the user supplied data types // to values in dataset var isUndefined = ggjs.util.isUndefined, toBoolean = ggjs.util.toBoolean, fieldName, dataType, i, val; if (!values) { return; } for (fieldName in dataTypes) { dataType = dataTypes[fieldName]; switch (dataType) { case "number": for (i = 0; i < values.length; i++) { val = values[i][fieldName]; if (!isUndefined(val)) { values[i][fieldName] = +val; } } break; case "boolean": for (i = 0; i < values.length; i++) { val = values[i][fieldName]; if (!isUndefined(val)) { values[i][fieldName] = toBoolean(val); } } break; default: throw "Can't apply data type, unrecognised data type " + dataType; } } }; prototype.applyDataTypes = function () { var dataTypes = this.dataTypes(), values = this.values(); this.applyDataTypesToValues(dataTypes, values); }; return dataset; })(); ggjs.dataset = function (s) { return new ggjs.Dataset(s); }; ggjs.Data = (function () { var datasets = function (s) { var i, dataset; this.datasets = {}; if (s) { for (i = 0; i < s.length; i++) { dataset = ggjs.dataset(s[i]); this.datasets[dataset.name()] = dataset; } } }; var prototype = datasets.prototype; prototype.dataset = function (datasetName, dataset) { // ToDo: Get or set dataset if (arguments.length < 1) throw "dataset function needs datasetName argument."; if (arguments.length == 1) return this.datasets[datasetName]; // ToDo: set as object, ggjs dataset (or either)? this.datasets[datasetName] = ggjs.dataset(dataset); return this; }; prototype.count = function () { return ggjs.util.countObjKeys(this.datasets); }; prototype.names = function () { return ggjs.util.objKeys(this.datasets); }; return datasets; })(); ggjs.datasets = function (s) { return new ggjs.Data(s); }; // ------------------ // Axes // ------------------ ggjs.Axis = (function() { var axis = function(spec) { spec = spec || {}; if (ggjs.util.isUndefined(spec.type)) throw "The axis type must be defined"; this.axis = { type: spec.type, scaleName: spec.scaleName || null }; //if (s) ggjs.extend(this.axis, s); }; var prototype = axis.prototype; prototype.type = function (val) { if (!arguments.length) return this.axis.type; this.axis.type = val; return this; }; prototype.scaleName = function(val) { if (!arguments.length) return this.axis.scaleName; // ToDo: set as object, ggjs scale (or either)? this.axis.scaleName = val; return this; }; return axis; })(); ggjs.axis = function (s) { return new ggjs.Axis(s); }; ggjs.Axes = (function() { var axes = function(s) { var i, axis; this.axes = {}; if (s) { for (i = 0; i < s.length; i++) { axis = ggjs.axis(s[i]); this.axes[axis.type()] = axis; } } }; var prototype = axes.prototype; prototype.axis = function(axisType, axis) { // ToDo: Get or set axis if (arguments.length < 1) throw "axis function needs axisType argument."; if (arguments.length == 1) return this.axes[axisType]; this.axes[axisType] = ggjs.axis(axis); return this; }; prototype.count = function() { return ggjs.util.countObjKeys(this.axes); // var size = 0, key; // for (key in this.axes) { // if (this.axes.hasOwnProperty(key)) size++; // } // return size; }; return axes; })(); ggjs.axes = function (s) { return new ggjs.Axes(s); }; // ------------------ // Scales // ------------------ ggjs.Scale = (function () { var scale = function(spec) { this.scale = { type: spec.type || null, name: spec.name || null, domain: spec.domain || null, range: spec.range || null }; //if (spec) ggjs.extend(this.scale, spec); }; var prototype = scale.prototype; prototype.type = function(val) { if (!arguments.length) return this.scale.type; this.scale.type = val; return this; }; prototype.name = function(val) { if (!arguments.length) return this.scale.name; this.scale.name = val; return this; }; prototype.domain = function(val) { if (!arguments.length) return this.scale.domain; this.scale.domain = val; return this; }; prototype.range = function(val) { if (!arguments.length) return this.scale.range; this.scale.range = val; return this; }; prototype.hasDomain = function () { // Whether a domain is specified for the scale // Read only return this.domain() != null; } prototype.hasRange = function () { // Whether a range is specified for the scale // Read only return this.range() != null; } prototype.isQuantitative = function () { var quantScales = ["linear", "sqrt", "pow", "log"]; return ggjs.util.array.contains(quantScales, this.type()); } prototype.isOrdinal = function () { var ordinalScales = ["ordinal", "category10", "category20", "category20b", "category20c"]; return ggjs.util.array.contains(ordinalScales, this.type()); } prototype.isTime = function () { var timeScales = ["time"]; return ggjs.util.array.contains(timeScales, this.type()); } return scale; })(); ggjs.scale = function (s) { return new ggjs.Scale(s); }; ggjs.Scales = (function() { var scales = function(s) { var i, scale; this.scales = {}; if (s) { for (i = 0; i < s.length; i++) { scale = ggjs.scale(s[i]); this.scales[scale.name()] = scale; } } }; var prototype = scales.prototype; prototype.scale = function(scaleName, scale) { // Gets or set scale by name if (arguments.length < 1) throw "scale function needs scaleName argument."; if (arguments.length == 1) return this.scales[scaleName]; this.scales[scaleName] = ggjs.scale(scale); return this; }; prototype.count = function() { var size = 0, key; for (key in this.scales) { if (this.scales.hasOwnProperty(key)) size++; } return size; }; return scales; })(); ggjs.scales = function (s) { return new ggjs.Scales(s); }; // ------------------ // Padding // ------------------ ggjs.Padding = (function () { var padding = function(s) { this.padding = { left: s.left || 40, right: s.right || 20, top: s.top || 20, bottom: s.bottom || 70 }; //if (s) ggjs.extend(this.padding, s); }; var prototype = padding.prototype; prototype.left = function (l) { if (!arguments.length) return this.padding.left; this.padding.left = l; return this; }; prototype.right = function (r) { if (!arguments.length) return this.padding.right; this.padding.right = r; return this; }; prototype.top = function (t) { if (!arguments.length) return this.padding.top; this.padding.top = t; return this; }; prototype.bottom = function (b) { if (!arguments.length) return this.padding.bottom; this.padding.bottom = b; return this; }; return padding; })(); ggjs.padding = function (s) { return new ggjs.Padding(s); }; // ------------------ // Aesthetic mappings // ------------------ ggjs.AesMapping = (function () { // Aesthetic mapping shows which variables are mapped to which // aesthetics. For example, we might map weight to x position, // height to y position, and age to size. // // GGPlot: // layer(aes(x = x, y = y, color = z)) // Ref [lg] 3.1.1 var aesmap = function(s) { this.aesmap = { aes: s.aes || null, field: s.field || null, scaleName: s.scaleName || null }; //if (s) ggjs.extend(this.aesmap, s); }; var prototype = aesmap.prototype; prototype.aes = function (val) { if (!arguments.length) return this.aesmap.aes; this.aesmap.aes = val; return this; }; prototype.field = function (val) { if (!arguments.length) return this.aesmap.field; this.aesmap.field = val; return this; }; prototype.scaleName = function (val) { if (!arguments.length) return this.aesmap.scaleName; this.aesmap.scaleName = val; return this; }; return aesmap; })(); ggjs.aesmapping = function (s) { return new ggjs.AesMapping(s); }; ggjs.AesMappings = (function () { var aesmappings = function(spec) { var i; this.aesmappings = []; for (i = 0; i < spec.length; i++) { this.aesmappings.push(ggjs.aesmapping(spec[i])); } }; var prototype = aesmappings.prototype; prototype.findByAes = function (aesName) { // Finds an aesthetic mapping by aesthetic name var mappings = this.aesmappings, i, tmpAesmap; for (i = 0; i < mappings.length; i++) { tmpAesmap = mappings[i]; if (tmpAesmap.aes() === aesName) { return tmpAesmap; } } return null; }; prototype.count = function () { return this.aesmappings.length; }; prototype.asArray = function () { return this.aesmappings; }; return aesmappings; })(); ggjs.aesmappings = function (s) { return new ggjs.AesMappings(s); }; // ------------------ // Layer Geom // ------------------ ggjs.Geom = (function () { var geom = function(s) { this.geom = { // Support JSON-LD type Geom type geomType: s.geomType || s["@type"] || "GeomBar" }; }; var prototype = geom.prototype; prototype.geomType = function (l) { if (!arguments.length) return this.geom.geomType; this.geom.geomType = l; return this; }; return geom; })(); ggjs.geom = function (s) { return new ggjs.Geom(s); }; // ------------------ // Layers // ------------------ ggjs.Layer = (function () { // Layers are responsible for creating the objects that we perceive on the plot. // A layer is composed of: // - data and aesthetic mapping, // - a statistical transformation (stat), // - a geometric object (geom), and // - a position adjustment // // GGPlot: // layer(aes(x = x, y = y, color = z), geom="line", // stat="smooth") // Ref [lg] 3.1 var layer = function(spec) { // ToDo: move Namespace info out into separate module var ggjsPrefix = "ggjs", fillAesMap, xAesMap; this.layer = { data: spec.data || null, geom: ggjs.geom(spec.geom || {}), // geom: spec.geom || null, position: spec.position || null, // Sometimes order id is prefixed because JSON-LD context // has conflicts with other vocabs using 'orderId'. orderId: spec.orderId || spec[ggjsPrefix + ":orderId"] || null, // Note: support 'aesmapping' as name for aesmapping collection as well // as 'aesmapping' to support Linked Data style naming aesmappings: ggjs.aesmappings(spec.aesmappings || spec.aesmapping || []) }; //if (s) ggjs.extend(this.layer, s); fillAesMap = this.layer.aesmappings.findByAes("fill"); xAesMap = this.layer.aesmappings.findByAes("x"); // Set defaults if (this.geom().geomType() === "GeomBar" && this.position() === "stack" && fillAesMap != null && xAesMap != null && fillAesMap.field() !== xAesMap.field()) { this.layer.useStackedData = true; } else { this.layer.useStackedData = false; } }; var prototype = layer.prototype; prototype.data = function (val) { if (!arguments.length) return this.layer.data; this.layer.data = val; return this; }; prototype.geom = function (val) { if (!arguments.length) return this.layer.geom; this.layer.geom = val; return this; }; prototype.position = function (val) { if (!arguments.length) return this.layer.position; this.layer.position = val; return this; }; prototype.orderId = function (val) { if (!arguments.length) return this.layer.orderId; this.layer.orderId = val; return this; }; prototype.aesmappings = function (val) { if (!arguments.length) return this.layer.aesmappings; // ToDo: should val be obj or Axes (or either)? this.layer.aesmappings = val; return this; }; prototype.useStackedData = function (val) { if (!arguments.length) return this.layer.useStackedData; this.layer.useStackedData = val; return this; }; // prototype.useStackedData = function () { // if (this.geom() === "bar" && this.position() === "stack") { // return true; // } // return false; // } return layer; })(); ggjs.layer = function(s) { return new ggjs.Layer(s); }; ggjs.Layers = (function () { var layers = function(spec) { var isNullOrUndefined = ggjs.util.isNullOrUndefined, i; this.layers = []; for (i = 0; i < spec.length; i++) { this.layers.push(ggjs.layer(spec[i])); } // Sort layers by orderId this.layers.sort(function (lhs, rhs) { var lhsOrderId = isNullOrUndefined(lhs.orderId()) ? 0 : lhs.orderId(), rhsOrderId = isNullOrUndefined(rhs.orderId()) ? 0 : rhs.orderId(); return lhsOrderId - rhsOrderId; }) }; var prototype = layers.prototype; prototype.count = function () { return this.layers.length; }; prototype.asArray = function () { return this.layers; }; return layers; })(); ggjs.layers = function(s) { return new ggjs.Layers(s); }; // ------------------ // Plot // ------------------ ggjs.Plot = (function () { // The layered grammar defines the components of a plot as: // - a default dataset and set of mappings from variables to aesthetics, // - one or more layers, with each layer having one geometric object, one statistical // transformation, one position adjustment, and optionally, one dataset and set of // aesthetic mappings, // - one scale for each aesthetic mapping used, // - a coordinate system, // - the facet specification. // ref: [lg] 3.0 var plot = function(spec) { this.plot = { // ToDo: get defaults from config? selector: spec.selector, // Note: let renderer set default width // width: spec.width || 500, width: spec.width, height: spec.height || 500, padding: ggjs.padding(spec.padding || {}), data: ggjs.datasets(spec.data || []), defaultDatasetName: null, // ToDo: automatically find co-ordinate system based on layers? coord: spec.coord || "cartesian", // Note: support 'scale' as name for scale collection as well // as 'scales' to support Linked Data style naming scales: ggjs.scales(spec.scales || spec.scale || []), // Note: support 'axis' as name for axis collection as well // as 'axes' to support Linked Data style naming axes: ggjs.axes(spec.axes || spec.axis || []), facet: spec.facet || null, // Note: support 'layer' as name for layers collection as well // as 'layers' to support Linked Data style naming layers: ggjs.layers(spec.layers || spec.layer || []) }; //if (spec) ggjs.extend(this.plot, spec); }; var prototype = plot.prototype; prototype.selector = function (val) { if (!arguments.length) return this.plot.selector; this.plot.selector = val; return this; }; prototype.width = function (val) { if (!arguments.length) return this.plot.width; this.plot.width = val; return this; }; prototype.height = function (val) { if (!arguments.length) return this.plot.height; this.plot.height = val; return this; }; prototype.padding = function (val) { if (!arguments.length) return this.plot.padding; this.plot.padding = ggjs.padding(val); return this; }; prototype.coord = function (val) { if (!arguments.length) return this.plot.coord; this.plot.coord = val; return this; }; prototype.data = function (val) { if (!arguments.length) return this.plot.data; // ToDo: should val be obj or Datasets (or either)? this.plot.data = val; return this; }; prototype.axes = function (val) { if (!arguments.length) return this.plot.axes; // ToDo: should val be obj or Axes (or either)? this.plot.axes = val; return this; }; prototype.scales = function (val) { if (!arguments.length) return this.plot.scales; // ToDo: should val be obj or Scales (or either)? this.plot.scales = val; return this; }; prototype.layers = function (val) { if (!arguments.length) return this.plot.layers; // ToDo: should val be obj or Layers (or either)? this.plot.layers = val; return this; }; // ---------------------- // Plot area information // ---------------------- prototype.plotAreaWidth = function () { // ToDo: take axis titles and legends size away from width return this.width() - this.padding().left() - this.padding().right(); }; prototype.plotAreaHeight = function () { // ToDo: take axis titles, plot title, legends size away from height return this.height() - this.padding().top() - this.padding().bottom(); }; prototype.plotAreaX = function () { // ToDo: add axis titles and legends size return this.padding().left(); }; prototype.plotAreaY = function () { // ToDo: add axis titles, plot title and legends size return this.padding().top(); }; // ---------------------- // Axis information // ---------------------- prototype.yAxisHeight = function () { switch (this.coord()) { case "cartesian": return this.plotAreaHeight(); case "polar": return Math.floor(this.plotAreaHeight() / 2); default: throw "Can't get y axis height, unknown co-ordinate system " + this.coord(); } }; // ---------------------- // Data information // ---------------------- prototype.defaultDatasetName = function (val) { if (!arguments.length) { if (this.plot.defaultDatasetName != null) { return this.plot.defaultDatasetName; } else if (this.plot.data.count() === 1) { // Treat sole dataset as default data return this.plot.data.names()[0]; } else { return null; } } this.plot.defaultDatasetName = val; return this; } return plot; })(); ggjs.plot = function(p) { return new ggjs.Plot(p); }; ggjs.Renderer = (function (d3) { var renderer = function (plotDef) { this.renderer = { plotDef: plotDef, plot: null, // The element to draw to xAxis: null, yAxis: null, scaleNameToD3Scale: {}, // Lookup to find D3 scale for scale name datasetsRetrieved: {}, warnings: [], defaultFillColor: "rgb(31, 119, 180)" }; this.geo = {}; this.dataAttrXField = "data-ggjs-x-field"; this.dataAttrXValue = "data-ggjs-x-value"; this.dataAttrYField = "data-ggjs-y-field"; this.dataAttrYValue = "data-ggjs-y-value"; // Width: autoset width if width is missing var width = plotDef.width(), parentWidth; if (typeof width === 'undefined' || width == null) { // Set width to parent container width try { parentWidth = d3.select(plotDef.selector()).node().offsetWidth; } catch (err) { throw "Couldn't find the width of the parent element."; } if (typeof parentWidth === 'undefined' || parentWidth == null) { throw "Couldn't find the width of the parent element."; } this.renderer.plotDef.width(parentWidth); } }; var prototype = renderer.prototype; // ---------- // Accessors // ---------- prototype.plotDef = function (val) { if (!arguments.length) return this.renderer.plotDef; this.renderer.plotDef = val; return this; }; prototype.d3Scale = function (scaleName, val) { if (!arguments.length) { throw "Must supply args when getting/setting d3 scale" } else if (arguments.length === 1) { return this.renderer.scaleNameToD3Scale[scaleName]; } else { this.renderer.scaleNameToD3Scale[scaleName] = val; } return this; }; prototype.warnings = function (val) { if (!arguments.length) return this.renderer.warnings; this.renderer.warnings = val; return this; }; // End Accessors prototype.warning = function (warning) { // Adds a warning to the log this.renderer.warnings.push(warning); } prototype.render = function () { var this_ = this; // Clear contents (so they disapper in the event of failed data load) d3.select(this.plotDef().selector()).select("svg").remove(); // Fetch data then render plot this.fetchData(function () { this_.renderPlot(); }) }; prototype.fetchData = function (finishedCallback) { var plotDef = this.plotDef(), datasetNames = plotDef.data().names(), loadData = function (url, datasetName, contentType, callback) { var contentTypeLC = contentType ? contentType.toLowerCase() : contentType, dataset = plotDef.data().dataset(datasetName); switch (contentTypeLC) { case "text/csv": d3.csv(url, function(err, res) { if (err) throw "Error fetching CSV results: " + err.statusText; dataset.values(res); dataset.applyDataTypes(); callback(null, res); }); break; case "text/tsv": case "text/tab-separated-values": d3.tsv(url, function(err, res) { if (err) throw "Error fetching TSV results: " + err.statusText; dataset.values(res); dataset.applyDataTypes(); callback(null, res); }); break; case "application/json": d3.json(url, function(err, res) { if (err) throw "Error fetching JSON results: " + err.statusText; dataset.values(res); dataset.applyDataTypes(); callback(null, res); }); break; case "application/vnd.geo+json": d3.json(url, function(err, res) { if (err) throw "Error fetching GEO JSON results: " + err.statusText; dataset.values(res); callback(null, res); }); break; default: throw "Don't know you to load data of type " + contentType; } }, q = queue(3), i, datasetName, dataset; // Queue all data held at url for (i = 0; i < datasetNames.length; i++) { datasetName = datasetNames[i]; dataset = plotDef.data().dataset(datasetName); if (dataset && dataset.url()) { q.defer(loadData, dataset.url(), datasetName, dataset.contentType()); } } q.awaitAll(function(error, results) { if (error) { // ToDo: write error in place of chart? throw "Error fetching data results: " + error.statusText; } // Data loaded - continue rendering finishedCallback(); }); }; prototype.setupGeo = function () { var this_ = this, plotDef = this.plotDef(), width = plotDef.plotAreaWidth(), height = plotDef.plotAreaHeight(); if (plotDef.coord() !== "mercator") { return; } // var width = Math.max(960, window.innerWidth), // height = Math.max(500, window.innerHeight); var projection = d3.geo.mercator() //.scale((1 << 12) / 2 / Math.PI) // US .scale((1 << 20) / 2 / Math.PI) // Lambeth .translate([width / 2, height / 2]); //var center = projection([-100, 40]); // US //var center = projection([-106, 37.5]); // US //var center = projection([-10, 55]); // UK var center = projection([-0.1046, 51.46]); // Lambeth var zoom = d3.behavior.zoom() .scale(projection.scale() * 2 * Math.PI) .scaleExtent([1 << 11, 1 << 14]) .translate([width - center[0], height - center[1]]) .on("zoom", this_.drawLayers); //.on("zoom", this_.drawLayers(this_.renderer.plot)); //.on("zoom", zoomed); this.geo.zoom = zoom; // With the center computed, now adjust the projection such that // it uses the zoom behavior’s translate and scale. projection .scale(1 / 2 / Math.PI) .translate([0, 0]); this.geo.projection = projection; }; // prototype.zoomed = function () { // console.log("Some zooming"); // } prototype.renderPlot = function () { var plotDef = this.plotDef(), plot; // d3.select(this.plotDef().selector()).select("svg").remove(); d3.select(plotDef.selector()).html(""); plot = d3.select(plotDef.selector()) .append("svg") .attr("width", plotDef.width()) .attr("height", plotDef.height()); this.renderer.plot = plot; console.log(plotDef.plotAreaX()); console.log(plotDef.plotAreaY()); console.log(plotDef.plotAreaHeight()); console.log(plotDef.plotAreaWidth()); // ToDo: if no domain set on axes, default to extent // of data for appropriate aes across layers this.buildScales(); this.setupXAxis(); this.setupYAxis(); this.setupGeo(); this.drawAxes(); this.drawLayers(); this.drawLegends(); }; prototype.drawLayers = function () { var plotDef = this.plotDef(), plot = this.renderer.plot, layerDefs = plotDef.layers().asArray(), i, layerDef, plotArea; // Setup layers switch (plotDef.coord()) { case "cartesian": plotArea = plot.append("g") .attr("transform", "translate(" + plotDef.plotAreaX() + "," + plotDef.plotAreaY() + ")"); break; case "polar": plotArea = plot.append("g") .attr("transform", "translate(" + (plotDef.plotAreaX() + Math.floor(plotDef.plotAreaWidth() / 2)) + "," + (plotDef.plotAreaY() + Math.floor(plotDef.plotAreaHeight() / 2)) + ")"); break; case "mercator": //plot.call(this.geo.zoom); plotArea = plot.append("g") .attr("transform", "translate(" + plotDef.plotAreaX() + "," + plotDef.plotAreaY() + ")"); //plotArea.on("zoom", function () {console.log("zooming")}) var zoom = d3.behavior.zoom() .scale(1 << 12) .scaleExtent([1 << 9, 1 << 23]) .translate([250, 250]) .on("zoom", function () {console.log("zooming")}); //plotArea.call(zoom); plotArea.on("mousemove", function () {console.log("mouse moved")}); break; } // Draw each layer for (i = 0; i < layerDefs.length; i++) { layerDef = layerDefs[i]; switch (layerDef.geom().geomType()) { case "GeomPoint": this.drawPointLayer(plotArea, layerDef); break; case "GeomBar": this.drawBarLayer(plotArea, layerDef); break; case "GeomText": this.drawTextLayer(plotArea, layerDef); break; case "GeomPath": this.drawPathLayer(plotArea, layerDef); break; case "GeomGeoTiles": this.drawMapTiles(plotArea, layerDef); break; default: throw "Cannot draw layer, geom type not supported: " + layerDef.geom().geomType(); } } // Post layer processing // switch (plotDef.coord()) { // case "mercator": // break; // } }; prototype.drawMapTiles = function (plotArea, layerDef) { // Draws geographic map tiles images onto plot area console.log("Drawing map tiles"); var plotDef = this.plotDef(), width = plotDef.plotAreaWidth(), height = plotDef.plotAreaHeight(), zoom = this.geo.zoom, plot = this.renderer.plot; //var width = Math.max(960, window.innerWidth), // height = Math.max(500, window.innerHeight); var tile = d3.geo.tile() .size([width, height]); // var svg = d3.select("body").append("svg") // .attr("width", width) // .attr("height", height); var svg = plot; var raster = svg.append("g"); //function zoomed() { var tiles = tile .scale(zoom.scale()) .translate(zoom.translate()) (); var image = raster .attr("transform", "scale(" + tiles.scale + ")translate(" + tiles.translate + ")") .selectAll("image") .data(tiles, function(d) { return d; }); image.exit() .remove(); image.enter().append("image") .attr("xlink:href", function(d) { return "http://" + ["a", "b", "c", "d"][Math.random() * 4 | 0] + ".tiles.mapbox.com/v3/examples.map-i86nkdio/" + d[2] + "/" + d[0] + "/" + d[1] + ".png"; }) .attr("class", "ggjs-tile") .attr("width", 1) .attr("height", 1) .attr("x", function(d) { return d[0]; }) .attr("y", function(d) { return d[1]; }); //} //zoomed(); }; prototype.drawPathLayer = function (plotArea, layerDef) { var plotDef = this.plotDef(); switch (plotDef.coord()) { case "mercator": this.drawMapPathLayer(plotArea, layerDef); break; default: throw "Do not know how to draw path for coord " + plotDef.coord(); } } prototype.drawMapPathLayer = function (plotArea, layerDef) { // Draws path on a map plot var plotDef = this.plotDef(), // width = plotDef.plotAreaWidth(), // height = plotDef.plotAreaHeight(), zoom = this.geo.zoom, projection = this.geo.projection, plot = this.renderer.plot; console.log("drawing map path"); var svg = plot; var path = d3.geo.path() .projection(projection); var vector = svg.append("path"); var vector2 = svg.append("g") .attr("transform", "translate(" + zoom.translate() + ")scale(" + zoom.scale() + ")"); //.style("stroke-width", 1 / zoom.scale()); d3.json("data/us.json", function(error, us) { //svg.call(zoom); vector.attr("d", path(topojson.mesh(us, us.objects.counties))) .attr("class", "ggjs-path-map"); aa = [-122.490402, 37.786453]; bb = [-122.389809, 37.72728]; vector2.selectAll("circle") .data([aa,bb]) .enter().append("circle") // .attr("cx", function (d) { console.log(projection(d)); return projection(d)[0]; }) // .attr("cy", function (d) { return projection(d)[1]; }) .attr("transform", function(d) {return "translate(" + projection(d) + ")";}) .attr("r", 5 / zoom.scale()) .attr("fill", "red") //zoomed(); vector .attr("transform", "translate(" + zoom.translate() + ")scale(" + zoom.scale() + ")") .style("stroke-width", 1 / zoom.scale()); // vector2 // .attr("transform", "translate(" + zoom.translate() + ")scale(" + zoom.scale() + ")") // .style("stroke-width", 1 / zoom.scale()); }); }; prototype.drawPointLayer = function (plotArea, layerDef) { var plotDef = this.plotDef(), aesmappings = layerDef.aesmappings(), xField = aesmappings.findByAes("x").field(), yField = aesmappings.findByAes("y").field(), xScale = this.xAxis().scale(), yScale = this.yAxis().scale(), datasetName = layerDef.data(), dataset = this.getDataset(datasetName), //dataset = plotDef.data().dataset(datasetName), values = dataset.values(); switch (plotDef.coord()) { case "cartesian": this.drawCartesianPointLayer(plotArea, values, aesmappings, xField, yField, xScale, yScale); break; case "mercator": this.drawMapPointLayer(plotArea, values, aesmappings, xField, yField, xScale, yScale); break; default: throw "Do not know how to draw point for coord " + plotDef.coord(); } }; // Draws points (e.g. circles) onto the plot area prototype.drawCartesianPointLayer = function (plotArea, values, aesmappings, xField, yField, xScale, yScale) { var xScaleType = this.xAxisScaleDef().type(), xOffset = xScaleType === 'ordinal' ? Math.ceil(xScale.rangeBand() / 2) : 0, points; points = plotArea.selectAll(".ggjs-point") .data(values) .enter().append("circle") .attr("class", "ggjs-point") .attr("r", 3.5) .attr("cx", function (d) { return xScale(d[xField]) + xOffset; }) .attr("cy", function (d) { return yScale(d[yField]); }); this.applyFillColour(points, aesmappings); }; prototype.drawMapPointLayer = function (plotArea, values, aesmappings, xField, yField, xScale, yScale) { // Draws points (e.g. circles) onto the plot area var projection = this.geo.projection, zoom = this.geo.zoom, plot = this.renderer.plot, dataAttrXField = this.dataAttrXField, dataAttrXValue = this.dataAttrXValue, dataAttrYField = this.dataAttrYField, dataAttrYValue = this.dataAttrYValue, svg = plot; // var points = plotArea.selectAll(".ggjs-point") // .data(values) // .enter().append("circle") // .attr("class", "ggjs-point") // .attr("r", 3.5) // .attr("cx", function (d) { return xScale(d[xField]); }) // .attr("cy", function (d) { return yScale(d[yField]); }); // console.log(values[0][xField]) // console.log(values[0][yField]) // console.log( projection([ +(values[0][yField]), +(values[0][xField]) ]) ) // var points = plotArea.selectAll(".pin") // .data(values) // .enter().append("circle", ".pin") // .attr("r", 5) // .attr("transform", function(d) { // return "translate(" + projection([ // d[yField], // d[xField] // ]) + ")"; }); var vector2 = svg.append("g") .attr("transform", "translate(" + zoom.translate() + ")scale(" + zoom.scale() + ")"); //.style("stroke-width", 1 / zoom.scale()); vector2.selectAll("circle") .data(values) .enter().append("circle") // .attr("cx", function (d) { console.log(projection(d)); return projection(d)[0]; }) // .attr("cy", function (d) { return projection(d)[1]; }) .attr("transform", function(d) {return "translate(" + projection([ +d[yField], +d[xField] ]) + ")";}) .attr("r", 5 / zoom.scale()) .attr("fill", "rgba(255,0,0,0.6)") .attr(dataAttrXField, xField) .attr(dataAttrXValue, function (d) { return d[xField]; }) .attr(dataAttrYField, yField) .attr(dataAttrYValue, function (d) { return d[yField]; }); // var coordinates = projection([mylon, mylat]); // plotArea.selectAll(".circle") // .data(values) // .enter().append('circle', ".circle") // .attr('cx', function (d) { return projection([ +d[yField], +d[xField] ])[0]; } ) // .attr('cy', function (d) { return projection([ +d[yField], +d[xField] ])[1]; } ) // .attr('r', 5); //this.applyFillColour(points, aesmappings); }; prototype.drawTextLayer = function (plotArea, layerDef) { // Draws text onto the plot area // Similar to point layer rendering var plotDef = this.plotDef(), aesmappings = layerDef.aesmappings(), xAes = aesmappings.findByAes("x"), yAes = aesmappings.findByAes("y"), labelAes = aesmappings.findByAes("label"), xScale = this.xAxis().scale(), yScale = this.yAxis().scale(), datasetName = layerDef.data(), dataset = this.getDataset(datasetName), //dataset = plotDef.data().dataset(datasetName), values = dataset.values(), xField, yField, labelField, points; if (xAes == null) throw "Cannot draw text layer, x aesthetic no specified"; if (yAes == null) throw "Cannot draw text layer, y aesthetic no specified"; xField = xAes.field(); yField = yAes.field(); labelField = labelAes == null ? null : labelAes.field(); if (labelField == null) { this.warning("No text field supplied for text layer, label will be blank."); } points = plotArea.selectAll("text.ggjs-label") .data(values) .enter().append("text") .attr("class", "ggjs-label") .attr("x", function (d) { return xScale(d[xField]); }) .attr("y", function (d) { return yScale(d[yField]); }) .text(function (d) { if (labelField != null) { return d[labelField]; } else { return ""; } }); //this.applyFillColour(points, aesmappings); }; prototype.drawBarLayer = function (plotArea, layerDef) { // Draws bars onto the plot area var plotDef = this.plotDef(), yAxisHeight = plotDef.yAxisHeight(), aesmappings = layerDef.aesmappings(), fillAesMap = aesmappings.findByAes("fill"), xField = aesmappings.findByAes("x").field(), yField = aesmappings.findByAes("y").field(), xScale = this.xAxis().scale(), yScale = this.yAxis().scale(), datasetName = layerDef.data(), //dataset = plotDef.data().dataset(datasetName), dataset = this.getDataset(datasetName), isStacked = layerDef.useStackedData(), bars, values; // if (dataset == null) { // // Use default dataset for the plot // var datasetNames = plotDef.data().names(); // if (datasetNames.length !== 1) { // throw "Expected one DataSet in the Plot to use as the default DataSet"; // } // datasetName = datasetNames[0]; // dataset = plotDef.data().dataset(datasetName); // if (dataset == null) { // throw "Couldn't find a layer DataSet or a default DataSet."; // } // } values = dataset.values(); // Stacked/dodged bar charts // ToDo: dodge bar charts if (isStacked) { // Work out new baseline for each x value var fillScaleDef = this.scaleDef(fillAesMap.scaleName()); if (fillScaleDef == null) { throw "No scale could be found for fill scale " + fillAesMap.scaleName(); } if (this.xAxisScaleDef().isOrdinal() && fillScaleDef.isOrdinal()) { values = ggjs.dataHelper.generateStackYValues(values, xField, fillAesMap.field(), yField); } else { throw "Do not know how to draw stacked/dodged bars with non ordinal scales." } } switch (plotDef.coord()) { case "cartesian": bars = this.drawCartesianBars(plotArea, values, xField, yField, xScale, yScale, yAxisHeight, isStacked); break; case "polar": bars = this.drawPolarBars(plotArea, values, xField, yField, xScale, yScale, yAxisHeight, isStacked); break; default: throw "Don't know how to draw bars for co-ordinate system " + plotDef.coord(); } this.applyFillColour(bars, aesmappings); }; prototype.drawCartesianBars = function (plotArea, values, xField, yField, xScale, yScale, yAxisHeight, isStacked) { var dataAttrXField = this.dataAttrXField, dataAttrXValue = this.dataAttrXValue, dataAttrYField = this.dataAttrYField, dataAttrYValue = this.dataAttrYValue, bars = plotArea.selectAll("rect.ggjs-bar") .data(values) .enter().append("rect") .attr("class", "ggjs-bar") .attr("x", function(d) { return xScale(d[xField]); }) .attr("y", function(d) { if (isStacked) { return yScale(d[yField] + d["__y0__"]); } else { return yScale(d[yField]); } }) .attr("height", function(d) { return yAxisHeight - yScale(d[yField]); }) .attr("width", xScale.rangeBand()) .attr(dataAttrXField, xField) .attr(dataAttrXValue, function (d) { return d[xField]; }) .attr(dataAttrYField, yField) .attr(dataAttrYValue, function (d) { return d[yField]; }); return bars; }; prototype.drawPolarBars = function (plotArea, values, xField, yField, xScale, yScale, yAxisHeight, isStacked) { var arc, bars; arc = d3.svg.arc() .innerRadius(0) //.outerRadius(150) .outerRadius(function (d) {return yAxisHeight - yScale(d[yField]); }) .startAngle(function (d) { console.log("startAngle d: " + d[xField]); console.log("startAngle: " + xScale(d[xField])); return xScale(d[xField]); }) .endAngle(function (d) { console.log("endAngle d: " + d[xField]); console.log("endAngle: " + xScale(d[xField]) + xScale.rangeBand()); return xScale(d[xField]) + xScale.rangeBand(); }); bars = plotArea.selectAll("path.ggjs-arc") .data(values) .enter().append("path") .attr("class", "ggjs-arc") .attr("d", arc) return bars; }; prototype.applyFillColour = function (svgItems, aesmappings) { // Applies fill colour to svg elements // Params: // svgItems: the svg elements as D3 select list // aesmappings: the layer's aesmappings // Fill colour // ToDo: setup colour scale across all layers, so colours // are matched across layers console.log("Warning: move colour mapping to all levels."); var plotDef = this.plotDef(), fillAesMap = aesmappings.findByAes("fill"), defaultFillColor = this.renderer.defaultFillColor; if (fillAesMap != null) { var colorField = fillAesMap.field(), colorScaleDef = this.scaleDef(fillAesMap.scaleName()), scaleName = fillAesMap.scaleName(), colorScale; // if (colorScaleDef == null) { // this.warning("Couldn't set colour on layer - fill colour scale missing.") // svgItems.style("fill", function(d) { return defaultFillColor; }); // } else { // colorScale = this.scale(colorScaleDef); // svgItems.style("fill", function(d) { return colorScale(d[colorField]); }); // } if (scaleName == null) { this.warning("Couldn't set colour on layer - fill colour scale missing.") svgItems.style("fill", function(d) { return defaultFillColor; }); } else { colorScale = this.d3Scale(scaleName); console.log("Using d3 scale", scaleName, colorScale.domain()) svgItems.style("fill", function(d) { return colorScale(d[colorField]); }); } } else { svgItems.style("fill", function(d) { return defaultFillColor; }); } }; prototype.drawAxes = function () { var plotDef = this.plotDef(), plot = this.renderer.plot; switch (plotDef.coord()) { case "cartesian": // Need an x and y axis // ToDo: support x2 and y2 axes //var xAxisDef = plotDef.axes().axis("x"); var xAxis = this.xAxis(), yAxis = this.yAxis(), xAxisY = plotDef.plotAreaY() + plotDef.plotAreaHeight(); plot.append("g") .attr("class", "ggjs-x ggjs-axis") .attr("transform", "translate(" + plotDef.plotAreaX() + "," + xAxisY + ")") .call(xAxis) // Tmp: orientate labels .selectAll("text") .attr("y", 5) .attr("x", 4) // .attr("dy", ".15em") .attr("dy", "12px") .attr("transform", "rotate(35)") .style("text-anchor", "start"); // ToDo: append x axis title plot.append("g") .attr("class", "ggjs-y ggjs-axis") .attr("transform", "translate(" + plotDef.plotAreaX() + "," + plotDef.plotAreaY() + ")") .call(yAxis); // ToDo: append x axis title break; case "polar": console.log("Draw polar axes"); break; case "mercator": break; default: throw "Unrecognised coordinate system used." } }; prototype.xAxis = function (val) { if (!arguments.length) return this.renderer.xAxis; this.renderer.xAxis = val; return this; }; prototype.yAxis = function (val) { if (!arguments.length) return this.renderer.yAxis; this.renderer.yAxis = val; return this; }; prototype.xAxisScaleDef = function (val) { if (!arguments.length) return this.renderer.xAxisScaleDef; this.renderer.xAxisScaleDef = val; return this; }; prototype.yAxisScaleDef = function (val) { if (!arguments.length) return this.renderer.yAxisScaleDef; this.renderer.yAxisScaleDef = val; return this; }; prototype.getDataset = function (datasetName) { var plotDef = this.plotDef(), dataset = plotDef.data().dataset(datasetName), datasetNames; if (dataset == null) { // Use default dataset for the plot datasetNames = plotDef.data().names(); if (datasetNames.length !== 1) { throw "Expected one DataSet in the Plot to use as the default DataSet"; } datasetName = datasetNames[0]; dataset = plotDef.data().dataset(datasetName); if (dataset == null) { throw "Couldn't find a layer DataSet or a default DataSet."; } } return dataset; }; prototype.statAcrossLayers = function (aes, stat) { // Looks at the data across all layers for an // aesthetic and gets info about it (e.g. max or min) var plotDef = this.plotDef(), layers = plotDef.layers().asArray(), statVal = null, i, layer, aesmap, field, tmpStat, datasetName, dataset; for (i = 0; i < layers.length; i++) { layer = layers[i]; aesmap = layer.aesmappings().findByAes(aes); // Layer data datasetName = layer.data(); if (!datasetName) { datasetName = plotDef.defaultDatasetName(); } //dataset = plotDef.data().dataset(datasetName); dataset = this.getDataset(datasetName); if (dataset == null) { throw "Unable to find dataset with name " + datasetName; } if (aesmap) { field = aesmap.field(); if (stat === "max" && layer.useStackedData()) { // Stack data tmpStat = this.layerStackedDataMax(layer, dataset, aes); } else { // Normal case for finding aes value tmpStat = ggjs.dataHelper.datatableStat(dataset.values(), field, stat); } if (!isNaN(tmpStat)) { if (statVal == null) statVal = tmpStat; statVal = stat === "min" ? Math.min(statVal, tmpStat) : Math.max(statVal, tmpStat); } } } return statVal; }; prototype.layerStackedDataMax = function (layer, dataset, aes) { // Find the max value for the stacked data on this level. // Highest value for stacked data is sum of values in group, // not the highest value across the whole value column var tmpStat, xAes = layer.aesmappings().findByAes("x"), fillAes = layer.aesmappings().findByAes("fill"), valueAes = layer.aesmappings().findByAes(aes); if (valueAes == null) { throw "Need value aes map to find stacked value"; } if (xAes == null) { throw "Need x aes map to find stacked value"; } if (fillAes == null) { throw "Need fill aes map to find stacked value"; } if (aes === "y") { // ToDo: is the fill aes the only way to specify stacked figures? tmpStat = ggjs.dataHelper.maxStackValue(dataset.values(), xAes.field(), fillAes.field(), valueAes.field()); } else { throw "Don't know how to find stacked value for value aes " + aes; } return tmpStat; } prototype.allValuesForLayer = function (layer, aesmap) { // Gets all data values for an aes in a layer var plotDef = this.plotDef(), values = [], //tmpVals, i, field, datasetName, dataset; // Layer data datasetName = layer.data(); if (!datasetName) { datasetName = plotDef.defaultDatasetName(); } dataset = this.getDataset(datasetName); if (dataset == null) { throw "Unable to find dataset with name " + datasetName; } if (aesmap) { field = aesmap.field(); if (dataset.values().map) { values = dataset.values().map(function (d) { return d[field]; }); } else { // backup way to get values from data // ToDo: use array.map polyfill so this can be removed? var dsVals = dataset.values(), j; this.warning("Old browser - doesn't support array.map"); for (j = 0; j < dsVals.length; j++) { values.push(dsVals[j][field]); } } // values = d3.merge([ values, tmpVals ]); } return values; }; prototype.allValuesAcrossLayers = function (aes) { // Looks at the data across all layers for an // aesthetic and gets all it's values var plotDef = this.plotDef(), layers = plotDef.layers().asArray(), values = [], tmpVals, i, layer, aesmap, field, datasetName, dataset; for (i = 0; i < layers.length; i++) { layer = layers[i]; aesmap = layer.aesmappings().findByAes(aes); tmpVals = this.allValuesForLayer(layer, aesmap); values = d3.merge([ values, tmpVals ]); // // Layer data // datasetName = layer.data(); // if (!datasetName) { // datasetName = plotDef.defaultDatasetName(); // } // //dataset = plotDef.data().dataset(datasetName); // dataset = this.getDataset(datasetName); // if (dataset == null) { // throw "Unable to find dataset with name " + datasetName; // } // if (aesmap) { // field = aesmap.field(); // if (dataset.values().map) { // tmpVals = dataset.values().map(function (d) { return d[field]; }); // } else { // // backup way to get values from data // // ToDo: use array.map polyfill so this can be removed? // var tmpVals = [], // dsVals = dataset.values(), // j; // this.warning("Old browser - doesn't support array.map"); // for (j = 0; j < dsVals.length; j++) { // tmpVals.push(dsVals[j][field]); // } // } // values = d3.merge([ values, tmpVals ]); // } } return values; }; // ------- // Scales // ------- // Build the scales based on data prototype.buildScales = function () { var plotDef = this.plotDef(), plot = this.renderer.plot, layerDefs = plotDef.layers().asArray(), i, j, layerDef, // scaleNamesLookup = {}, // scaleNames = [], scaleNameToLayerInfos = {}, // scaleNameToLayer = {}, // scaleNameToAesMap = {}, scaleDef, layerInfo, layerInfos, layerDef, tmpScale, values, tmpVals, aesmappings, aesmapping, aes, scaleName, scale; // Find names of all the scales used for (i = 0; i < layerDefs.length; i++) { layerDef = layerDefs[i]; aesmappings = layerDef.aesmappings().asArray(); // console.log("aesmappings", aesmappings) if (aesmappings) { for (j = 0; j < aesmappings.length; j++) { aesmapping = aesmappings[j]; // console.log(aesmapping) aes = aesmapping.aes(); // Skip aesthetics which are already display as axis // if (aes === "x" || aes === "y") { // continue; // } scaleName = aesmapping.scaleName(); if (scaleName == null) { continue; } // Store the information about where scale is used layerInfo = { layerDef: layerDef, aesmapping: aesmapping }; if (typeof scaleNameToLayerInfos[scaleName] === 'undefined') { scaleNameToLayerInfos[scaleName] = [layerInfo]; } else { scaleNameToLayerInfos[scaleName].push(layerInfo); } // scaleNameToLayer[scaleName] = layer; // scaleNameToAesMap[scaleName] = aesmapping; // console.log("aesmapping", aes, scaleName); // if (scaleName != null && typeof scaleNamesLookup[scaleName] === 'undefined') { // scaleNames.push(scaleName); // scaleNamesLookup[scaleName] = true; // } } } } // Create a D3 scale for each scale // console.log("Creating d3 scales") for (scaleName in scaleNameToLayerInfos) { scaleDef = plotDef.scales().scale(scaleName); scale = this.scale(scaleDef); if (scaleDef.hasDomain()) { scale.domain(scaleDef.domain()); } else { // If scale domain hasn't been set, use data to find it if (scaleDef.isQuantitative()) { max = this.statAcrossLayers(aes, "max"); if (!isNaN(max)) { scale.domain([0, max]).nice(); } } else if (scaleDef.isOrdinal()) { // Find values across all layers layerInfos = scaleNameToLayerInfos[scaleName]; values = []; // console.log("scaleName", scaleName) for (i = 0; i < layerInfos.length; i++) { layerInfo = layerInfos[i]; layerDef = layerInfo.layerDef; aesmapping = layerInfo.aesmapping; // ToDo: cache values for layer/field combos // console.log("layer info", scaleName, layerDef.data(), aesmapping.aes(), aesmapping.field()); tmpVals = this.allValuesForLayer(layerDef, aesmapping); values = d3.merge([ values, tmpVals ]); } scale.domain(values); } } this.d3Scale(scaleName, scale); } }; prototype.setupAxisScale = function (aes, scale, scaleDef) { var min = 0, max, allValues = []; if (scaleDef.hasDomain()) { scale.domain(scaleDef.domain()); } else { // If scale domain hasn't been set, use data to find it if (scaleDef.isQuantitative()) { max = this.statAcrossLayers(aes, "max"); if (!isNaN(max)) { scale.domain([0, max]).nice(); } } else if (scaleDef.isOrdinal()) { allValues = this.allValuesAcrossLayers(aes); scale.domain(allValues); //scale.domain(data.map(function(d) { return d.letter; })); } } }; prototype.setupXAxis = function () { // Produces D3 x axis var plotDef = this.plotDef(), axis = d3.svg.axis() .orient("bottom"), axisDef = this.plotDef().axes().axis("x") || {}, scaleRef = axisDef.scaleName(), scaleDef = plotDef.scales().scale(scaleRef), scale = this.scale(scaleDef); // ToDo: determine if domain has been manually set on x axis // ToDo: account for facets //x.domain(d3.extent(data, function(d) { return d.sepalWidth; })).nice(); // Set scale range // ToDo: account for facets switch (plotDef.coord()) { case "cartesian": // X scale range is always width of plot area scale.range([0, plotDef.plotAreaWidth()]); if (scaleDef.isOrdinal()) { scale.rangeRoundBands([0, plotDef.plotAreaWidth()], .1); } break; case "polar": scale.range([0, 2 * Math.PI]); if (scaleDef.isOrdinal()) { scale.rangeBands([0, 2 * Math.PI], 0); } break; } this.setupAxisScale("x", scale, scaleDef); axis.scale(scale); axis.ticks(5); this.xAxisScaleDef(scaleDef); this.xAxis(axis); }; prototype.setupYAxis = function () { // Produces D3 y axis var plotDef = this.plotDef(), axis = d3.svg.axis() .orient("left"), axisDef = this.plotDef().axes().axis("y") || {}, scaleRef = axisDef.scaleName(), scaleDef = plotDef.scales().scale(scaleRef), scale = this.scale(scaleDef); // ToDo: determine if domain has been manually set on y axis // ToDo: account for facets //y.domain(d3.extent(data, function(d) { return d.sepalLength; })).nice(); // ToDo: account for facets switch (plotDef.coord()) { case "cartesian": // Y scale range is height of plot area scale.range([plotDef.plotAreaHeight(), 0]); break; case "polar": // Y scale range is half height of plot area scale.range([Math.floor(plotDef.plotAreaHeight() / 2), 0]); break; } this.setupAxisScale("y", scale, scaleDef); axis.scale(scale); axis.ticks(5); this.yAxisScaleDef(scaleDef); this.yAxis(axis); }; prototype.scaleDef = function (scaleName) { return this.plotDef().scales().scale(scaleName); }; prototype.scale = function (scaleDef) { // Produces D3 scale from ggjs scale definition var scale = null; scaleDef = scaleDef || ggjs.scale({}); switch (scaleDef.type()) { case "linear": scale = d3.scale.linear(); break; case "ordinal": scale = d3.scale.ordinal(); break; case "pow": scale = d3.scale.pow(); break; case "time": scale = d3.time.scale(); break; case "category10": scale = d3.scale.category10(); break; default: throw "Unknow D3 scale type " + scaleDef.type(); } if (scale == null) { scale = d3.scale.linear(); } return scale; }; // -------- // Legends // -------- function scaleLegend () { // Legend attributes // Scale var _scale = null, _layout = "horizontal", _itemOffsetX = 0, // Horizontal gap between items _itemOffsetY = 10, // Vertical gap between items _itemRadius = Math.floor(_itemOffsetY / 2) _itemMarkerLabelGap = 10; // Legend function. function legend (selection) { selection.each(function (data) { var legendContainer = d3.select(this); legendContainer.selectAll(".ggjs-legend-item-marker") .data(data) .enter().append("circle") .attr("class", "ggjs-legend-item-marker") .attr("r", _itemRadius) // .attr("cx", 0) // .attr("cy", 0) .attr("cx", function (d, i) { return (i * _itemOffsetX) - _itemRadius; }) .attr("cy", function (d, i) { return (i * _itemOffsetY) - _itemRadius; }) .style("fill", function (d) { return _scale(d); }) .style("stroke", "black"); legendContainer.selectAll(".ggjs-legend-item-label") .data(data) .enter().append("text") .attr("class", "ggjs-legend-item-label") .attr("x", function (d, i) { return (i * _itemOffsetX) + _itemMarkerLabelGap; }) .attr("y", function (d, i) { return i * _itemOffsetY; }) .text(function (d) { return d; }); // Add the label 'Legend' on enter // containerDiv.selectAll('b') // .data([data]) // .enter().append('b') // .text('Legend'); }); } // Accessor methods // Scale accessor legend.scale = function (value) { if (!arguments.length) { return _scale; } _scale = value; return legend; }; // Y offset accessor legend.itemOffsetX = function (value) { if (!arguments.length) { return _itemOffsetX; } _itemOffsetX = value; return legend; }; // Y offset accessor legend.itemOffsetY = function (value) { if (!arguments.length) { return _itemOffsetY; } _itemOffsetY = value; return legend; }; // Radius accessor legend.itemRadius = function (value) { if (!arguments.length) { return _itemRadius; } _itemRadius = value; return legend; }; return legend; } prototype.drawLegends = function () { // ToDo: find the legends for all aes across all layers // ToDo: combine aes if possible, like fill and shape // Find rules to combine legends - e.g. if same fields // are used for different aes, then legends can be combined. // E.g. if 'country' field is used for aes 'shape' and 'fill' // then draw a single legend for 'country' values adapting // the fill and shape of the markers var plotDef = this.plotDef(), plot = this.renderer.plot, layerDefs = plotDef.layers().asArray(), legendX = 0, // Cummalative legend offset legendY = 0, // Cummalative legend offset itemOffsetX = 0, // Horizontal gap between legend items itemOffsetY = 18, // Vertical gap between legend items itemRadius = 5, // Radius of circle markers titleHeight = 12, // Height of legend title i, j, layerDef, legendArea, legendBaseX, legendBaseY, scaleNamesLookup = {}, scaleNamesToDisplay = [], legendX, legendY, legendData, aesmappings, aesmapping, aes, scaleName, scale; // ToDo: legend position switch ("top") { case "top": itemOffsetX = 100, itemOffsetY = 0, legendBaseX = Math.max(0, plotDef.plotAreaX() - itemOffsetY); legendArea = plot.append("g") .attr("transform", "translate(" + legendBaseX + "," + plotDef.plotAreaY() + ")"); break; // case "bottom": // case "left": case "right": default: itemOffsetX = 0, itemOffsetY = 18, legendBaseX = plotDef.plotAreaX() + (0.7 * plotDef.plotAreaWidth()) legendArea = plot.append("g") .attr("transform", "translate(" + legendBaseX + "," + plotDef.plotAreaY() + ")"); break; } // Look for scales to turn into legends for (i = 0; i < layerDefs.length; i++) { layerDef = layerDefs[i]; aesmappings = layerDef.aesmappings().asArray(); // console.log("aesmappings", aesmappings) if (aesmappings) { for (j = 0; j < aesmappings.length; j++) { aesmapping = aesmappings[j]; // console.log(aesmapping) aes = aesmapping.aes(); // Skip aesthetics which are already display as axis if (aes === "x" || aes === "y") { continue; } scaleName = aesmapping.scaleName(); // console.log("aesmapping", aes, scaleName); if (scaleName != null && typeof scaleNamesLookup[scaleName] === 'undefined') { scaleNamesToDisplay.push(scaleName); scaleNamesLookup[scaleName] = true; } } } } for (i = 0; i < scaleNamesToDisplay.length; i++) { // ToDo: check type of scale // if ordinal: when setting up plot find the domain values // then look them up here // if quan: display box with range of values (gradient?) scaleName = scaleNamesToDisplay[i]; scale = this.d3Scale(scaleName); legendData = scale.domain(); // legendData = ["a", "b", "c"]; // console.log("scale: ", scaleNamesToDisplay[i]); // find the scale // scale = d3.scale.category20(); // scale.domain(legendData); var lgnd = scaleLegend() .itemOffsetX(itemOffsetX) .itemOffsetY(itemOffsetY) .itemRadius(itemRadius) .scale(scale); legend = legendArea.append("g") .attr("transform", "translate(0," + legendY + ")") .attr("class", "legend") .data([legendData]) // .attr("transform","translate(50,30)") .style("font-size","12px") .call(lgnd); // Set up offsets for next legend collection legendY += titleHeight + legendData.length * itemOffsetY; } }; return renderer; })(d3); ggjs.renderer = function(s) { return new ggjs.Renderer(s); }; // ------------------ // Data Helper // ------------------ ggjs.dataHelper = (function (d3) { var datatableMin = function (datatable, field) { // Finds the min value of the field in the datatable return d3.min(datatable, function (d) { return d[field]; }); }, datatableMax = function (datatable, field) { // Finds the max value of the field in the datatable return d3.max(datatable, function (d) { return d[field]; }); }, datatableSum = function (datatable, field) { // Finds the sum of values for the field in the datatable return d3.sum(datatable, function (d) { return d[field]; }); }, datatableStat = function (datatable, field, stat) { // Finds the value of the stat (e.g. max) for the field in the datatable var statVal = null; switch (stat) { case "min": case "max": statVal = stat === "min" ? datatableMin(datatable, field) : datatableMax(datatable, field); break; case "sum": statVal = datatableSum(datatable, field); break; default: throw "Can't get datatables stat, unknown stat " + stat; } return statVal; }, datatablesStat = function (datatables, field, stat) { var statVal = null, i, tmpStat; switch (stat) { case "min": case "max": for (i = 0; i < datatables.length; i++) { tmpStat = stat === "min" ? datatableMin(datatables[i], field) : datatableMax(datatables[i], field); if (!isNaN(tmpStat)) { if (statVal == null) statVal = tmpStat; statVal = stat === "min" ? Math.min(statVal, tmpStat) : Math.max(statVal, tmpStat); } } break; default: throw "Can't get datatables stat, unknown stat " + stat; } return statVal; }, generateStackYValues = function (data, groupField, stackField, valueField) { // Adds an extra y value called __y0__ to the data // which gives the y value of the previous record within // the stacked items of the group. // Useful for stacked bar charts where an extra y value is // needed to know where the last bar in the group was placed. var dataCopy = ggjs.util.deepCopy(data), nested = d3.nest() .key(function (d) { return d[groupField]; }) .key(function (d) { return d[stackField]; }) .entries(dataCopy), groupKeys, stackKeys, values, i, j, k, prevValue; for (i = 0; i < nested.length; i++) { // Group 1 level prevValue = 0; groupKeys = nested[i]; for (j = 0; j < groupKeys.values.length; j++) { // Group 2 level stackKeys = groupKeys.values[j]; for (k = 0; k < stackKeys.values.length; k++) { // Values level values = stackKeys.values[k]; values["__y0__"] = prevValue; prevValue += values[valueField]; } } } return dataCopy; }, maxStackValue = function (data, groupField, stackField, valueField) { // Finds the max value by summing stacked items within a group, // then find the max across groups. // For example it finds the max height of all the layers bars in // a stacked bar chart. var nested_data, max; // Get sum of each stack grouping nested_data = d3.nest() .key(function(d) { return d[groupField]; }) //.key(function(d) { return d[stackField]; }) .rollup(function(leaves) { return {"stack_sum": d3.sum(leaves, function(d) {return d[valueField];})} }) .entries(data); // Find max value across stack groupings max = d3.max(nested_data, function (d) { return d.values.stack_sum; }) return max; };; return { datatableMin: datatableMin, datatableMax: datatableMax, datatableSum: datatableSum, datatableStat: datatableStat, datatablesStat: datatablesStat, generateStackYValues: generateStackYValues, maxStackValue: maxStackValue } })(d3); ggjs.ggjs = (function () { // Init var render = function (spec) { // Load spec var plotDef = ggjs.plot(spec); // Render chart ggjs.renderer(plotDef).render(); }; return { render: render } })();
ggjs-0.0.1.js
var ggjs = ggjs || {}; // ------------------ // Utilities // ------------------ ggjs.util = (function () { var isUndefined = function (val) { return typeof val === 'undefined'; }, isNullOrUndefined = function (val) { return isUndefined(val) || val == null; }, objKeys = function (obj) { var keys = [], key; for (key in obj) { if (obj.hasOwnProperty(key)) keys.push(key); } return keys; }, countObjKeys = function (obj) { return objKeys(obj).length; }, deepCopy = function (obj) { return JSON.parse(JSON.stringify(obj)); }, toBoolean = function(obj){ var str; if (obj === null || isUndefined(obj)) { return false; } str = String(obj).trim().toLowerCase(); switch(str){ case "true": case "yes": case "1": return true; case "false": case "no": case "0": return false; default: return Boolean(str); } }; return { isUndefined: isUndefined, isNullOrUndefined: isNullOrUndefined, objKeys: objKeys, countObjKeys: countObjKeys, deepCopy: deepCopy, toBoolean: toBoolean } })(); ggjs.util.array = (function () { var indexOf = function(arr, item) { // Finds the index of item in array var index = -1, i; for(i = 0; i < arr.length; i++) { if(arr[i] === item) { index = i; break; } } return index; }, contains = function (arr, item) { return indexOf(arr, item) !== -1; }; return { indexOf: indexOf, contains: contains } })(); // ------------------ // Datasets // ------------------ ggjs.Dataset = (function() { var dataset = function(spec) { spec = spec || {}; if (ggjs.util.isUndefined(spec.name)) throw "The dataset name must be defined"; this.dataset = { name: spec.name, values: spec.values || null, url: spec.url || null, contentType: spec.contentType || null, dataTypes: spec.dataTypes || {} }; //if (s) ggjs.extend(this.dataset, s); }; var prototype = dataset.prototype; prototype.name = function (val) { if (!arguments.length) return this.dataset.name; this.dataset.name = val; return this; }; prototype.values = function(val) { // Note: values should be JSON style data, e.g: // [{"a": 1, "b": 1}, {"a": 2, "b": 2}] if (!arguments.length) return this.dataset.values; this.dataset.values = val; return this; }; prototype.url = function (val) { if (!arguments.length) return this.dataset.url; this.dataset.url = val; return this; }; prototype.contentType = function (val) { if (!arguments.length) return this.dataset.contentType; this.dataset.contentType = val; return this; }; prototype.dataTypes = function (val) { if (!arguments.length) return this.dataset.dataTypes; this.dataset.dataTypes = val; return this; }; prototype.applyDataTypesToValues = function (dataTypes, values) { // Applies the user supplied data types // to values in dataset var isUndefined = ggjs.util.isUndefined, toBoolean = ggjs.util.toBoolean, fieldName, dataType, i, val; if (!values) { return; } for (fieldName in dataTypes) { dataType = dataTypes[fieldName]; switch (dataType) { case "number": for (i = 0; i < values.length; i++) { val = values[i][fieldName]; if (!isUndefined(val)) { values[i][fieldName] = +val; } } break; case "boolean": for (i = 0; i < values.length; i++) { val = values[i][fieldName]; if (!isUndefined(val)) { values[i][fieldName] = toBoolean(val); } } break; default: throw "Can't apply data type, unrecognised data type " + dataType; } } }; prototype.applyDataTypes = function () { var dataTypes = this.dataTypes(), values = this.values(); this.applyDataTypesToValues(dataTypes, values); }; return dataset; })(); ggjs.dataset = function (s) { return new ggjs.Dataset(s); }; ggjs.Data = (function () { var datasets = function (s) { var i, dataset; this.datasets = {}; if (s) { for (i = 0; i < s.length; i++) { dataset = ggjs.dataset(s[i]); this.datasets[dataset.name()] = dataset; } } }; var prototype = datasets.prototype; prototype.dataset = function (datasetName, dataset) { // ToDo: Get or set dataset if (arguments.length < 1) throw "dataset function needs datasetName argument."; if (arguments.length == 1) return this.datasets[datasetName]; // ToDo: set as object, ggjs dataset (or either)? this.datasets[datasetName] = ggjs.dataset(dataset); return this; }; prototype.count = function () { return ggjs.util.countObjKeys(this.datasets); }; prototype.names = function () { return ggjs.util.objKeys(this.datasets); }; return datasets; })(); ggjs.datasets = function (s) { return new ggjs.Data(s); }; // ------------------ // Axes // ------------------ ggjs.Axis = (function() { var axis = function(spec) { spec = spec || {}; if (ggjs.util.isUndefined(spec.type)) throw "The axis type must be defined"; this.axis = { type: spec.type, scaleName: spec.scaleName || null }; //if (s) ggjs.extend(this.axis, s); }; var prototype = axis.prototype; prototype.type = function (val) { if (!arguments.length) return this.axis.type; this.axis.type = val; return this; }; prototype.scaleName = function(val) { if (!arguments.length) return this.axis.scaleName; // ToDo: set as object, ggjs scale (or either)? this.axis.scaleName = val; return this; }; return axis; })(); ggjs.axis = function (s) { return new ggjs.Axis(s); }; ggjs.Axes = (function() { var axes = function(s) { var i, axis; this.axes = {}; if (s) { for (i = 0; i < s.length; i++) { axis = ggjs.axis(s[i]); this.axes[axis.type()] = axis; } } }; var prototype = axes.prototype; prototype.axis = function(axisType, axis) { // ToDo: Get or set axis if (arguments.length < 1) throw "axis function needs axisType argument."; if (arguments.length == 1) return this.axes[axisType]; this.axes[axisType] = ggjs.axis(axis); return this; }; prototype.count = function() { return ggjs.util.countObjKeys(this.axes); // var size = 0, key; // for (key in this.axes) { // if (this.axes.hasOwnProperty(key)) size++; // } // return size; }; return axes; })(); ggjs.axes = function (s) { return new ggjs.Axes(s); }; // ------------------ // Scales // ------------------ ggjs.Scale = (function () { var scale = function(spec) { this.scale = { type: spec.type || null, name: spec.name || null, domain: spec.domain || null, range: spec.range || null }; //if (spec) ggjs.extend(this.scale, spec); }; var prototype = scale.prototype; prototype.type = function(val) { if (!arguments.length) return this.scale.type; this.scale.type = val; return this; }; prototype.name = function(val) { if (!arguments.length) return this.scale.name; this.scale.name = val; return this; }; prototype.domain = function(val) { if (!arguments.length) return this.scale.domain; this.scale.domain = val; return this; }; prototype.range = function(val) { if (!arguments.length) return this.scale.range; this.scale.range = val; return this; }; prototype.hasDomain = function () { // Whether a domain is specified for the scale // Read only return this.domain() != null; } prototype.hasRange = function () { // Whether a range is specified for the scale // Read only return this.range() != null; } prototype.isQuantitative = function () { var quantScales = ["linear", "sqrt", "pow", "log"]; return ggjs.util.array.contains(quantScales, this.type()); } prototype.isOrdinal = function () { var ordinalScales = ["ordinal", "category10", "category20", "category20b", "category20c"]; return ggjs.util.array.contains(ordinalScales, this.type()); } prototype.isTime = function () { var timeScales = ["time"]; return ggjs.util.array.contains(timeScales, this.type()); } return scale; })(); ggjs.scale = function (s) { return new ggjs.Scale(s); }; ggjs.Scales = (function() { var scales = function(s) { var i, scale; this.scales = {}; if (s) { for (i = 0; i < s.length; i++) { scale = ggjs.scale(s[i]); this.scales[scale.name()] = scale; } } }; var prototype = scales.prototype; prototype.scale = function(scaleName, scale) { // Gets or set scale by name if (arguments.length < 1) throw "scale function needs scaleName argument."; if (arguments.length == 1) return this.scales[scaleName]; this.scales[scaleName] = ggjs.scale(scale); return this; }; prototype.count = function() { var size = 0, key; for (key in this.scales) { if (this.scales.hasOwnProperty(key)) size++; } return size; }; return scales; })(); ggjs.scales = function (s) { return new ggjs.Scales(s); }; // ------------------ // Padding // ------------------ ggjs.Padding = (function () { var padding = function(s) { this.padding = { left: s.left || 40, right: s.right || 20, top: s.top || 20, bottom: s.bottom || 70 }; //if (s) ggjs.extend(this.padding, s); }; var prototype = padding.prototype; prototype.left = function (l) { if (!arguments.length) return this.padding.left; this.padding.left = l; return this; }; prototype.right = function (r) { if (!arguments.length) return this.padding.right; this.padding.right = r; return this; }; prototype.top = function (t) { if (!arguments.length) return this.padding.top; this.padding.top = t; return this; }; prototype.bottom = function (b) { if (!arguments.length) return this.padding.bottom; this.padding.bottom = b; return this; }; return padding; })(); ggjs.padding = function (s) { return new ggjs.Padding(s); }; // ------------------ // Aesthetic mappings // ------------------ ggjs.AesMapping = (function () { // Aesthetic mapping shows which variables are mapped to which // aesthetics. For example, we might map weight to x position, // height to y position, and age to size. // // GGPlot: // layer(aes(x = x, y = y, color = z)) // Ref [lg] 3.1.1 var aesmap = function(s) { this.aesmap = { aes: s.aes || null, field: s.field || null, scaleName: s.scaleName || null }; //if (s) ggjs.extend(this.aesmap, s); }; var prototype = aesmap.prototype; prototype.aes = function (val) { if (!arguments.length) return this.aesmap.aes; this.aesmap.aes = val; return this; }; prototype.field = function (val) { if (!arguments.length) return this.aesmap.field; this.aesmap.field = val; return this; }; prototype.scaleName = function (val) { if (!arguments.length) return this.aesmap.scaleName; this.aesmap.scaleName = val; return this; }; return aesmap; })(); ggjs.aesmapping = function (s) { return new ggjs.AesMapping(s); }; ggjs.AesMappings = (function () { var aesmappings = function(spec) { var i; this.aesmappings = []; for (i = 0; i < spec.length; i++) { this.aesmappings.push(ggjs.aesmapping(spec[i])); } }; var prototype = aesmappings.prototype; prototype.findByAes = function (aesName) { // Finds an aesthetic mapping by aesthetic name var mappings = this.aesmappings, i, tmpAesmap; for (i = 0; i < mappings.length; i++) { tmpAesmap = mappings[i]; if (tmpAesmap.aes() === aesName) { return tmpAesmap; } } return null; }; prototype.count = function () { return this.aesmappings.length; }; prototype.asArray = function () { return this.aesmappings; }; return aesmappings; })(); ggjs.aesmappings = function (s) { return new ggjs.AesMappings(s); }; // ------------------ // Layer Geom // ------------------ ggjs.Geom = (function () { var geom = function(s) { this.geom = { // Support JSON-LD type Geom type geomType: s.geomType || s["@type"] || "GeomBar" }; }; var prototype = geom.prototype; prototype.geomType = function (l) { if (!arguments.length) return this.geom.geomType; this.geom.geomType = l; return this; }; return geom; })(); ggjs.geom = function (s) { return new ggjs.Geom(s); }; // ------------------ // Layers // ------------------ ggjs.Layer = (function () { // Layers are responsible for creating the objects that we perceive on the plot. // A layer is composed of: // - data and aesthetic mapping, // - a statistical transformation (stat), // - a geometric object (geom), and // - a position adjustment // // GGPlot: // layer(aes(x = x, y = y, color = z), geom="line", // stat="smooth") // Ref [lg] 3.1 var layer = function(spec) { // ToDo: move Namespace info out into separate module var ggjsPrefix = "ggjs", fillAesMap, xAesMap; this.layer = { data: spec.data || null, geom: ggjs.geom(spec.geom || {}), // geom: spec.geom || null, position: spec.position || null, // Sometimes order id is prefixed because JSON-LD context // has conflicts with other vocabs using 'orderId'. orderId: spec.orderId || spec[ggjsPrefix + ":orderId"] || null, // Note: support 'aesmapping' as name for aesmapping collection as well // as 'aesmapping' to support Linked Data style naming aesmappings: ggjs.aesmappings(spec.aesmappings || spec.aesmapping || []) }; //if (s) ggjs.extend(this.layer, s); fillAesMap = this.layer.aesmappings.findByAes("fill"); xAesMap = this.layer.aesmappings.findByAes("x"); // Set defaults if (this.geom().geomType() === "GeomBar" && this.position() === "stack" && fillAesMap != null && xAesMap != null && fillAesMap.field() !== xAesMap.field()) { this.layer.useStackedData = true; } else { this.layer.useStackedData = false; } }; var prototype = layer.prototype; prototype.data = function (val) { if (!arguments.length) return this.layer.data; this.layer.data = val; return this; }; prototype.geom = function (val) { if (!arguments.length) return this.layer.geom; this.layer.geom = val; return this; }; prototype.position = function (val) { if (!arguments.length) return this.layer.position; this.layer.position = val; return this; }; prototype.orderId = function (val) { if (!arguments.length) return this.layer.orderId; this.layer.orderId = val; return this; }; prototype.aesmappings = function (val) { if (!arguments.length) return this.layer.aesmappings; // ToDo: should val be obj or Axes (or either)? this.layer.aesmappings = val; return this; }; prototype.useStackedData = function (val) { if (!arguments.length) return this.layer.useStackedData; this.layer.useStackedData = val; return this; }; // prototype.useStackedData = function () { // if (this.geom() === "bar" && this.position() === "stack") { // return true; // } // return false; // } return layer; })(); ggjs.layer = function(s) { return new ggjs.Layer(s); }; ggjs.Layers = (function () { var layers = function(spec) { var isNullOrUndefined = ggjs.util.isNullOrUndefined, i; this.layers = []; for (i = 0; i < spec.length; i++) { this.layers.push(ggjs.layer(spec[i])); } // Sort layers by orderId this.layers.sort(function (lhs, rhs) { var lhsOrderId = isNullOrUndefined(lhs.orderId()) ? 0 : lhs.orderId(), rhsOrderId = isNullOrUndefined(rhs.orderId()) ? 0 : rhs.orderId(); return lhsOrderId - rhsOrderId; }) }; var prototype = layers.prototype; prototype.count = function () { return this.layers.length; }; prototype.asArray = function () { return this.layers; }; return layers; })(); ggjs.layers = function(s) { return new ggjs.Layers(s); }; // ------------------ // Plot // ------------------ ggjs.Plot = (function () { // The layered grammar defines the components of a plot as: // - a default dataset and set of mappings from variables to aesthetics, // - one or more layers, with each layer having one geometric object, one statistical // transformation, one position adjustment, and optionally, one dataset and set of // aesthetic mappings, // - one scale for each aesthetic mapping used, // - a coordinate system, // - the facet specification. // ref: [lg] 3.0 var plot = function(spec) { this.plot = { // ToDo: get defaults from config? selector: spec.selector, // Note: let renderer set default width // width: spec.width || 500, width: spec.width, height: spec.height || 500, padding: ggjs.padding(spec.padding || {}), data: ggjs.datasets(spec.data || []), defaultDatasetName: null, // ToDo: automatically find co-ordinate system based on layers? coord: spec.coord || "cartesian", // Note: support 'scale' as name for scale collection as well // as 'scales' to support Linked Data style naming scales: ggjs.scales(spec.scales || spec.scale || []), // Note: support 'axis' as name for axis collection as well // as 'axes' to support Linked Data style naming axes: ggjs.axes(spec.axes || spec.axis || []), facet: spec.facet || null, // Note: support 'layer' as name for layers collection as well // as 'layers' to support Linked Data style naming layers: ggjs.layers(spec.layers || spec.layer || []) }; //if (spec) ggjs.extend(this.plot, spec); }; var prototype = plot.prototype; prototype.selector = function (val) { if (!arguments.length) return this.plot.selector; this.plot.selector = val; return this; }; prototype.width = function (val) { if (!arguments.length) return this.plot.width; this.plot.width = val; return this; }; prototype.height = function (val) { if (!arguments.length) return this.plot.height; this.plot.height = val; return this; }; prototype.padding = function (val) { if (!arguments.length) return this.plot.padding; this.plot.padding = ggjs.padding(val); return this; }; prototype.coord = function (val) { if (!arguments.length) return this.plot.coord; this.plot.coord = val; return this; }; prototype.data = function (val) { if (!arguments.length) return this.plot.data; // ToDo: should val be obj or Datasets (or either)? this.plot.data = val; return this; }; prototype.axes = function (val) { if (!arguments.length) return this.plot.axes; // ToDo: should val be obj or Axes (or either)? this.plot.axes = val; return this; }; prototype.scales = function (val) { if (!arguments.length) return this.plot.scales; // ToDo: should val be obj or Scales (or either)? this.plot.scales = val; return this; }; prototype.layers = function (val) { if (!arguments.length) return this.plot.layers; // ToDo: should val be obj or Layers (or either)? this.plot.layers = val; return this; }; // ---------------------- // Plot area information // ---------------------- prototype.plotAreaWidth = function () { // ToDo: take axis titles and legends size away from width return this.width() - this.padding().left() - this.padding().right(); }; prototype.plotAreaHeight = function () { // ToDo: take axis titles, plot title, legends size away from height return this.height() - this.padding().top() - this.padding().bottom(); }; prototype.plotAreaX = function () { // ToDo: add axis titles and legends size return this.padding().left(); }; prototype.plotAreaY = function () { // ToDo: add axis titles, plot title and legends size return this.padding().top(); }; // ---------------------- // Axis information // ---------------------- prototype.yAxisHeight = function () { switch (this.coord()) { case "cartesian": return this.plotAreaHeight(); case "polar": return Math.floor(this.plotAreaHeight() / 2); default: throw "Can't get y axis height, unknown co-ordinate system " + this.coord(); } }; // ---------------------- // Data information // ---------------------- prototype.defaultDatasetName = function (val) { if (!arguments.length) { if (this.plot.defaultDatasetName != null) { return this.plot.defaultDatasetName; } else if (this.plot.data.count() === 1) { // Treat sole dataset as default data return this.plot.data.names()[0]; } else { return null; } } this.plot.defaultDatasetName = val; return this; } return plot; })(); ggjs.plot = function(p) { return new ggjs.Plot(p); }; ggjs.Renderer = (function (d3) { var renderer = function (plotDef) { this.renderer = { plotDef: plotDef, plot: null, // The element to draw to xAxis: null, yAxis: null, scaleNameToD3Scale: {}, // Lookup to find D3 scale for scale name datasetsRetrieved: {}, warnings: [], defaultFillColor: "rgb(31, 119, 180)" }; this.geo = {}; this.dataAttrXField = "data-ggjs-x-field"; this.dataAttrXValue = "data-ggjs-x-value"; this.dataAttrYField = "data-ggjs-y-field"; this.dataAttrYValue = "data-ggjs-y-value"; // Width: autoset width if width is missing var width = plotDef.width(), parentWidth; if (typeof width === 'undefined' || width == null) { // Set width to parent container width try { parentWidth = d3.select(plotDef.selector()).node().offsetWidth; } catch (err) { throw "Couldn't find the width of the parent element."; } if (typeof parentWidth === 'undefined' || parentWidth == null) { throw "Couldn't find the width of the parent element."; } this.renderer.plotDef.width(parentWidth); } }; var prototype = renderer.prototype; prototype.plotDef = function (val) { if (!arguments.length) return this.renderer.plotDef; this.renderer.plotDef = val; return this; }; prototype.warning = function (warning) { // Adds a warning to the log this.renderer.warnings.push(warning); } prototype.warnings = function (val) { if (!arguments.length) return this.renderer.warnings; this.renderer.warnings = val; return this; }; prototype.render = function () { var this_ = this; // Clear contents (so they disapper in the event of failed data load) d3.select(this.plotDef().selector()).select("svg").remove(); // Fetch data then render plot this.fetchData(function () { this_.renderPlot(); }) }; prototype.fetchData = function (finishedCallback) { var plotDef = this.plotDef(), datasetNames = plotDef.data().names(), loadData = function (url, datasetName, contentType, callback) { var contentTypeLC = contentType ? contentType.toLowerCase() : contentType, dataset = plotDef.data().dataset(datasetName); switch (contentTypeLC) { case "text/csv": d3.csv(url, function(err, res) { if (err) throw "Error fetching CSV results: " + err.statusText; dataset.values(res); dataset.applyDataTypes(); callback(null, res); }); break; case "text/tsv": case "text/tab-separated-values": d3.tsv(url, function(err, res) { if (err) throw "Error fetching TSV results: " + err.statusText; dataset.values(res); dataset.applyDataTypes(); callback(null, res); }); break; case "application/json": d3.json(url, function(err, res) { if (err) throw "Error fetching JSON results: " + err.statusText; dataset.values(res); dataset.applyDataTypes(); callback(null, res); }); break; case "application/vnd.geo+json": d3.json(url, function(err, res) { if (err) throw "Error fetching GEO JSON results: " + err.statusText; dataset.values(res); callback(null, res); }); break; default: throw "Don't know you to load data of type " + contentType; } }, q = queue(3), i, datasetName, dataset; // Queue all data held at url for (i = 0; i < datasetNames.length; i++) { datasetName = datasetNames[i]; dataset = plotDef.data().dataset(datasetName); if (dataset && dataset.url()) { q.defer(loadData, dataset.url(), datasetName, dataset.contentType()); } } q.awaitAll(function(error, results) { if (error) { // ToDo: write error in place of chart? throw "Error fetching data results: " + error.statusText; } // Data loaded - continue rendering finishedCallback(); }); }; prototype.setupGeo = function () { var this_ = this, plotDef = this.plotDef(), width = plotDef.plotAreaWidth(), height = plotDef.plotAreaHeight(); if (plotDef.coord() !== "mercator") { return; } // var width = Math.max(960, window.innerWidth), // height = Math.max(500, window.innerHeight); var projection = d3.geo.mercator() //.scale((1 << 12) / 2 / Math.PI) // US .scale((1 << 20) / 2 / Math.PI) // Lambeth .translate([width / 2, height / 2]); //var center = projection([-100, 40]); // US //var center = projection([-106, 37.5]); // US //var center = projection([-10, 55]); // UK var center = projection([-0.1046, 51.46]); // Lambeth var zoom = d3.behavior.zoom() .scale(projection.scale() * 2 * Math.PI) .scaleExtent([1 << 11, 1 << 14]) .translate([width - center[0], height - center[1]]) .on("zoom", this_.drawLayers); //.on("zoom", this_.drawLayers(this_.renderer.plot)); //.on("zoom", zoomed); this.geo.zoom = zoom; // With the center computed, now adjust the projection such that // it uses the zoom behavior’s translate and scale. projection .scale(1 / 2 / Math.PI) .translate([0, 0]); this.geo.projection = projection; }; // prototype.zoomed = function () { // console.log("Some zooming"); // } prototype.renderPlot = function () { var plotDef = this.plotDef(), plot; // d3.select(this.plotDef().selector()).select("svg").remove(); d3.select(plotDef.selector()).html(""); plot = d3.select(plotDef.selector()) .append("svg") .attr("width", plotDef.width()) .attr("height", plotDef.height()); this.renderer.plot = plot; console.log(plotDef.plotAreaX()); console.log(plotDef.plotAreaY()); console.log(plotDef.plotAreaHeight()); console.log(plotDef.plotAreaWidth()); // ToDo: if no domain set on axes, default to extent // of data for appropriate aes across layers this.buildScales(); this.setupXAxis(); this.setupYAxis(); this.setupGeo(); this.drawAxes(); this.drawLayers(); this.drawLegends(); }; prototype.drawLayers = function () { var plotDef = this.plotDef(), plot = this.renderer.plot, layerDefs = plotDef.layers().asArray(), i, layerDef, plotArea; // Setup layers switch (plotDef.coord()) { case "cartesian": plotArea = plot.append("g") .attr("transform", "translate(" + plotDef.plotAreaX() + "," + plotDef.plotAreaY() + ")"); break; case "polar": plotArea = plot.append("g") .attr("transform", "translate(" + (plotDef.plotAreaX() + Math.floor(plotDef.plotAreaWidth() / 2)) + "," + (plotDef.plotAreaY() + Math.floor(plotDef.plotAreaHeight() / 2)) + ")"); break; case "mercator": //plot.call(this.geo.zoom); plotArea = plot.append("g") .attr("transform", "translate(" + plotDef.plotAreaX() + "," + plotDef.plotAreaY() + ")"); //plotArea.on("zoom", function () {console.log("zooming")}) var zoom = d3.behavior.zoom() .scale(1 << 12) .scaleExtent([1 << 9, 1 << 23]) .translate([250, 250]) .on("zoom", function () {console.log("zooming")}); //plotArea.call(zoom); plotArea.on("mousemove", function () {console.log("mouse moved")}); break; } // Draw each layer for (i = 0; i < layerDefs.length; i++) { layerDef = layerDefs[i]; switch (layerDef.geom().geomType()) { case "GeomPoint": this.drawPointLayer(plotArea, layerDef); break; case "GeomBar": this.drawBarLayer(plotArea, layerDef); break; case "GeomText": this.drawTextLayer(plotArea, layerDef); break; case "GeomPath": this.drawPathLayer(plotArea, layerDef); break; case "GeomGeoTiles": this.drawMapTiles(plotArea, layerDef); break; default: throw "Cannot draw layer, geom type not supported: " + layerDef.geom().geomType(); } } // Post layer processing // switch (plotDef.coord()) { // case "mercator": // break; // } }; prototype.drawMapTiles = function (plotArea, layerDef) { // Draws geographic map tiles images onto plot area console.log("Drawing map tiles"); var plotDef = this.plotDef(), width = plotDef.plotAreaWidth(), height = plotDef.plotAreaHeight(), zoom = this.geo.zoom, plot = this.renderer.plot; //var width = Math.max(960, window.innerWidth), // height = Math.max(500, window.innerHeight); var tile = d3.geo.tile() .size([width, height]); // var svg = d3.select("body").append("svg") // .attr("width", width) // .attr("height", height); var svg = plot; var raster = svg.append("g"); //function zoomed() { var tiles = tile .scale(zoom.scale()) .translate(zoom.translate()) (); var image = raster .attr("transform", "scale(" + tiles.scale + ")translate(" + tiles.translate + ")") .selectAll("image") .data(tiles, function(d) { return d; }); image.exit() .remove(); image.enter().append("image") .attr("xlink:href", function(d) { return "http://" + ["a", "b", "c", "d"][Math.random() * 4 | 0] + ".tiles.mapbox.com/v3/examples.map-i86nkdio/" + d[2] + "/" + d[0] + "/" + d[1] + ".png"; }) .attr("class", "ggjs-tile") .attr("width", 1) .attr("height", 1) .attr("x", function(d) { return d[0]; }) .attr("y", function(d) { return d[1]; }); //} //zoomed(); }; prototype.drawPathLayer = function (plotArea, layerDef) { var plotDef = this.plotDef(); switch (plotDef.coord()) { case "mercator": this.drawMapPathLayer(plotArea, layerDef); break; default: throw "Do not know how to draw path for coord " + plotDef.coord(); } } prototype.drawMapPathLayer = function (plotArea, layerDef) { // Draws path on a map plot var plotDef = this.plotDef(), // width = plotDef.plotAreaWidth(), // height = plotDef.plotAreaHeight(), zoom = this.geo.zoom, projection = this.geo.projection, plot = this.renderer.plot; console.log("drawing map path"); var svg = plot; var path = d3.geo.path() .projection(projection); var vector = svg.append("path"); var vector2 = svg.append("g") .attr("transform", "translate(" + zoom.translate() + ")scale(" + zoom.scale() + ")"); //.style("stroke-width", 1 / zoom.scale()); d3.json("data/us.json", function(error, us) { //svg.call(zoom); vector.attr("d", path(topojson.mesh(us, us.objects.counties))) .attr("class", "ggjs-path-map"); aa = [-122.490402, 37.786453]; bb = [-122.389809, 37.72728]; vector2.selectAll("circle") .data([aa,bb]) .enter().append("circle") // .attr("cx", function (d) { console.log(projection(d)); return projection(d)[0]; }) // .attr("cy", function (d) { return projection(d)[1]; }) .attr("transform", function(d) {return "translate(" + projection(d) + ")";}) .attr("r", 5 / zoom.scale()) .attr("fill", "red") //zoomed(); vector .attr("transform", "translate(" + zoom.translate() + ")scale(" + zoom.scale() + ")") .style("stroke-width", 1 / zoom.scale()); // vector2 // .attr("transform", "translate(" + zoom.translate() + ")scale(" + zoom.scale() + ")") // .style("stroke-width", 1 / zoom.scale()); }); }; prototype.drawPointLayer = function (plotArea, layerDef) { var plotDef = this.plotDef(), aesmappings = layerDef.aesmappings(), xField = aesmappings.findByAes("x").field(), yField = aesmappings.findByAes("y").field(), xScale = this.xAxis().scale(), yScale = this.yAxis().scale(), datasetName = layerDef.data(), dataset = this.getDataset(datasetName), //dataset = plotDef.data().dataset(datasetName), values = dataset.values(); switch (plotDef.coord()) { case "cartesian": this.drawCartesianPointLayer(plotArea, values, aesmappings, xField, yField, xScale, yScale); break; case "mercator": this.drawMapPointLayer(plotArea, values, aesmappings, xField, yField, xScale, yScale); break; default: throw "Do not know how to draw point for coord " + plotDef.coord(); } }; // Draws points (e.g. circles) onto the plot area prototype.drawCartesianPointLayer = function (plotArea, values, aesmappings, xField, yField, xScale, yScale) { var xScaleType = this.xAxisScaleDef().type(), xOffset = xScaleType === 'ordinal' ? Math.ceil(xScale.rangeBand() / 2) : 0, points; points = plotArea.selectAll(".ggjs-point") .data(values) .enter().append("circle") .attr("class", "ggjs-point") .attr("r", 3.5) .attr("cx", function (d) { return xScale(d[xField]) + xOffset; }) .attr("cy", function (d) { return yScale(d[yField]); }); this.applyFillColour(points, aesmappings); }; prototype.drawMapPointLayer = function (plotArea, values, aesmappings, xField, yField, xScale, yScale) { // Draws points (e.g. circles) onto the plot area var projection = this.geo.projection, zoom = this.geo.zoom, plot = this.renderer.plot, dataAttrXField = this.dataAttrXField, dataAttrXValue = this.dataAttrXValue, dataAttrYField = this.dataAttrYField, dataAttrYValue = this.dataAttrYValue, svg = plot; // var points = plotArea.selectAll(".ggjs-point") // .data(values) // .enter().append("circle") // .attr("class", "ggjs-point") // .attr("r", 3.5) // .attr("cx", function (d) { return xScale(d[xField]); }) // .attr("cy", function (d) { return yScale(d[yField]); }); // console.log(values[0][xField]) // console.log(values[0][yField]) // console.log( projection([ +(values[0][yField]), +(values[0][xField]) ]) ) // var points = plotArea.selectAll(".pin") // .data(values) // .enter().append("circle", ".pin") // .attr("r", 5) // .attr("transform", function(d) { // return "translate(" + projection([ // d[yField], // d[xField] // ]) + ")"; }); var vector2 = svg.append("g") .attr("transform", "translate(" + zoom.translate() + ")scale(" + zoom.scale() + ")"); //.style("stroke-width", 1 / zoom.scale()); vector2.selectAll("circle") .data(values) .enter().append("circle") // .attr("cx", function (d) { console.log(projection(d)); return projection(d)[0]; }) // .attr("cy", function (d) { return projection(d)[1]; }) .attr("transform", function(d) {return "translate(" + projection([ +d[yField], +d[xField] ]) + ")";}) .attr("r", 5 / zoom.scale()) .attr("fill", "rgba(255,0,0,0.6)") .attr(dataAttrXField, xField) .attr(dataAttrXValue, function (d) { return d[xField]; }) .attr(dataAttrYField, yField) .attr(dataAttrYValue, function (d) { return d[yField]; }); // var coordinates = projection([mylon, mylat]); // plotArea.selectAll(".circle") // .data(values) // .enter().append('circle', ".circle") // .attr('cx', function (d) { return projection([ +d[yField], +d[xField] ])[0]; } ) // .attr('cy', function (d) { return projection([ +d[yField], +d[xField] ])[1]; } ) // .attr('r', 5); //this.applyFillColour(points, aesmappings); }; prototype.drawTextLayer = function (plotArea, layerDef) { // Draws text onto the plot area // Similar to point layer rendering var plotDef = this.plotDef(), aesmappings = layerDef.aesmappings(), xAes = aesmappings.findByAes("x"), yAes = aesmappings.findByAes("y"), labelAes = aesmappings.findByAes("label"), xScale = this.xAxis().scale(), yScale = this.yAxis().scale(), datasetName = layerDef.data(), dataset = this.getDataset(datasetName), //dataset = plotDef.data().dataset(datasetName), values = dataset.values(), xField, yField, labelField, points; if (xAes == null) throw "Cannot draw text layer, x aesthetic no specified"; if (yAes == null) throw "Cannot draw text layer, y aesthetic no specified"; xField = xAes.field(); yField = yAes.field(); labelField = labelAes == null ? null : labelAes.field(); if (labelField == null) { this.warning("No text field supplied for text layer, label will be blank."); } points = plotArea.selectAll("text.ggjs-label") .data(values) .enter().append("text") .attr("class", "ggjs-label") .attr("x", function (d) { return xScale(d[xField]); }) .attr("y", function (d) { return yScale(d[yField]); }) .text(function (d) { if (labelField != null) { return d[labelField]; } else { return ""; } }); //this.applyFillColour(points, aesmappings); }; prototype.drawBarLayer = function (plotArea, layerDef) { // Draws bars onto the plot area var plotDef = this.plotDef(), yAxisHeight = plotDef.yAxisHeight(), aesmappings = layerDef.aesmappings(), fillAesMap = aesmappings.findByAes("fill"), xField = aesmappings.findByAes("x").field(), yField = aesmappings.findByAes("y").field(), xScale = this.xAxis().scale(), yScale = this.yAxis().scale(), datasetName = layerDef.data(), //dataset = plotDef.data().dataset(datasetName), dataset = this.getDataset(datasetName), isStacked = layerDef.useStackedData(), bars, values; // if (dataset == null) { // // Use default dataset for the plot // var datasetNames = plotDef.data().names(); // if (datasetNames.length !== 1) { // throw "Expected one DataSet in the Plot to use as the default DataSet"; // } // datasetName = datasetNames[0]; // dataset = plotDef.data().dataset(datasetName); // if (dataset == null) { // throw "Couldn't find a layer DataSet or a default DataSet."; // } // } values = dataset.values(); // Stacked/dodged bar charts // ToDo: dodge bar charts if (isStacked) { // Work out new baseline for each x value var fillScaleDef = this.scaleDef(fillAesMap.scaleName()); if (fillScaleDef == null) { throw "No scale could be found for fill scale " + fillAesMap.scaleName(); } if (this.xAxisScaleDef().isOrdinal() && fillScaleDef.isOrdinal()) { values = ggjs.dataHelper.generateStackYValues(values, xField, fillAesMap.field(), yField); } else { throw "Do not know how to draw stacked/dodged bars with non ordinal scales." } } switch (plotDef.coord()) { case "cartesian": bars = this.drawCartesianBars(plotArea, values, xField, yField, xScale, yScale, yAxisHeight, isStacked); break; case "polar": bars = this.drawPolarBars(plotArea, values, xField, yField, xScale, yScale, yAxisHeight, isStacked); break; default: throw "Don't know how to draw bars for co-ordinate system " + plotDef.coord(); } this.applyFillColour(bars, aesmappings); }; prototype.drawCartesianBars = function (plotArea, values, xField, yField, xScale, yScale, yAxisHeight, isStacked) { var dataAttrXField = this.dataAttrXField, dataAttrXValue = this.dataAttrXValue, dataAttrYField = this.dataAttrYField, dataAttrYValue = this.dataAttrYValue, bars = plotArea.selectAll("rect.ggjs-bar") .data(values) .enter().append("rect") .attr("class", "ggjs-bar") .attr("x", function(d) { return xScale(d[xField]); }) .attr("y", function(d) { if (isStacked) { return yScale(d[yField] + d["__y0__"]); } else { return yScale(d[yField]); } }) .attr("height", function(d) { return yAxisHeight - yScale(d[yField]); }) .attr("width", xScale.rangeBand()) .attr(dataAttrXField, xField) .attr(dataAttrXValue, function (d) { return d[xField]; }) .attr(dataAttrYField, yField) .attr(dataAttrYValue, function (d) { return d[yField]; }); return bars; }; prototype.drawPolarBars = function (plotArea, values, xField, yField, xScale, yScale, yAxisHeight, isStacked) { var arc, bars; arc = d3.svg.arc() .innerRadius(0) //.outerRadius(150) .outerRadius(function (d) {return yAxisHeight - yScale(d[yField]); }) .startAngle(function (d) { console.log("startAngle d: " + d[xField]); console.log("startAngle: " + xScale(d[xField])); return xScale(d[xField]); }) .endAngle(function (d) { console.log("endAngle d: " + d[xField]); console.log("endAngle: " + xScale(d[xField]) + xScale.rangeBand()); return xScale(d[xField]) + xScale.rangeBand(); }); bars = plotArea.selectAll("path.ggjs-arc") .data(values) .enter().append("path") .attr("class", "ggjs-arc") .attr("d", arc) return bars; }; prototype.applyFillColour = function (svgItems, aesmappings) { // Applies fill colour to svg elements // Params: // svgItems: the svg elements as D3 select list // aesmappings: the layer's aesmappings // Fill colour // ToDo: setup colour scale across all layers, so colours // are matched across layers console.log("Warning: move colour mapping to all levels."); var plotDef = this.plotDef(), fillAesMap = aesmappings.findByAes("fill"), defaultFillColor = this.renderer.defaultFillColor; if (fillAesMap != null) { var colorField = fillAesMap.field(), colorScaleDef = this.scaleDef(fillAesMap.scaleName()), colorScale; if (colorScaleDef == null) { this.warning("Couldn't set colour on layer - fill colour scale missing.") svgItems.style("fill", function(d) { return defaultFillColor; }); } else { colorScale = this.scale(colorScaleDef); svgItems.style("fill", function(d) { return colorScale(d[colorField]); }); } } else { svgItems.style("fill", function(d) { return defaultFillColor; }); } }; prototype.drawAxes = function () { var plotDef = this.plotDef(), plot = this.renderer.plot; switch (plotDef.coord()) { case "cartesian": // Need an x and y axis // ToDo: support x2 and y2 axes //var xAxisDef = plotDef.axes().axis("x"); var xAxis = this.xAxis(), yAxis = this.yAxis(), xAxisY = plotDef.plotAreaY() + plotDef.plotAreaHeight(); plot.append("g") .attr("class", "ggjs-x ggjs-axis") .attr("transform", "translate(" + plotDef.plotAreaX() + "," + xAxisY + ")") .call(xAxis) // Tmp: orientate labels .selectAll("text") .attr("y", 5) .attr("x", 4) // .attr("dy", ".15em") .attr("dy", "12px") .attr("transform", "rotate(35)") .style("text-anchor", "start"); // ToDo: append x axis title plot.append("g") .attr("class", "ggjs-y ggjs-axis") .attr("transform", "translate(" + plotDef.plotAreaX() + "," + plotDef.plotAreaY() + ")") .call(yAxis); // ToDo: append x axis title break; case "polar": console.log("Draw polar axes"); break; case "mercator": break; default: throw "Unrecognised coordinate system used." } }; prototype.xAxis = function (val) { if (!arguments.length) return this.renderer.xAxis; this.renderer.xAxis = val; return this; }; prototype.yAxis = function (val) { if (!arguments.length) return this.renderer.yAxis; this.renderer.yAxis = val; return this; }; prototype.xAxisScaleDef = function (val) { if (!arguments.length) return this.renderer.xAxisScaleDef; this.renderer.xAxisScaleDef = val; return this; }; prototype.yAxisScaleDef = function (val) { if (!arguments.length) return this.renderer.yAxisScaleDef; this.renderer.yAxisScaleDef = val; return this; }; prototype.getDataset = function (datasetName) { var plotDef = this.plotDef(), dataset = plotDef.data().dataset(datasetName), datasetNames; if (dataset == null) { // Use default dataset for the plot datasetNames = plotDef.data().names(); if (datasetNames.length !== 1) { throw "Expected one DataSet in the Plot to use as the default DataSet"; } datasetName = datasetNames[0]; dataset = plotDef.data().dataset(datasetName); if (dataset == null) { throw "Couldn't find a layer DataSet or a default DataSet."; } } return dataset; }; prototype.statAcrossLayers = function (aes, stat) { // Looks at the data across all layers for an // aesthetic and gets info about it (e.g. max or min) var plotDef = this.plotDef(), layers = plotDef.layers().asArray(), statVal = null, i, layer, aesmap, field, tmpStat, datasetName, dataset; for (i = 0; i < layers.length; i++) { layer = layers[i]; aesmap = layer.aesmappings().findByAes(aes); // Layer data datasetName = layer.data(); if (!datasetName) { datasetName = plotDef.defaultDatasetName(); } //dataset = plotDef.data().dataset(datasetName); dataset = this.getDataset(datasetName); if (dataset == null) { throw "Unable to find dataset with name " + datasetName; } if (aesmap) { field = aesmap.field(); if (stat === "max" && layer.useStackedData()) { // Stack data tmpStat = this.layerStackedDataMax(layer, dataset, aes); } else { // Normal case for finding aes value tmpStat = ggjs.dataHelper.datatableStat(dataset.values(), field, stat); } if (!isNaN(tmpStat)) { if (statVal == null) statVal = tmpStat; statVal = stat === "min" ? Math.min(statVal, tmpStat) : Math.max(statVal, tmpStat); } } } return statVal; }; prototype.layerStackedDataMax = function (layer, dataset, aes) { // Find the max value for the stacked data on this level. // Highest value for stacked data is sum of values in group, // not the highest value across the whole value column var tmpStat, xAes = layer.aesmappings().findByAes("x"), fillAes = layer.aesmappings().findByAes("fill"), valueAes = layer.aesmappings().findByAes(aes); if (valueAes == null) { throw "Need value aes map to find stacked value"; } if (xAes == null) { throw "Need x aes map to find stacked value"; } if (fillAes == null) { throw "Need fill aes map to find stacked value"; } if (aes === "y") { // ToDo: is the fill aes the only way to specify stacked figures? tmpStat = ggjs.dataHelper.maxStackValue(dataset.values(), xAes.field(), fillAes.field(), valueAes.field()); } else { throw "Don't know how to find stacked value for value aes " + aes; } return tmpStat; } prototype.allValuesForLayer = function (layer, aesmap) { // Gets all data values for an aes in a layer var plotDef = this.plotDef(), values = [], //tmpVals, i, field, datasetName, dataset; // Layer data datasetName = layer.data(); if (!datasetName) { datasetName = plotDef.defaultDatasetName(); } dataset = this.getDataset(datasetName); if (dataset == null) { throw "Unable to find dataset with name " + datasetName; } if (aesmap) { field = aesmap.field(); if (dataset.values().map) { values = dataset.values().map(function (d) { return d[field]; }); } else { // backup way to get values from data // ToDo: use array.map polyfill so this can be removed? var dsVals = dataset.values(), j; this.warning("Old browser - doesn't support array.map"); for (j = 0; j < dsVals.length; j++) { values.push(dsVals[j][field]); } } // values = d3.merge([ values, tmpVals ]); } return values; }; prototype.allValuesAcrossLayers = function (aes) { // Looks at the data across all layers for an // aesthetic and gets all it's values var plotDef = this.plotDef(), layers = plotDef.layers().asArray(), values = [], tmpVals, i, layer, aesmap, field, datasetName, dataset; for (i = 0; i < layers.length; i++) { layer = layers[i]; aesmap = layer.aesmappings().findByAes(aes); tmpVals = this.allValuesForLayer(layer, aesmap); values = d3.merge([ values, tmpVals ]); // // Layer data // datasetName = layer.data(); // if (!datasetName) { // datasetName = plotDef.defaultDatasetName(); // } // //dataset = plotDef.data().dataset(datasetName); // dataset = this.getDataset(datasetName); // if (dataset == null) { // throw "Unable to find dataset with name " + datasetName; // } // if (aesmap) { // field = aesmap.field(); // if (dataset.values().map) { // tmpVals = dataset.values().map(function (d) { return d[field]; }); // } else { // // backup way to get values from data // // ToDo: use array.map polyfill so this can be removed? // var tmpVals = [], // dsVals = dataset.values(), // j; // this.warning("Old browser - doesn't support array.map"); // for (j = 0; j < dsVals.length; j++) { // tmpVals.push(dsVals[j][field]); // } // } // values = d3.merge([ values, tmpVals ]); // } } return values; }; // ------- // Scales // ------- // Build the scales based on data prototype.buildScales = function () { var plotDef = this.plotDef(), plot = this.renderer.plot, layerDefs = plotDef.layers().asArray(), i, j, layerDef, // scaleNamesLookup = {}, // scaleNames = [], scaleNameToLayerInfos = {}, // scaleNameToLayer = {}, // scaleNameToAesMap = {}, scaleDef, layerInfo, layerInfos, layerDef, tmpScale, values, tmpVals, aesmappings, aesmapping, aes, scaleName, scale; // Find names of all the scales used for (i = 0; i < layerDefs.length; i++) { layerDef = layerDefs[i]; aesmappings = layerDef.aesmappings().asArray(); console.log("aesmappings", aesmappings) if (aesmappings) { for (j = 0; j < aesmappings.length; j++) { aesmapping = aesmappings[j]; console.log(aesmapping) aes = aesmapping.aes(); // Skip aesthetics which are already display as axis // if (aes === "x" || aes === "y") { // continue; // } scaleName = aesmapping.scaleName(); if (scaleName == null) { continue; } // Store the information about where scale is used layerInfo = { layerDef: layerDef, aesmapping: aesmapping }; if (typeof scaleNameToLayerInfos[scaleName] === 'undefined') { scaleNameToLayerInfos[scaleName] = [layerInfo]; } else { scaleNameToLayerInfos[scaleName].push(layerInfo); } // scaleNameToLayer[scaleName] = layer; // scaleNameToAesMap[scaleName] = aesmapping; // console.log("aesmapping", aes, scaleName); // if (scaleName != null && typeof scaleNamesLookup[scaleName] === 'undefined') { // scaleNames.push(scaleName); // scaleNamesLookup[scaleName] = true; // } } } } // Create a D3 scale for each scale console.log("Creating d3 scales") for (scaleName in scaleNameToLayerInfos) { scaleDef = plotDef.scales().scale(scaleName); scale = this.scale(scaleDef); if (scaleDef.hasDomain()) { scale.domain(scaleDef.domain()); } else { // If scale domain hasn't been set, use data to find it if (scaleDef.isQuantitative()) { max = this.statAcrossLayers(aes, "max"); if (!isNaN(max)) { scale.domain([0, max]).nice(); } } else if (scaleDef.isOrdinal()) { // Find values across all layers layerInfos = scaleNameToLayerInfos[scaleName]; values = []; console.log("scaleName", scaleName) for (i = 0; i < layerInfos.length; i++) { layerInfo = layerInfos[i]; layerDef = layerInfo.layerDef; aesmapping = layerInfo.aesmapping; // ToDo: cache values for layer/field combos console.log("layer info", scaleName, layerDef.data(), aesmapping.aes(), aesmapping.field()); tmpVals = this.allValuesForLayer(layerDef, aesmapping); values = d3.merge([ values, tmpVals ]); } scale.domain(values); } } this.renderer.scaleNameToD3Scale[scaleName] = scale; } }; prototype.setupAxisScale = function (aes, scale, scaleDef) { var min = 0, max, allValues = []; if (scaleDef.hasDomain()) { scale.domain(scaleDef.domain()); } else { // If scale domain hasn't been set, use data to find it if (scaleDef.isQuantitative()) { max = this.statAcrossLayers(aes, "max"); if (!isNaN(max)) { scale.domain([0, max]).nice(); } } else if (scaleDef.isOrdinal()) { allValues = this.allValuesAcrossLayers(aes); scale.domain(allValues); //scale.domain(data.map(function(d) { return d.letter; })); } } }; prototype.setupXAxis = function () { // Produces D3 x axis var plotDef = this.plotDef(), axis = d3.svg.axis() .orient("bottom"), axisDef = this.plotDef().axes().axis("x") || {}, scaleRef = axisDef.scaleName(), scaleDef = plotDef.scales().scale(scaleRef), scale = this.scale(scaleDef); // ToDo: determine if domain has been manually set on x axis // ToDo: account for facets //x.domain(d3.extent(data, function(d) { return d.sepalWidth; })).nice(); // Set scale range // ToDo: account for facets switch (plotDef.coord()) { case "cartesian": // X scale range is always width of plot area scale.range([0, plotDef.plotAreaWidth()]); if (scaleDef.isOrdinal()) { scale.rangeRoundBands([0, plotDef.plotAreaWidth()], .1); } break; case "polar": scale.range([0, 2 * Math.PI]); if (scaleDef.isOrdinal()) { scale.rangeBands([0, 2 * Math.PI], 0); } break; } this.setupAxisScale("x", scale, scaleDef); axis.scale(scale); axis.ticks(5); this.xAxisScaleDef(scaleDef); this.xAxis(axis); }; prototype.setupYAxis = function () { // Produces D3 y axis var plotDef = this.plotDef(), axis = d3.svg.axis() .orient("left"), axisDef = this.plotDef().axes().axis("y") || {}, scaleRef = axisDef.scaleName(), scaleDef = plotDef.scales().scale(scaleRef), scale = this.scale(scaleDef); // ToDo: determine if domain has been manually set on y axis // ToDo: account for facets //y.domain(d3.extent(data, function(d) { return d.sepalLength; })).nice(); // ToDo: account for facets switch (plotDef.coord()) { case "cartesian": // Y scale range is height of plot area scale.range([plotDef.plotAreaHeight(), 0]); break; case "polar": // Y scale range is half height of plot area scale.range([Math.floor(plotDef.plotAreaHeight() / 2), 0]); break; } this.setupAxisScale("y", scale, scaleDef); axis.scale(scale); axis.ticks(5); this.yAxisScaleDef(scaleDef); this.yAxis(axis); }; prototype.scaleDef = function (scaleName) { return this.plotDef().scales().scale(scaleName); }; prototype.scale = function (scaleDef) { // Produces D3 scale from ggjs scale definition var scale = null; scaleDef = scaleDef || ggjs.scale({}); switch (scaleDef.type()) { case "linear": scale = d3.scale.linear(); break; case "ordinal": scale = d3.scale.ordinal(); break; case "pow": scale = d3.scale.pow(); break; case "time": scale = d3.time.scale(); break; case "category10": scale = d3.scale.category10(); break; default: throw "Unknow D3 scale type " + scaleDef.type(); } if (scale == null) { scale = d3.scale.linear(); } return scale; }; // Legends function scaleLegend () { // Legend attributes // Scale var _scale = null, _itemOffsetY = 5; // The gap between items // Legend function. function legend (selection) { selection.each(function (data) { var legendContainer = d3.select(this); legendContainer.selectAll(".ggjs-legend-marker") .data(data) .enter().append("circle") .attr("class", "ggjs-legend-marker") .attr("r", 5) // .attr("cx", 5) // .attr("cy", 5); .attr("cx", 5) .attr("cy", function (d, i) { return +i * _itemOffsetY; }) .style("fill", function (d) { return _scale(d); }); legendContainer.selectAll(".ggjs-legend-marker-label") .data(data) .enter().append("text") .attr("class", "ggjs-legend-marker-label") .attr("x", 15) .attr("y", function (d, i) { return +i * _itemOffsetY; }) .text(function (d) { return d; }); // Add the label 'Legend' on enter // containerDiv.selectAll('b') // .data([data]) // .enter().append('b') // .text('Legend'); }); } // Accessor methods // Scale accessor legend.scale = function (value) { if (!arguments.length) { return _scale; } _scale = value; return legend; }; // Y offset accessor legend.itemOffsetY = function (value) { if (!arguments.length) { return _itemOffsetY; } _itemOffsetY = value; return legend; }; return legend; } prototype.drawLegends = function () { // ToDo: find the legends for all aes across all layers // ToDo: combine aes if possible, like fill and shape // Find rules to combine legends - e.g. if same fields // are used for different aes, then legends can be combined. // E.g. if 'country' field is used for aes 'shape' and 'fill' // then draw a single legend for 'country' values adapting // the fill and shape of the markers var plotDef = this.plotDef(), plot = this.renderer.plot, layerDefs = plotDef.layers().asArray(), legendX = 0, // Cummalative legend offset legendY = 0, // Cummalative legend offset itemOffsetY = 12, // gap between legend items titleHeight = 12, // Height of legend title i, j, layerDef, legendArea, legendBaseX, legendBaseY, scaleNamesLookup = {}, scaleNamesToDisplay = [], legendX, legendY, legendData, aesmappings, aesmapping, aes, scaleName, scale; // ToDo: legend position switch ("ToDo: legend position") { // case "top": // case "bottom": // case "left": // case "right": default: legendBaseX = plotDef.plotAreaX() + (0.7 * plotDef.plotAreaWidth()) legendArea = plot.append("g") .attr("transform", "translate(" + legendBaseX + "," + plotDef.plotAreaY() + ")"); break; } // Look for scales to turn into legends for (i = 0; i < layerDefs.length; i++) { layerDef = layerDefs[i]; aesmappings = layerDef.aesmappings().asArray(); console.log("aesmappings", aesmappings) if (aesmappings) { for (j = 0; j < aesmappings.length; j++) { aesmapping = aesmappings[j]; console.log(aesmapping) aes = aesmapping.aes(); // Skip aesthetics which are already display as axis if (aes === "x" || aes === "y") { continue; } scaleName = aesmapping.scaleName(); console.log("aesmapping", aes, scaleName); if (scaleName != null && typeof scaleNamesLookup[scaleName] === 'undefined') { scaleNamesToDisplay.push(scaleName); scaleNamesLookup[scaleName] = true; } } } // Demo data: legendData = ["a", "b", "c"]; scale = d3.scale.category20(); scale.domain(legendData); var lgnd = scaleLegend() .itemOffsetY(itemOffsetY) .scale(scale); legend = legendArea.append("g") .attr("transform", "translate(0," + legendY + ")") .attr("class", "legend") .data([legendData]) // .attr("transform","translate(50,30)") .style("font-size","12px") .call(lgnd); // Set up offsets for next legend collection legendY += titleHeight + legendData.length * itemOffsetY; } for (i = 0; i < scaleNamesToDisplay.length; i++) { // ToDo: check type of scale // if ordinal: when setting up plot find the domain values // then look them up here // if quan: display box with range of values (gradient?) legendData = ["a", "b", "c"]; console.log("scale: ", scaleNamesToDisplay[i]); // find the scale scale = d3.scale.category20(); scale.domain(legendData); var lgnd = scaleLegend() .itemOffsetY(itemOffsetY) .scale(scale); legend = legendArea.append("g") .attr("transform", "translate(0," + legendY + ")") .attr("class", "legend") .data([legendData]) // .attr("transform","translate(50,30)") .style("font-size","12px") .call(lgnd); // Set up offsets for next legend collection legendY += titleHeight + legendData.length * itemOffsetY; } }; return renderer; })(d3); ggjs.renderer = function(s) { return new ggjs.Renderer(s); }; // ------------------ // Data Helper // ------------------ ggjs.dataHelper = (function (d3) { var datatableMin = function (datatable, field) { // Finds the min value of the field in the datatable return d3.min(datatable, function (d) { return d[field]; }); }, datatableMax = function (datatable, field) { // Finds the max value of the field in the datatable return d3.max(datatable, function (d) { return d[field]; }); }, datatableSum = function (datatable, field) { // Finds the sum of values for the field in the datatable return d3.sum(datatable, function (d) { return d[field]; }); }, datatableStat = function (datatable, field, stat) { // Finds the value of the stat (e.g. max) for the field in the datatable var statVal = null; switch (stat) { case "min": case "max": statVal = stat === "min" ? datatableMin(datatable, field) : datatableMax(datatable, field); break; case "sum": statVal = datatableSum(datatable, field); break; default: throw "Can't get datatables stat, unknown stat " + stat; } return statVal; }, datatablesStat = function (datatables, field, stat) { var statVal = null, i, tmpStat; switch (stat) { case "min": case "max": for (i = 0; i < datatables.length; i++) { tmpStat = stat === "min" ? datatableMin(datatables[i], field) : datatableMax(datatables[i], field); if (!isNaN(tmpStat)) { if (statVal == null) statVal = tmpStat; statVal = stat === "min" ? Math.min(statVal, tmpStat) : Math.max(statVal, tmpStat); } } break; default: throw "Can't get datatables stat, unknown stat " + stat; } return statVal; }, generateStackYValues = function (data, groupField, stackField, valueField) { // Adds an extra y value called __y0__ to the data // which gives the y value of the previous record within // the stacked items of the group. // Useful for stacked bar charts where an extra y value is // needed to know where the last bar in the group was placed. var dataCopy = ggjs.util.deepCopy(data), nested = d3.nest() .key(function (d) { return d[groupField]; }) .key(function (d) { return d[stackField]; }) .entries(dataCopy), groupKeys, stackKeys, values, i, j, k, prevValue; for (i = 0; i < nested.length; i++) { // Group 1 level prevValue = 0; groupKeys = nested[i]; for (j = 0; j < groupKeys.values.length; j++) { // Group 2 level stackKeys = groupKeys.values[j]; for (k = 0; k < stackKeys.values.length; k++) { // Values level values = stackKeys.values[k]; values["__y0__"] = prevValue; prevValue += values[valueField]; } } } return dataCopy; }, maxStackValue = function (data, groupField, stackField, valueField) { // Finds the max value by summing stacked items within a group, // then find the max across groups. // For example it finds the max height of all the layers bars in // a stacked bar chart. var nested_data, max; // Get sum of each stack grouping nested_data = d3.nest() .key(function(d) { return d[groupField]; }) //.key(function(d) { return d[stackField]; }) .rollup(function(leaves) { return {"stack_sum": d3.sum(leaves, function(d) {return d[valueField];})} }) .entries(data); // Find max value across stack groupings max = d3.max(nested_data, function (d) { return d.values.stack_sum; }) return max; };; return { datatableMin: datatableMin, datatableMax: datatableMax, datatableSum: datatableSum, datatableStat: datatableStat, datatablesStat: datatablesStat, generateStackYValues: generateStackYValues, maxStackValue: maxStackValue } })(d3); ggjs.ggjs = (function () { // Init var render = function (spec) { // Load spec var plotDef = ggjs.plot(spec); // Render chart ggjs.renderer(plotDef).render(); }; return { render: render } })();
Add legends.
ggjs-0.0.1.js
Add legends.
<ide><path>gjs-0.0.1.js <ide> <ide> var prototype = renderer.prototype; <ide> <add> // ---------- <add> // Accessors <add> // ---------- <add> <ide> prototype.plotDef = function (val) { <ide> if (!arguments.length) return this.renderer.plotDef; <ide> this.renderer.plotDef = val; <ide> return this; <ide> }; <add> <add> prototype.d3Scale = function (scaleName, val) { <add> if (!arguments.length) { <add> throw "Must supply args when getting/setting d3 scale" <add> } <add> else if (arguments.length === 1) { <add> return this.renderer.scaleNameToD3Scale[scaleName]; <add> } else { <add> this.renderer.scaleNameToD3Scale[scaleName] = val; <add> } <add> <add> return this; <add> }; <add> <add> prototype.warnings = function (val) { <add> if (!arguments.length) return this.renderer.warnings; <add> this.renderer.warnings = val; <add> return this; <add> }; <add> <add> // End Accessors <ide> <ide> prototype.warning = function (warning) { <ide> // Adds a warning to the log <ide> this.renderer.warnings.push(warning); <ide> } <del> <del> prototype.warnings = function (val) { <del> if (!arguments.length) return this.renderer.warnings; <del> this.renderer.warnings = val; <del> return this; <del> }; <ide> <ide> prototype.render = function () { <ide> var this_ = this; <ide> if (fillAesMap != null) { <ide> var colorField = fillAesMap.field(), <ide> colorScaleDef = this.scaleDef(fillAesMap.scaleName()), <add> scaleName = fillAesMap.scaleName(), <ide> colorScale; <del> if (colorScaleDef == null) { <add> // if (colorScaleDef == null) { <add> // this.warning("Couldn't set colour on layer - fill colour scale missing.") <add> // svgItems.style("fill", function(d) { return defaultFillColor; }); <add> // } else { <add> // colorScale = this.scale(colorScaleDef); <add> // svgItems.style("fill", function(d) { return colorScale(d[colorField]); }); <add> // } <add> <add> if (scaleName == null) { <ide> this.warning("Couldn't set colour on layer - fill colour scale missing.") <ide> svgItems.style("fill", function(d) { return defaultFillColor; }); <ide> } else { <del> colorScale = this.scale(colorScaleDef); <add> colorScale = this.d3Scale(scaleName); <add> console.log("Using d3 scale", scaleName, colorScale.domain()) <ide> svgItems.style("fill", function(d) { return colorScale(d[colorField]); }); <del> } <add> } <ide> } else { <ide> svgItems.style("fill", function(d) { return defaultFillColor; }); <ide> } <ide> layerDef = layerDefs[i]; <ide> aesmappings = layerDef.aesmappings().asArray(); <ide> <del> console.log("aesmappings", aesmappings) <add> // console.log("aesmappings", aesmappings) <ide> if (aesmappings) { <ide> for (j = 0; j < aesmappings.length; j++) { <ide> aesmapping = aesmappings[j]; <del> console.log(aesmapping) <add> // console.log(aesmapping) <ide> aes = aesmapping.aes(); <ide> // Skip aesthetics which are already display as axis <ide> // if (aes === "x" || aes === "y") { <ide> } <ide> <ide> // Create a D3 scale for each scale <del> console.log("Creating d3 scales") <add> // console.log("Creating d3 scales") <ide> for (scaleName in scaleNameToLayerInfos) { <ide> scaleDef = plotDef.scales().scale(scaleName); <ide> scale = this.scale(scaleDef); <ide> // Find values across all layers <ide> layerInfos = scaleNameToLayerInfos[scaleName]; <ide> values = []; <del> console.log("scaleName", scaleName) <add> // console.log("scaleName", scaleName) <ide> for (i = 0; i < layerInfos.length; i++) { <ide> layerInfo = layerInfos[i]; <ide> layerDef = layerInfo.layerDef; <ide> aesmapping = layerInfo.aesmapping; <ide> // ToDo: cache values for layer/field combos <del> console.log("layer info", scaleName, layerDef.data(), aesmapping.aes(), aesmapping.field()); <add> // console.log("layer info", scaleName, layerDef.data(), aesmapping.aes(), aesmapping.field()); <ide> tmpVals = this.allValuesForLayer(layerDef, aesmapping); <ide> values = d3.merge([ values, tmpVals ]); <ide> } <ide> } <ide> } <ide> <del> this.renderer.scaleNameToD3Scale[scaleName] = scale; <add> this.d3Scale(scaleName, scale); <ide> } <ide> }; <ide> <ide> return scale; <ide> }; <ide> <add> <add> // -------- <ide> // Legends <add> // -------- <add> <ide> function scaleLegend () { <ide> // Legend attributes <ide> <ide> // Scale <ide> var _scale = null, <del> _itemOffsetY = 5; // The gap between items <add> _layout = "horizontal", <add> _itemOffsetX = 0, // Horizontal gap between items <add> _itemOffsetY = 10, // Vertical gap between items <add> _itemRadius = Math.floor(_itemOffsetY / 2) <add> _itemMarkerLabelGap = 10; <ide> <ide> // Legend function. <ide> function legend (selection) { <ide> selection.each(function (data) { <ide> var legendContainer = d3.select(this); <ide> <del> legendContainer.selectAll(".ggjs-legend-marker") <add> legendContainer.selectAll(".ggjs-legend-item-marker") <ide> .data(data) <ide> .enter().append("circle") <del> .attr("class", "ggjs-legend-marker") <del> .attr("r", 5) <del> // .attr("cx", 5) <del> // .attr("cy", 5); <del> .attr("cx", 5) <del> .attr("cy", function (d, i) { return +i * _itemOffsetY; }) <del> .style("fill", function (d) { return _scale(d); }); <del> <del> legendContainer.selectAll(".ggjs-legend-marker-label") <add> .attr("class", "ggjs-legend-item-marker") <add> .attr("r", _itemRadius) <add> // .attr("cx", 0) <add> // .attr("cy", 0) <add> .attr("cx", function (d, i) { return (i * _itemOffsetX) - _itemRadius; }) <add> .attr("cy", function (d, i) { return (i * _itemOffsetY) - _itemRadius; }) <add> .style("fill", function (d) { return _scale(d); }) <add> .style("stroke", "black"); <add> <add> legendContainer.selectAll(".ggjs-legend-item-label") <ide> .data(data) <ide> .enter().append("text") <del> .attr("class", "ggjs-legend-marker-label") <del> .attr("x", 15) <del> .attr("y", function (d, i) { return +i * _itemOffsetY; }) <add> .attr("class", "ggjs-legend-item-label") <add> .attr("x", function (d, i) { return (i * _itemOffsetX) + _itemMarkerLabelGap; }) <add> .attr("y", function (d, i) { return i * _itemOffsetY; }) <ide> .text(function (d) { return d; }); <ide> <ide> // Add the label 'Legend' on enter <ide> }; <ide> <ide> // Y offset accessor <add> legend.itemOffsetX = function (value) { <add> if (!arguments.length) { return _itemOffsetX; } <add> _itemOffsetX = value; <add> return legend; <add> }; <add> <add> // Y offset accessor <ide> legend.itemOffsetY = function (value) { <ide> if (!arguments.length) { return _itemOffsetY; } <ide> _itemOffsetY = value; <add> return legend; <add> }; <add> <add> // Radius accessor <add> legend.itemRadius = function (value) { <add> if (!arguments.length) { return _itemRadius; } <add> _itemRadius = value; <ide> return legend; <ide> }; <ide> <ide> layerDefs = plotDef.layers().asArray(), <ide> legendX = 0, // Cummalative legend offset <ide> legendY = 0, // Cummalative legend offset <del> itemOffsetY = 12, // gap between legend items <add> itemOffsetX = 0, // Horizontal gap between legend items <add> itemOffsetY = 18, // Vertical gap between legend items <add> itemRadius = 5, // Radius of circle markers <ide> titleHeight = 12, // Height of legend title <ide> i, j, layerDef, legendArea, legendBaseX, legendBaseY, <ide> scaleNamesLookup = {}, <ide> legendX, legendY, legendData, aesmappings, aesmapping, aes, scaleName, scale; <ide> <ide> // ToDo: legend position <del> switch ("ToDo: legend position") { <del> // case "top": <add> switch ("top") { <add> case "top": <add> itemOffsetX = 100, <add> itemOffsetY = 0, <add> legendBaseX = Math.max(0, plotDef.plotAreaX() - itemOffsetY); <add> legendArea = plot.append("g") <add> .attr("transform", "translate(" + legendBaseX + "," + plotDef.plotAreaY() + ")"); <add> break; <ide> // case "bottom": <ide> // case "left": <del> // case "right": <add> case "right": <ide> default: <add> itemOffsetX = 0, <add> itemOffsetY = 18, <ide> legendBaseX = plotDef.plotAreaX() + (0.7 * plotDef.plotAreaWidth()) <ide> legendArea = plot.append("g") <ide> .attr("transform", "translate(" + legendBaseX + "," + plotDef.plotAreaY() + ")"); <ide> layerDef = layerDefs[i]; <ide> aesmappings = layerDef.aesmappings().asArray(); <ide> <del> console.log("aesmappings", aesmappings) <add> // console.log("aesmappings", aesmappings) <ide> if (aesmappings) { <ide> for (j = 0; j < aesmappings.length; j++) { <ide> aesmapping = aesmappings[j]; <del> console.log(aesmapping) <add> // console.log(aesmapping) <ide> aes = aesmapping.aes(); <ide> // Skip aesthetics which are already display as axis <ide> if (aes === "x" || aes === "y") { <ide> continue; <ide> } <ide> scaleName = aesmapping.scaleName(); <del> console.log("aesmapping", aes, scaleName); <add> // console.log("aesmapping", aes, scaleName); <ide> if (scaleName != null && typeof scaleNamesLookup[scaleName] === 'undefined') { <ide> scaleNamesToDisplay.push(scaleName); <ide> scaleNamesLookup[scaleName] = true; <ide> } <ide> } <ide> } <del> <del> // Demo data: <del> legendData = ["a", "b", "c"]; <del> <del> scale = d3.scale.category20(); <del> scale.domain(legendData); <del> <del> var lgnd = scaleLegend() <del> .itemOffsetY(itemOffsetY) <del> .scale(scale); <del> <del> legend = legendArea.append("g") <del> .attr("transform", "translate(0," + legendY + ")") <del> .attr("class", "legend") <del> .data([legendData]) <del> // .attr("transform","translate(50,30)") <del> .style("font-size","12px") <del> .call(lgnd); <del> <del> // Set up offsets for next legend collection <del> legendY += titleHeight + legendData.length * itemOffsetY; <ide> } <ide> <ide> for (i = 0; i < scaleNamesToDisplay.length; i++) { <ide> // if ordinal: when setting up plot find the domain values <ide> // then look them up here <ide> // if quan: display box with range of values (gradient?) <del> legendData = ["a", "b", "c"]; <del> console.log("scale: ", scaleNamesToDisplay[i]); <add> scaleName = scaleNamesToDisplay[i]; <add> scale = this.d3Scale(scaleName); <add> legendData = scale.domain(); <add> // legendData = ["a", "b", "c"]; <add> // console.log("scale: ", scaleNamesToDisplay[i]); <ide> // find the scale <del> scale = d3.scale.category20(); <del> scale.domain(legendData); <add> // scale = d3.scale.category20(); <add> // scale.domain(legendData); <ide> <ide> var lgnd = scaleLegend() <add> .itemOffsetX(itemOffsetX) <ide> .itemOffsetY(itemOffsetY) <add> .itemRadius(itemRadius) <ide> .scale(scale); <ide> <ide> legend = legendArea.append("g")
JavaScript
mit
dab2f90bfc572132bd82bb74ca8ed6e770c2855d
0
davidkpiano/redux-simple-form,davidkpiano/react-redux-form
import get from '../utils/get'; import isPlainObject from '../utils/is-plain-object'; import pathStartsWith, { pathDifference } from '../utils/path-starts-with'; const defaultStrategy = { get, keys: (state) => Object.keys(state), isObject: (state) => isPlainObject(state), }; function joinPaths(...paths) { return paths.filter(path => !!path && path.length).join('.'); } export function getFormStateKey(state, model, s = defaultStrategy, currentPath = '') { const deepCandidateKeys = []; let result = null; s.keys(state).some((key) => { if (key === '') { console.warn('react-redux-form skipped over an empty property key: %s', currentPath); return false; } const subState = s.get(state, key); if (subState && s.get(subState, '$form')) { const subStateModel = s.get(subState, '$form.model'); if (pathStartsWith(model, subStateModel) || subStateModel === '') { const localPath = pathDifference(model, subStateModel); const resultPath = [currentPath, key]; let currentState = subState; localPath.every((segment) => { if (s.get(currentState, segment) && s.get(currentState, `${segment}.$form`)) { currentState = s.get(currentState, segment); resultPath.push(segment); return true; } return false; }); result = joinPaths(...resultPath); return true; } return false; } if (s.isObject(subState)) { deepCandidateKeys.push(key); } return false; }); if (result) return result; deepCandidateKeys.some((key) => { result = getFormStateKey(s.get(state, key), model, s, joinPaths(currentPath, key)); return !!result; }); if (result) return result; return null; } let formStateKeyCache = {}; export const clearGetFormCache = () => formStateKeyCache = {}; // eslint-disable-line no-return-assign const getFormStateKeyCached = (() => (state, modelString, s = defaultStrategy) => { if (formStateKeyCache[modelString]) return formStateKeyCache[modelString]; const result = getFormStateKey(state, modelString, s); formStateKeyCache[modelString] = result; // eslint-disable-line no-return-assign return result; })(); function getForm(state, modelString, s = defaultStrategy) { const formStateKey = getFormStateKeyCached(state, modelString, s); if (!formStateKey) { return null; } const form = s.get(state, formStateKey); return form; } export default getForm;
src/utils/get-form.js
import get from '../utils/get'; import isPlainObject from '../utils/is-plain-object'; import pathStartsWith, { pathDifference } from '../utils/path-starts-with'; const defaultStrategy = { get, keys: (state) => Object.keys(state), isObject: (state) => isPlainObject(state), }; function joinPaths(...paths) { return paths.filter(path => !!path && path.length).join('.'); } export function getFormStateKey(state, model, s = defaultStrategy, currentPath = '') { const deepCandidateKeys = []; let result = null; s.keys(state).some((key) => { if (key === '') { return false; } const subState = s.get(state, key); if (subState && s.get(subState, '$form')) { const subStateModel = s.get(subState, '$form.model'); if (pathStartsWith(model, subStateModel) || subStateModel === '') { const localPath = pathDifference(model, subStateModel); const resultPath = [currentPath, key]; let currentState = subState; localPath.every((segment) => { if (s.get(currentState, segment) && s.get(currentState, `${segment}.$form`)) { currentState = s.get(currentState, segment); resultPath.push(segment); return true; } return false; }); result = joinPaths(...resultPath); return true; } return false; } if (s.isObject(subState)) { deepCandidateKeys.push(key); } return false; }); if (result) return result; deepCandidateKeys.some((key) => { result = getFormStateKey(s.get(state, key), model, s, joinPaths(currentPath, key)); return !!result; }); if (result) return result; return null; } let formStateKeyCache = {}; export const clearGetFormCache = () => formStateKeyCache = {}; // eslint-disable-line no-return-assign const getFormStateKeyCached = (() => (state, modelString, s = defaultStrategy) => { if (formStateKeyCache[modelString]) return formStateKeyCache[modelString]; const result = getFormStateKey(state, modelString, s); formStateKeyCache[modelString] = result; // eslint-disable-line no-return-assign return result; })(); function getForm(state, modelString, s = defaultStrategy) { const formStateKey = getFormStateKeyCached(state, modelString, s); if (!formStateKey) { return null; } const form = s.get(state, formStateKey); return form; } export default getForm;
add console warn
src/utils/get-form.js
add console warn
<ide><path>rc/utils/get-form.js <ide> <ide> s.keys(state).some((key) => { <ide> if (key === '') { <add> console.warn('react-redux-form skipped over an empty property key: %s', currentPath); <ide> return false; <ide> } <ide> const subState = s.get(state, key);
Java
agpl-3.0
c851aefc8ecb13b3889d4e3c8f85f3a4faf779fd
0
Heiner1/AndroidAPS,PoweRGbg/AndroidAPS,jotomo/AndroidAPS,MilosKozak/AndroidAPS,MilosKozak/AndroidAPS,RoumenGeorgiev/AndroidAPS,AdrianLxM/AndroidAPS,RoumenGeorgiev/AndroidAPS,LadyViktoria/AndroidAPS,Heiner1/AndroidAPS,winni67/AndroidAPS,samihusseingit/AndroidAPS,MilosKozak/AndroidAPS,LadyViktoria/AndroidAPS,PoweRGbg/AndroidAPS,AdrianLxM/AndroidAPS,PoweRGbg/AndroidAPS,Heiner1/AndroidAPS,winni67/AndroidAPS,jotomo/AndroidAPS,jotomo/AndroidAPS,samihusseingit/AndroidAPS,Heiner1/AndroidAPS
package info.nightscout.androidaps; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.joanzapata.iconify.Iconify; import com.joanzapata.iconify.fonts.FontAwesomeModule; import com.squareup.otto.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.plugins.DanaR.Services.ExecutionService; import info.nightscout.androidaps.receivers.KeepAliveReceiver; import info.nightscout.androidaps.tabs.SlidingTabLayout; import info.nightscout.androidaps.tabs.TabPageAdapter; import info.nightscout.utils.ImportExportPrefs; import info.nightscout.utils.LocaleHelper; public class MainActivity extends AppCompatActivity { private static Logger log = LoggerFactory.getLogger(MainActivity.class); private static KeepAliveReceiver keepAliveReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Iconify.with(new FontAwesomeModule()); LocaleHelper.onCreate(this, "en"); setContentView(R.layout.activity_main); checkEula(); if (Config.logFunctionCalls) log.debug("onCreate"); // show version in toolbar try { setTitle(getString(R.string.app_name) + " " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); registerBus(); try { getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setIcon(R.mipmap.ic_launcher); } catch (NullPointerException e) { // no action } if (keepAliveReceiver == null) { keepAliveReceiver = new KeepAliveReceiver(); startService(new Intent(this, ExecutionService.class)); keepAliveReceiver.setAlarm(this); } setUpTabs(false); } @Subscribe public void onStatusEvent(final EventRefreshGui ev) { SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String lang = SP.getString("language", "en"); LocaleHelper.setLocale(getApplicationContext(), lang); recreate(); try { // activity may be destroyed setUpTabs(ev.isSwitchToLast()); } catch (IllegalStateException e) { e.printStackTrace(); } } private void setUpTabs(boolean switchToLast) { TabPageAdapter pageAdapter = new TabPageAdapter(getSupportFragmentManager(), this); for (PluginBase p : MainApp.getPluginsList()) { pageAdapter.registerNewFragment(p); } ViewPager mPager = (ViewPager) findViewById(R.id.pager); mPager.setAdapter(pageAdapter); SlidingTabLayout mTabs = (SlidingTabLayout) findViewById(R.id.tabs); mTabs.setViewPager(mPager); if (switchToLast) mPager.setCurrentItem(pageAdapter.getCount() - 1, false); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.nav_preferences: Intent i = new Intent(getApplicationContext(), PreferencesActivity.class); startActivity(i); break; case R.id.nav_resetdb: MainApp.getDbHelper().resetDatabases(); break; case R.id.nav_export: ImportExportPrefs.verifyStoragePermissions(this); ImportExportPrefs.exportSharedPreferences(this); break; case R.id.nav_import: ImportExportPrefs.verifyStoragePermissions(this); ImportExportPrefs.importSharedPreferences(this); break; // case R.id.nav_test_alarm: // final int REQUEST_CODE_ASK_PERMISSIONS = 2355; // int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.SYSTEM_ALERT_WINDOW); // if (permission != PackageManager.PERMISSION_GRANTED) { // // We don't have permission so prompt the user // // On Android 6 give permission for alarming in Settings -> Apps -> Draw over other apps // ActivityCompat.requestPermissions( // this, // new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW}, // REQUEST_CODE_ASK_PERMISSIONS // ); // } // Intent alertServiceIntent = new Intent(getApplicationContext(), AlertService.class); // alertServiceIntent.putExtra("alertText", getString(R.string.nav_test_alert)); // getApplicationContext().startService(alertServiceIntent); // break; case R.id.nav_exit: log.debug("Exiting"); keepAliveReceiver.cancelAlarm(this); MainApp.bus().post(new EventAppExit()); MainApp.closeDbHelper(); finish(); System.runFinalization(); System.exit(0); break; } return super.onOptionsItemSelected(item); } private void registerBus() { try { MainApp.bus().unregister(this); } catch (RuntimeException x) { // Ignore } MainApp.bus().register(this); } private void checkEula() { boolean IUnderstand = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("I_understand", false); if (!IUnderstand) { Intent intent = new Intent(getApplicationContext(), AgreementActivity.class); startActivity(intent); finish(); } } }
app/src/main/java/info/nightscout/androidaps/MainActivity.java
package info.nightscout.androidaps; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.joanzapata.iconify.Iconify; import com.joanzapata.iconify.fonts.FontAwesomeModule; import com.squareup.otto.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.plugins.DanaR.Services.ExecutionService; import info.nightscout.androidaps.receivers.KeepAliveReceiver; import info.nightscout.androidaps.tabs.SlidingTabLayout; import info.nightscout.androidaps.tabs.TabPageAdapter; import info.nightscout.utils.ImportExportPrefs; import info.nightscout.utils.LocaleHelper; public class MainActivity extends AppCompatActivity { private static Logger log = LoggerFactory.getLogger(MainActivity.class); private static KeepAliveReceiver keepAliveReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Iconify.with(new FontAwesomeModule()); LocaleHelper.onCreate(this, "en"); setContentView(R.layout.activity_main); checkEula(); if (Config.logFunctionCalls) log.debug("onCreate"); // show version in toolbar try { setTitle(getString(R.string.app_name) + " " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); registerBus(); try { getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setIcon(R.mipmap.ic_launcher); } catch (NullPointerException e) { // no action } if (keepAliveReceiver == null) { keepAliveReceiver = new KeepAliveReceiver(); startService(new Intent(this, ExecutionService.class)); keepAliveReceiver.setAlarm(this); } setUpTabs(false); } @Subscribe public void onStatusEvent(final EventRefreshGui ev) { SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String lang = SP.getString("language", "en"); LocaleHelper.setLocale(getApplicationContext(), lang); recreate(); try { // activity may be destroyed setUpTabs(true); } catch (IllegalStateException e) { e.printStackTrace(); } } private void setUpTabs(boolean switchToLast) { TabPageAdapter pageAdapter = new TabPageAdapter(getSupportFragmentManager(), this); for (PluginBase p : MainApp.getPluginsList()) { pageAdapter.registerNewFragment(p); } ViewPager mPager = (ViewPager) findViewById(R.id.pager); mPager.setAdapter(pageAdapter); SlidingTabLayout mTabs = (SlidingTabLayout) findViewById(R.id.tabs); mTabs.setViewPager(mPager); if (switchToLast) mPager.setCurrentItem(pageAdapter.getCount() - 1, false); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.nav_preferences: Intent i = new Intent(getApplicationContext(), PreferencesActivity.class); startActivity(i); break; case R.id.nav_resetdb: MainApp.getDbHelper().resetDatabases(); break; case R.id.nav_export: ImportExportPrefs.verifyStoragePermissions(this); ImportExportPrefs.exportSharedPreferences(this); break; case R.id.nav_import: ImportExportPrefs.verifyStoragePermissions(this); ImportExportPrefs.importSharedPreferences(this); break; // case R.id.nav_test_alarm: // final int REQUEST_CODE_ASK_PERMISSIONS = 2355; // int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.SYSTEM_ALERT_WINDOW); // if (permission != PackageManager.PERMISSION_GRANTED) { // // We don't have permission so prompt the user // // On Android 6 give permission for alarming in Settings -> Apps -> Draw over other apps // ActivityCompat.requestPermissions( // this, // new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW}, // REQUEST_CODE_ASK_PERMISSIONS // ); // } // Intent alertServiceIntent = new Intent(getApplicationContext(), AlertService.class); // alertServiceIntent.putExtra("alertText", getString(R.string.nav_test_alert)); // getApplicationContext().startService(alertServiceIntent); // break; case R.id.nav_exit: log.debug("Exiting"); keepAliveReceiver.cancelAlarm(this); MainApp.bus().post(new EventAppExit()); MainApp.closeDbHelper(); finish(); System.runFinalization(); System.exit(0); break; } return super.onOptionsItemSelected(item); } private void registerBus() { try { MainApp.bus().unregister(this); } catch (RuntimeException x) { // Ignore } MainApp.bus().register(this); } private void checkEula() { boolean IUnderstand = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("I_understand", false); if (!IUnderstand) { Intent intent = new Intent(getApplicationContext(), AgreementActivity.class); startActivity(intent); finish(); } } }
Update MainActivity.java
app/src/main/java/info/nightscout/androidaps/MainActivity.java
Update MainActivity.java
<ide><path>pp/src/main/java/info/nightscout/androidaps/MainActivity.java <ide> LocaleHelper.setLocale(getApplicationContext(), lang); <ide> recreate(); <ide> try { // activity may be destroyed <del> setUpTabs(true); <add> setUpTabs(ev.isSwitchToLast()); <ide> } catch (IllegalStateException e) { <ide> e.printStackTrace(); <ide> }
Java
mpl-2.0
44f5df3856bbb4ec0667a88d3e7c07a49c953adf
0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PropertyHandlerImpl.java,v $ * * $Revision: 1.3 $ * * last change: $Author: sg $ $Date: 2006-07-28 09:03:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ package helper; import com.sun.star.inspection.XPropertyHandler; import com.sun.star.inspection.LineDescriptor; /** * This implementation of <CODE>PropertyHandler</CODE> do currently nothig. * All methods are implemented, but not filled with content. * @see com.sun.star.inspection.XPropertyHandler */ public class PropertyHandlerImpl implements XPropertyHandler{ /** Creates a new instance of PropertyHandlerImpl */ public PropertyHandlerImpl() { } /** * This method currently do nothig * @param ActuatingPropertyName the id of the actuating property. * @param NewValue the new value of the property * @param OldValue the old value of the property * @param InspectorUI a callback for updating the object inspector UI * @param FirstTimeInit If true , the method is called for the first-time update of the respective property, that is, when the property browser is just initializing with the properties of the introspected object. * If false , there was a real ::com::sun::star::beans::XPropertyChangeListener::propertyChange event which triggered the call. * * In some cases it may be necessary to differentiate between both situations. For instance, if you want to set the value of another property when an actuating property's value changed, you should definately not do this when FirstTimeInit is true . * @throws com.sun.star.lang.NullPointerException ::com::sun::star::lang::NullPointerException if InspectorUI is NULL */ public void actuatingPropertyChanged( String ActuatingPropertyName, Object NewValue, Object OldValue, com.sun.star.inspection.XObjectInspectorUI InspectorUI, boolean FirstTimeInit) throws com.sun.star.lang.NullPointerException { } /** * This method currently do nothig * @param xEventListener the listener to notify about changes */ public void addEventListener(com.sun.star.lang.XEventListener xEventListener) { } /** * This method currently do nothig * @param xPropertyChangeListener the listener to notify about property changes * @throws com.sun.star.lang.NullPointerException com::sun::star::lang::NullPointerException if the listener is NULL */ public void addPropertyChangeListener(com.sun.star.beans.XPropertyChangeListener xPropertyChangeListener) throws com.sun.star.lang.NullPointerException { } /** * This method currently do nothig * @param PropertyName The name of the property whose value is to be converted. * @param PropertyValue The to-be-converted property value. * @param ControlValueType The target type of the conversion. This type is determined by the control which is used to display the property, which in turn is determined by the handler itself in describePropertyLine . * Speaking strictly, this is passed for convenience only, since every XPropertyHandler implementation should know exactly which type to expect, since it implicitly determined this type in describePropertyLine by creating an appropriate XPropertyControl . * * @throws com.sun.star.beans.UnknownPropertyException ::com::sun::star::beans::UnknownPropertyException if the given property is not supported by the property handler * @return null */ public Object convertToControlValue( String PropertyName, Object PropertyValue, com.sun.star.uno.Type ControlValueType) throws com.sun.star.beans.UnknownPropertyException { return null; } /** * This method currently do nothig * @param PropertyName The name of the conversion's target property. * @param ControlValue The to-be-converted control value. This value has been obtained from an XPropertyControl , using its Value attribute. * @throws com.sun.star.beans.UnknownPropertyException ::com::sun::star::beans::UnknownPropertyException if the given property is not supported by the property handler * @return null */ public Object convertToPropertyValue(String PropertyName, Object ControlValue) throws com.sun.star.beans.UnknownPropertyException { return null; } /** * This method currently do nothig * @param PropertyName the name of the property whose user interface is to be described * @param out_Descriptor the descriptor of the property line, to be filled by the XPropertyHandler implementation * @param ControlFactory a factory for creating XPropertyControl instances. Must not be NULL . * @throws com.sun.star.beans.UnknownPropertyException ::com::sun::star::beans::UnknownPropertyException if the given property is not supported by this handler * * @throws com.sun.star.lang.NullPointerException ::com::sun::star::lang::NullPointerException if ControlFactory is NULL . */ public LineDescriptor describePropertyLine( String PropertyName, com.sun.star.inspection.XPropertyControlFactory ControlFactory) throws com.sun.star.beans.UnknownPropertyException, com.sun.star.lang.NullPointerException { return null; } /** * This method currently do nothig */ public void dispose() { } /** * This method currently do nothig * @return null */ public String[] getActuatingProperties() { return null; } /** * This method currently do nothig * @param PropertyName the name of the property whose state is to be retrieved * @throws com.sun.star.beans.UnknownPropertyException ::com::sun::star::beans::UnknownPropertyException if the given property is not supported by the property handler * @return null */ public com.sun.star.beans.PropertyState getPropertyState(String PropertyName) throws com.sun.star.beans.UnknownPropertyException { return null; } /** * This method currently do nothig * @param PropertyName the name of the property whose value is to be retrieved * @throws com.sun.star.beans.UnknownPropertyException ::com::sun::star::beans::UnknownPropertyException if the given property is not supported by the property handler * @return null */ public Object getPropertyValue(String PropertyName) throws com.sun.star.beans.UnknownPropertyException { return null; } /** * This method currently do nothig * @return null */ public String[] getSupersededProperties() { return null; } /** * This method currently do nothig * @return null */ public com.sun.star.beans.Property[] getSupportedProperties() { return null; } /** * This method currently do nothig * @param Component the component to inspect. Must not be NULL * @throws com.sun.star.lang.NullPointerException com::sun::star::lang::NullPointerException if the component is NULL */ public void inspect(Object Component) throws com.sun.star.lang.NullPointerException { } /** * This method currently do nothig * @param PropertyName the name of the property whose composability is to be determined * @throws com.sun.star.beans.UnknownPropertyException ::com::sun::star::beans::UnknownPropertyException if the given property is not supported by the property handler * * * @return null */ public boolean isComposable(String PropertyName) throws com.sun.star.beans.UnknownPropertyException { return false; } /** * This method currently do nothig * @param PropertyName The name of the property whose browse button has been clicked * @param Primary true if and only if the primary button has been clicked, false otherwise * @param out_Data If the method returns InteractiveSelectionResult::ObtainedValue , then _rData contains the value which has been interactively obtained from the user, and which still needs to be set at the inspected component. * @param InspectorUI provides access to the object inspector UI. Implementations should use this if the property selection requires non-modal user input. In those cases, onInteractivePropertySelection should return InteractiveSelectionResult::Pending , and the UI for (at least) the property whose input is still pending should be disabled. * * @throws com.sun.star.beans.UnknownPropertyException ::com::sun::star::beans::UnknownPropertyException if the given property is not supported by the property handler * @throws com.sun.star.lang.NullPointerException ::com::sun::star::lang::NullPointerException if InspectorUI is NULL * @return null */ public com.sun.star.inspection.InteractiveSelectionResult onInteractivePropertySelection( String PropertyName, boolean Primary, Object[] out_Data, com.sun.star.inspection.XObjectInspectorUI InspectorUI) throws com.sun.star.beans.UnknownPropertyException, com.sun.star.lang.NullPointerException { return null; } /** * This method currently do nothig * @param xEventListener the listener to be revoked */ public void removeEventListener(com.sun.star.lang.XEventListener xEventListener) { } /** * This method currently do nothig * @param xPropertyChangeListener the listener to be revoke */ public void removePropertyChangeListener(com.sun.star.beans.XPropertyChangeListener xPropertyChangeListener) { } /** * This method currently do nothig * @param PropertyName the name of the property whose value is to be set * @param Value the property value to set * @throws com.sun.star.beans.UnknownPropertyException ::com::sun::star::beans::UnknownPropertyException if the given property is not supported by the property handler */ public void setPropertyValue(String PropertyName, Object Value) throws com.sun.star.beans.UnknownPropertyException { } /** * This method currently do nothig * @param Suspend Whether the handler is to be suspended true or reactivated ( false ). The latter happens if a handler was successfully suspended, but an external instance vetoed the whole suspension process. * @return false */ public boolean suspend(boolean Suspend) { return false; } }
qadevOOo/runner/helper/PropertyHandlerImpl.java
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PropertyHandlerImpl.java,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2006-03-14 11:49:09 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ package helper; import com.sun.star.inspection.XPropertyHandler; /** * This implementation of <CODE>PropertyHandler</CODE> do currently nothig. * All methods are implemented, but not filled with content. * @see com.sun.star.inspection.XPropertyHandler */ public class PropertyHandlerImpl implements XPropertyHandler{ /** Creates a new instance of PropertyHandlerImpl */ public PropertyHandlerImpl() { } /** * This method currently do nothig * @param ActuatingPropertyName the id of the actuating property. * @param NewValue the new value of the property * @param OldValue the old value of the property * @param InspectorUI a callback for updating the object inspector UI * @param FirstTimeInit If true , the method is called for the first-time update of the respective property, that is, when the property browser is just initializing with the properties of the introspected object. * If false , there was a real ::com::sun::star::beans::XPropertyChangeListener::propertyChange event which triggered the call. * * In some cases it may be necessary to differentiate between both situations. For instance, if you want to set the value of another property when an actuating property's value changed, you should definately not do this when FirstTimeInit is true . * @throws com.sun.star.lang.NullPointerException ::com::sun::star::lang::NullPointerException if InspectorUI is NULL */ public void actuatingPropertyChanged( String ActuatingPropertyName, Object NewValue, Object OldValue, com.sun.star.inspection.XObjectInspectorUI InspectorUI, boolean FirstTimeInit) throws com.sun.star.lang.NullPointerException { } /** * This method currently do nothig * @param xEventListener the listener to notify about changes */ public void addEventListener(com.sun.star.lang.XEventListener xEventListener) { } /** * This method currently do nothig * @param xPropertyChangeListener the listener to notify about property changes * @throws com.sun.star.lang.NullPointerException com::sun::star::lang::NullPointerException if the listener is NULL */ public void addPropertyChangeListener(com.sun.star.beans.XPropertyChangeListener xPropertyChangeListener) throws com.sun.star.lang.NullPointerException { } /** * This method currently do nothig * @param PropertyName The name of the property whose value is to be converted. * @param PropertyValue The to-be-converted property value. * @param ControlValueType The target type of the conversion. This type is determined by the control which is used to display the property, which in turn is determined by the handler itself in describePropertyLine . * Speaking strictly, this is passed for convenience only, since every XPropertyHandler implementation should know exactly which type to expect, since it implicitly determined this type in describePropertyLine by creating an appropriate XPropertyControl . * * @throws com.sun.star.beans.UnknownPropertyException ::com::sun::star::beans::UnknownPropertyException if the given property is not supported by the property handler * @return null */ public Object convertToControlValue( String PropertyName, Object PropertyValue, com.sun.star.uno.Type ControlValueType) throws com.sun.star.beans.UnknownPropertyException { return null; } /** * This method currently do nothig * @param PropertyName The name of the conversion's target property. * @param ControlValue The to-be-converted control value. This value has been obtained from an XPropertyControl , using its Value attribute. * @throws com.sun.star.beans.UnknownPropertyException ::com::sun::star::beans::UnknownPropertyException if the given property is not supported by the property handler * @return null */ public Object convertToPropertyValue(String PropertyName, Object ControlValue) throws com.sun.star.beans.UnknownPropertyException { return null; } /** * This method currently do nothig * @param PropertyName the name of the property whose user interface is to be described * @param out_Descriptor the descriptor of the property line, to be filled by the XPropertyHandler implementation * @param ControlFactory a factory for creating XPropertyControl instances. Must not be NULL . * @throws com.sun.star.beans.UnknownPropertyException ::com::sun::star::beans::UnknownPropertyException if the given property is not supported by this handler * * @throws com.sun.star.lang.NullPointerException ::com::sun::star::lang::NullPointerException if ControlFactory is NULL . */ public void describePropertyLine( String PropertyName, com.sun.star.inspection.LineDescriptor[] out_Descriptor, com.sun.star.inspection.XPropertyControlFactory ControlFactory) throws com.sun.star.beans.UnknownPropertyException, com.sun.star.lang.NullPointerException { } /** * This method currently do nothig */ public void dispose() { } /** * This method currently do nothig * @return null */ public String[] getActuatingProperties() { return null; } /** * This method currently do nothig * @param PropertyName the name of the property whose state is to be retrieved * @throws com.sun.star.beans.UnknownPropertyException ::com::sun::star::beans::UnknownPropertyException if the given property is not supported by the property handler * @return null */ public com.sun.star.beans.PropertyState getPropertyState(String PropertyName) throws com.sun.star.beans.UnknownPropertyException { return null; } /** * This method currently do nothig * @param PropertyName the name of the property whose value is to be retrieved * @throws com.sun.star.beans.UnknownPropertyException ::com::sun::star::beans::UnknownPropertyException if the given property is not supported by the property handler * @return null */ public Object getPropertyValue(String PropertyName) throws com.sun.star.beans.UnknownPropertyException { return null; } /** * This method currently do nothig * @return null */ public String[] getSupersededProperties() { return null; } /** * This method currently do nothig * @return null */ public com.sun.star.beans.Property[] getSupportedProperties() { return null; } /** * This method currently do nothig * @param Component the component to inspect. Must not be NULL * @throws com.sun.star.lang.NullPointerException com::sun::star::lang::NullPointerException if the component is NULL */ public void inspect(Object Component) throws com.sun.star.lang.NullPointerException { } /** * This method currently do nothig * @param PropertyName the name of the property whose composability is to be determined * @throws com.sun.star.beans.UnknownPropertyException ::com::sun::star::beans::UnknownPropertyException if the given property is not supported by the property handler * * * @return null */ public boolean isComposable(String PropertyName) throws com.sun.star.beans.UnknownPropertyException { return false; } /** * This method currently do nothig * @param PropertyName The name of the property whose browse button has been clicked * @param Primary true if and only if the primary button has been clicked, false otherwise * @param out_Data If the method returns InteractiveSelectionResult::ObtainedValue , then _rData contains the value which has been interactively obtained from the user, and which still needs to be set at the inspected component. * @param InspectorUI provides access to the object inspector UI. Implementations should use this if the property selection requires non-modal user input. In those cases, onInteractivePropertySelection should return InteractiveSelectionResult::Pending , and the UI for (at least) the property whose input is still pending should be disabled. * * @throws com.sun.star.beans.UnknownPropertyException ::com::sun::star::beans::UnknownPropertyException if the given property is not supported by the property handler * @throws com.sun.star.lang.NullPointerException ::com::sun::star::lang::NullPointerException if InspectorUI is NULL * @return null */ public com.sun.star.inspection.InteractiveSelectionResult onInteractivePropertySelection( String PropertyName, boolean Primary, Object[] out_Data, com.sun.star.inspection.XObjectInspectorUI InspectorUI) throws com.sun.star.beans.UnknownPropertyException, com.sun.star.lang.NullPointerException { return null; } /** * This method currently do nothig * @param xEventListener the listener to be revoked */ public void removeEventListener(com.sun.star.lang.XEventListener xEventListener) { } /** * This method currently do nothig * @param xPropertyChangeListener the listener to be revoke */ public void removePropertyChangeListener(com.sun.star.beans.XPropertyChangeListener xPropertyChangeListener) { } /** * This method currently do nothig * @param PropertyName the name of the property whose value is to be set * @param Value the property value to set * @throws com.sun.star.beans.UnknownPropertyException ::com::sun::star::beans::UnknownPropertyException if the given property is not supported by the property handler */ public void setPropertyValue(String PropertyName, Object Value) throws com.sun.star.beans.UnknownPropertyException { } /** * This method currently do nothig * @param Suspend Whether the handler is to be suspended true or reactivated ( false ). The latter happens if a handler was successfully suspended, but an external instance vetoed the whole suspension process. * @return false */ public boolean suspend(boolean Suspend) { return false; } }
#i67853# adapt to changes in XPropertyHandler
qadevOOo/runner/helper/PropertyHandlerImpl.java
#i67853# adapt to changes in XPropertyHandler
<ide><path>adevOOo/runner/helper/PropertyHandlerImpl.java <ide> * <ide> * $RCSfile: PropertyHandlerImpl.java,v $ <ide> * <del> * $Revision: 1.2 $ <del> * <del> * last change: $Author: vg $ $Date: 2006-03-14 11:49:09 $ <add> * $Revision: 1.3 $ <add> * <add> * last change: $Author: sg $ $Date: 2006-07-28 09:03:24 $ <ide> * <ide> * The Contents of this file are made available subject to <ide> * the terms of GNU Lesser General Public License Version 2.1. <ide> package helper; <ide> <ide> import com.sun.star.inspection.XPropertyHandler; <del> <add>import com.sun.star.inspection.LineDescriptor; <ide> <ide> /** <ide> * This implementation of <CODE>PropertyHandler</CODE> do currently nothig. <ide> * <ide> * @throws com.sun.star.lang.NullPointerException ::com::sun::star::lang::NullPointerException if ControlFactory is NULL . <ide> */ <del> public void describePropertyLine( <add> public LineDescriptor describePropertyLine( <ide> String PropertyName, <del> com.sun.star.inspection.LineDescriptor[] out_Descriptor, <ide> com.sun.star.inspection.XPropertyControlFactory ControlFactory) <ide> throws com.sun.star.beans.UnknownPropertyException, <ide> com.sun.star.lang.NullPointerException { <add> return null; <ide> } <ide> <ide> /**
Java
apache-2.0
020ab729f63eec04bc54e9e70dca2f135c8d22c0
0
eandresblasco/phonegap-googlemaps-plugin,CPlus/phonegap-googlemaps-plugin,hitoci/phonegap-googlemaps-plugin,snoopconsulting/phonegap-googlemaps-plugin,hungdoan2/phonegap-googlemaps-plugin,wolf-s/phonegap-googlemaps-plugin,rynomster/cordova-plugin-googlemaps,matsprea/phonegap-googlemaps-plugin,elwahid/plugin.google.maps,CPlus/phonegap-googlemaps-plugin,hitoci/phonegap-googlemaps-plugin,wolf-s/phonegap-googlemaps-plugin,eandresblasco/phonegap-googlemaps-plugin,edivancamargo/phonegap-googlemaps-plugin,eandresblasco/phonegap-googlemaps-plugin,iDay/phonegap-googlemaps-plugin,alexislg2/phonegap-googlemaps-plugin,alexislg2/phonegap-googlemaps-plugin,smcpjames/cordova-plugin-googlemaps,CPlus/phonegap-googlemaps-plugin,LouisMazel/cordova-plugin-googlemaps,LouisMazel/cordova-plugin-googlemaps,rynomster/cordova-plugin-googlemaps,blanedaze/phonegap-googlemaps-plugin,cabify/cordova-plugin-googlemaps,wolf-s/phonegap-googlemaps-plugin,iDay/phonegap-googlemaps-plugin,Nipher/phonegap-googlemaps-plugin,piotrbelina/phonegap-googlemaps-plugin,arilsonkarmo/phonegap-googlemaps-plugin,mapsplugin/cordova-plugin-googlemaps,joewoodhouse/phonegap-googlemaps-plugin,smcpjames/cordova-plugin-googlemaps,elwahid/plugin.google.maps,elwahid/plugin.google.maps,wf9a5m75/phonegap-googlemaps-plugin,Jerome2606/phonegap-googlemaps-plugin,denisbabineau/phonegap-googlemaps-plugin,blanedaze/phonegap-googlemaps-plugin,otreva/phonegap-googlemaps-plugin,Jerome2606/phonegap-googlemaps-plugin,pinkbike/phonegap-googlemaps-plugin,otreva/phonegap-googlemaps-plugin,Nipher/phonegap-googlemaps-plugin,athiradandira/phonegap-googlemaps-plugin,piotrbelina/phonegap-googlemaps-plugin,athiradandira/phonegap-googlemaps-plugin,arilsonkarmo/phonegap-googlemaps-plugin,wf9a5m75/phonegap-googlemaps-plugin,denisbabineau/cordova-plugin-googlemaps,otreva/phonegap-googlemaps-plugin,denisbabineau/cordova-plugin-googlemaps,denisbabineau/phonegap-googlemaps-plugin,Nipher/phonegap-googlemaps-plugin,EmilianStankov/cordova-plugin-googlemaps,roberthovhannisyan/phonegap-googlemaps-plugin,hungdoan2/phonegap-googlemaps-plugin,roberthovhannisyan/phonegap-googlemaps-plugin,blanedaze/phonegap-googlemaps-plugin,wolf-s/phonegap-googlemaps-plugin,Skysurfer0110/phonegap-googlemaps-plugin,iDay/phonegap-googlemaps-plugin,EmilianStankov/cordova-plugin-googlemaps,dukhanov/cordova-plugin-googlemaps,smcpjames/cordova-plugin-googlemaps,quiuquio/cordova-plugin-googlemaps,hitoci/phonegap-googlemaps-plugin,eandresblasco/phonegap-googlemaps-plugin,alexislg2/phonegap-googlemaps-plugin,rynomster/cordova-plugin-googlemaps,quiuquio/cordova-plugin-googlemaps,edivancamargo/phonegap-googlemaps-plugin,Skysurfer0110/phonegap-googlemaps-plugin,matsprea/phonegap-googlemaps-plugin,cabify/cordova-plugin-googlemaps,piotrbelina/phonegap-googlemaps-plugin,dukhanov/cordova-plugin-googlemaps,Jerome2606/phonegap-googlemaps-plugin,roberthovhannisyan/phonegap-googlemaps-plugin,mapsplugin/cordova-plugin-googlemaps,arilsonkarmo/phonegap-googlemaps-plugin,LouisMazel/cordova-plugin-googlemaps,hungdoan2/phonegap-googlemaps-plugin,dukhanov/cordova-plugin-googlemaps,Skysurfer0110/phonegap-googlemaps-plugin,elwahid/plugin.google.maps,Jerome2606/phonegap-googlemaps-plugin,snoopconsulting/phonegap-googlemaps-plugin,hitoci/phonegap-googlemaps-plugin,pinkbike/phonegap-googlemaps-plugin,quiuquio/cordova-plugin-googlemaps,mapsplugin/cordova-plugin-googlemaps,snoopconsulting/phonegap-googlemaps-plugin,edivancamargo/phonegap-googlemaps-plugin,denisbabineau/phonegap-googlemaps-plugin,denisbabineau/cordova-plugin-googlemaps,otreva/phonegap-googlemaps-plugin,athiradandira/phonegap-googlemaps-plugin,EmilianStankov/cordova-plugin-googlemaps,edivancamargo/phonegap-googlemaps-plugin,wf9a5m75/phonegap-googlemaps-plugin,cabify/cordova-plugin-googlemaps,Nipher/phonegap-googlemaps-plugin,joewoodhouse/phonegap-googlemaps-plugin,snoopconsulting/phonegap-googlemaps-plugin,matsprea/phonegap-googlemaps-plugin,piotrbelina/phonegap-googlemaps-plugin,pinkbike/phonegap-googlemaps-plugin,CPlus/phonegap-googlemaps-plugin,iDay/phonegap-googlemaps-plugin,arilsonkarmo/phonegap-googlemaps-plugin,joewoodhouse/phonegap-googlemaps-plugin,matsprea/phonegap-googlemaps-plugin,Skysurfer0110/phonegap-googlemaps-plugin,athiradandira/phonegap-googlemaps-plugin,hungdoan2/phonegap-googlemaps-plugin
package plugin.google.maps; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.cordova.CordovaWebView; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.os.Build; import android.os.Build.VERSION; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AbsoluteLayout; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ScrollView; public class MyPluginLayout extends FrameLayout { private CordovaWebView webView; private ViewGroup root; private RectF drawRect = new RectF(); private Context context; private FrontLayerLayout frontLayer; private ScrollView scrollView = null; private FrameLayout scrollFrameLayout = null; private View backgroundView = null; private TouchableWrapper touchableWrapper; private ViewGroup myView = null; private boolean isScrolling = false; private ViewGroup.LayoutParams orgLayoutParams = null; private boolean isDebug = false; private boolean isClickable = true; private Map<String, RectF> HTMLNodes = new HashMap<String, RectF>(); private Activity mActivity = null; @SuppressLint("NewApi") public MyPluginLayout(CordovaWebView webView, Activity activity) { super(webView.getContext()); mActivity = activity; this.webView = webView; this.root = (ViewGroup) webView.getParent(); this.context = webView.getContext(); webView.setBackgroundColor(Color.TRANSPARENT); if (VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } frontLayer = new FrontLayerLayout(this.context); scrollView = new ScrollView(this.context); scrollView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); backgroundView = new View(this.context); backgroundView.setBackgroundColor(Color.WHITE); backgroundView.setVerticalScrollBarEnabled(false); backgroundView.setHorizontalScrollBarEnabled(false); backgroundView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 9999)); scrollFrameLayout = new FrameLayout(this.context); scrollFrameLayout.addView(backgroundView); scrollFrameLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); this.touchableWrapper = new TouchableWrapper(this.context); } public void setDrawingRect(float left, float top, float right, float bottom) { this.drawRect.left = left; this.drawRect.top = top; this.drawRect.right = right; this.drawRect.bottom = bottom; if (this.isDebug == true) { this.inValidate(); } } public void putHTMLElement(String domId, float left, float top, float right, float bottom) { RectF rect = null; if (this.HTMLNodes.containsKey(domId)) { rect = this.HTMLNodes.get(domId); } else { rect = new RectF(); } rect.left = left; rect.top = top; rect.right = right; rect.bottom = bottom; this.HTMLNodes.put(domId, rect); if (this.isDebug == true) { this.inValidate(); } } public void removeHTMLElement(String domId) { this.HTMLNodes.remove(domId); if (this.isDebug == true) { this.inValidate(); } } public void clearHTMLElement() { this.HTMLNodes.clear(); if (this.isDebug == true) { this.inValidate(); } } public void setClickable(boolean clickable) { this.isClickable = clickable; if (this.isDebug == true) { this.inValidate(); } } @SuppressWarnings("deprecation") public void updateViewPosition() { if (myView == null) { return; } ViewGroup.LayoutParams lParams = this.myView.getLayoutParams(); int scrollY = webView.getScrollY(); if (lParams instanceof AbsoluteLayout.LayoutParams) { AbsoluteLayout.LayoutParams params = (AbsoluteLayout.LayoutParams) lParams; params.width = (int) this.drawRect.width(); params.height = (int) this.drawRect.height(); params.x = (int) this.drawRect.left; params.y = (int) this.drawRect.top + scrollY; myView.setLayoutParams(params); } else if (lParams instanceof LinearLayout.LayoutParams) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) lParams; params.width = (int) this.drawRect.width(); params.height = (int) this.drawRect.height(); params.topMargin = (int) this.drawRect.top + scrollY; params.leftMargin = (int) this.drawRect.left; myView.setLayoutParams(params); } else if (lParams instanceof FrameLayout.LayoutParams) { FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) lParams; params.width = (int) this.drawRect.width(); params.height = (int) this.drawRect.height(); params.topMargin = (int) this.drawRect.top + scrollY; params.leftMargin = (int) this.drawRect.left; params.gravity = Gravity.TOP; myView.setLayoutParams(params); } if (android.os.Build.VERSION.SDK_INT < 11) { // Force redraw myView.requestLayout(); } this.frontLayer.invalidate(); } public View getMyView() { return myView; } public void setDebug(boolean debug) { this.isDebug = debug; if (this.isDebug == true) { this.inValidate(); } } public void detachMyView() { if (myView == null) { return; } root.removeView(this); this.removeView(frontLayer); frontLayer.removeView(webView); scrollFrameLayout.removeView(myView); myView.removeView(this.touchableWrapper); this.removeView(this.scrollView); this.scrollView.removeView(scrollFrameLayout); if (orgLayoutParams != null) { myView.setLayoutParams(orgLayoutParams); } root.addView(webView); myView = null; mActivity.getWindow().getDecorView().requestFocus(); } public void attachMyView(ViewGroup pluginView) { scrollView.scrollTo(webView.getScrollX(), webView.getScrollY()); if (myView == pluginView) { return; } else { this.detachMyView(); } //backgroundView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, (int) (webView.getContentHeight() * webView.getScale() + webView.getHeight()))); myView = pluginView; ViewGroup.LayoutParams lParams = myView.getLayoutParams(); orgLayoutParams = null; if (lParams != null) { orgLayoutParams = new ViewGroup.LayoutParams(lParams); } root.removeView(webView); scrollView.addView(scrollFrameLayout); this.addView(scrollView); pluginView.addView(this.touchableWrapper); scrollFrameLayout.addView(pluginView); frontLayer.addView(webView); this.addView(frontLayer); root.addView(this); mActivity.getWindow().getDecorView().requestFocus(); } public void setPageSize(int width, int height) { android.view.ViewGroup.LayoutParams lParams = backgroundView.getLayoutParams(); lParams.width = width; lParams.height = height; backgroundView.setLayoutParams(lParams); } public void scrollTo(int x, int y) { this.scrollView.scrollTo(x, y); } public void setBackgroundColor(int color) { this.backgroundView.setBackgroundColor(color); } public void inValidate() { this.frontLayer.invalidate(); } private class FrontLayerLayout extends FrameLayout { public FrontLayerLayout(Context context) { super(context); this.setWillNotDraw(false); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { if (isClickable == false || myView == null || myView.getVisibility() != View.VISIBLE) { webView.requestFocus(View.FOCUS_DOWN); return false; } int x = (int)event.getX(); int y = (int)event.getY(); int scrollY = webView.getScrollY(); boolean contains = drawRect.contains(x, y); int action = event.getAction(); isScrolling = (contains == false && action == MotionEvent.ACTION_DOWN) ? true : isScrolling; isScrolling = (action == MotionEvent.ACTION_UP) ? false : isScrolling; contains = isScrolling == true ? false : contains; if (contains) { // Is the touch point on any HTML elements? Set<Entry<String, RectF>> elements = MyPluginLayout.this.HTMLNodes.entrySet(); Iterator<Entry<String, RectF>> iterator = elements.iterator(); Entry <String, RectF> entry; RectF rect; while(iterator.hasNext() && contains == true) { entry = iterator.next(); rect = entry.getValue(); rect.top -= scrollY; rect.bottom -= scrollY; if (entry.getValue().contains(x, y)) { contains = false; } rect.top += scrollY; rect.bottom += scrollY; } } if (!contains) { webView.requestFocus(View.FOCUS_DOWN); } return contains; } @Override protected void onDraw(Canvas canvas) { if (drawRect == null || isDebug == false) { return; } int width = canvas.getWidth(); int height = canvas.getHeight(); int scrollY = webView.getScrollY(); Paint paint = new Paint(); paint.setColor(Color.argb(100, 0, 255, 0)); if (isClickable == false) { canvas.drawRect(0f, 0f, width, height, paint); return; } canvas.drawRect(0f, 0f, width, drawRect.top, paint); canvas.drawRect(0, drawRect.top, drawRect.left, drawRect.bottom, paint); canvas.drawRect(drawRect.right, drawRect.top, width, drawRect.bottom, paint); canvas.drawRect(0, drawRect.bottom, width, height, paint); paint.setColor(Color.argb(100, 255, 0, 0)); Set<Entry<String, RectF>> elements = MyPluginLayout.this.HTMLNodes.entrySet(); Iterator<Entry<String, RectF>> iterator = elements.iterator(); Entry <String, RectF> entry; RectF rect; while(iterator.hasNext()) { entry = iterator.next(); rect = entry.getValue(); rect.top -= scrollY; rect.bottom -= scrollY; canvas.drawRect(rect, paint); rect.top += scrollY; rect.bottom += scrollY; } } } private class TouchableWrapper extends FrameLayout { public TouchableWrapper(Context context) { super(context); } @Override public boolean dispatchTouchEvent(MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) { scrollView.requestDisallowInterceptTouchEvent(true); } return super.dispatchTouchEvent(event); } } }
src/android/plugin/google/maps/MyPluginLayout.java
package plugin.google.maps; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.cordova.CordovaWebView; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.os.Build; import android.os.Build.VERSION; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AbsoluteLayout; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ScrollView; public class MyPluginLayout extends FrameLayout { private CordovaWebView webView; private ViewGroup root; private RectF drawRect = new RectF(); private Context context; private FrontLayerLayout frontLayer; private ScrollView scrollView = null; private FrameLayout scrollFrameLayout = null; private View backgroundView = null; private TouchableWrapper touchableWrapper; private ViewGroup myView = null; private boolean isScrolling = false; private ViewGroup.LayoutParams orgLayoutParams = null; private boolean isDebug = false; private boolean isClickable = true; private Map<String, RectF> HTMLNodes = new HashMap<String, RectF>(); private Activity mActivity = null; @SuppressLint("NewApi") public MyPluginLayout(CordovaWebView webView, Activity activity) { super(webView.getContext()); mActivity = activity; this.webView = webView; this.root = (ViewGroup) webView.getParent(); this.context = webView.getContext(); webView.setBackgroundColor(Color.TRANSPARENT); if (VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } frontLayer = new FrontLayerLayout(this.context); scrollView = new ScrollView(this.context); scrollView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); backgroundView = new View(this.context); backgroundView.setBackgroundColor(Color.WHITE); backgroundView.setVerticalScrollBarEnabled(false); backgroundView.setHorizontalScrollBarEnabled(false); backgroundView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 9999)); scrollFrameLayout = new FrameLayout(this.context); scrollFrameLayout.addView(backgroundView); scrollFrameLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); this.touchableWrapper = new TouchableWrapper(this.context); } public void setDrawingRect(float left, float top, float right, float bottom) { this.drawRect.left = left; this.drawRect.top = top; this.drawRect.right = right; this.drawRect.bottom = bottom; if (this.isDebug == true) { this.inValidate(); } } public void putHTMLElement(String domId, float left, float top, float right, float bottom) { RectF rect = null; if (this.HTMLNodes.containsKey(domId)) { rect = this.HTMLNodes.get(domId); } else { rect = new RectF(); } rect.left = left; rect.top = top; rect.right = right; rect.bottom = bottom; this.HTMLNodes.put(domId, rect); if (this.isDebug == true) { this.inValidate(); } } public void removeHTMLElement(String domId) { this.HTMLNodes.remove(domId); if (this.isDebug == true) { this.inValidate(); } } public void clearHTMLElement() { this.HTMLNodes.clear(); if (this.isDebug == true) { this.inValidate(); } } public void setClickable(boolean clickable) { this.isClickable = clickable; if (this.isDebug == true) { this.inValidate(); } } @SuppressWarnings("deprecation") public void updateViewPosition() { if (myView == null) { return; } ViewGroup.LayoutParams lParams = this.myView.getLayoutParams(); int scrollY = webView.getScrollY(); if (lParams instanceof AbsoluteLayout.LayoutParams) { AbsoluteLayout.LayoutParams params = (AbsoluteLayout.LayoutParams) lParams; params.width = (int) this.drawRect.width(); params.height = (int) this.drawRect.height(); params.x = (int) this.drawRect.left; params.y = (int) this.drawRect.top + scrollY; myView.setLayoutParams(params); } else if (lParams instanceof LinearLayout.LayoutParams) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) lParams; params.width = (int) this.drawRect.width(); params.height = (int) this.drawRect.height(); params.topMargin = (int) this.drawRect.top + scrollY; params.leftMargin = (int) this.drawRect.left; myView.setLayoutParams(params); } else if (lParams instanceof FrameLayout.LayoutParams) { FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) lParams; params.width = (int) this.drawRect.width(); params.height = (int) this.drawRect.height(); params.topMargin = (int) this.drawRect.top + scrollY; params.leftMargin = (int) this.drawRect.left; params.gravity = Gravity.TOP; myView.setLayoutParams(params); } if (android.os.Build.VERSION.SDK_INT < 11) { // Force redraw myView.requestLayout(); } this.frontLayer.invalidate(); } public View getMyView() { return myView; } public void setDebug(boolean debug) { this.isDebug = debug; if (this.isDebug == true) { this.inValidate(); } } public void detachMyView() { if (myView == null) { return; } root.removeView(this); this.removeView(frontLayer); frontLayer.removeView(webView); scrollFrameLayout.removeView(myView); myView.removeView(this.touchableWrapper); this.removeView(this.scrollView); this.scrollView.removeView(scrollFrameLayout); if (orgLayoutParams != null) { myView.setLayoutParams(orgLayoutParams); } root.addView(webView); myView = null; mActivity.getWindow().getDecorView().requestFocus(); } public void attachMyView(ViewGroup pluginView) { scrollView.scrollTo(webView.getScrollX(), webView.getScrollY()); if (myView == pluginView) { return; } else { this.detachMyView(); } //backgroundView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, (int) (webView.getContentHeight() * webView.getScale() + webView.getHeight()))); myView = pluginView; ViewGroup.LayoutParams lParams = myView.getLayoutParams(); orgLayoutParams = null; if (lParams != null) { orgLayoutParams = new ViewGroup.LayoutParams(lParams); } root.removeView(webView); scrollView.addView(scrollFrameLayout); this.addView(scrollView); pluginView.addView(this.touchableWrapper); scrollFrameLayout.addView(pluginView); frontLayer.addView(webView); this.addView(frontLayer); root.addView(this); mActivity.getWindow().getDecorView().requestFocus(); } public void setPageSize(int width, int height) { android.view.ViewGroup.LayoutParams lParams = backgroundView.getLayoutParams(); lParams.width = width; lParams.height = height; backgroundView.setLayoutParams(lParams); } public void scrollTo(int x, int y) { this.scrollView.scrollTo(x, y); } public void setBackgroundColor(int color) { this.backgroundView.setBackgroundColor(color); } public void inValidate() { this.frontLayer.invalidate(); } private class FrontLayerLayout extends FrameLayout { public FrontLayerLayout(Context context) { super(context); this.setWillNotDraw(false); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { if (isClickable == false || myView.getVisibility() != View.VISIBLE) { webView.requestFocus(View.FOCUS_DOWN); return false; } int x = (int)event.getX(); int y = (int)event.getY(); int scrollY = webView.getScrollY(); boolean contains = drawRect.contains(x, y); int action = event.getAction(); isScrolling = (contains == false && action == MotionEvent.ACTION_DOWN) ? true : isScrolling; isScrolling = (action == MotionEvent.ACTION_UP) ? false : isScrolling; contains = isScrolling == true ? false : contains; if (contains) { // Is the touch point on any HTML elements? Set<Entry<String, RectF>> elements = MyPluginLayout.this.HTMLNodes.entrySet(); Iterator<Entry<String, RectF>> iterator = elements.iterator(); Entry <String, RectF> entry; RectF rect; while(iterator.hasNext() && contains == true) { entry = iterator.next(); rect = entry.getValue(); rect.top -= scrollY; rect.bottom -= scrollY; if (entry.getValue().contains(x, y)) { contains = false; } rect.top += scrollY; rect.bottom += scrollY; } } if (!contains) { webView.requestFocus(View.FOCUS_DOWN); } return contains; } @Override protected void onDraw(Canvas canvas) { if (drawRect == null || isDebug == false) { return; } int width = canvas.getWidth(); int height = canvas.getHeight(); int scrollY = webView.getScrollY(); Paint paint = new Paint(); paint.setColor(Color.argb(100, 0, 255, 0)); if (isClickable == false) { canvas.drawRect(0f, 0f, width, height, paint); return; } canvas.drawRect(0f, 0f, width, drawRect.top, paint); canvas.drawRect(0, drawRect.top, drawRect.left, drawRect.bottom, paint); canvas.drawRect(drawRect.right, drawRect.top, width, drawRect.bottom, paint); canvas.drawRect(0, drawRect.bottom, width, height, paint); paint.setColor(Color.argb(100, 255, 0, 0)); Set<Entry<String, RectF>> elements = MyPluginLayout.this.HTMLNodes.entrySet(); Iterator<Entry<String, RectF>> iterator = elements.iterator(); Entry <String, RectF> entry; RectF rect; while(iterator.hasNext()) { entry = iterator.next(); rect = entry.getValue(); rect.top -= scrollY; rect.bottom -= scrollY; canvas.drawRect(rect, paint); rect.top += scrollY; rect.bottom += scrollY; } } } private class TouchableWrapper extends FrameLayout { public TouchableWrapper(Context context) { super(context); } @Override public boolean dispatchTouchEvent(MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) { scrollView.requestDisallowInterceptTouchEvent(true); } return super.dispatchTouchEvent(event); } } }
Ignore the click detection if the mapView is null
src/android/plugin/google/maps/MyPluginLayout.java
Ignore the click detection if the mapView is null
<ide><path>rc/android/plugin/google/maps/MyPluginLayout.java <ide> <ide> @Override <ide> public boolean onInterceptTouchEvent(MotionEvent event) { <del> if (isClickable == false || myView.getVisibility() != View.VISIBLE) { <add> if (isClickable == false || myView == null || myView.getVisibility() != View.VISIBLE) { <ide> webView.requestFocus(View.FOCUS_DOWN); <ide> return false; <ide> }
JavaScript
mit
27f8ebcb4b41eb1160fe06c194072f1c51dc8901
0
gabriel17carmo/primeng,gilhanan/primeng,blver/primeng,nhnb/primeng,mmercan/primeng,donriver/primeng,pauly815/primeng,davidkirolos/primeng,davidkirolos/primeng,danielkay/primeng,kcjonesevans/primeng,primefaces/primeng,gabriel17carmo/primeng,blver/primeng,danielkay/primeng,aclarktcc/primeng,nhnb/primeng,gilhanan/primeng,blver/primeng,laserus/primeng,311devs/primeng,fusion-ffn/primeng,laserus/primeng,primefaces/primeng,primefaces/primeng,howlettt/primeng,kcjonesevans/primeng,ConradSchmidt/primeng,hryktrd/primeng,sourabh8003/ultimate-primeNg,aaraggornn/primeng,nhnb/primeng,kojisaiki/primeng,ConradSchmidt/primeng,howlettt/primeng,sourabh8003/ultimate-primeNg,odedolive/primeng,aaraggornn/primeng,pecko/primeng,311devs/primeng,pecko/primeng,WebRota/primeng,davidkirolos/primeng,kojisaiki/primeng,fusion-ffn/primeng,howlettt/primeng,kojisaiki/primeng,aaraggornn/primeng,WebRota/primeng,311devs/primeng,hryktrd/primeng,pecko/primeng,311devs/primeng,sourabh8003/ultimate-primeNg,mmercan/primeng,donriver/primeng,gabriel17carmo/primeng,mmercan/primeng,sourabh8003/ultimate-primeNg,fusion-ffn/primeng,odedolive/primeng,donriver/primeng,odedolive/primeng,carlosearaujo/primeng,WebRota/primeng,carlosearaujo/primeng,aclarktcc/primeng,laserus/primeng,pauly815/primeng,aclarktcc/primeng,primefaces/primeng,blver/primeng,pauly815/primeng,laserus/primeng,aclarktcc/primeng,ConradSchmidt/primeng,donriver/primeng,davidkirolos/primeng,carlosearaujo/primeng,pecko/primeng,mmercan/primeng,gabriel17carmo/primeng,danielkay/primeng,nhnb/primeng,gilhanan/primeng,kcjonesevans/primeng,gilhanan/primeng,pauly815/primeng,hryktrd/primeng,carlosearaujo/primeng,kcjonesevans/primeng,aaraggornn/primeng,ConradSchmidt/primeng,hryktrd/primeng,kojisaiki/primeng,WebRota/primeng,odedolive/primeng
systemjs.config.js
(function(global) { // map tells the System loader where to look for things var map = { 'rxjs': 'node_modules/rxjs', 'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api', '@angular': 'node_modules/@angular' }; // packages tells the System loader how to load when no filename and/or no extension var packages = { 'showcase': { main: 'boot.js', defaultExtension: 'js' }, 'components': { defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' }, 'angular2-in-memory-web-api': { defaultExtension: 'js' } }; var packageNames = [ '@angular/common', '@angular/compiler', '@angular/core', '@angular/http', '@angular/platform-browser', '@angular/platform-browser-dynamic', '@angular/router', '@angular/testing', '@angular/upgrade', '@angular/forms' ]; // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' } packageNames.forEach(function(pkgName) { packages[pkgName] = { main: 'index.js', defaultExtension: 'js' }; }); var config = { map: map, packages: packages } // filterSystemConfig - index.html's chance to modify config before we register it. if (global.filterSystemConfig) { global.filterSystemConfig(config); } System.config(config); })(this);
Removed system.js
systemjs.config.js
Removed system.js
<ide><path>ystemjs.config.js <del>(function(global) { <del> <del> // map tells the System loader where to look for things <del> var map = { <del> 'rxjs': 'node_modules/rxjs', <del> 'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api', <del> '@angular': 'node_modules/@angular' <del> }; <del> <del> // packages tells the System loader how to load when no filename and/or no extension <del> var packages = { <del> 'showcase': { main: 'boot.js', defaultExtension: 'js' }, <del> 'components': { defaultExtension: 'js' }, <del> 'rxjs': { defaultExtension: 'js' }, <del> 'angular2-in-memory-web-api': { defaultExtension: 'js' } <del> }; <del> <del> var packageNames = [ <del> '@angular/common', <del> '@angular/compiler', <del> '@angular/core', <del> '@angular/http', <del> '@angular/platform-browser', <del> '@angular/platform-browser-dynamic', <del> '@angular/router', <del> '@angular/testing', <del> '@angular/upgrade', <del> '@angular/forms' <del> ]; <del> <del> // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' } <del> packageNames.forEach(function(pkgName) { <del> packages[pkgName] = { main: 'index.js', defaultExtension: 'js' }; <del> }); <del> <del> var config = { <del> map: map, <del> packages: packages <del> } <del> <del> // filterSystemConfig - index.html's chance to modify config before we register it. <del> if (global.filterSystemConfig) { global.filterSystemConfig(config); } <del> <del> System.config(config); <del> <del>})(this);
JavaScript
apache-2.0
387bf40918e17e68ac32cca51f2ecf757128cfb3
0
ggetz/cesium,YonatanKra/cesium,denverpierce/cesium,omh1280/cesium,AnimatedRNG/cesium,aelatgt/cesium,NaderCHASER/cesium,AnalyticalGraphicsInc/cesium,jason-crow/cesium,AnimatedRNG/cesium,esraerik/cesium,denverpierce/cesium,geoscan/cesium,CesiumGS/cesium,esraerik/cesium,YonatanKra/cesium,likangning93/cesium,esraerik/cesium,likangning93/cesium,soceur/cesium,hodbauer/cesium,emackey/cesium,ggetz/cesium,jason-crow/cesium,wallw-bits/cesium,NaderCHASER/cesium,jasonbeverage/cesium,YonatanKra/cesium,josh-bernstein/cesium,emackey/cesium,likangning93/cesium,NaderCHASER/cesium,omh1280/cesium,kiselev-dv/cesium,oterral/cesium,aelatgt/cesium,emackey/cesium,hodbauer/cesium,oterral/cesium,emackey/cesium,wallw-bits/cesium,progsung/cesium,AnalyticalGraphicsInc/cesium,ggetz/cesium,CesiumGS/cesium,kiselev-dv/cesium,hodbauer/cesium,AnimatedRNG/cesium,kiselev-dv/cesium,CesiumGS/cesium,jason-crow/cesium,likangning93/cesium,progsung/cesium,aelatgt/cesium,CesiumGS/cesium,kaktus40/cesium,esraerik/cesium,jason-crow/cesium,ggetz/cesium,jasonbeverage/cesium,omh1280/cesium,geoscan/cesium,denverpierce/cesium,CesiumGS/cesium,kiselev-dv/cesium,oterral/cesium,likangning93/cesium,aelatgt/cesium,denverpierce/cesium,AnimatedRNG/cesium,YonatanKra/cesium,wallw-bits/cesium,josh-bernstein/cesium,wallw-bits/cesium,soceur/cesium,omh1280/cesium,soceur/cesium,kaktus40/cesium
/*global define*/ define([ '../Core/BoundingRectangle', '../Core/BoundingSphere', '../Core/Cartesian2', '../Core/Cartesian3', '../Core/Cartesian4', '../Core/Color', '../Core/ColorGeometryInstanceAttribute', '../Core/createGuid', '../Core/defaultValue', '../Core/defined', '../Core/defineProperties', '../Core/deprecationWarning', '../Core/destroyObject', '../Core/DeveloperError', '../Core/EllipsoidGeometry', '../Core/Event', '../Core/GeographicProjection', '../Core/GeometryInstance', '../Core/GeometryPipeline', '../Core/getTimestamp', '../Core/Intersect', '../Core/Interval', '../Core/JulianDate', '../Core/Math', '../Core/Matrix4', '../Core/mergeSort', '../Core/Occluder', '../Core/ShowGeometryInstanceAttribute', '../Renderer/ClearCommand', '../Renderer/Context', '../Renderer/PassState', './Camera', './CreditDisplay', './CullingVolume', './FrameState', './FrustumCommands', './FXAA', './GlobeDepth', './OIT', './OrthographicFrustum', './Pass', './PerformanceDisplay', './PerInstanceColorAppearance', './PerspectiveFrustum', './PerspectiveOffCenterFrustum', './PickDepth', './Primitive', './PrimitiveCollection', './SceneMode', './SceneTransforms', './SceneTransitioner', './ScreenSpaceCameraController', './SunPostProcess', './TweenCollection' ], function( BoundingRectangle, BoundingSphere, Cartesian2, Cartesian3, Cartesian4, Color, ColorGeometryInstanceAttribute, createGuid, defaultValue, defined, defineProperties, deprecationWarning, destroyObject, DeveloperError, EllipsoidGeometry, Event, GeographicProjection, GeometryInstance, GeometryPipeline, getTimestamp, Intersect, Interval, JulianDate, CesiumMath, Matrix4, mergeSort, Occluder, ShowGeometryInstanceAttribute, ClearCommand, Context, PassState, Camera, CreditDisplay, CullingVolume, FrameState, FrustumCommands, FXAA, GlobeDepth, OIT, OrthographicFrustum, Pass, PerformanceDisplay, PerInstanceColorAppearance, PerspectiveFrustum, PerspectiveOffCenterFrustum, PickDepth, Primitive, PrimitiveCollection, SceneMode, SceneTransforms, SceneTransitioner, ScreenSpaceCameraController, SunPostProcess, TweenCollection) { "use strict"; /** * The container for all 3D graphical objects and state in a Cesium virtual scene. Generally, * a scene is not created directly; instead, it is implicitly created by {@link CesiumWidget}. * <p> * <em><code>contextOptions</code> parameter details:</em> * </p> * <p> * The default values are: * <code> * { * webgl : { * alpha : false, * depth : true, * stencil : false, * antialias : true, * premultipliedAlpha : true, * preserveDrawingBuffer : false * failIfMajorPerformanceCaveat : true * }, * allowTextureFilterAnisotropic : true * } * </code> * </p> * <p> * The <code>webgl</code> property corresponds to the {@link http://www.khronos.org/registry/webgl/specs/latest/#5.2|WebGLContextAttributes} * object used to create the WebGL context. * </p> * <p> * <code>webgl.alpha</code> defaults to false, which can improve performance compared to the standard WebGL default * of true. If an application needs to composite Cesium above other HTML elements using alpha-blending, set * <code>webgl.alpha</code> to true. * </p> * <p> * <code>webgl.failIfMajorPerformanceCaveat</code> defaults to true, which ensures a context is not successfully created * if the system has a major performance issue such as only supporting software rendering. The standard WebGL default is false, * which is not appropriate for almost any Cesium app. * </p> * <p> * The other <code>webgl</code> properties match the WebGL defaults for {@link http://www.khronos.org/registry/webgl/specs/latest/#5.2|WebGLContextAttributes}. * </p> * <p> * <code>allowTextureFilterAnisotropic</code> defaults to true, which enables anisotropic texture filtering when the * WebGL extension is supported. Setting this to false will improve performance, but hurt visual quality, especially for horizon views. * </p> * * @alias Scene * @constructor * * @param {Object} [options] Object with the following properties: * @param {Canvas} options.canvas The HTML canvas element to create the scene for. * @param {Object} [options.contextOptions] Context and WebGL creation properties. See details above. * @param {Element} [options.creditContainer] The HTML element in which the credits will be displayed. * @param {MapProjection} [options.mapProjection=new GeographicProjection()] The map projection to use in 2D and Columbus View modes. * @param {Boolean} [options.orderIndependentTranslucency=true] If true and the configuration supports it, use order independent translucency. * @param {Boolean} [options.scene3DOnly=false] If true, optimizes memory use and performance for 3D mode but disables the ability to use 2D or Columbus View. * * @see CesiumWidget * @see {@link http://www.khronos.org/registry/webgl/specs/latest/#5.2|WebGLContextAttributes} * * @exception {DeveloperError} options and options.canvas are required. * * @example * // Create scene without anisotropic texture filtering * var scene = new Cesium.Scene({ * canvas : canvas, * contextOptions : { * allowTextureFilterAnisotropic : false * } * }); */ var Scene = function(options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); var canvas = options.canvas; var contextOptions = options.contextOptions; var creditContainer = options.creditContainer; //>>includeStart('debug', pragmas.debug); if (!defined(canvas)) { throw new DeveloperError('options and options.canvas are required.'); } //>>includeEnd('debug'); var context = new Context(canvas, contextOptions); if (!defined(creditContainer)) { creditContainer = document.createElement('div'); creditContainer.style.position = 'absolute'; creditContainer.style.bottom = '0'; creditContainer.style['text-shadow'] = '0px 0px 2px #000000'; creditContainer.style.color = '#ffffff'; creditContainer.style['font-size'] = '10px'; creditContainer.style['padding-right'] = '5px'; canvas.parentNode.appendChild(creditContainer); } this._id = createGuid(); this._frameState = new FrameState(new CreditDisplay(creditContainer)); this._frameState.scene3DOnly = defaultValue(options.scene3DOnly, false); this._passState = new PassState(context); this._canvas = canvas; this._context = context; this._globe = undefined; this._primitives = new PrimitiveCollection(); this._tweens = new TweenCollection(); this._shaderFrameCount = 0; this._sunPostProcess = undefined; this._commandList = []; this._frustumCommandsList = []; this._overlayCommandList = []; this._pickFramebuffer = undefined; this._useOIT = defaultValue(options.orderIndependentTranslucency, true); this._executeOITFunction = undefined; var globeDepth; if (context.depthTexture) { globeDepth = new GlobeDepth(); } var oit; if (this._useOIT && defined(globeDepth)) { oit = new OIT(context); } this._globeDepth = globeDepth; this._oit = oit; this._fxaa = new FXAA(); this._clearColorCommand = new ClearCommand({ color : new Color(), owner : this }); this._depthClearCommand = new ClearCommand({ depth : 1.0, owner : this }); this._pickDepths = []; this._debugGlobeDepths = []; this._transitioner = new SceneTransitioner(this); this._renderError = new Event(); this._preRender = new Event(); this._postRender = new Event(); this._cameraStartFired = false; this._cameraMovedTime = undefined; /** * Exceptions occurring in <code>render</code> are always caught in order to raise the * <code>renderError</code> event. If this property is true, the error is rethrown * after the event is raised. If this property is false, the <code>render</code> function * returns normally after raising the event. * * @type {Boolean} * @default false */ this.rethrowRenderErrors = false; /** * Determines whether or not to instantly complete the * scene transition animation on user input. * * @type {Boolean} * @default true */ this.completeMorphOnUserInput = true; /** * The event fired at the beginning of a scene transition. * @type {Event} * @default Event() */ this.morphStart = new Event(); /** * The event fired at the completion of a scene transition. * @type {Event} * @default Event() */ this.morphComplete = new Event(); /** * The {@link SkyBox} used to draw the stars. * * @type {SkyBox} * @default undefined * * @see Scene#backgroundColor */ this.skyBox = undefined; /** * The sky atmosphere drawn around the globe. * * @type {SkyAtmosphere} * @default undefined */ this.skyAtmosphere = undefined; /** * The {@link Sun}. * * @type {Sun} * @default undefined */ this.sun = undefined; /** * Uses a bloom filter on the sun when enabled. * * @type {Boolean} * @default true */ this.sunBloom = true; this._sunBloom = undefined; /** * The {@link Moon} * * @type Moon * @default undefined */ this.moon = undefined; /** * The background color, which is only visible if there is no sky box, i.e., {@link Scene#skyBox} is undefined. * * @type {Color} * @default {@link Color.BLACK} * * @see Scene#skyBox */ this.backgroundColor = Color.clone(Color.BLACK); this._mode = SceneMode.SCENE3D; this._mapProjection = defined(options.mapProjection) ? options.mapProjection : new GeographicProjection(); this._transitioner = new SceneTransitioner(this, this._mapProjection.ellipsoid); /** * The current morph transition time between 2D/Columbus View and 3D, * with 0.0 being 2D or Columbus View and 1.0 being 3D. * * @type {Number} * @default 1.0 */ this.morphTime = 1.0; /** * The far-to-near ratio of the multi-frustum. The default is 1,000.0. * * @type {Number} * @default 1000.0 */ this.farToNearRatio = 1000.0; /** * This property is for debugging only; it is not for production use. * <p> * A function that determines what commands are executed. As shown in the examples below, * the function receives the command's <code>owner</code> as an argument, and returns a boolean indicating if the * command should be executed. * </p> * <p> * The default is <code>undefined</code>, indicating that all commands are executed. * </p> * * @type Function * * @default undefined * * @example * // Do not execute any commands. * scene.debugCommandFilter = function(command) { * return false; * }; * * // Execute only the billboard's commands. That is, only draw the billboard. * var billboards = new Cesium.BillboardCollection(); * scene.debugCommandFilter = function(command) { * return command.owner === billboards; * }; */ this.debugCommandFilter = undefined; /** * This property is for debugging only; it is not for production use. * <p> * When <code>true</code>, commands are randomly shaded. This is useful * for performance analysis to see what parts of a scene or model are * command-dense and could benefit from batching. * </p> * * @type Boolean * * @default false */ this.debugShowCommands = false; /** * This property is for debugging only; it is not for production use. * <p> * When <code>true</code>, commands are shaded based on the frustums they * overlap. Commands in the closest frustum are tinted red, commands in * the next closest are green, and commands in the farthest frustum are * blue. If a command overlaps more than one frustum, the color components * are combined, e.g., a command overlapping the first two frustums is tinted * yellow. * </p> * * @type Boolean * * @default false */ this.debugShowFrustums = false; this._debugFrustumStatistics = undefined; /** * This property is for debugging only; it is not for production use. * <p> * Displays frames per second and time between frames. * </p> * * @type Boolean * * @default false */ this.debugShowFramesPerSecond = false; /** * This property is for debugging only; it is not for production use. * <p> * Displays depth information for the indicated frustum. * </p> * * @type Boolean * * @default false */ this.debugShowGlobeDepth = false; /** * This property is for debugging only; it is not for production use. * <p> * Indicates which frustum will have depth information displayed. * </p> * * @type Number * * @default 1 */ this.debugShowDepthFrustum = 1; /** * When <code>true</code>, enables Fast Approximate Anti-aliasing even when order independent translucency * is unsupported. * * @type Boolean * @default true */ this.fxaa = true; this._fxaaOrderIndependentTranslucency = true; /** * The time in milliseconds to wait before checking if the camera has not moved and fire the cameraMoveEnd event. * @type {Number} * @default 500.0 * @private */ this.cameraEventWaitTime = 500.0; /** * Set to true to copy the depth texture after rendering the globe. Makes czm_globeDepthTexture valid. * @type {Boolean} * @default false * @private */ this.copyGlobeDepth = false; this._performanceDisplay = undefined; this._debugSphere = undefined; var camera = new Camera(this); this._camera = camera; this._cameraClone = Camera.clone(camera); this._screenSpaceCameraController = new ScreenSpaceCameraController(this); // initial guess at frustums. var near = camera.frustum.near; var far = camera.frustum.far; var numFrustums = Math.ceil(Math.log(far / near) / Math.log(this.farToNearRatio)); updateFrustums(near, far, this.farToNearRatio, numFrustums, this._frustumCommandsList); // give frameState, camera, and screen space camera controller initial state before rendering updateFrameState(this, 0.0, JulianDate.now()); this.initializeFrame(); }; var OPAQUE_FRUSTUM_NEAR_OFFSET = 0.99; defineProperties(Scene.prototype, { /** * Gets the canvas element to which this scene is bound. * @memberof Scene.prototype * * @type {Element} * @readonly */ canvas : { get : function() { return this._canvas; } }, /** * The drawingBufferWidth of the underlying GL context. * @memberof Scene.prototype * * @type {Number} * @readonly * * @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferWidth|drawingBufferWidth} */ drawingBufferHeight : { get : function() { return this._context.drawingBufferHeight; } }, /** * The drawingBufferHeight of the underlying GL context. * @memberof Scene.prototype * * @type {Number} * @readonly * * @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferHeight|drawingBufferHeight} */ drawingBufferWidth : { get : function() { return this._context.drawingBufferWidth; } }, /** * The maximum aliased line width, in pixels, supported by this WebGL implementation. It will be at least one. * @memberof Scene.prototype * * @type {Number} * @readonly * * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>ALIASED_LINE_WIDTH_RANGE</code>. */ maximumAliasedLineWidth : { get : function() { return this._context.maximumAliasedLineWidth; } }, /** * The maximum length in pixels of one edge of a cube map, supported by this WebGL implementation. It will be at least 16. * @memberof Scene.prototype * * @type {Number} * @readonly * * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>GL_MAX_CUBE_MAP_TEXTURE_SIZE</code>. */ maximumCubeMapSize : { get : function() { return this._context.maximumCubeMapSize; } }, /** * Returns true if the pickPosition function is supported. * * @type {Boolean} * @readonly */ pickPositionSupported : { get : function() { return this._context.depthTexture; } }, /** * Gets or sets the depth-test ellipsoid. * @memberof Scene.prototype * * @type {Globe} */ globe : { get: function() { return this._globe; }, set: function(globe) { this._globe = this._globe && this._globe.destroy(); this._globe = globe; } }, /** * Gets the collection of primitives. * @memberof Scene.prototype * * @type {PrimitiveCollection} * @readonly */ primitives : { get : function() { return this._primitives; } }, /** * Gets the camera. * @memberof Scene.prototype * * @type {Camera} * @readonly */ camera : { get : function() { return this._camera; } }, // TODO: setCamera /** * Gets the controller for camera input handling. * @memberof Scene.prototype * * @type {ScreenSpaceCameraController} * @readonly */ screenSpaceCameraController : { get : function() { return this._screenSpaceCameraController; } }, /** * Get the map projection to use in 2D and Columbus View modes. * @memberof Scene.prototype * * @type {MapProjection} * @readonly * * @default new GeographicProjection() */ mapProjection : { get: function() { return this._mapProjection; } }, /** * Gets state information about the current scene. If called outside of a primitive's <code>update</code> * function, the previous frame's state is returned. * @memberof Scene.prototype * * @type {FrameState} * @readonly * * @private */ frameState : { get: function() { return this._frameState; } }, /** * Gets the collection of tweens taking place in the scene. * @memberof Scene.prototype * * @type {TweenCollection} * @readonly * * @private */ tweens : { get : function() { return this._tweens; } }, /** * Gets the collection of image layers that will be rendered on the globe. * @memberof Scene.prototype * * @type {ImageryLayerCollection} * @readonly */ imageryLayers : { get : function() { return this.globe.imageryLayers; } }, /** * The terrain provider providing surface geometry for the globe. * @memberof Scene.prototype * * @type {TerrainProvider} */ terrainProvider : { get : function() { return this.globe.terrainProvider; }, set : function(terrainProvider) { this.globe.terrainProvider = terrainProvider; } }, /** * Gets the event that will be raised when an error is thrown inside the <code>render</code> function. * The Scene instance and the thrown error are the only two parameters passed to the event handler. * By default, errors are not rethrown after this event is raised, but that can be changed by setting * the <code>rethrowRenderErrors</code> property. * @memberof Scene.prototype * * @type {Event} * @readonly */ renderError : { get : function() { return this._renderError; } }, /** * Gets the event that will be raised at the start of each call to <code>render</code>. Subscribers to the event * receive the Scene instance as the first parameter and the current time as the second parameter. * @memberof Scene.prototype * * @type {Event} * @readonly */ preRender : { get : function() { return this._preRender; } }, /** * Gets the event that will be raised at the end of each call to <code>render</code>. Subscribers to the event * receive the Scene instance as the first parameter and the current time as the second parameter. * @memberof Scene.prototype * * @type {Event} * @readonly */ postRender : { get : function() { return this._postRender; } }, /** * @memberof Scene.prototype * @private * @readonly */ context : { get : function() { return this._context; } }, /** * This property is for debugging only; it is not for production use. * <p> * When {@link Scene.debugShowFrustums} is <code>true</code>, this contains * properties with statistics about the number of command execute per frustum. * <code>totalCommands</code> is the total number of commands executed, ignoring * overlap. <code>commandsInFrustums</code> is an array with the number of times * commands are executed redundantly, e.g., how many commands overlap two or * three frustums. * </p> * * @memberof Scene.prototype * * @type {Object} * @readonly * * @default undefined */ debugFrustumStatistics : { get : function() { return this._debugFrustumStatistics; } }, /** * Gets whether or not the scene is optimized for 3D only viewing. * @memberof Scene.prototype * @type {Boolean} * @readonly */ scene3DOnly : { get : function() { return this._frameState.scene3DOnly; } }, /** * Gets whether or not the scene has order independent translucency enabled. * Note that this only reflects the original construction option, and there are * other factors that could prevent OIT from functioning on a given system configuration. * @memberof Scene.prototype * @type {Boolean} * @readonly */ orderIndependentTranslucency : { get : function() { return defined(this._oit); } }, /** * Gets the unique identifier for this scene. * @memberof Scene.prototype * @type {String} * @readonly */ id : { get : function() { return this._id; } }, /** * Gets or sets the current mode of the scene. * @memberof Scene.prototype * @type {SceneMode} * @default {@link SceneMode.SCENE3D} */ mode : { get : function() { return this._mode; }, set : function(value) { if (this.scene3DOnly && value !== SceneMode.SCENE3D) { throw new DeveloperError('Only SceneMode.SCENE3D is valid when scene3DOnly is true.'); } this._mode = value; } }, /** * Gets the number of frustums used in the last frame. * @memberof Scene.prototype * @type {Number} * * @private */ numberOfFrustums : { get : function() { return this._frustumCommandsList.length; } }, /** * If <code>true</code>, enables Fast Aproximate Anti-aliasing only if order independent translucency * is supported. * @memberof Scene.prototype * @type {Boolean} * @default true * * @deprecated */ fxaaOrderIndependentTranslucency : { get : function() { return this._fxaaOrderIndependentTranslucency; }, set : function(value) { deprecationWarning('Scene.fxaaOrderIndependentTranslucency', 'Scene.fxaaOrderIndependentTranslucency has been deprecated. Use Scene.fxaa instead.'); this._fxaaOrderIndependentTranslucency = value; } } }); var scratchPosition0 = new Cartesian3(); var scratchPosition1 = new Cartesian3(); function maxComponent(a, b) { var x = Math.max(Math.abs(a.x), Math.abs(b.x)); var y = Math.max(Math.abs(a.y), Math.abs(b.y)); var z = Math.max(Math.abs(a.z), Math.abs(b.z)); return Math.max(Math.max(x, y), z); } function cameraEqual(camera0, camera1, epsilon) { var scalar = 1 / Math.max(1, maxComponent(camera0.position, camera1.position)); Cartesian3.multiplyByScalar(camera0.position, scalar, scratchPosition0); Cartesian3.multiplyByScalar(camera1.position, scalar, scratchPosition1); return Cartesian3.equalsEpsilon(scratchPosition0, scratchPosition1, epsilon) && Cartesian3.equalsEpsilon(camera0.direction, camera1.direction, epsilon) && Cartesian3.equalsEpsilon(camera0.up, camera1.up, epsilon) && Cartesian3.equalsEpsilon(camera0.right, camera1.right, epsilon) && Matrix4.equalsEpsilon(camera0.transform, camera1.transform, epsilon); } var scratchOccluderBoundingSphere = new BoundingSphere(); var scratchOccluder; function getOccluder(scene) { // TODO: The occluder is the top-level globe. When we add // support for multiple central bodies, this should be the closest one. var globe = scene.globe; if (scene._mode === SceneMode.SCENE3D && defined(globe)) { var ellipsoid = globe.ellipsoid; scratchOccluderBoundingSphere.radius = ellipsoid.minimumRadius; scratchOccluder = Occluder.fromBoundingSphere(scratchOccluderBoundingSphere, scene._camera.positionWC, scratchOccluder); return scratchOccluder; } return undefined; } function clearPasses(passes) { passes.render = false; passes.pick = false; } function updateFrameState(scene, frameNumber, time) { var camera = scene._camera; var frameState = scene._frameState; frameState.mode = scene._mode; frameState.morphTime = scene.morphTime; frameState.mapProjection = scene.mapProjection; frameState.frameNumber = frameNumber; frameState.time = JulianDate.clone(time, frameState.time); frameState.camera = camera; frameState.cullingVolume = camera.frustum.computeCullingVolume(camera.positionWC, camera.directionWC, camera.upWC); frameState.occluder = getOccluder(scene); clearPasses(frameState.passes); } function updateFrustums(near, far, farToNearRatio, numFrustums, frustumCommandsList) { frustumCommandsList.length = numFrustums; for (var m = 0; m < numFrustums; ++m) { var curNear = Math.max(near, Math.pow(farToNearRatio, m) * near); var curFar = Math.min(far, farToNearRatio * curNear); var frustumCommands = frustumCommandsList[m]; if (!defined(frustumCommands)) { frustumCommands = frustumCommandsList[m] = new FrustumCommands(curNear, curFar); } else { frustumCommands.near = curNear; frustumCommands.far = curFar; } } } function insertIntoBin(scene, command, distance) { if (scene.debugShowFrustums) { command.debugOverlappingFrustums = 0; } var frustumCommandsList = scene._frustumCommandsList; var length = frustumCommandsList.length; for (var i = 0; i < length; ++i) { var frustumCommands = frustumCommandsList[i]; var curNear = frustumCommands.near; var curFar = frustumCommands.far; if (distance.start > curFar) { continue; } if (distance.stop < curNear) { break; } var pass = command instanceof ClearCommand ? Pass.OPAQUE : command.pass; var index = frustumCommands.indices[pass]++; frustumCommands.commands[pass][index] = command; if (scene.debugShowFrustums) { command.debugOverlappingFrustums |= (1 << i); } if (command.executeInClosestFrustum) { break; } } if (scene.debugShowFrustums) { var cf = scene._debugFrustumStatistics.commandsInFrustums; cf[command.debugOverlappingFrustums] = defined(cf[command.debugOverlappingFrustums]) ? cf[command.debugOverlappingFrustums] + 1 : 1; ++scene._debugFrustumStatistics.totalCommands; } } var scratchCullingVolume = new CullingVolume(); var distances = new Interval(); function createPotentiallyVisibleSet(scene) { var commandList = scene._commandList; var overlayList = scene._overlayCommandList; var cullingVolume = scene._frameState.cullingVolume; var camera = scene._camera; var direction = camera.directionWC; var position = camera.positionWC; if (scene.debugShowFrustums) { scene._debugFrustumStatistics = { totalCommands : 0, commandsInFrustums : {} }; } var frustumCommandsList = scene._frustumCommandsList; var numberOfFrustums = frustumCommandsList.length; var numberOfPasses = Pass.NUMBER_OF_PASSES; for (var n = 0; n < numberOfFrustums; ++n) { for (var p = 0; p < numberOfPasses; ++p) { frustumCommandsList[n].indices[p] = 0; } } overlayList.length = 0; var near = Number.MAX_VALUE; var far = Number.MIN_VALUE; var undefBV = false; var occluder; if (scene._frameState.mode === SceneMode.SCENE3D) { occluder = scene._frameState.occluder; } // get user culling volume minus the far plane. var planes = scratchCullingVolume.planes; for (var m = 0; m < 5; ++m) { planes[m] = cullingVolume.planes[m]; } cullingVolume = scratchCullingVolume; var length = commandList.length; for (var i = 0; i < length; ++i) { var command = commandList[i]; var pass = command.pass; if (pass === Pass.OVERLAY) { overlayList.push(command); } else { var boundingVolume = command.boundingVolume; if (defined(boundingVolume)) { if (command.cull && ((cullingVolume.computeVisibility(boundingVolume) === Intersect.OUTSIDE) || (defined(occluder) && !occluder.isBoundingSphereVisible(boundingVolume)))) { continue; } distances = BoundingSphere.computePlaneDistances(boundingVolume, position, direction, distances); near = Math.min(near, distances.start); far = Math.max(far, distances.stop); } else { // Clear commands don't need a bounding volume - just add the clear to all frustums. // If another command has no bounding volume, though, we need to use the camera's // worst-case near and far planes to avoid clipping something important. distances.start = camera.frustum.near; distances.stop = camera.frustum.far; undefBV = !(command instanceof ClearCommand); } insertIntoBin(scene, command, distances); } } if (undefBV) { near = camera.frustum.near; far = camera.frustum.far; } else { // The computed near plane must be between the user defined near and far planes. // The computed far plane must between the user defined far and computed near. // This will handle the case where the computed near plane is further than the user defined far plane. near = Math.min(Math.max(near, camera.frustum.near), camera.frustum.far); far = Math.max(Math.min(far, camera.frustum.far), near); } // Exploit temporal coherence. If the frustums haven't changed much, use the frustums computed // last frame, else compute the new frustums and sort them by frustum again. var farToNearRatio = scene.farToNearRatio; var numFrustums = Math.ceil(Math.log(far / near) / Math.log(farToNearRatio)); if (near !== Number.MAX_VALUE && (numFrustums !== numberOfFrustums || (frustumCommandsList.length !== 0 && (near < frustumCommandsList[0].near || far > frustumCommandsList[numberOfFrustums - 1].far)))) { updateFrustums(near, far, farToNearRatio, numFrustums, frustumCommandsList); createPotentiallyVisibleSet(scene); } } function getAttributeLocations(shaderProgram) { var attributeLocations = {}; var attributes = shaderProgram.vertexAttributes; for (var a in attributes) { if (attributes.hasOwnProperty(a)) { attributeLocations[a] = attributes[a].index; } } return attributeLocations; } function createDebugFragmentShaderProgram(command, scene, shaderProgram) { var context = scene.context; var sp = defaultValue(shaderProgram, command.shaderProgram); var fs = sp.fragmentShaderSource.clone(); fs.sources = fs.sources.map(function(source) { source = source.replace(/void\s+main\s*\(\s*(?:void)?\s*\)/g, 'void czm_Debug_main()'); return source; }); var newMain = 'void main() \n' + '{ \n' + ' czm_Debug_main(); \n'; if (scene.debugShowCommands) { if (!defined(command._debugColor)) { command._debugColor = Color.fromRandom(); } var c = command._debugColor; newMain += ' gl_FragColor.rgb *= vec3(' + c.red + ', ' + c.green + ', ' + c.blue + '); \n'; } if (scene.debugShowFrustums) { // Support up to three frustums. If a command overlaps all // three, it's code is not changed. var r = (command.debugOverlappingFrustums & (1 << 0)) ? '1.0' : '0.0'; var g = (command.debugOverlappingFrustums & (1 << 1)) ? '1.0' : '0.0'; var b = (command.debugOverlappingFrustums & (1 << 2)) ? '1.0' : '0.0'; newMain += ' gl_FragColor.rgb *= vec3(' + r + ', ' + g + ', ' + b + '); \n'; } newMain += '}'; fs.sources.push(newMain); var attributeLocations = getAttributeLocations(sp); return context.createShaderProgram(sp.vertexShaderSource, fs, attributeLocations); } function executeDebugCommand(command, scene, passState, renderState, shaderProgram) { if (defined(command.shaderProgram) || defined(shaderProgram)) { // Replace shader for frustum visualization var sp = createDebugFragmentShaderProgram(command, scene, shaderProgram); command.execute(scene.context, passState, renderState, sp); sp.destroy(); } } var transformFrom2D = new Matrix4(0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0); transformFrom2D = Matrix4.inverseTransformation(transformFrom2D, transformFrom2D); function executeCommand(command, scene, context, passState, renderState, shaderProgram, debugFramebuffer) { if ((defined(scene.debugCommandFilter)) && !scene.debugCommandFilter(command)) { return; } if (scene.debugShowCommands || scene.debugShowFrustums) { executeDebugCommand(command, scene, passState, renderState, shaderProgram); } else { command.execute(context, passState, renderState, shaderProgram); } if (command.debugShowBoundingVolume && (defined(command.boundingVolume))) { // Debug code to draw bounding volume for command. Not optimized! // Assumes bounding volume is a bounding sphere. if (defined(scene._debugSphere)) { scene._debugSphere.destroy(); } var frameState = scene._frameState; var boundingVolume = command.boundingVolume; var radius = boundingVolume.radius; var center = boundingVolume.center; var geometry = GeometryPipeline.toWireframe(EllipsoidGeometry.createGeometry(new EllipsoidGeometry({ radii : new Cartesian3(radius, radius, radius), vertexFormat : PerInstanceColorAppearance.FLAT_VERTEX_FORMAT }))); if (frameState.mode !== SceneMode.SCENE3D) { center = Matrix4.multiplyByPoint(transformFrom2D, center, center); var projection = frameState.mapProjection; var centerCartographic = projection.unproject(center); center = projection.ellipsoid.cartographicToCartesian(centerCartographic); } scene._debugSphere = new Primitive({ geometryInstances : new GeometryInstance({ geometry : geometry, modelMatrix : Matrix4.multiplyByTranslation(Matrix4.IDENTITY, center, new Matrix4()), attributes : { color : new ColorGeometryInstanceAttribute(1.0, 0.0, 0.0, 1.0) } }), appearance : new PerInstanceColorAppearance({ flat : true, translucent : false }), asynchronous : false }); var commandList = []; scene._debugSphere.update(context, frameState, commandList); var framebuffer; if (defined(debugFramebuffer)) { framebuffer = passState.framebuffer; passState.framebuffer = debugFramebuffer; } commandList[0].execute(context, passState); if (defined(framebuffer)) { passState.framebuffer = framebuffer; } } } function isVisible(command, frameState) { if (!defined(command)) { return; } var occluder = (frameState.mode === SceneMode.SCENE3D) ? frameState.occluder: undefined; var cullingVolume = frameState.cullingVolume; // get user culling volume minus the far plane. var planes = scratchCullingVolume.planes; for (var k = 0; k < 5; ++k) { planes[k] = cullingVolume.planes[k]; } cullingVolume = scratchCullingVolume; var boundingVolume = command.boundingVolume; return ((defined(command)) && ((!defined(command.boundingVolume)) || !command.cull || ((cullingVolume.computeVisibility(boundingVolume) !== Intersect.OUTSIDE) && (!defined(occluder) || occluder.isBoundingSphereVisible(boundingVolume))))); } function translucentCompare(a, b, position) { return BoundingSphere.distanceSquaredTo(b.boundingVolume, position) - BoundingSphere.distanceSquaredTo(a.boundingVolume, position); } function executeTranslucentCommandsSorted(scene, executeFunction, passState, commands) { var context = scene.context; mergeSort(commands, translucentCompare, scene._camera.positionWC); var length = commands.length; for (var j = 0; j < length; ++j) { executeFunction(commands[j], scene, context, passState); } } function getDebugGlobeDepth(scene, index) { var globeDepth = scene._debugGlobeDepths[index]; if (!defined(globeDepth) && scene.context.depthTexture) { globeDepth = new GlobeDepth(); scene._debugGlobeDepths[index] = globeDepth; } return globeDepth; } function getPickDepth(scene, index) { var pickDepth = scene._pickDepths[index]; if (!defined(pickDepth)) { pickDepth = new PickDepth(); scene._pickDepths[index] = pickDepth; } return pickDepth; } var scratchPerspectiveFrustum = new PerspectiveFrustum(); var scratchPerspectiveOffCenterFrustum = new PerspectiveOffCenterFrustum(); var scratchOrthographicFrustum = new OrthographicFrustum(); function executeCommands(scene, passState, clearColor, picking) { var i; var j; var frameState = scene._frameState; var camera = scene._camera; var context = scene.context; var us = context.uniformState; // Manage sun bloom post-processing effect. if (defined(scene.sun) && scene.sunBloom !== scene._sunBloom) { if (scene.sunBloom) { scene._sunPostProcess = new SunPostProcess(); } else if(defined(scene._sunPostProcess)){ scene._sunPostProcess = scene._sunPostProcess.destroy(); } scene._sunBloom = scene.sunBloom; } else if (!defined(scene.sun) && defined(scene._sunPostProcess)) { scene._sunPostProcess = scene._sunPostProcess.destroy(); scene._sunBloom = false; } // Manage celestial and terrestrial environment effects. var renderPass = frameState.passes.render; var skyBoxCommand = (renderPass && defined(scene.skyBox)) ? scene.skyBox.update(context, frameState) : undefined; var skyAtmosphereCommand = (renderPass && defined(scene.skyAtmosphere)) ? scene.skyAtmosphere.update(context, frameState) : undefined; var sunCommand = (renderPass && defined(scene.sun)) ? scene.sun.update(scene) : undefined; var sunVisible = isVisible(sunCommand, frameState); var moonCommand = (renderPass && defined(scene.moon)) ? scene.moon.update(context, frameState) : undefined; var moonVisible = isVisible(moonCommand, frameState); // Preserve the reference to the original framebuffer. var originalFramebuffer = passState.framebuffer; // Create a working frustum from the original camera frustum. var frustum; if (defined(camera.frustum.fov)) { frustum = camera.frustum.clone(scratchPerspectiveFrustum); } else if (defined(camera.frustum.infiniteProjectionMatrix)){ frustum = camera.frustum.clone(scratchPerspectiveOffCenterFrustum); } else { frustum = camera.frustum.clone(scratchOrthographicFrustum); } // Clear the pass state framebuffer. var clear = scene._clearColorCommand; Color.clone(clearColor, clear.color); clear.execute(context, passState); // Update globe depth rendering based on the current context and clear the globe depth framebuffer. if (defined(scene._globeDepth)) { scene._globeDepth.update(context); scene._globeDepth.clear(context, passState, clearColor); } // Determine if there are any translucent surfaces in any of the frustums. var renderTranslucentCommands = false; var frustumCommandsList = scene._frustumCommandsList; var numFrustums = frustumCommandsList.length; for (i = 0; i < numFrustums; ++i) { if (frustumCommandsList[i].indices[Pass.TRANSLUCENT] > 0) { renderTranslucentCommands = true; break; } } // If supported, configure OIT to use the globe depth framebuffer and clear the OIT framebuffer. var useOIT = !picking && renderTranslucentCommands && defined(scene._oit) && scene._oit.isSupported(); if (useOIT) { scene._oit.update(context, scene._globeDepth.framebuffer); scene._oit.clear(context, passState, clearColor); useOIT = useOIT && scene._oit.isSupported(); } // If supported, configure FXAA to use the globe depth color texture and clear the FXAA framebuffer. var useFXAA = !picking && scene.fxaa; if (useFXAA) { var fxaaTexture = !useOIT && defined(scene._globeDepth) ? scene._globeDepth._colorTexture : undefined; scene._fxaa.update(context, fxaaTexture); scene._fxaa.clear(context, passState, clearColor); } if (sunVisible && scene.sunBloom) { passState.framebuffer = scene._sunPostProcess.update(context); } else if (defined(scene._globeDepth)) { passState.framebuffer = scene._globeDepth.framebuffer; } else if (useFXAA) { passState.framebuffer = scene._fxaa.getColorFramebuffer(); } if (defined(passState.framebuffer)) { clear.execute(context, passState); } // Ideally, we would render the sky box and atmosphere last for // early-z, but we would have to draw it in each frustum frustum.near = camera.frustum.near; frustum.far = camera.frustum.far; us.updateFrustum(frustum); if (defined(skyBoxCommand)) { executeCommand(skyBoxCommand, scene, context, passState); } if (defined(skyAtmosphereCommand)) { executeCommand(skyAtmosphereCommand, scene, context, passState); } if (sunVisible) { sunCommand.execute(context, passState); if (scene.sunBloom) { var framebuffer; if (defined(scene._globeDepth)) { framebuffer = scene._globeDepth.framebuffer; } else if (scene.fxaa) { framebuffer = scene._fxaa.getColorFramebuffer(); } else { framebuffer = originalFramebuffer; } scene._sunPostProcess.execute(context, framebuffer); passState.framebuffer = framebuffer; } } // Moon can be seen through the atmosphere, since the sun is rendered after the atmosphere. if (moonVisible) { moonCommand.execute(context, passState); } // Determine how translucent surfaces will be handled. var executeTranslucentCommands; if (useOIT) { if (!defined(scene._executeOITFunction)) { scene._executeOITFunction = function(scene, executeFunction, passState, commands) { scene._oit.executeCommands(scene, executeFunction, passState, commands); }; } executeTranslucentCommands = scene._executeOITFunction; } else { executeTranslucentCommands = executeTranslucentCommandsSorted; } // Execute commands in each frustum in back to front order var clearDepth = scene._depthClearCommand; for (i = 0; i < numFrustums; ++i) { var index = numFrustums - i - 1; var frustumCommands = frustumCommandsList[index]; frustum.near = frustumCommands.near; frustum.far = frustumCommands.far; if (index !== 0) { // Avoid tearing artifacts between adjacent frustums in the opaque passes frustum.near *= OPAQUE_FRUSTUM_NEAR_OFFSET; } var globeDepth = scene.debugShowGlobeDepth ? getDebugGlobeDepth(scene, index) : scene._globeDepth; var fb; if (scene.debugShowGlobeDepth && defined(globeDepth)) { fb = passState.framebuffer; passState.framebuffer = globeDepth.framebuffer; } us.updateFrustum(frustum); clearDepth.execute(context, passState); var commands = frustumCommands.commands[Pass.GLOBE]; var length = frustumCommands.indices[Pass.GLOBE]; for (j = 0; j < length; ++j) { executeCommand(commands[j], scene, context, passState); } if (defined(globeDepth) && (scene.copyGlobeDepth || scene.debugShowGlobeDepth)) { globeDepth.update(context); globeDepth.executeCopyDepth(context, passState); } if (scene.debugShowGlobeDepth && defined(globeDepth)) { passState.framebuffer = fb; } // Execute commands in order by pass up to the translucent pass. // Translucent geometry needs special handling (sorting/OIT). var startPass = Pass.GLOBE + 1; var endPass = Pass.TRANSLUCENT; for (var pass = startPass; pass < endPass; ++pass) { commands = frustumCommands.commands[pass]; length = frustumCommands.indices[pass]; for (j = 0; j < length; ++j) { executeCommand(commands[j], scene, context, passState); } } if (index !== 0) { // Do not overlap frustums in the translucent pass to avoid blending artifacts frustum.near = frustumCommands.near; us.updateFrustum(frustum); } commands = frustumCommands.commands[Pass.TRANSLUCENT]; commands.length = frustumCommands.indices[Pass.TRANSLUCENT]; executeTranslucentCommands(scene, executeCommand, passState, commands); if (defined(globeDepth)) { // PERFORMANCE_IDEA: Use MRT to avoid the extra copy. var pickDepth = getPickDepth(scene, index); pickDepth.update(context, globeDepth.framebuffer.depthStencilTexture); pickDepth.executeCopyDepth(context, passState); } } if (scene.debugShowGlobeDepth && defined(scene._globeDepth)) { var gd = getDebugGlobeDepth(scene, scene.debugShowDepthFrustum - 1); gd.executeDebugGlobeDepth(context, passState); } if (scene.debugShowPickDepth && defined(scene._globeDepth)) { var pd = getPickDepth(scene, scene.debugShowDepthFrustum - 1); pd.executeDebugPickDepth(context, passState); } if (useOIT) { passState.framebuffer = useFXAA ? scene._fxaa.getColorFramebuffer() : undefined; scene._oit.execute(context, passState); } if (useFXAA) { passState.framebuffer = originalFramebuffer; scene._fxaa.execute(context, passState); } if (!useOIT && !useFXAA && defined(scene._globeDepth)) { passState.framebuffer = originalFramebuffer; scene._globeDepth.executeCopyColor(context, passState); } } function executeOverlayCommands(scene, passState) { var context = scene.context; var commandList = scene._overlayCommandList; var length = commandList.length; for (var i = 0; i < length; ++i) { commandList[i].execute(context, passState); } } function updatePrimitives(scene) { var context = scene.context; var frameState = scene._frameState; var commandList = scene._commandList; if (scene._globe) { scene._globe.update(context, frameState, commandList); } scene._primitives.update(context, frameState, commandList); } function callAfterRenderFunctions(frameState) { // Functions are queued up during primitive update and executed here in case // the function modifies scene state that should remain constant over the frame. var functions = frameState.afterRender; for (var i = 0, length = functions.length; i < length; ++i) { functions[i](); } functions.length = 0; } /** * @private */ Scene.prototype.initializeFrame = function() { // Destroy released shaders once every 120 frames to avoid thrashing the cache if (this._shaderFrameCount++ === 120) { this._shaderFrameCount = 0; this._context.shaderCache.destroyReleasedShaderPrograms(); } this._tweens.update(); this._camera.update(this._mode); this._screenSpaceCameraController.update(); }; function render(scene, time) { if (!defined(time)) { time = JulianDate.now(); } var camera = scene._camera; if (!cameraEqual(camera, scene._cameraClone, CesiumMath.EPSILON6)) { if (!scene._cameraStartFired) { camera.moveStart.raiseEvent(); scene._cameraStartFired = true; } scene._cameraMovedTime = getTimestamp(); Camera.clone(camera, scene._cameraClone); } else if (scene._cameraStartFired && getTimestamp() - scene._cameraMovedTime > scene.cameraEventWaitTime) { camera.moveEnd.raiseEvent(); scene._cameraStartFired = false; } scene._preRender.raiseEvent(scene, time); var us = scene.context.uniformState; var frameState = scene._frameState; var frameNumber = CesiumMath.incrementWrap(frameState.frameNumber, 15000000.0, 1.0); updateFrameState(scene, frameNumber, time); frameState.passes.render = true; frameState.creditDisplay.beginFrame(); var context = scene.context; us.update(context, frameState); scene._commandList.length = 0; scene._overlayCommandList.length = 0; updatePrimitives(scene); createPotentiallyVisibleSet(scene); var passState = scene._passState; passState.framebuffer = undefined; passState.blendingEnabled = undefined; passState.scissorTest = undefined; executeCommands(scene, passState, defaultValue(scene.backgroundColor, Color.BLACK)); executeOverlayCommands(scene, passState); frameState.creditDisplay.endFrame(); if (scene.debugShowFramesPerSecond) { if (!defined(scene._performanceDisplay)) { var performanceContainer = document.createElement('div'); performanceContainer.className = 'cesium-performanceDisplay'; performanceContainer.style.position = 'absolute'; performanceContainer.style.top = '50px'; performanceContainer.style.right = '10px'; var container = scene._canvas.parentNode; container.appendChild(performanceContainer); var performanceDisplay = new PerformanceDisplay({container: performanceContainer}); scene._performanceDisplay = performanceDisplay; scene._performanceContainer = performanceContainer; } scene._performanceDisplay.update(); } else if (defined(scene._performanceDisplay)) { scene._performanceDisplay = scene._performanceDisplay && scene._performanceDisplay.destroy(); scene._performanceContainer.parentNode.removeChild(scene._performanceContainer); } context.endFrame(); callAfterRenderFunctions(frameState); scene._postRender.raiseEvent(scene, time); } /** * @private */ Scene.prototype.render = function(time) { try { render(this, time); } catch (error) { this._renderError.raiseEvent(this, error); if (this.rethrowRenderErrors) { throw error; } } }; /** * @private */ Scene.prototype.clampLineWidth = function(width) { var context = this._context; return Math.max(context.minimumAliasedLineWidth, Math.min(width, context.maximumAliasedLineWidth)); }; var orthoPickingFrustum = new OrthographicFrustum(); var scratchOrigin = new Cartesian3(); var scratchDirection = new Cartesian3(); var scratchBufferDimensions = new Cartesian2(); var scratchPixelSize = new Cartesian2(); var scratchPickVolumeMatrix4 = new Matrix4(); function getPickOrthographicCullingVolume(scene, drawingBufferPosition, width, height) { var camera = scene._camera; var frustum = camera.frustum; var drawingBufferWidth = scene.drawingBufferWidth; var drawingBufferHeight = scene.drawingBufferHeight; var x = (2.0 / drawingBufferWidth) * drawingBufferPosition.x - 1.0; x *= (frustum.right - frustum.left) * 0.5; var y = (2.0 / drawingBufferHeight) * (drawingBufferHeight - drawingBufferPosition.y) - 1.0; y *= (frustum.top - frustum.bottom) * 0.5; var transform = Matrix4.clone(camera.transform, scratchPickVolumeMatrix4); camera._setTransform(Matrix4.IDENTITY); var origin = Cartesian3.clone(camera.position, scratchOrigin); Cartesian3.multiplyByScalar(camera.right, x, scratchDirection); Cartesian3.add(scratchDirection, origin, origin); Cartesian3.multiplyByScalar(camera.up, y, scratchDirection); Cartesian3.add(scratchDirection, origin, origin); camera._setTransform(transform); Cartesian3.fromElements(origin.z, origin.x, origin.y, origin); scratchBufferDimensions.x = drawingBufferWidth; scratchBufferDimensions.y = drawingBufferHeight; var pixelSize = frustum.getPixelSize(scratchBufferDimensions, undefined, scratchPixelSize); var ortho = orthoPickingFrustum; ortho.right = pixelSize.x * 0.5; ortho.left = -ortho.right; ortho.top = pixelSize.y * 0.5; ortho.bottom = -ortho.top; ortho.near = frustum.near; ortho.far = frustum.far; return ortho.computeCullingVolume(origin, camera.directionWC, camera.upWC); } var perspPickingFrustum = new PerspectiveOffCenterFrustum(); function getPickPerspectiveCullingVolume(scene, drawingBufferPosition, width, height) { var camera = scene._camera; var frustum = camera.frustum; var near = frustum.near; var drawingBufferWidth = scene.drawingBufferWidth; var drawingBufferHeight = scene.drawingBufferHeight; var tanPhi = Math.tan(frustum.fovy * 0.5); var tanTheta = frustum.aspectRatio * tanPhi; var x = (2.0 / drawingBufferWidth) * drawingBufferPosition.x - 1.0; var y = (2.0 / drawingBufferHeight) * (drawingBufferHeight - drawingBufferPosition.y) - 1.0; var xDir = x * near * tanTheta; var yDir = y * near * tanPhi; scratchBufferDimensions.x = drawingBufferWidth; scratchBufferDimensions.y = drawingBufferHeight; var pixelSize = frustum.getPixelSize(scratchBufferDimensions, undefined, scratchPixelSize); var pickWidth = pixelSize.x * width * 0.5; var pickHeight = pixelSize.y * height * 0.5; var offCenter = perspPickingFrustum; offCenter.top = yDir + pickHeight; offCenter.bottom = yDir - pickHeight; offCenter.right = xDir + pickWidth; offCenter.left = xDir - pickWidth; offCenter.near = near; offCenter.far = frustum.far; return offCenter.computeCullingVolume(camera.positionWC, camera.directionWC, camera.upWC); } function getPickCullingVolume(scene, drawingBufferPosition, width, height) { if (scene._mode === SceneMode.SCENE2D) { return getPickOrthographicCullingVolume(scene, drawingBufferPosition, width, height); } return getPickPerspectiveCullingVolume(scene, drawingBufferPosition, width, height); } // pick rectangle width and height, assumed odd var rectangleWidth = 3.0; var rectangleHeight = 3.0; var scratchRectangle = new BoundingRectangle(0.0, 0.0, rectangleWidth, rectangleHeight); var scratchColorZero = new Color(0.0, 0.0, 0.0, 0.0); var scratchPosition = new Cartesian2(); /** * Returns an object with a `primitive` property that contains the first (top) primitive in the scene * at a particular window coordinate or undefined if nothing is at the location. Other properties may * potentially be set depending on the type of primitive. * * @param {Cartesian2} windowPosition Window coordinates to perform picking on. * @returns {Object} Object containing the picked primitive. * * @exception {DeveloperError} windowPosition is undefined. */ Scene.prototype.pick = function(windowPosition) { //>>includeStart('debug', pragmas.debug); if(!defined(windowPosition)) { throw new DeveloperError('windowPosition is undefined.'); } //>>includeEnd('debug'); var context = this._context; var us = context.uniformState; var frameState = this._frameState; var drawingBufferPosition = SceneTransforms.transformWindowToDrawingBuffer(this, windowPosition, scratchPosition); if (!defined(this._pickFramebuffer)) { this._pickFramebuffer = context.createPickFramebuffer(); } // Update with previous frame's number and time, assuming that render is called before picking. updateFrameState(this, frameState.frameNumber, frameState.time); frameState.cullingVolume = getPickCullingVolume(this, drawingBufferPosition, rectangleWidth, rectangleHeight); frameState.passes.pick = true; us.update(context, frameState); this._commandList.length = 0; updatePrimitives(this); createPotentiallyVisibleSet(this); scratchRectangle.x = drawingBufferPosition.x - ((rectangleWidth - 1.0) * 0.5); scratchRectangle.y = (this.drawingBufferHeight - drawingBufferPosition.y) - ((rectangleHeight - 1.0) * 0.5); executeCommands(this, this._pickFramebuffer.begin(scratchRectangle), scratchColorZero, true); var object = this._pickFramebuffer.end(scratchRectangle); context.endFrame(); callAfterRenderFunctions(frameState); return object; }; var scratchPickDepthPosition = new Cartesian3(); var scratchMinDistPos = new Cartesian3(); var scratchPackedDepth = new Cartesian4(); var packedDepthScale = new Cartesian4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0); /** * Returns the cartesian position reconstructed from the depth buffer and window position. * * @param {Cartesian2} windowPosition Window coordinates to perform picking on. * @param {Cartesian3} [result] The object on which to restore the result. * @returns {Cartesian3} The cartesian position. * * @exception {DeveloperError} Picking from the depth buffer is not supported. Check pickPositionSupported. * @exception {DeveloperError} 2D is not supported. An orthographic projection matrix is not invertible. */ Scene.prototype.pickPosition = function(windowPosition, result) { //>>includeStart('debug', pragmas.debug); if(!defined(windowPosition)) { throw new DeveloperError('windowPosition is undefined.'); } if (!defined(this._globeDepth)) { throw new DeveloperError('Picking from the depth buffer is not supported. Check pickPositionSupported.'); } //>>includeEnd('debug'); var context = this._context; var uniformState = context.uniformState; var drawingBufferPosition = SceneTransforms.transformWindowToDrawingBuffer(this, windowPosition, scratchPosition); drawingBufferPosition.y = this.drawingBufferHeight - drawingBufferPosition.y; var camera = this._camera; // Create a working frustum from the original camera frustum. var frustum; if (defined(camera.frustum.fov)) { frustum = camera.frustum.clone(scratchPerspectiveFrustum); } else if (defined(camera.frustum.infiniteProjectionMatrix)){ frustum = camera.frustum.clone(scratchPerspectiveOffCenterFrustum); } else { //>>includeStart('debug', pragmas.debug); throw new DeveloperError('2D is not supported. An orthographic projection matrix is not invertible.'); //>>includeEnd('debug'); } var minimumPosition; var minDistance; var numFrustums = this.numberOfFrustums; for (var i = 0; i < numFrustums; ++i) { var pickDepth = getPickDepth(this, i); var pixels = context.readPixels({ x : drawingBufferPosition.x, y : drawingBufferPosition.y, width : 1, height : 1, framebuffer : pickDepth.framebuffer }); var packedDepth = Cartesian4.unpack(pixels, 0, scratchPackedDepth); Cartesian4.divideByScalar(packedDepth, 255.0, packedDepth); var depth = Cartesian4.dot(packedDepth, packedDepthScale); if (depth > 0.0 && depth < 1.0) { var renderedFrustum = this._frustumCommandsList[i]; frustum.near = renderedFrustum.near; frustum.far = renderedFrustum.far; uniformState.updateFrustum(frustum); var position = SceneTransforms.drawingBufferToWgs84Coordinates(this, drawingBufferPosition, depth, scratchPickDepthPosition); var distance = Cartesian3.distance(position, camera.positionWC); if (!defined(minimumPosition) || distance < minDistance) { minimumPosition = Cartesian3.clone(position, result); minDistance = distance; } } } return minimumPosition; }; /** * Returns a list of objects, each containing a `primitive` property, for all primitives at * a particular window coordinate position. Other properties may also be set depending on the * type of primitive. The primitives in the list are ordered by their visual order in the * scene (front to back). * * @param {Cartesian2} windowPosition Window coordinates to perform picking on. * @param {Number} [limit] If supplied, stop drilling after collecting this many picks. * @returns {Object[]} Array of objects, each containing 1 picked primitives. * * @exception {DeveloperError} windowPosition is undefined. * * @example * var pickedObjects = Cesium.Scene.drillPick(new Cesium.Cartesian2(100.0, 200.0)); */ Scene.prototype.drillPick = function(windowPosition, limit) { // PERFORMANCE_IDEA: This function calls each primitive's update for each pass. Instead // we could update the primitive once, and then just execute their commands for each pass, // and cull commands for picked primitives. e.g., base on the command's owner. //>>includeStart('debug', pragmas.debug); if (!defined(windowPosition)) { throw new DeveloperError('windowPosition is undefined.'); } //>>includeEnd('debug'); var i; var attributes; var result = []; var pickedPrimitives = []; var pickedAttributes = []; if (!defined(limit)) { limit = Number.MAX_VALUE; } var pickedResult = this.pick(windowPosition); while (defined(pickedResult) && defined(pickedResult.primitive)) { result.push(pickedResult); if (0 >= --limit) { break; } var primitive = pickedResult.primitive; var hasShowAttribute = false; //If the picked object has a show attribute, use it. if (typeof primitive.getGeometryInstanceAttributes === 'function') { if (defined(pickedResult.id)) { attributes = primitive.getGeometryInstanceAttributes(pickedResult.id); if (defined(attributes) && defined(attributes.show)) { hasShowAttribute = true; attributes.show = ShowGeometryInstanceAttribute.toValue(false, attributes.show); pickedAttributes.push(attributes); } } } //Otherwise, hide the entire primitive if (!hasShowAttribute) { primitive.show = false; pickedPrimitives.push(primitive); } pickedResult = this.pick(windowPosition); } // unhide everything we hid while drill picking for (i = 0; i < pickedPrimitives.length; ++i) { pickedPrimitives[i].show = true; } for (i = 0; i < pickedAttributes.length; ++i) { attributes = pickedAttributes[i]; attributes.show = ShowGeometryInstanceAttribute.toValue(true, attributes.show); } return result; }; /** * Instantly completes an active transition. */ Scene.prototype.completeMorph = function(){ this._transitioner.completeMorph(); }; /** * Asynchronously transitions the scene to 2D. * @param {Number} [duration=2.0] The amount of time, in seconds, for transition animations to complete. */ Scene.prototype.morphTo2D = function(duration) { var ellipsoid; var globe = this.globe; if (defined(globe)) { ellipsoid = globe.ellipsoid; } else { ellipsoid = this.mapProjection.ellipsoid; } duration = defaultValue(duration, 2.0); this._transitioner.morphTo2D(duration, ellipsoid); }; /** * Asynchronously transitions the scene to Columbus View. * @param {Number} [duration=2.0] The amount of time, in seconds, for transition animations to complete. */ Scene.prototype.morphToColumbusView = function(duration) { var ellipsoid; var globe = this.globe; if (defined(globe)) { ellipsoid = globe.ellipsoid; } else { ellipsoid = this.mapProjection.ellipsoid; } duration = defaultValue(duration, 2.0); this._transitioner.morphToColumbusView(duration, ellipsoid); }; /** * Asynchronously transitions the scene to 3D. * @param {Number} [duration=2.0] The amount of time, in seconds, for transition animations to complete. */ Scene.prototype.morphTo3D = function(duration) { var ellipsoid; var globe = this.globe; if (defined(globe)) { ellipsoid = globe.ellipsoid; } else { ellipsoid = this.mapProjection.ellipsoid; } duration = defaultValue(duration, 2.0); this._transitioner.morphTo3D(duration, ellipsoid); }; /** * Returns true if this object was destroyed; otherwise, false. * <br /><br /> * If this object was destroyed, it should not be used; calling any function other than * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. * * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>. * * @see Scene#destroy */ Scene.prototype.isDestroyed = function() { return false; }; /** * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic * release of WebGL resources, instead of relying on the garbage collector to destroy this object. * <br /><br /> * Once an object is destroyed, it should not be used; calling any function other than * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore, * assign the return value (<code>undefined</code>) to the object as done in the example. * * @returns {undefined} * * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called. * * @see Scene#isDestroyed * * @example * scene = scene && scene.destroy(); */ Scene.prototype.destroy = function() { this._tweens.removeAll(); this._screenSpaceCameraController = this._screenSpaceCameraController && this._screenSpaceCameraController.destroy(); this._pickFramebuffer = this._pickFramebuffer && this._pickFramebuffer.destroy(); this._primitives = this._primitives && this._primitives.destroy(); this._globe = this._globe && this._globe.destroy(); this.skyBox = this.skyBox && this.skyBox.destroy(); this.skyAtmosphere = this.skyAtmosphere && this.skyAtmosphere.destroy(); this._debugSphere = this._debugSphere && this._debugSphere.destroy(); this.sun = this.sun && this.sun.destroy(); this._sunPostProcess = this._sunPostProcess && this._sunPostProcess.destroy(); this._transitioner.destroy(); this._globeDepth.destroy(); if (defined(this._oit)) { this._oit.destroy(); } this._fxaa.destroy(); this._context = this._context && this._context.destroy(); this._frameState.creditDisplay.destroy(); if (defined(this._performanceDisplay)){ this._performanceDisplay = this._performanceDisplay && this._performanceDisplay.destroy(); this._performanceContainer.parentNode.removeChild(this._performanceContainer); } return destroyObject(this); }; return Scene; });
Source/Scene/Scene.js
/*global define*/ define([ '../Core/BoundingRectangle', '../Core/BoundingSphere', '../Core/Cartesian2', '../Core/Cartesian3', '../Core/Cartesian4', '../Core/Color', '../Core/ColorGeometryInstanceAttribute', '../Core/createGuid', '../Core/defaultValue', '../Core/defined', '../Core/defineProperties', '../Core/deprecationWarning', '../Core/destroyObject', '../Core/DeveloperError', '../Core/EllipsoidGeometry', '../Core/Event', '../Core/GeographicProjection', '../Core/GeometryInstance', '../Core/GeometryPipeline', '../Core/getTimestamp', '../Core/Intersect', '../Core/Interval', '../Core/JulianDate', '../Core/Math', '../Core/Matrix4', '../Core/mergeSort', '../Core/Occluder', '../Core/ShowGeometryInstanceAttribute', '../Renderer/ClearCommand', '../Renderer/Context', '../Renderer/PassState', './Camera', './CreditDisplay', './CullingVolume', './FrameState', './FrustumCommands', './FXAA', './GlobeDepth', './OIT', './OrthographicFrustum', './Pass', './PerformanceDisplay', './PerInstanceColorAppearance', './PerspectiveFrustum', './PerspectiveOffCenterFrustum', './PickDepth', './Primitive', './PrimitiveCollection', './SceneMode', './SceneTransforms', './SceneTransitioner', './ScreenSpaceCameraController', './SunPostProcess', './TweenCollection' ], function( BoundingRectangle, BoundingSphere, Cartesian2, Cartesian3, Cartesian4, Color, ColorGeometryInstanceAttribute, createGuid, defaultValue, defined, defineProperties, deprecationWarning, destroyObject, DeveloperError, EllipsoidGeometry, Event, GeographicProjection, GeometryInstance, GeometryPipeline, getTimestamp, Intersect, Interval, JulianDate, CesiumMath, Matrix4, mergeSort, Occluder, ShowGeometryInstanceAttribute, ClearCommand, Context, PassState, Camera, CreditDisplay, CullingVolume, FrameState, FrustumCommands, FXAA, GlobeDepth, OIT, OrthographicFrustum, Pass, PerformanceDisplay, PerInstanceColorAppearance, PerspectiveFrustum, PerspectiveOffCenterFrustum, PickDepth, Primitive, PrimitiveCollection, SceneMode, SceneTransforms, SceneTransitioner, ScreenSpaceCameraController, SunPostProcess, TweenCollection) { "use strict"; /** * The container for all 3D graphical objects and state in a Cesium virtual scene. Generally, * a scene is not created directly; instead, it is implicitly created by {@link CesiumWidget}. * <p> * <em><code>contextOptions</code> parameter details:</em> * </p> * <p> * The default values are: * <code> * { * webgl : { * alpha : false, * depth : true, * stencil : false, * antialias : true, * premultipliedAlpha : true, * preserveDrawingBuffer : false * failIfMajorPerformanceCaveat : true * }, * allowTextureFilterAnisotropic : true * } * </code> * </p> * <p> * The <code>webgl</code> property corresponds to the {@link http://www.khronos.org/registry/webgl/specs/latest/#5.2|WebGLContextAttributes} * object used to create the WebGL context. * </p> * <p> * <code>webgl.alpha</code> defaults to false, which can improve performance compared to the standard WebGL default * of true. If an application needs to composite Cesium above other HTML elements using alpha-blending, set * <code>webgl.alpha</code> to true. * </p> * <p> * <code>webgl.failIfMajorPerformanceCaveat</code> defaults to true, which ensures a context is not successfully created * if the system has a major performance issue such as only supporting software rendering. The standard WebGL default is false, * which is not appropriate for almost any Cesium app. * </p> * <p> * The other <code>webgl</code> properties match the WebGL defaults for {@link http://www.khronos.org/registry/webgl/specs/latest/#5.2|WebGLContextAttributes}. * </p> * <p> * <code>allowTextureFilterAnisotropic</code> defaults to true, which enables anisotropic texture filtering when the * WebGL extension is supported. Setting this to false will improve performance, but hurt visual quality, especially for horizon views. * </p> * * @alias Scene * @constructor * * @param {Object} [options] Object with the following properties: * @param {Canvas} options.canvas The HTML canvas element to create the scene for. * @param {Object} [options.contextOptions] Context and WebGL creation properties. See details above. * @param {Element} [options.creditContainer] The HTML element in which the credits will be displayed. * @param {MapProjection} [options.mapProjection=new GeographicProjection()] The map projection to use in 2D and Columbus View modes. * @param {Boolean} [options.orderIndependentTranslucency=true] If true and the configuration supports it, use order independent translucency. * @param {Boolean} [options.scene3DOnly=false] If true, optimizes memory use and performance for 3D mode but disables the ability to use 2D or Columbus View. * * @see CesiumWidget * @see {@link http://www.khronos.org/registry/webgl/specs/latest/#5.2|WebGLContextAttributes} * * @exception {DeveloperError} options and options.canvas are required. * * @example * // Create scene without anisotropic texture filtering * var scene = new Cesium.Scene({ * canvas : canvas, * contextOptions : { * allowTextureFilterAnisotropic : false * } * }); */ var Scene = function(options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); var canvas = options.canvas; var contextOptions = options.contextOptions; var creditContainer = options.creditContainer; //>>includeStart('debug', pragmas.debug); if (!defined(canvas)) { throw new DeveloperError('options and options.canvas are required.'); } //>>includeEnd('debug'); var context = new Context(canvas, contextOptions); if (!defined(creditContainer)) { creditContainer = document.createElement('div'); creditContainer.style.position = 'absolute'; creditContainer.style.bottom = '0'; creditContainer.style['text-shadow'] = '0px 0px 2px #000000'; creditContainer.style.color = '#ffffff'; creditContainer.style['font-size'] = '10px'; creditContainer.style['padding-right'] = '5px'; canvas.parentNode.appendChild(creditContainer); } this._id = createGuid(); this._frameState = new FrameState(new CreditDisplay(creditContainer)); this._frameState.scene3DOnly = defaultValue(options.scene3DOnly, false); this._passState = new PassState(context); this._canvas = canvas; this._context = context; this._globe = undefined; this._primitives = new PrimitiveCollection(); this._tweens = new TweenCollection(); this._shaderFrameCount = 0; this._sunPostProcess = undefined; this._commandList = []; this._frustumCommandsList = []; this._overlayCommandList = []; this._pickFramebuffer = undefined; this._useOIT = defaultValue(options.orderIndependentTranslucency, true); this._executeOITFunction = undefined; var globeDepth; if (context.depthTexture) { globeDepth = new GlobeDepth(); } var oit; if (this._useOIT && defined(globeDepth)) { oit = new OIT(context); } this._globeDepth = globeDepth; this._oit = oit; this._fxaa = new FXAA(); this._clearColorDepthCommand = new ClearCommand({ color : new Color(), depth : 1.0, owner : this }); this._depthClearCommand = new ClearCommand({ depth : 1.0, owner : this }); this._pickDepths = []; this._debugGlobeDepths = []; this._transitioner = new SceneTransitioner(this); this._renderError = new Event(); this._preRender = new Event(); this._postRender = new Event(); this._cameraStartFired = false; this._cameraMovedTime = undefined; /** * Exceptions occurring in <code>render</code> are always caught in order to raise the * <code>renderError</code> event. If this property is true, the error is rethrown * after the event is raised. If this property is false, the <code>render</code> function * returns normally after raising the event. * * @type {Boolean} * @default false */ this.rethrowRenderErrors = false; /** * Determines whether or not to instantly complete the * scene transition animation on user input. * * @type {Boolean} * @default true */ this.completeMorphOnUserInput = true; /** * The event fired at the beginning of a scene transition. * @type {Event} * @default Event() */ this.morphStart = new Event(); /** * The event fired at the completion of a scene transition. * @type {Event} * @default Event() */ this.morphComplete = new Event(); /** * The {@link SkyBox} used to draw the stars. * * @type {SkyBox} * @default undefined * * @see Scene#backgroundColor */ this.skyBox = undefined; /** * The sky atmosphere drawn around the globe. * * @type {SkyAtmosphere} * @default undefined */ this.skyAtmosphere = undefined; /** * The {@link Sun}. * * @type {Sun} * @default undefined */ this.sun = undefined; /** * Uses a bloom filter on the sun when enabled. * * @type {Boolean} * @default true */ this.sunBloom = true; this._sunBloom = undefined; /** * The {@link Moon} * * @type Moon * @default undefined */ this.moon = undefined; /** * The background color, which is only visible if there is no sky box, i.e., {@link Scene#skyBox} is undefined. * * @type {Color} * @default {@link Color.BLACK} * * @see Scene#skyBox */ this.backgroundColor = Color.clone(Color.BLACK); this._mode = SceneMode.SCENE3D; this._mapProjection = defined(options.mapProjection) ? options.mapProjection : new GeographicProjection(); this._transitioner = new SceneTransitioner(this, this._mapProjection.ellipsoid); /** * The current morph transition time between 2D/Columbus View and 3D, * with 0.0 being 2D or Columbus View and 1.0 being 3D. * * @type {Number} * @default 1.0 */ this.morphTime = 1.0; /** * The far-to-near ratio of the multi-frustum. The default is 1,000.0. * * @type {Number} * @default 1000.0 */ this.farToNearRatio = 1000.0; /** * This property is for debugging only; it is not for production use. * <p> * A function that determines what commands are executed. As shown in the examples below, * the function receives the command's <code>owner</code> as an argument, and returns a boolean indicating if the * command should be executed. * </p> * <p> * The default is <code>undefined</code>, indicating that all commands are executed. * </p> * * @type Function * * @default undefined * * @example * // Do not execute any commands. * scene.debugCommandFilter = function(command) { * return false; * }; * * // Execute only the billboard's commands. That is, only draw the billboard. * var billboards = new Cesium.BillboardCollection(); * scene.debugCommandFilter = function(command) { * return command.owner === billboards; * }; */ this.debugCommandFilter = undefined; /** * This property is for debugging only; it is not for production use. * <p> * When <code>true</code>, commands are randomly shaded. This is useful * for performance analysis to see what parts of a scene or model are * command-dense and could benefit from batching. * </p> * * @type Boolean * * @default false */ this.debugShowCommands = false; /** * This property is for debugging only; it is not for production use. * <p> * When <code>true</code>, commands are shaded based on the frustums they * overlap. Commands in the closest frustum are tinted red, commands in * the next closest are green, and commands in the farthest frustum are * blue. If a command overlaps more than one frustum, the color components * are combined, e.g., a command overlapping the first two frustums is tinted * yellow. * </p> * * @type Boolean * * @default false */ this.debugShowFrustums = false; this._debugFrustumStatistics = undefined; /** * This property is for debugging only; it is not for production use. * <p> * Displays frames per second and time between frames. * </p> * * @type Boolean * * @default false */ this.debugShowFramesPerSecond = false; /** * This property is for debugging only; it is not for production use. * <p> * Displays depth information for the indicated frustum. * </p> * * @type Boolean * * @default false */ this.debugShowGlobeDepth = false; /** * This property is for debugging only; it is not for production use. * <p> * Indicates which frustum will have depth information displayed. * </p> * * @type Number * * @default 1 */ this.debugShowDepthFrustum = 1; /** * When <code>true</code>, enables Fast Approximate Anti-aliasing even when order independent translucency * is unsupported. * * @type Boolean * @default true */ this.fxaa = true; this._fxaaOrderIndependentTranslucency = true; /** * The time in milliseconds to wait before checking if the camera has not moved and fire the cameraMoveEnd event. * @type {Number} * @default 500.0 * @private */ this.cameraEventWaitTime = 500.0; /** * Set to true to copy the depth texture after rendering the globe. Makes czm_globeDepthTexture valid. * @type {Boolean} * @default false * @private */ this.copyGlobeDepth = false; this._performanceDisplay = undefined; this._debugSphere = undefined; var camera = new Camera(this); this._camera = camera; this._cameraClone = Camera.clone(camera); this._screenSpaceCameraController = new ScreenSpaceCameraController(this); // initial guess at frustums. var near = camera.frustum.near; var far = camera.frustum.far; var numFrustums = Math.ceil(Math.log(far / near) / Math.log(this.farToNearRatio)); updateFrustums(near, far, this.farToNearRatio, numFrustums, this._frustumCommandsList); // give frameState, camera, and screen space camera controller initial state before rendering updateFrameState(this, 0.0, JulianDate.now()); this.initializeFrame(); }; var OPAQUE_FRUSTUM_NEAR_OFFSET = 0.99; defineProperties(Scene.prototype, { /** * Gets the canvas element to which this scene is bound. * @memberof Scene.prototype * * @type {Element} * @readonly */ canvas : { get : function() { return this._canvas; } }, /** * The drawingBufferWidth of the underlying GL context. * @memberof Scene.prototype * * @type {Number} * @readonly * * @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferWidth|drawingBufferWidth} */ drawingBufferHeight : { get : function() { return this._context.drawingBufferHeight; } }, /** * The drawingBufferHeight of the underlying GL context. * @memberof Scene.prototype * * @type {Number} * @readonly * * @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferHeight|drawingBufferHeight} */ drawingBufferWidth : { get : function() { return this._context.drawingBufferWidth; } }, /** * The maximum aliased line width, in pixels, supported by this WebGL implementation. It will be at least one. * @memberof Scene.prototype * * @type {Number} * @readonly * * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>ALIASED_LINE_WIDTH_RANGE</code>. */ maximumAliasedLineWidth : { get : function() { return this._context.maximumAliasedLineWidth; } }, /** * The maximum length in pixels of one edge of a cube map, supported by this WebGL implementation. It will be at least 16. * @memberof Scene.prototype * * @type {Number} * @readonly * * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>GL_MAX_CUBE_MAP_TEXTURE_SIZE</code>. */ maximumCubeMapSize : { get : function() { return this._context.maximumCubeMapSize; } }, /** * Returns true if the pickPosition function is supported. * * @type {Boolean} * @readonly */ pickPositionSupported : { get : function() { return this._context.depthTexture; } }, /** * Gets or sets the depth-test ellipsoid. * @memberof Scene.prototype * * @type {Globe} */ globe : { get: function() { return this._globe; }, set: function(globe) { this._globe = this._globe && this._globe.destroy(); this._globe = globe; } }, /** * Gets the collection of primitives. * @memberof Scene.prototype * * @type {PrimitiveCollection} * @readonly */ primitives : { get : function() { return this._primitives; } }, /** * Gets the camera. * @memberof Scene.prototype * * @type {Camera} * @readonly */ camera : { get : function() { return this._camera; } }, // TODO: setCamera /** * Gets the controller for camera input handling. * @memberof Scene.prototype * * @type {ScreenSpaceCameraController} * @readonly */ screenSpaceCameraController : { get : function() { return this._screenSpaceCameraController; } }, /** * Get the map projection to use in 2D and Columbus View modes. * @memberof Scene.prototype * * @type {MapProjection} * @readonly * * @default new GeographicProjection() */ mapProjection : { get: function() { return this._mapProjection; } }, /** * Gets state information about the current scene. If called outside of a primitive's <code>update</code> * function, the previous frame's state is returned. * @memberof Scene.prototype * * @type {FrameState} * @readonly * * @private */ frameState : { get: function() { return this._frameState; } }, /** * Gets the collection of tweens taking place in the scene. * @memberof Scene.prototype * * @type {TweenCollection} * @readonly * * @private */ tweens : { get : function() { return this._tweens; } }, /** * Gets the collection of image layers that will be rendered on the globe. * @memberof Scene.prototype * * @type {ImageryLayerCollection} * @readonly */ imageryLayers : { get : function() { return this.globe.imageryLayers; } }, /** * The terrain provider providing surface geometry for the globe. * @memberof Scene.prototype * * @type {TerrainProvider} */ terrainProvider : { get : function() { return this.globe.terrainProvider; }, set : function(terrainProvider) { this.globe.terrainProvider = terrainProvider; } }, /** * Gets the event that will be raised when an error is thrown inside the <code>render</code> function. * The Scene instance and the thrown error are the only two parameters passed to the event handler. * By default, errors are not rethrown after this event is raised, but that can be changed by setting * the <code>rethrowRenderErrors</code> property. * @memberof Scene.prototype * * @type {Event} * @readonly */ renderError : { get : function() { return this._renderError; } }, /** * Gets the event that will be raised at the start of each call to <code>render</code>. Subscribers to the event * receive the Scene instance as the first parameter and the current time as the second parameter. * @memberof Scene.prototype * * @type {Event} * @readonly */ preRender : { get : function() { return this._preRender; } }, /** * Gets the event that will be raised at the end of each call to <code>render</code>. Subscribers to the event * receive the Scene instance as the first parameter and the current time as the second parameter. * @memberof Scene.prototype * * @type {Event} * @readonly */ postRender : { get : function() { return this._postRender; } }, /** * @memberof Scene.prototype * @private * @readonly */ context : { get : function() { return this._context; } }, /** * This property is for debugging only; it is not for production use. * <p> * When {@link Scene.debugShowFrustums} is <code>true</code>, this contains * properties with statistics about the number of command execute per frustum. * <code>totalCommands</code> is the total number of commands executed, ignoring * overlap. <code>commandsInFrustums</code> is an array with the number of times * commands are executed redundantly, e.g., how many commands overlap two or * three frustums. * </p> * * @memberof Scene.prototype * * @type {Object} * @readonly * * @default undefined */ debugFrustumStatistics : { get : function() { return this._debugFrustumStatistics; } }, /** * Gets whether or not the scene is optimized for 3D only viewing. * @memberof Scene.prototype * @type {Boolean} * @readonly */ scene3DOnly : { get : function() { return this._frameState.scene3DOnly; } }, /** * Gets whether or not the scene has order independent translucency enabled. * Note that this only reflects the original construction option, and there are * other factors that could prevent OIT from functioning on a given system configuration. * @memberof Scene.prototype * @type {Boolean} * @readonly */ orderIndependentTranslucency : { get : function() { return defined(this._oit); } }, /** * Gets the unique identifier for this scene. * @memberof Scene.prototype * @type {String} * @readonly */ id : { get : function() { return this._id; } }, /** * Gets or sets the current mode of the scene. * @memberof Scene.prototype * @type {SceneMode} * @default {@link SceneMode.SCENE3D} */ mode : { get : function() { return this._mode; }, set : function(value) { if (this.scene3DOnly && value !== SceneMode.SCENE3D) { throw new DeveloperError('Only SceneMode.SCENE3D is valid when scene3DOnly is true.'); } this._mode = value; } }, /** * Gets the number of frustums used in the last frame. * @memberof Scene.prototype * @type {Number} * * @private */ numberOfFrustums : { get : function() { return this._frustumCommandsList.length; } }, /** * If <code>true</code>, enables Fast Aproximate Anti-aliasing only if order independent translucency * is supported. * @memberof Scene.prototype * @type {Boolean} * @default true * * @deprecated */ fxaaOrderIndependentTranslucency : { get : function() { return this._fxaaOrderIndependentTranslucency; }, set : function(value) { deprecationWarning('Scene.fxaaOrderIndependentTranslucency', 'Scene.fxaaOrderIndependentTranslucency has been deprecated. Use Scene.fxaa instead.'); this._fxaaOrderIndependentTranslucency = value; } } }); var scratchPosition0 = new Cartesian3(); var scratchPosition1 = new Cartesian3(); function maxComponent(a, b) { var x = Math.max(Math.abs(a.x), Math.abs(b.x)); var y = Math.max(Math.abs(a.y), Math.abs(b.y)); var z = Math.max(Math.abs(a.z), Math.abs(b.z)); return Math.max(Math.max(x, y), z); } function cameraEqual(camera0, camera1, epsilon) { var scalar = 1 / Math.max(1, maxComponent(camera0.position, camera1.position)); Cartesian3.multiplyByScalar(camera0.position, scalar, scratchPosition0); Cartesian3.multiplyByScalar(camera1.position, scalar, scratchPosition1); return Cartesian3.equalsEpsilon(scratchPosition0, scratchPosition1, epsilon) && Cartesian3.equalsEpsilon(camera0.direction, camera1.direction, epsilon) && Cartesian3.equalsEpsilon(camera0.up, camera1.up, epsilon) && Cartesian3.equalsEpsilon(camera0.right, camera1.right, epsilon) && Matrix4.equalsEpsilon(camera0.transform, camera1.transform, epsilon); } var scratchOccluderBoundingSphere = new BoundingSphere(); var scratchOccluder; function getOccluder(scene) { // TODO: The occluder is the top-level globe. When we add // support for multiple central bodies, this should be the closest one. var globe = scene.globe; if (scene._mode === SceneMode.SCENE3D && defined(globe)) { var ellipsoid = globe.ellipsoid; scratchOccluderBoundingSphere.radius = ellipsoid.minimumRadius; scratchOccluder = Occluder.fromBoundingSphere(scratchOccluderBoundingSphere, scene._camera.positionWC, scratchOccluder); return scratchOccluder; } return undefined; } function clearPasses(passes) { passes.render = false; passes.pick = false; } function updateFrameState(scene, frameNumber, time) { var camera = scene._camera; var frameState = scene._frameState; frameState.mode = scene._mode; frameState.morphTime = scene.morphTime; frameState.mapProjection = scene.mapProjection; frameState.frameNumber = frameNumber; frameState.time = JulianDate.clone(time, frameState.time); frameState.camera = camera; frameState.cullingVolume = camera.frustum.computeCullingVolume(camera.positionWC, camera.directionWC, camera.upWC); frameState.occluder = getOccluder(scene); clearPasses(frameState.passes); } function updateFrustums(near, far, farToNearRatio, numFrustums, frustumCommandsList) { frustumCommandsList.length = numFrustums; for (var m = 0; m < numFrustums; ++m) { var curNear = Math.max(near, Math.pow(farToNearRatio, m) * near); var curFar = Math.min(far, farToNearRatio * curNear); var frustumCommands = frustumCommandsList[m]; if (!defined(frustumCommands)) { frustumCommands = frustumCommandsList[m] = new FrustumCommands(curNear, curFar); } else { frustumCommands.near = curNear; frustumCommands.far = curFar; } } } function insertIntoBin(scene, command, distance) { if (scene.debugShowFrustums) { command.debugOverlappingFrustums = 0; } var frustumCommandsList = scene._frustumCommandsList; var length = frustumCommandsList.length; for (var i = 0; i < length; ++i) { var frustumCommands = frustumCommandsList[i]; var curNear = frustumCommands.near; var curFar = frustumCommands.far; if (distance.start > curFar) { continue; } if (distance.stop < curNear) { break; } var pass = command instanceof ClearCommand ? Pass.OPAQUE : command.pass; var index = frustumCommands.indices[pass]++; frustumCommands.commands[pass][index] = command; if (scene.debugShowFrustums) { command.debugOverlappingFrustums |= (1 << i); } if (command.executeInClosestFrustum) { break; } } if (scene.debugShowFrustums) { var cf = scene._debugFrustumStatistics.commandsInFrustums; cf[command.debugOverlappingFrustums] = defined(cf[command.debugOverlappingFrustums]) ? cf[command.debugOverlappingFrustums] + 1 : 1; ++scene._debugFrustumStatistics.totalCommands; } } var scratchCullingVolume = new CullingVolume(); var distances = new Interval(); function createPotentiallyVisibleSet(scene) { var commandList = scene._commandList; var overlayList = scene._overlayCommandList; var cullingVolume = scene._frameState.cullingVolume; var camera = scene._camera; var direction = camera.directionWC; var position = camera.positionWC; if (scene.debugShowFrustums) { scene._debugFrustumStatistics = { totalCommands : 0, commandsInFrustums : {} }; } var frustumCommandsList = scene._frustumCommandsList; var numberOfFrustums = frustumCommandsList.length; var numberOfPasses = Pass.NUMBER_OF_PASSES; for (var n = 0; n < numberOfFrustums; ++n) { for (var p = 0; p < numberOfPasses; ++p) { frustumCommandsList[n].indices[p] = 0; } } overlayList.length = 0; var near = Number.MAX_VALUE; var far = Number.MIN_VALUE; var undefBV = false; var occluder; if (scene._frameState.mode === SceneMode.SCENE3D) { occluder = scene._frameState.occluder; } // get user culling volume minus the far plane. var planes = scratchCullingVolume.planes; for (var m = 0; m < 5; ++m) { planes[m] = cullingVolume.planes[m]; } cullingVolume = scratchCullingVolume; var length = commandList.length; for (var i = 0; i < length; ++i) { var command = commandList[i]; var pass = command.pass; if (pass === Pass.OVERLAY) { overlayList.push(command); } else { var boundingVolume = command.boundingVolume; if (defined(boundingVolume)) { if (command.cull && ((cullingVolume.computeVisibility(boundingVolume) === Intersect.OUTSIDE) || (defined(occluder) && !occluder.isBoundingSphereVisible(boundingVolume)))) { continue; } distances = BoundingSphere.computePlaneDistances(boundingVolume, position, direction, distances); near = Math.min(near, distances.start); far = Math.max(far, distances.stop); } else { // Clear commands don't need a bounding volume - just add the clear to all frustums. // If another command has no bounding volume, though, we need to use the camera's // worst-case near and far planes to avoid clipping something important. distances.start = camera.frustum.near; distances.stop = camera.frustum.far; undefBV = !(command instanceof ClearCommand); } insertIntoBin(scene, command, distances); } } if (undefBV) { near = camera.frustum.near; far = camera.frustum.far; } else { // The computed near plane must be between the user defined near and far planes. // The computed far plane must between the user defined far and computed near. // This will handle the case where the computed near plane is further than the user defined far plane. near = Math.min(Math.max(near, camera.frustum.near), camera.frustum.far); far = Math.max(Math.min(far, camera.frustum.far), near); } // Exploit temporal coherence. If the frustums haven't changed much, use the frustums computed // last frame, else compute the new frustums and sort them by frustum again. var farToNearRatio = scene.farToNearRatio; var numFrustums = Math.ceil(Math.log(far / near) / Math.log(farToNearRatio)); if (near !== Number.MAX_VALUE && (numFrustums !== numberOfFrustums || (frustumCommandsList.length !== 0 && (near < frustumCommandsList[0].near || far > frustumCommandsList[numberOfFrustums - 1].far)))) { updateFrustums(near, far, farToNearRatio, numFrustums, frustumCommandsList); createPotentiallyVisibleSet(scene); } } function getAttributeLocations(shaderProgram) { var attributeLocations = {}; var attributes = shaderProgram.vertexAttributes; for (var a in attributes) { if (attributes.hasOwnProperty(a)) { attributeLocations[a] = attributes[a].index; } } return attributeLocations; } function createDebugFragmentShaderProgram(command, scene, shaderProgram) { var context = scene.context; var sp = defaultValue(shaderProgram, command.shaderProgram); var fs = sp.fragmentShaderSource.clone(); fs.sources = fs.sources.map(function(source) { source = source.replace(/void\s+main\s*\(\s*(?:void)?\s*\)/g, 'void czm_Debug_main()'); return source; }); var newMain = 'void main() \n' + '{ \n' + ' czm_Debug_main(); \n'; if (scene.debugShowCommands) { if (!defined(command._debugColor)) { command._debugColor = Color.fromRandom(); } var c = command._debugColor; newMain += ' gl_FragColor.rgb *= vec3(' + c.red + ', ' + c.green + ', ' + c.blue + '); \n'; } if (scene.debugShowFrustums) { // Support up to three frustums. If a command overlaps all // three, it's code is not changed. var r = (command.debugOverlappingFrustums & (1 << 0)) ? '1.0' : '0.0'; var g = (command.debugOverlappingFrustums & (1 << 1)) ? '1.0' : '0.0'; var b = (command.debugOverlappingFrustums & (1 << 2)) ? '1.0' : '0.0'; newMain += ' gl_FragColor.rgb *= vec3(' + r + ', ' + g + ', ' + b + '); \n'; } newMain += '}'; fs.sources.push(newMain); var attributeLocations = getAttributeLocations(sp); return context.createShaderProgram(sp.vertexShaderSource, fs, attributeLocations); } function executeDebugCommand(command, scene, passState, renderState, shaderProgram) { if (defined(command.shaderProgram) || defined(shaderProgram)) { // Replace shader for frustum visualization var sp = createDebugFragmentShaderProgram(command, scene, shaderProgram); command.execute(scene.context, passState, renderState, sp); sp.destroy(); } } var transformFrom2D = new Matrix4(0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0); transformFrom2D = Matrix4.inverseTransformation(transformFrom2D, transformFrom2D); function executeCommand(command, scene, context, passState, renderState, shaderProgram, debugFramebuffer) { if ((defined(scene.debugCommandFilter)) && !scene.debugCommandFilter(command)) { return; } if (scene.debugShowCommands || scene.debugShowFrustums) { executeDebugCommand(command, scene, passState, renderState, shaderProgram); } else { command.execute(context, passState, renderState, shaderProgram); } if (command.debugShowBoundingVolume && (defined(command.boundingVolume))) { // Debug code to draw bounding volume for command. Not optimized! // Assumes bounding volume is a bounding sphere. if (defined(scene._debugSphere)) { scene._debugSphere.destroy(); } var frameState = scene._frameState; var boundingVolume = command.boundingVolume; var radius = boundingVolume.radius; var center = boundingVolume.center; var geometry = GeometryPipeline.toWireframe(EllipsoidGeometry.createGeometry(new EllipsoidGeometry({ radii : new Cartesian3(radius, radius, radius), vertexFormat : PerInstanceColorAppearance.FLAT_VERTEX_FORMAT }))); if (frameState.mode !== SceneMode.SCENE3D) { center = Matrix4.multiplyByPoint(transformFrom2D, center, center); var projection = frameState.mapProjection; var centerCartographic = projection.unproject(center); center = projection.ellipsoid.cartographicToCartesian(centerCartographic); } scene._debugSphere = new Primitive({ geometryInstances : new GeometryInstance({ geometry : geometry, modelMatrix : Matrix4.multiplyByTranslation(Matrix4.IDENTITY, center, new Matrix4()), attributes : { color : new ColorGeometryInstanceAttribute(1.0, 0.0, 0.0, 1.0) } }), appearance : new PerInstanceColorAppearance({ flat : true, translucent : false }), asynchronous : false }); var commandList = []; scene._debugSphere.update(context, frameState, commandList); var framebuffer; if (defined(debugFramebuffer)) { framebuffer = passState.framebuffer; passState.framebuffer = debugFramebuffer; } commandList[0].execute(context, passState); if (defined(framebuffer)) { passState.framebuffer = framebuffer; } } } function isVisible(command, frameState) { if (!defined(command)) { return; } var occluder = (frameState.mode === SceneMode.SCENE3D) ? frameState.occluder: undefined; var cullingVolume = frameState.cullingVolume; // get user culling volume minus the far plane. var planes = scratchCullingVolume.planes; for (var k = 0; k < 5; ++k) { planes[k] = cullingVolume.planes[k]; } cullingVolume = scratchCullingVolume; var boundingVolume = command.boundingVolume; return ((defined(command)) && ((!defined(command.boundingVolume)) || !command.cull || ((cullingVolume.computeVisibility(boundingVolume) !== Intersect.OUTSIDE) && (!defined(occluder) || occluder.isBoundingSphereVisible(boundingVolume))))); } function translucentCompare(a, b, position) { return BoundingSphere.distanceSquaredTo(b.boundingVolume, position) - BoundingSphere.distanceSquaredTo(a.boundingVolume, position); } function executeTranslucentCommandsSorted(scene, executeFunction, passState, commands) { var context = scene.context; mergeSort(commands, translucentCompare, scene._camera.positionWC); var length = commands.length; for (var j = 0; j < length; ++j) { executeFunction(commands[j], scene, context, passState); } } function getDebugGlobeDepth(scene, index) { var globeDepth = scene._debugGlobeDepths[index]; if (!defined(globeDepth) && scene.context.depthTexture) { globeDepth = new GlobeDepth(); scene._debugGlobeDepths[index] = globeDepth; } return globeDepth; } function getPickDepth(scene, index) { var pickDepth = scene._pickDepths[index]; if (!defined(pickDepth)) { pickDepth = new PickDepth(); scene._pickDepths[index] = pickDepth; } return pickDepth; } var scratchPerspectiveFrustum = new PerspectiveFrustum(); var scratchPerspectiveOffCenterFrustum = new PerspectiveOffCenterFrustum(); var scratchOrthographicFrustum = new OrthographicFrustum(); function executeCommands(scene, passState, clearColor, picking) { var i; var j; var frameState = scene._frameState; var camera = scene._camera; var context = scene.context; var us = context.uniformState; // Manage sun bloom post-processing effect. if (defined(scene.sun) && scene.sunBloom !== scene._sunBloom) { if (scene.sunBloom) { scene._sunPostProcess = new SunPostProcess(); } else if(defined(scene._sunPostProcess)){ scene._sunPostProcess = scene._sunPostProcess.destroy(); } scene._sunBloom = scene.sunBloom; } else if (!defined(scene.sun) && defined(scene._sunPostProcess)) { scene._sunPostProcess = scene._sunPostProcess.destroy(); scene._sunBloom = false; } // Manage celestial and terrestrial environment effects. var renderPass = frameState.passes.render; var skyBoxCommand = (renderPass && defined(scene.skyBox)) ? scene.skyBox.update(context, frameState) : undefined; var skyAtmosphereCommand = (renderPass && defined(scene.skyAtmosphere)) ? scene.skyAtmosphere.update(context, frameState) : undefined; var sunCommand = (renderPass && defined(scene.sun)) ? scene.sun.update(scene) : undefined; var sunVisible = isVisible(sunCommand, frameState); var moonCommand = (renderPass && defined(scene.moon)) ? scene.moon.update(context, frameState) : undefined; var moonVisible = isVisible(moonCommand, frameState); // Preserve the reference to the original framebuffer. var originalFramebuffer = passState.framebuffer; // Create a working frustum from the original camera frustum. var frustum; if (defined(camera.frustum.fov)) { frustum = camera.frustum.clone(scratchPerspectiveFrustum); } else if (defined(camera.frustum.infiniteProjectionMatrix)){ frustum = camera.frustum.clone(scratchPerspectiveOffCenterFrustum); } else { frustum = camera.frustum.clone(scratchOrthographicFrustum); } // Clear the pass state framebuffer. var clear = scene._clearColorDepthCommand; Color.clone(clearColor, clear.color); clear.execute(context, passState); // Update globe depth rendering based on the current context and clear the globe depth framebuffer. if (defined(scene._globeDepth)) { scene._globeDepth.update(context); scene._globeDepth.clear(context, passState, clearColor); } // Determine if there are any translucent surfaces in any of the frustums. var renderTranslucentCommands = false; var frustumCommandsList = scene._frustumCommandsList; var numFrustums = frustumCommandsList.length; for (i = 0; i < numFrustums; ++i) { if (frustumCommandsList[i].indices[Pass.TRANSLUCENT] > 0) { renderTranslucentCommands = true; break; } } // If supported, configure OIT to use the globe depth framebuffer and clear the OIT framebuffer. var useOIT = !picking && renderTranslucentCommands && defined(scene._oit) && scene._oit.isSupported(); if (useOIT) { scene._oit.update(context, scene._globeDepth.framebuffer); scene._oit.clear(context, passState, clearColor); useOIT = useOIT && scene._oit.isSupported(); } // If supported, configure FXAA to use the globe depth color texture and clear the FXAA framebuffer. var useFXAA = !picking && scene.fxaa; if (useFXAA) { var fxaaTexture = !useOIT && defined(scene._globeDepth) ? scene._globeDepth._colorTexture : undefined; scene._fxaa.update(context, fxaaTexture); scene._fxaa.clear(context, passState, clearColor); } if (sunVisible && scene.sunBloom) { passState.framebuffer = scene._sunPostProcess.update(context); } else if (defined(scene._globeDepth)) { passState.framebuffer = scene._globeDepth.framebuffer; } else if (useFXAA) { passState.framebuffer = scene._fxaa.getColorFramebuffer(); } if (defined(passState.framebuffer)) { clear.execute(context, passState); } // Ideally, we would render the sky box and atmosphere last for // early-z, but we would have to draw it in each frustum frustum.near = camera.frustum.near; frustum.far = camera.frustum.far; us.updateFrustum(frustum); if (defined(skyBoxCommand)) { executeCommand(skyBoxCommand, scene, context, passState); } if (defined(skyAtmosphereCommand)) { executeCommand(skyAtmosphereCommand, scene, context, passState); } if (sunVisible) { sunCommand.execute(context, passState); if (scene.sunBloom) { var framebuffer; if (defined(scene._globeDepth)) { framebuffer = scene._globeDepth.framebuffer; } else if (scene.fxaa) { framebuffer = scene._fxaa.getColorFramebuffer(); } else { framebuffer = originalFramebuffer; } scene._sunPostProcess.execute(context, framebuffer); passState.framebuffer = framebuffer; } } // Moon can be seen through the atmosphere, since the sun is rendered after the atmosphere. if (moonVisible) { moonCommand.execute(context, passState); } // Determine how translucent surfaces will be handled. var executeTranslucentCommands; if (useOIT) { if (!defined(scene._executeOITFunction)) { scene._executeOITFunction = function(scene, executeFunction, passState, commands) { scene._oit.executeCommands(scene, executeFunction, passState, commands); }; } executeTranslucentCommands = scene._executeOITFunction; } else { executeTranslucentCommands = executeTranslucentCommandsSorted; } // Execute commands in each frustum in back to front order var clearDepth = scene._depthClearCommand; for (i = 0; i < numFrustums; ++i) { var index = numFrustums - i - 1; var frustumCommands = frustumCommandsList[index]; frustum.near = frustumCommands.near; frustum.far = frustumCommands.far; if (index !== 0) { // Avoid tearing artifacts between adjacent frustums in the opaque passes frustum.near *= OPAQUE_FRUSTUM_NEAR_OFFSET; } var globeDepth = scene.debugShowGlobeDepth ? getDebugGlobeDepth(scene, index) : scene._globeDepth; var fb; if (scene.debugShowGlobeDepth && defined(globeDepth)) { fb = passState.framebuffer; passState.framebuffer = globeDepth.framebuffer; } us.updateFrustum(frustum); clearDepth.execute(context, passState); var commands = frustumCommands.commands[Pass.GLOBE]; var length = frustumCommands.indices[Pass.GLOBE]; for (j = 0; j < length; ++j) { executeCommand(commands[j], scene, context, passState); } if (defined(globeDepth) && (scene.copyGlobeDepth || scene.debugShowGlobeDepth)) { globeDepth.update(context); globeDepth.executeCopyDepth(context, passState); } if (scene.debugShowGlobeDepth && defined(globeDepth)) { passState.framebuffer = fb; } // Execute commands in order by pass up to the translucent pass. // Translucent geometry needs special handling (sorting/OIT). var startPass = Pass.GLOBE + 1; var endPass = Pass.TRANSLUCENT; for (var pass = startPass; pass < endPass; ++pass) { commands = frustumCommands.commands[pass]; length = frustumCommands.indices[pass]; for (j = 0; j < length; ++j) { executeCommand(commands[j], scene, context, passState); } } if (index !== 0) { // Do not overlap frustums in the translucent pass to avoid blending artifacts frustum.near = frustumCommands.near; us.updateFrustum(frustum); } commands = frustumCommands.commands[Pass.TRANSLUCENT]; commands.length = frustumCommands.indices[Pass.TRANSLUCENT]; executeTranslucentCommands(scene, executeCommand, passState, commands); if (defined(globeDepth)) { // PERFORMANCE_IDEA: Use MRT to avoid the extra copy. var pickDepth = getPickDepth(scene, index); pickDepth.update(context, globeDepth.framebuffer.depthStencilTexture); pickDepth.executeCopyDepth(context, passState); } } if (scene.debugShowGlobeDepth && defined(scene._globeDepth)) { var gd = getDebugGlobeDepth(scene, scene.debugShowDepthFrustum - 1); gd.executeDebugGlobeDepth(context, passState); } if (scene.debugShowPickDepth && defined(scene._globeDepth)) { var pd = getPickDepth(scene, scene.debugShowDepthFrustum - 1); pd.executeDebugPickDepth(context, passState); } if (useOIT) { passState.framebuffer = useFXAA ? scene._fxaa.getColorFramebuffer() : undefined; scene._oit.execute(context, passState); } if (useFXAA) { passState.framebuffer = originalFramebuffer; scene._fxaa.execute(context, passState); } if (!useOIT && !useFXAA && defined(scene._globeDepth)) { passState.framebuffer = originalFramebuffer; scene._globeDepth.executeCopyColor(context, passState); } } function executeOverlayCommands(scene, passState) { var context = scene.context; var commandList = scene._overlayCommandList; var length = commandList.length; for (var i = 0; i < length; ++i) { commandList[i].execute(context, passState); } } function updatePrimitives(scene) { var context = scene.context; var frameState = scene._frameState; var commandList = scene._commandList; if (scene._globe) { scene._globe.update(context, frameState, commandList); } scene._primitives.update(context, frameState, commandList); } function callAfterRenderFunctions(frameState) { // Functions are queued up during primitive update and executed here in case // the function modifies scene state that should remain constant over the frame. var functions = frameState.afterRender; for (var i = 0, length = functions.length; i < length; ++i) { functions[i](); } functions.length = 0; } /** * @private */ Scene.prototype.initializeFrame = function() { // Destroy released shaders once every 120 frames to avoid thrashing the cache if (this._shaderFrameCount++ === 120) { this._shaderFrameCount = 0; this._context.shaderCache.destroyReleasedShaderPrograms(); } this._tweens.update(); this._camera.update(this._mode); this._screenSpaceCameraController.update(); }; function render(scene, time) { if (!defined(time)) { time = JulianDate.now(); } var camera = scene._camera; if (!cameraEqual(camera, scene._cameraClone, CesiumMath.EPSILON6)) { if (!scene._cameraStartFired) { camera.moveStart.raiseEvent(); scene._cameraStartFired = true; } scene._cameraMovedTime = getTimestamp(); Camera.clone(camera, scene._cameraClone); } else if (scene._cameraStartFired && getTimestamp() - scene._cameraMovedTime > scene.cameraEventWaitTime) { camera.moveEnd.raiseEvent(); scene._cameraStartFired = false; } scene._preRender.raiseEvent(scene, time); var us = scene.context.uniformState; var frameState = scene._frameState; var frameNumber = CesiumMath.incrementWrap(frameState.frameNumber, 15000000.0, 1.0); updateFrameState(scene, frameNumber, time); frameState.passes.render = true; frameState.creditDisplay.beginFrame(); var context = scene.context; us.update(context, frameState); scene._commandList.length = 0; scene._overlayCommandList.length = 0; updatePrimitives(scene); createPotentiallyVisibleSet(scene); var passState = scene._passState; passState.framebuffer = undefined; passState.blendingEnabled = undefined; passState.scissorTest = undefined; executeCommands(scene, passState, defaultValue(scene.backgroundColor, Color.BLACK)); executeOverlayCommands(scene, passState); frameState.creditDisplay.endFrame(); if (scene.debugShowFramesPerSecond) { if (!defined(scene._performanceDisplay)) { var performanceContainer = document.createElement('div'); performanceContainer.className = 'cesium-performanceDisplay'; performanceContainer.style.position = 'absolute'; performanceContainer.style.top = '50px'; performanceContainer.style.right = '10px'; var container = scene._canvas.parentNode; container.appendChild(performanceContainer); var performanceDisplay = new PerformanceDisplay({container: performanceContainer}); scene._performanceDisplay = performanceDisplay; scene._performanceContainer = performanceContainer; } scene._performanceDisplay.update(); } else if (defined(scene._performanceDisplay)) { scene._performanceDisplay = scene._performanceDisplay && scene._performanceDisplay.destroy(); scene._performanceContainer.parentNode.removeChild(scene._performanceContainer); } context.endFrame(); callAfterRenderFunctions(frameState); scene._postRender.raiseEvent(scene, time); } /** * @private */ Scene.prototype.render = function(time) { try { render(this, time); } catch (error) { this._renderError.raiseEvent(this, error); if (this.rethrowRenderErrors) { throw error; } } }; /** * @private */ Scene.prototype.clampLineWidth = function(width) { var context = this._context; return Math.max(context.minimumAliasedLineWidth, Math.min(width, context.maximumAliasedLineWidth)); }; var orthoPickingFrustum = new OrthographicFrustum(); var scratchOrigin = new Cartesian3(); var scratchDirection = new Cartesian3(); var scratchBufferDimensions = new Cartesian2(); var scratchPixelSize = new Cartesian2(); var scratchPickVolumeMatrix4 = new Matrix4(); function getPickOrthographicCullingVolume(scene, drawingBufferPosition, width, height) { var camera = scene._camera; var frustum = camera.frustum; var drawingBufferWidth = scene.drawingBufferWidth; var drawingBufferHeight = scene.drawingBufferHeight; var x = (2.0 / drawingBufferWidth) * drawingBufferPosition.x - 1.0; x *= (frustum.right - frustum.left) * 0.5; var y = (2.0 / drawingBufferHeight) * (drawingBufferHeight - drawingBufferPosition.y) - 1.0; y *= (frustum.top - frustum.bottom) * 0.5; var transform = Matrix4.clone(camera.transform, scratchPickVolumeMatrix4); camera._setTransform(Matrix4.IDENTITY); var origin = Cartesian3.clone(camera.position, scratchOrigin); Cartesian3.multiplyByScalar(camera.right, x, scratchDirection); Cartesian3.add(scratchDirection, origin, origin); Cartesian3.multiplyByScalar(camera.up, y, scratchDirection); Cartesian3.add(scratchDirection, origin, origin); camera._setTransform(transform); Cartesian3.fromElements(origin.z, origin.x, origin.y, origin); scratchBufferDimensions.x = drawingBufferWidth; scratchBufferDimensions.y = drawingBufferHeight; var pixelSize = frustum.getPixelSize(scratchBufferDimensions, undefined, scratchPixelSize); var ortho = orthoPickingFrustum; ortho.right = pixelSize.x * 0.5; ortho.left = -ortho.right; ortho.top = pixelSize.y * 0.5; ortho.bottom = -ortho.top; ortho.near = frustum.near; ortho.far = frustum.far; return ortho.computeCullingVolume(origin, camera.directionWC, camera.upWC); } var perspPickingFrustum = new PerspectiveOffCenterFrustum(); function getPickPerspectiveCullingVolume(scene, drawingBufferPosition, width, height) { var camera = scene._camera; var frustum = camera.frustum; var near = frustum.near; var drawingBufferWidth = scene.drawingBufferWidth; var drawingBufferHeight = scene.drawingBufferHeight; var tanPhi = Math.tan(frustum.fovy * 0.5); var tanTheta = frustum.aspectRatio * tanPhi; var x = (2.0 / drawingBufferWidth) * drawingBufferPosition.x - 1.0; var y = (2.0 / drawingBufferHeight) * (drawingBufferHeight - drawingBufferPosition.y) - 1.0; var xDir = x * near * tanTheta; var yDir = y * near * tanPhi; scratchBufferDimensions.x = drawingBufferWidth; scratchBufferDimensions.y = drawingBufferHeight; var pixelSize = frustum.getPixelSize(scratchBufferDimensions, undefined, scratchPixelSize); var pickWidth = pixelSize.x * width * 0.5; var pickHeight = pixelSize.y * height * 0.5; var offCenter = perspPickingFrustum; offCenter.top = yDir + pickHeight; offCenter.bottom = yDir - pickHeight; offCenter.right = xDir + pickWidth; offCenter.left = xDir - pickWidth; offCenter.near = near; offCenter.far = frustum.far; return offCenter.computeCullingVolume(camera.positionWC, camera.directionWC, camera.upWC); } function getPickCullingVolume(scene, drawingBufferPosition, width, height) { if (scene._mode === SceneMode.SCENE2D) { return getPickOrthographicCullingVolume(scene, drawingBufferPosition, width, height); } return getPickPerspectiveCullingVolume(scene, drawingBufferPosition, width, height); } // pick rectangle width and height, assumed odd var rectangleWidth = 3.0; var rectangleHeight = 3.0; var scratchRectangle = new BoundingRectangle(0.0, 0.0, rectangleWidth, rectangleHeight); var scratchColorZero = new Color(0.0, 0.0, 0.0, 0.0); var scratchPosition = new Cartesian2(); /** * Returns an object with a `primitive` property that contains the first (top) primitive in the scene * at a particular window coordinate or undefined if nothing is at the location. Other properties may * potentially be set depending on the type of primitive. * * @param {Cartesian2} windowPosition Window coordinates to perform picking on. * @returns {Object} Object containing the picked primitive. * * @exception {DeveloperError} windowPosition is undefined. */ Scene.prototype.pick = function(windowPosition) { //>>includeStart('debug', pragmas.debug); if(!defined(windowPosition)) { throw new DeveloperError('windowPosition is undefined.'); } //>>includeEnd('debug'); var context = this._context; var us = context.uniformState; var frameState = this._frameState; var drawingBufferPosition = SceneTransforms.transformWindowToDrawingBuffer(this, windowPosition, scratchPosition); if (!defined(this._pickFramebuffer)) { this._pickFramebuffer = context.createPickFramebuffer(); } // Update with previous frame's number and time, assuming that render is called before picking. updateFrameState(this, frameState.frameNumber, frameState.time); frameState.cullingVolume = getPickCullingVolume(this, drawingBufferPosition, rectangleWidth, rectangleHeight); frameState.passes.pick = true; us.update(context, frameState); this._commandList.length = 0; updatePrimitives(this); createPotentiallyVisibleSet(this); scratchRectangle.x = drawingBufferPosition.x - ((rectangleWidth - 1.0) * 0.5); scratchRectangle.y = (this.drawingBufferHeight - drawingBufferPosition.y) - ((rectangleHeight - 1.0) * 0.5); executeCommands(this, this._pickFramebuffer.begin(scratchRectangle), scratchColorZero, true); var object = this._pickFramebuffer.end(scratchRectangle); context.endFrame(); callAfterRenderFunctions(frameState); return object; }; var scratchPickDepthPosition = new Cartesian3(); var scratchMinDistPos = new Cartesian3(); var scratchPackedDepth = new Cartesian4(); var packedDepthScale = new Cartesian4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0); /** * Returns the cartesian position reconstructed from the depth buffer and window position. * * @param {Cartesian2} windowPosition Window coordinates to perform picking on. * @param {Cartesian3} [result] The object on which to restore the result. * @returns {Cartesian3} The cartesian position. * * @exception {DeveloperError} Picking from the depth buffer is not supported. Check pickPositionSupported. * @exception {DeveloperError} 2D is not supported. An orthographic projection matrix is not invertible. */ Scene.prototype.pickPosition = function(windowPosition, result) { //>>includeStart('debug', pragmas.debug); if(!defined(windowPosition)) { throw new DeveloperError('windowPosition is undefined.'); } if (!defined(this._globeDepth)) { throw new DeveloperError('Picking from the depth buffer is not supported. Check pickPositionSupported.'); } //>>includeEnd('debug'); var context = this._context; var uniformState = context.uniformState; var drawingBufferPosition = SceneTransforms.transformWindowToDrawingBuffer(this, windowPosition, scratchPosition); drawingBufferPosition.y = this.drawingBufferHeight - drawingBufferPosition.y; var camera = this._camera; // Create a working frustum from the original camera frustum. var frustum; if (defined(camera.frustum.fov)) { frustum = camera.frustum.clone(scratchPerspectiveFrustum); } else if (defined(camera.frustum.infiniteProjectionMatrix)){ frustum = camera.frustum.clone(scratchPerspectiveOffCenterFrustum); } else { //>>includeStart('debug', pragmas.debug); throw new DeveloperError('2D is not supported. An orthographic projection matrix is not invertible.'); //>>includeEnd('debug'); } var minimumPosition; var minDistance; var numFrustums = this.numberOfFrustums; for (var i = 0; i < numFrustums; ++i) { var pickDepth = getPickDepth(this, i); var pixels = context.readPixels({ x : drawingBufferPosition.x, y : drawingBufferPosition.y, width : 1, height : 1, framebuffer : pickDepth.framebuffer }); var packedDepth = Cartesian4.unpack(pixels, 0, scratchPackedDepth); Cartesian4.divideByScalar(packedDepth, 255.0, packedDepth); var depth = Cartesian4.dot(packedDepth, packedDepthScale); if (depth > 0.0 && depth < 1.0) { var renderedFrustum = this._frustumCommandsList[i]; frustum.near = renderedFrustum.near; frustum.far = renderedFrustum.far; uniformState.updateFrustum(frustum); var position = SceneTransforms.drawingBufferToWgs84Coordinates(this, drawingBufferPosition, depth, scratchPickDepthPosition); var distance = Cartesian3.distance(position, camera.positionWC); if (!defined(minimumPosition) || distance < minDistance) { minimumPosition = Cartesian3.clone(position, result); minDistance = distance; } } } return minimumPosition; }; /** * Returns a list of objects, each containing a `primitive` property, for all primitives at * a particular window coordinate position. Other properties may also be set depending on the * type of primitive. The primitives in the list are ordered by their visual order in the * scene (front to back). * * @param {Cartesian2} windowPosition Window coordinates to perform picking on. * @param {Number} [limit] If supplied, stop drilling after collecting this many picks. * @returns {Object[]} Array of objects, each containing 1 picked primitives. * * @exception {DeveloperError} windowPosition is undefined. * * @example * var pickedObjects = Cesium.Scene.drillPick(new Cesium.Cartesian2(100.0, 200.0)); */ Scene.prototype.drillPick = function(windowPosition, limit) { // PERFORMANCE_IDEA: This function calls each primitive's update for each pass. Instead // we could update the primitive once, and then just execute their commands for each pass, // and cull commands for picked primitives. e.g., base on the command's owner. //>>includeStart('debug', pragmas.debug); if (!defined(windowPosition)) { throw new DeveloperError('windowPosition is undefined.'); } //>>includeEnd('debug'); var i; var attributes; var result = []; var pickedPrimitives = []; var pickedAttributes = []; if (!defined(limit)) { limit = Number.MAX_VALUE; } var pickedResult = this.pick(windowPosition); while (defined(pickedResult) && defined(pickedResult.primitive)) { result.push(pickedResult); if (0 >= --limit) { break; } var primitive = pickedResult.primitive; var hasShowAttribute = false; //If the picked object has a show attribute, use it. if (typeof primitive.getGeometryInstanceAttributes === 'function') { if (defined(pickedResult.id)) { attributes = primitive.getGeometryInstanceAttributes(pickedResult.id); if (defined(attributes) && defined(attributes.show)) { hasShowAttribute = true; attributes.show = ShowGeometryInstanceAttribute.toValue(false, attributes.show); pickedAttributes.push(attributes); } } } //Otherwise, hide the entire primitive if (!hasShowAttribute) { primitive.show = false; pickedPrimitives.push(primitive); } pickedResult = this.pick(windowPosition); } // unhide everything we hid while drill picking for (i = 0; i < pickedPrimitives.length; ++i) { pickedPrimitives[i].show = true; } for (i = 0; i < pickedAttributes.length; ++i) { attributes = pickedAttributes[i]; attributes.show = ShowGeometryInstanceAttribute.toValue(true, attributes.show); } return result; }; /** * Instantly completes an active transition. */ Scene.prototype.completeMorph = function(){ this._transitioner.completeMorph(); }; /** * Asynchronously transitions the scene to 2D. * @param {Number} [duration=2.0] The amount of time, in seconds, for transition animations to complete. */ Scene.prototype.morphTo2D = function(duration) { var ellipsoid; var globe = this.globe; if (defined(globe)) { ellipsoid = globe.ellipsoid; } else { ellipsoid = this.mapProjection.ellipsoid; } duration = defaultValue(duration, 2.0); this._transitioner.morphTo2D(duration, ellipsoid); }; /** * Asynchronously transitions the scene to Columbus View. * @param {Number} [duration=2.0] The amount of time, in seconds, for transition animations to complete. */ Scene.prototype.morphToColumbusView = function(duration) { var ellipsoid; var globe = this.globe; if (defined(globe)) { ellipsoid = globe.ellipsoid; } else { ellipsoid = this.mapProjection.ellipsoid; } duration = defaultValue(duration, 2.0); this._transitioner.morphToColumbusView(duration, ellipsoid); }; /** * Asynchronously transitions the scene to 3D. * @param {Number} [duration=2.0] The amount of time, in seconds, for transition animations to complete. */ Scene.prototype.morphTo3D = function(duration) { var ellipsoid; var globe = this.globe; if (defined(globe)) { ellipsoid = globe.ellipsoid; } else { ellipsoid = this.mapProjection.ellipsoid; } duration = defaultValue(duration, 2.0); this._transitioner.morphTo3D(duration, ellipsoid); }; /** * Returns true if this object was destroyed; otherwise, false. * <br /><br /> * If this object was destroyed, it should not be used; calling any function other than * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. * * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>. * * @see Scene#destroy */ Scene.prototype.isDestroyed = function() { return false; }; /** * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic * release of WebGL resources, instead of relying on the garbage collector to destroy this object. * <br /><br /> * Once an object is destroyed, it should not be used; calling any function other than * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore, * assign the return value (<code>undefined</code>) to the object as done in the example. * * @returns {undefined} * * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called. * * @see Scene#isDestroyed * * @example * scene = scene && scene.destroy(); */ Scene.prototype.destroy = function() { this._tweens.removeAll(); this._screenSpaceCameraController = this._screenSpaceCameraController && this._screenSpaceCameraController.destroy(); this._pickFramebuffer = this._pickFramebuffer && this._pickFramebuffer.destroy(); this._primitives = this._primitives && this._primitives.destroy(); this._globe = this._globe && this._globe.destroy(); this.skyBox = this.skyBox && this.skyBox.destroy(); this.skyAtmosphere = this.skyAtmosphere && this.skyAtmosphere.destroy(); this._debugSphere = this._debugSphere && this._debugSphere.destroy(); this.sun = this.sun && this.sun.destroy(); this._sunPostProcess = this._sunPostProcess && this._sunPostProcess.destroy(); this._transitioner.destroy(); this._globeDepth.destroy(); if (defined(this._oit)) { this._oit.destroy(); } this._fxaa.destroy(); this._context = this._context && this._context.destroy(); this._frameState.creditDisplay.destroy(); if (defined(this._performanceDisplay)){ this._performanceDisplay = this._performanceDisplay && this._performanceDisplay.destroy(); this._performanceContainer.parentNode.removeChild(this._performanceContainer); } return destroyObject(this); }; return Scene; });
Revert clear command.
Source/Scene/Scene.js
Revert clear command.
<ide><path>ource/Scene/Scene.js <ide> this._oit = oit; <ide> this._fxaa = new FXAA(); <ide> <del> this._clearColorDepthCommand = new ClearCommand({ <add> this._clearColorCommand = new ClearCommand({ <ide> color : new Color(), <del> depth : 1.0, <ide> owner : this <ide> }); <ide> this._depthClearCommand = new ClearCommand({ <ide> } <ide> <ide> // Clear the pass state framebuffer. <del> var clear = scene._clearColorDepthCommand; <add> var clear = scene._clearColorCommand; <ide> Color.clone(clearColor, clear.color); <ide> clear.execute(context, passState); <ide>
Java
apache-2.0
b215bbdc42cb50cc79fc3d4581c5f960f96f1066
0
AxonFramework/AxonFramework,krosenvold/AxonFramework
/* * Copyright (c) 2010-2020. Axon Framework * * 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.axonframework.eventhandling.gateway; import org.axonframework.eventhandling.EventBus; import org.axonframework.eventhandling.EventMessage; import org.axonframework.messaging.Message; import org.axonframework.messaging.reactive.ReactorMessageDispatchInterceptorSupport; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import java.util.Arrays; import java.util.List; /** * Variation of the {@link EventGateway}, wrapping a {@link EventBus} for a friendlier API. Provides support for reactive return types such as {@link Flux} from Project * Reactor. * * @author Milan Savic * @since 4.4 */ public interface ReactorEventGateway extends ReactorMessageDispatchInterceptorSupport<EventMessage<?>> { /** * Publishes given {@code events} once the caller subscribes to the resulting Flux. Returns immediately. * <p/> * Given {@code events} are wrapped as payloads of a {@link EventMessage} that are eventually published on the * {@link EventBus}, unless {@code event} already implements {@link Message}. In that case, a {@code EventMessage} * is constructed from that message's payload and {@link org.axonframework.messaging.MetaData}. * * @param events events to be published * @return events that were published. DO NOTE: if there were some interceptors registered to this {@code gateway}, * they will be processed first, before returning events to the caller. The order of returned events is the same as * one provided as the input parameter. */ default Flux<Object> publish(Object... events) { // NOSONAR return publish(Arrays.asList(events)); } /** * Publishes given {@code events} once the caller subscribes to the resulting Flux. Returns immediately. * <p/> * Given {@code events} are wrapped as payloads of a {@link EventMessage} that are eventually published on the * {@link EventBus}, unless {@code event} already implements {@link Message}. In that case, a {@code EventMessage} * is constructed from that message's payload and {@link org.axonframework.messaging.MetaData}. * * @param events the list of events to be published * @return events that were published. DO NOTE: if there were some interceptors registered to this {@code gateway}, * they will be processed first, before returning events to the caller. The order of returned events is the same as * one provided as the input parameter. */ Flux<Object> publish(List<?> events); /** * Publishes given {@code events} once the caller subscribes to the resulting Flux. Returns immediately. * <p/> * Given {@code events} are wrapped as payloads of a {@link EventMessage} that are eventually published on the * {@link EventBus}, unless {@code event} already implements {@link Message}. In that case, a {@code EventMessage} * is constructed from that message's payload and {@link org.axonframework.messaging.MetaData}. * * @param events the publisher of events to be published * @return events that were published. DO NOTE: if there were some interceptors registered to this {@code gateway}, * they will be processed first, before returning events to the caller. The order of returned events is the same as * one provided as the input parameter. */ default Flux<Object> publishAll(Publisher<?> events) { return Flux.from(events) .concatMap(this::publish); } }
messaging/src/main/java/org/axonframework/eventhandling/gateway/ReactorEventGateway.java
/* * Copyright (c) 2010-2020. Axon Framework * * 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.axonframework.eventhandling.gateway; import org.axonframework.eventhandling.EventBus; import org.axonframework.eventhandling.EventMessage; import org.axonframework.messaging.Message; import org.axonframework.messaging.reactive.ReactorMessageDispatchInterceptorSupport; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import java.util.Arrays; import java.util.List; /** * Variation of {@link EventGateway}. Provides support for reactive return types such as {@link Flux} from Project * Reactor. * * @author Milan Savic * @since 4.4 */ public interface ReactorEventGateway extends ReactorMessageDispatchInterceptorSupport<EventMessage<?>> { /** * Publishes given {@code events} once the caller subscribes to the resulting Flux. Returns immediately. * <p/> * Given {@code events} are wrapped as payloads of a {@link EventMessage} that are eventually published on the * {@link EventBus}, unless {@code event} already implements {@link Message}. In that case, a {@code EventMessage} * is constructed from that message's payload and {@link org.axonframework.messaging.MetaData}. * * @param events events to be published * @return events that were published. DO NOTE: if there were some interceptors registered to this {@code gateway}, * they will be processed first, before returning events to the caller. The order of returned events is the same as * one provided as the input parameter. */ default Flux<Object> publish(Object... events) { // NOSONAR return publish(Arrays.asList(events)); } /** * Publishes given {@code events} once the caller subscribes to the resulting Flux. Returns immediately. * <p/> * Given {@code events} are wrapped as payloads of a {@link EventMessage} that are eventually published on the * {@link EventBus}, unless {@code event} already implements {@link Message}. In that case, a {@code EventMessage} * is constructed from that message's payload and {@link org.axonframework.messaging.MetaData}. * * @param events the list of events to be published * @return events that were published. DO NOTE: if there were some interceptors registered to this {@code gateway}, * they will be processed first, before returning events to the caller. The order of returned events is the same as * one provided as the input parameter. */ Flux<Object> publish(List<?> events); /** * Publishes given {@code events} once the caller subscribes to the resulting Flux. Returns immediately. * <p/> * Given {@code events} are wrapped as payloads of a {@link EventMessage} that are eventually published on the * {@link EventBus}, unless {@code event} already implements {@link Message}. In that case, a {@code EventMessage} * is constructed from that message's payload and {@link org.axonframework.messaging.MetaData}. * * @param events the publisher of events to be published * @return events that were published. DO NOTE: if there were some interceptors registered to this {@code gateway}, * they will be processed first, before returning events to the caller. The order of returned events is the same as * one provided as the input parameter. */ default Flux<Object> publishAll(Publisher<?> events) { return Flux.from(events) .concatMap(this::publish); } }
Update messaging/src/main/java/org/axonframework/eventhandling/gateway/ReactorEventGateway.java Co-authored-by: Steven van Beelen <[email protected]>
messaging/src/main/java/org/axonframework/eventhandling/gateway/ReactorEventGateway.java
Update messaging/src/main/java/org/axonframework/eventhandling/gateway/ReactorEventGateway.java
<ide><path>essaging/src/main/java/org/axonframework/eventhandling/gateway/ReactorEventGateway.java <ide> import java.util.List; <ide> <ide> /** <del> * Variation of {@link EventGateway}. Provides support for reactive return types such as {@link Flux} from Project <add> * Variation of the {@link EventGateway}, wrapping a {@link EventBus} for a friendlier API. Provides support for reactive return types such as {@link Flux} from Project <ide> * Reactor. <ide> * <ide> * @author Milan Savic
Java
apache-2.0
14cf129644bb18bfde3b4acd78fdab7b7de76a21
0
kchodorow/bazel,iamthearm/bazel,dropbox/bazel,UrbanCompass/bazel,safarmer/bazel,aehlig/bazel,UrbanCompass/bazel,davidzchen/bazel,davidzchen/bazel,mrdomino/bazel,hermione521/bazel,damienmg/bazel,safarmer/bazel,dslomov/bazel-windows,LuminateWireless/bazel,dslomov/bazel,perezd/bazel,mikelikespie/bazel,ButterflyNetwork/bazel,katre/bazel,damienmg/bazel,davidzchen/bazel,meteorcloudy/bazel,ulfjack/bazel,dropbox/bazel,dropbox/bazel,abergmeier-dsfishlabs/bazel,ulfjack/bazel,variac/bazel,bazelbuild/bazel,meteorcloudy/bazel,twitter-forks/bazel,cushon/bazel,damienmg/bazel,hermione521/bazel,snnn/bazel,akira-baruah/bazel,safarmer/bazel,juhalindfors/bazel-patches,LuminateWireless/bazel,ulfjack/bazel,UrbanCompass/bazel,hermione521/bazel,anupcshan/bazel,LuminateWireless/bazel,anupcshan/bazel,anupcshan/bazel,iamthearm/bazel,cushon/bazel,davidzchen/bazel,ButterflyNetwork/bazel,snnn/bazel,Asana/bazel,meteorcloudy/bazel,mrdomino/bazel,twitter-forks/bazel,dslomov/bazel,katre/bazel,anupcshan/bazel,bazelbuild/bazel,juhalindfors/bazel-patches,mikelalcon/bazel,meteorcloudy/bazel,ulfjack/bazel,dslomov/bazel-windows,zhexuany/bazel,ulfjack/bazel,mikelikespie/bazel,kchodorow/bazel,dslomov/bazel,snnn/bazel,snnn/bazel,dslomov/bazel,ButterflyNetwork/bazel,perezd/bazel,abergmeier-dsfishlabs/bazel,davidzchen/bazel,aehlig/bazel,safarmer/bazel,variac/bazel,twitter-forks/bazel,LuminateWireless/bazel,mikelalcon/bazel,aehlig/bazel,dropbox/bazel,zhexuany/bazel,mikelikespie/bazel,mikelikespie/bazel,mrdomino/bazel,zhexuany/bazel,damienmg/bazel,mikelalcon/bazel,dslomov/bazel,mbrukman/bazel,meteorcloudy/bazel,kchodorow/bazel-1,whuwxl/bazel,Asana/bazel,cushon/bazel,werkt/bazel,perezd/bazel,dslomov/bazel-windows,perezd/bazel,spxtr/bazel,dropbox/bazel,hermione521/bazel,hermione521/bazel,Asana/bazel,abergmeier-dsfishlabs/bazel,damienmg/bazel,akira-baruah/bazel,bazelbuild/bazel,juhalindfors/bazel-patches,mbrukman/bazel,spxtr/bazel,snnn/bazel,damienmg/bazel,mikelikespie/bazel,juhalindfors/bazel-patches,anupcshan/bazel,mbrukman/bazel,akira-baruah/bazel,ButterflyNetwork/bazel,whuwxl/bazel,aehlig/bazel,werkt/bazel,safarmer/bazel,juhalindfors/bazel-patches,mikelikespie/bazel,davidzchen/bazel,variac/bazel,bazelbuild/bazel,abergmeier-dsfishlabs/bazel,kchodorow/bazel,variac/bazel,iamthearm/bazel,cushon/bazel,perezd/bazel,katre/bazel,twitter-forks/bazel,LuminateWireless/bazel,kchodorow/bazel,snnn/bazel,variac/bazel,zhexuany/bazel,mbrukman/bazel,kchodorow/bazel-1,katre/bazel,aehlig/bazel,ButterflyNetwork/bazel,dslomov/bazel-windows,dslomov/bazel,bazelbuild/bazel,aehlig/bazel,cushon/bazel,akira-baruah/bazel,twitter-forks/bazel,UrbanCompass/bazel,abergmeier-dsfishlabs/bazel,mikelalcon/bazel,akira-baruah/bazel,Asana/bazel,spxtr/bazel,anupcshan/bazel,abergmeier-dsfishlabs/bazel,mrdomino/bazel,kchodorow/bazel,Asana/bazel,mbrukman/bazel,ButterflyNetwork/bazel,iamthearm/bazel,cushon/bazel,mrdomino/bazel,kchodorow/bazel-1,zhexuany/bazel,iamthearm/bazel,spxtr/bazel,mikelalcon/bazel,katre/bazel,Asana/bazel,variac/bazel,ulfjack/bazel,juhalindfors/bazel-patches,damienmg/bazel,UrbanCompass/bazel,spxtr/bazel,LuminateWireless/bazel,kchodorow/bazel,variac/bazel,twitter-forks/bazel,mbrukman/bazel,perezd/bazel,mrdomino/bazel,twitter-forks/bazel,dslomov/bazel-windows,davidzchen/bazel,whuwxl/bazel,dslomov/bazel,perezd/bazel,meteorcloudy/bazel,ulfjack/bazel,spxtr/bazel,whuwxl/bazel,kchodorow/bazel-1,werkt/bazel,iamthearm/bazel,spxtr/bazel,dslomov/bazel-windows,dropbox/bazel,whuwxl/bazel,UrbanCompass/bazel,aehlig/bazel,bazelbuild/bazel,meteorcloudy/bazel,kchodorow/bazel-1,Asana/bazel,kchodorow/bazel-1,hermione521/bazel,kchodorow/bazel,werkt/bazel,katre/bazel,safarmer/bazel,werkt/bazel,werkt/bazel,whuwxl/bazel,akira-baruah/bazel,mikelalcon/bazel,snnn/bazel,juhalindfors/bazel-patches,zhexuany/bazel
// Copyright 2015 The Bazel Authors. 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 com.google.devtools.build.lib.cmdline; import com.google.common.collect.ComparisonChain; import com.google.common.collect.Interner; import com.google.common.collect.Interners; import com.google.devtools.build.lib.util.Preconditions; import com.google.devtools.build.lib.vfs.Canonicalizer; import com.google.devtools.build.lib.vfs.PathFragment; import java.io.Serializable; import javax.annotation.concurrent.Immutable; /** * Uniquely identifies a package, given a repository name and a package's path fragment. * * <p>The repository the build is happening in is the <i>default workspace</i>, and is identified * by the workspace name "". Other repositories can be named in the WORKSPACE file. These * workspaces are prefixed by {@literal @}.</p> */ @Immutable public final class PackageIdentifier implements Comparable<PackageIdentifier>, Serializable { private static final Interner<PackageIdentifier> INTERNER = Interners.newWeakInterner(); public static PackageIdentifier create(String repository, PathFragment pkgName) throws LabelSyntaxException { return create(RepositoryName.create(repository), pkgName); } public static PackageIdentifier create(RepositoryName repository, PathFragment pkgName) { return INTERNER.intern(new PackageIdentifier(repository, pkgName)); } public static final String DEFAULT_REPOSITORY = ""; public static final RepositoryName DEFAULT_REPOSITORY_NAME; public static final RepositoryName MAIN_REPOSITORY_NAME; static { try { DEFAULT_REPOSITORY_NAME = RepositoryName.create(DEFAULT_REPOSITORY); MAIN_REPOSITORY_NAME = RepositoryName.create("@"); } catch (LabelSyntaxException e) { throw new IllegalStateException(e); } } public static PackageIdentifier createInMainRepo(String name) { return createInMainRepo(new PathFragment(name)); } public static PackageIdentifier createInMainRepo(PathFragment name) { return create(MAIN_REPOSITORY_NAME, name); } /** * The identifier for this repository. This is either "" or prefixed with an "@", * e.g., "@myrepo". */ private final RepositoryName repository; /** The name of the package. Canonical (i.e. x.equals(y) <=> x==y). */ private final PathFragment pkgName; private PackageIdentifier(RepositoryName repository, PathFragment pkgName) { this.repository = Preconditions.checkNotNull(repository); this.pkgName = Canonicalizer.fragments().intern( Preconditions.checkNotNull(pkgName).normalize()); } public static PackageIdentifier parse(String input) throws LabelSyntaxException { String repo; String packageName; int packageStartPos = input.indexOf("//"); if (input.startsWith("@") && packageStartPos > 0) { repo = input.substring(0, packageStartPos); packageName = input.substring(packageStartPos + 2); } else if (input.startsWith("@")) { throw new LabelSyntaxException("starts with a '@' but does not contain '//'"); } else if (packageStartPos == 0) { repo = PackageIdentifier.DEFAULT_REPOSITORY; packageName = input.substring(2); } else { repo = PackageIdentifier.DEFAULT_REPOSITORY; packageName = input; } String error = RepositoryName.validate(repo); if (error != null) { throw new LabelSyntaxException(error); } error = LabelValidator.validatePackageName(packageName); if (error != null) { throw new LabelSyntaxException(error); } return create(repo, new PathFragment(packageName)); } public RepositoryName getRepository() { return repository; } public PathFragment getPackageFragment() { return pkgName; } /** * Returns a relative path that should be unique across all remote and packages, based on the * repository and package names. */ public PathFragment getPathFragment() { return repository.getPathFragment().getRelative(pkgName); } public PackageIdentifier makeAbsolute() { if (!repository.isDefault()) { return this; } return create(MAIN_REPOSITORY_NAME, pkgName); } /** * Returns the name of this package. * * <p>There are certain places that expect the path fragment as the package name ('foo/bar') as a * package identifier. This isn't specific enough for packages in other repositories, so their * stringified version is '@baz//foo/bar'.</p> */ @Override public String toString() { return (repository.isDefault() || repository.isMain() ? "" : repository + "//") + pkgName; } @Override public boolean equals(Object object) { if (this == object) { return true; } if (!(object instanceof PackageIdentifier)) { return false; } PackageIdentifier that = (PackageIdentifier) object; return pkgName.equals(that.pkgName) && repository.equals(that.repository); } @Override public int hashCode() { return 31 * repository.hashCode() + pkgName.hashCode(); } @Override public int compareTo(PackageIdentifier that) { return ComparisonChain.start() .compare(repository.toString(), that.repository.toString()) .compare(pkgName, that.pkgName) .result(); } }
src/main/java/com/google/devtools/build/lib/cmdline/PackageIdentifier.java
// Copyright 2015 The Bazel Authors. 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 com.google.devtools.build.lib.cmdline; import com.google.common.collect.ComparisonChain; import com.google.common.collect.Interner; import com.google.common.collect.Interners; import com.google.devtools.build.lib.util.Preconditions; import com.google.devtools.build.lib.vfs.Canonicalizer; import com.google.devtools.build.lib.vfs.PathFragment; import java.io.Serializable; import javax.annotation.concurrent.Immutable; /** * Uniquely identifies a package, given a repository name and a package's path fragment. * * <p>The repository the build is happening in is the <i>default workspace</i>, and is identified * by the workspace name "". Other repositories can be named in the WORKSPACE file. These * workspaces are prefixed by {@literal @}.</p> */ @Immutable public final class PackageIdentifier implements Comparable<PackageIdentifier>, Serializable { private static final Interner<PackageIdentifier> INTERNER = Interners.newWeakInterner(); public static PackageIdentifier create(String repository, PathFragment pkgName) throws LabelSyntaxException { return create(RepositoryName.create(repository), pkgName); } public static PackageIdentifier create(RepositoryName repository, PathFragment pkgName) { return INTERNER.intern(new PackageIdentifier(repository, pkgName)); } public static final String DEFAULT_REPOSITORY = ""; public static final RepositoryName DEFAULT_REPOSITORY_NAME; public static final RepositoryName MAIN_REPOSITORY_NAME; static { try { DEFAULT_REPOSITORY_NAME = RepositoryName.create(DEFAULT_REPOSITORY); MAIN_REPOSITORY_NAME = RepositoryName.create("@"); } catch (LabelSyntaxException e) { throw new IllegalStateException(e); } } /** * This is only used by legacy callers. Actually creates the package identifier in the main * repository, not the default one. */ // TODO(lberki): Remove this method. @Deprecated public static PackageIdentifier createInDefaultRepo(String name) { return create(MAIN_REPOSITORY_NAME, new PathFragment(name)); } public static PackageIdentifier createInMainRepo(String name) { return createInMainRepo(new PathFragment(name)); } public static PackageIdentifier createInMainRepo(PathFragment name) { return create(MAIN_REPOSITORY_NAME, name); } /** * The identifier for this repository. This is either "" or prefixed with an "@", * e.g., "@myrepo". */ private final RepositoryName repository; /** The name of the package. Canonical (i.e. x.equals(y) <=> x==y). */ private final PathFragment pkgName; private PackageIdentifier(RepositoryName repository, PathFragment pkgName) { this.repository = Preconditions.checkNotNull(repository); this.pkgName = Canonicalizer.fragments().intern( Preconditions.checkNotNull(pkgName).normalize()); } public static PackageIdentifier parse(String input) throws LabelSyntaxException { String repo; String packageName; int packageStartPos = input.indexOf("//"); if (input.startsWith("@") && packageStartPos > 0) { repo = input.substring(0, packageStartPos); packageName = input.substring(packageStartPos + 2); } else if (input.startsWith("@")) { throw new LabelSyntaxException("starts with a '@' but does not contain '//'"); } else if (packageStartPos == 0) { repo = PackageIdentifier.DEFAULT_REPOSITORY; packageName = input.substring(2); } else { repo = PackageIdentifier.DEFAULT_REPOSITORY; packageName = input; } String error = RepositoryName.validate(repo); if (error != null) { throw new LabelSyntaxException(error); } error = LabelValidator.validatePackageName(packageName); if (error != null) { throw new LabelSyntaxException(error); } return create(repo, new PathFragment(packageName)); } public RepositoryName getRepository() { return repository; } public PathFragment getPackageFragment() { return pkgName; } /** * Returns a relative path that should be unique across all remote and packages, based on the * repository and package names. */ public PathFragment getPathFragment() { return repository.getPathFragment().getRelative(pkgName); } public PackageIdentifier makeAbsolute() { if (!repository.isDefault()) { return this; } return create(MAIN_REPOSITORY_NAME, pkgName); } /** * Returns the name of this package. * * <p>There are certain places that expect the path fragment as the package name ('foo/bar') as a * package identifier. This isn't specific enough for packages in other repositories, so their * stringified version is '@baz//foo/bar'.</p> */ @Override public String toString() { return (repository.isDefault() || repository.isMain() ? "" : repository + "//") + pkgName; } @Override public boolean equals(Object object) { if (this == object) { return true; } if (!(object instanceof PackageIdentifier)) { return false; } PackageIdentifier that = (PackageIdentifier) object; return pkgName.equals(that.pkgName) && repository.equals(that.repository); } @Override public int hashCode() { return 31 * repository.hashCode() + pkgName.hashCode(); } @Override public int compareTo(PackageIdentifier that) { return ComparisonChain.start() .compare(repository.toString(), that.repository.toString()) .compare(pkgName, that.pkgName) .result(); } }
Remove PackageIdentifier#createInDefaultRepo now that all the callers have been migrated. -- MOS_MIGRATED_REVID=118571367
src/main/java/com/google/devtools/build/lib/cmdline/PackageIdentifier.java
Remove PackageIdentifier#createInDefaultRepo now that all the callers have been migrated.
<ide><path>rc/main/java/com/google/devtools/build/lib/cmdline/PackageIdentifier.java <ide> } catch (LabelSyntaxException e) { <ide> throw new IllegalStateException(e); <ide> } <del> } <del> <del> /** <del> * This is only used by legacy callers. Actually creates the package identifier in the main <del> * repository, not the default one. <del> */ <del> // TODO(lberki): Remove this method. <del> @Deprecated <del> public static PackageIdentifier createInDefaultRepo(String name) { <del> return create(MAIN_REPOSITORY_NAME, new PathFragment(name)); <ide> } <ide> <ide> public static PackageIdentifier createInMainRepo(String name) {
Java
apache-2.0
73fe4e82a3fbb27b2eced12c02bd0a4f16650633
0
apache/olingo-odata2,apache/olingo-odata2
/******************************************************************************* * 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.olingo.odata2.jpa.processor.core.access.data; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import javax.persistence.EntityManager; import org.apache.olingo.odata2.api.edm.EdmEntitySet; import org.apache.olingo.odata2.api.edm.EdmException; import org.apache.olingo.odata2.api.edm.EdmNavigationProperty; import org.apache.olingo.odata2.api.edm.EdmSimpleType; import org.apache.olingo.odata2.api.ep.entry.ODataEntry; import org.apache.olingo.odata2.api.exception.ODataException; import org.apache.olingo.odata2.api.uri.KeyPredicate; import org.apache.olingo.odata2.api.uri.NavigationSegment; import org.apache.olingo.odata2.api.uri.UriInfo; import org.apache.olingo.odata2.api.uri.info.DeleteUriInfo; import org.apache.olingo.odata2.api.uri.info.GetEntitySetUriInfo; import org.apache.olingo.odata2.api.uri.info.GetEntityUriInfo; import org.apache.olingo.odata2.api.uri.info.PostUriInfo; import org.apache.olingo.odata2.api.uri.info.PutMergePatchUriInfo; import org.apache.olingo.odata2.jpa.processor.api.ODataJPAContext; import org.apache.olingo.odata2.jpa.processor.api.ODataJPATransaction; import org.apache.olingo.odata2.jpa.processor.api.access.JPAProcessor; import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPAModelException; import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException; import org.apache.olingo.odata2.jpa.processor.api.factory.ODataJPAFactory; import org.apache.olingo.odata2.jpa.processor.core.ODataEntityParser; import org.apache.olingo.odata2.jpa.processor.core.model.JPAEdmMappingImpl; public class JPALink { private static final String SPACE = " "; private static final String ODATA_COMMAND_FILTER = "$filter"; private static final String ODATA_OPERATOR_OR = "or"; private static final String ODATA_OPERATOR_NE = "ne"; private ODataJPAContext context; private JPAProcessor jpaProcessor; private ODataEntityParser parser; private Object targetJPAEntity; private Object sourceJPAEntity; public JPALink(final ODataJPAContext context) { this.context = context; jpaProcessor = ODataJPAFactory.createFactory().getJPAAccessFactory().getJPAProcessor(this.context); parser = new ODataEntityParser(this.context); } public void setSourceJPAEntity(final Object jpaEntity) { sourceJPAEntity = jpaEntity; } public void setTargetJPAEntity(final Object jpaEntity) { targetJPAEntity = jpaEntity; } public Object getTargetJPAEntity() { return targetJPAEntity; } public Object getSourceJPAEntity() { return sourceJPAEntity; } public void create(final PostUriInfo uriInfo, final InputStream content, final String requestContentType, final String contentType) throws ODataJPARuntimeException, ODataJPAModelException { modifyLink((UriInfo) uriInfo, content, requestContentType); } public void update(final PutMergePatchUriInfo putUriInfo, final InputStream content, final String requestContentType, final String contentType) throws ODataJPARuntimeException, ODataJPAModelException { modifyLink((UriInfo) putUriInfo, content, requestContentType); } public void delete(final DeleteUriInfo uriInfo) throws ODataJPARuntimeException { try { int index = context.getODataContext().getPathInfo().getODataSegments().size() - 2; List<String> linkSegments = new ArrayList<String>(); String customLinkSegment = context.getODataContext().getPathInfo().getODataSegments().get(0).getPath(); linkSegments.add(customLinkSegment); customLinkSegment = uriInfo.getNavigationSegments().get(0).getNavigationProperty().getName(); linkSegments.add(customLinkSegment); HashMap<String, String> options = new HashMap<String, String>(); List<KeyPredicate> keyPredicates = uriInfo.getNavigationSegments().get(0).getKeyPredicates(); StringBuffer condition = new StringBuffer(); String literal = null; KeyPredicate keyPredicate = null; int size = keyPredicates.size(); for (int i = 0; i < size; i++) { keyPredicate = keyPredicates.get(i); literal = ((EdmSimpleType) keyPredicate.getProperty().getType()).toUriLiteral(keyPredicate.getLiteral()); condition.append(keyPredicate.getProperty().getName()).append(SPACE); condition.append(ODATA_OPERATOR_NE).append(SPACE); condition.append(literal).append(SPACE); if (i != size - 1) { condition.append(ODATA_OPERATOR_OR).append(SPACE); } } if (condition.length() > 0) { options.put(ODATA_COMMAND_FILTER, condition.toString()); } UriInfo parsedUriInfo = parser.parseLinkSegments(linkSegments, options); List<Object> relatedEntities = jpaProcessor.process((GetEntitySetUriInfo) parsedUriInfo); parsedUriInfo = parser.parseURISegment(0, index); if (parsedUriInfo != null) { targetJPAEntity = jpaProcessor.process((GetEntityUriInfo) parsedUriInfo); if (targetJPAEntity == null) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.RESOURCE_X_NOT_FOUND .addContent(parsedUriInfo.getTargetEntitySet().getName()), null); } NavigationSegment navigationSegment = uriInfo.getNavigationSegments().get(0); EdmNavigationProperty navigationProperty = navigationSegment.getNavigationProperty(); delinkJPAEntities(targetJPAEntity, relatedEntities, navigationProperty); } } catch (EdmException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } catch (ODataException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } } public void save() { EntityManager em = context.getEntityManager(); ODataJPATransaction tx = context.getODataJPATransaction(); boolean isLocalTransaction = false; if (!tx.isActive()) { tx.begin(); isLocalTransaction = true; } if (sourceJPAEntity != null) { em.persist(sourceJPAEntity); } if (targetJPAEntity != null) { em.persist(targetJPAEntity); } if (isLocalTransaction && ((sourceJPAEntity != null && em.contains(sourceJPAEntity)) || (targetJPAEntity != null && em .contains(targetJPAEntity)))) { tx.commit(); } } public void create(final EdmEntitySet entitySet, final ODataEntry oDataEntry, final List<String> navigationPropertyNames) throws ODataJPARuntimeException, ODataJPAModelException { List<Object> targetJPAEntities = new ArrayList<Object>(); try { for (String navPropertyName : navigationPropertyNames) { List<String> links = oDataEntry.getMetadata().getAssociationUris(navPropertyName); if (links == null || links.isEmpty() == true) { links = extractLinkURI(oDataEntry, navPropertyName); } if (links != null && links.isEmpty() == false) { EdmNavigationProperty navProperty = (EdmNavigationProperty) entitySet.getEntityType() .getProperty( navPropertyName); for (String link : links) { UriInfo bindingUriInfo = parser.parseBindingLink(link, new HashMap<String, String>()); targetJPAEntity = jpaProcessor.process((GetEntityUriInfo) bindingUriInfo); if (targetJPAEntity != null) { targetJPAEntities.add(targetJPAEntity); } } if (targetJPAEntity == null){ throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.RESOURCE_X_NOT_FOUND .addContent(navPropertyName), null); } if (!targetJPAEntities.isEmpty()) { linkJPAEntities(targetJPAEntities, sourceJPAEntity, navProperty); } targetJPAEntities.clear(); } } } catch (EdmException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } } @SuppressWarnings("unchecked") public static void linkJPAEntities(final Collection<Object> targetJPAEntities, final Object sourceJPAEntity, final EdmNavigationProperty navigationProperty) throws ODataJPARuntimeException { if (targetJPAEntities == null || sourceJPAEntity == null || navigationProperty == null) { return; } try { JPAEntityParser entityParser = new JPAEntityParser(); Method setMethod = entityParser.getAccessModifier(sourceJPAEntity.getClass(), navigationProperty, JPAEntityParser.ACCESS_MODIFIER_SET); JPAEdmMappingImpl jpaEdmMappingImpl = null; if (navigationProperty.getMapping() instanceof JPAEdmMappingImpl) { jpaEdmMappingImpl = (JPAEdmMappingImpl) navigationProperty.getMapping(); } if (jpaEdmMappingImpl != null && jpaEdmMappingImpl.isVirtualAccess()) { setMethod.invoke(sourceJPAEntity, jpaEdmMappingImpl.getInternalName(), targetJPAEntities.iterator().next()); } else { switch (navigationProperty.getMultiplicity()) { case MANY: Method getMethod = entityParser.getAccessModifier(sourceJPAEntity.getClass(), navigationProperty, JPAEntityParser.ACCESS_MODIFIER_GET); Collection<Object> relatedEntities = (Collection<Object>) getMethod.invoke(sourceJPAEntity); if (relatedEntities == null) { throw ODataJPARuntimeException.throwException( ODataJPARuntimeException.ERROR_JPQL_CREATE_REQUEST, null); } relatedEntities.addAll(targetJPAEntities); setMethod.invoke(sourceJPAEntity, relatedEntities); break; case ONE: case ZERO_TO_ONE: setMethod.invoke(sourceJPAEntity, targetJPAEntities.iterator().next()); break; } } } catch (EdmException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } catch (IllegalArgumentException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } catch (IllegalAccessException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } catch (InvocationTargetException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } } @SuppressWarnings("unchecked") private List<String> extractLinkURI(ODataEntry oDataEntry, String navigationPropertyName) { List<String> links = new ArrayList<String>(); String link = null; Object object = oDataEntry.getProperties().get(navigationPropertyName); if (object == null) { return links; } if (object instanceof ODataEntry) { link = ((ODataEntry) object).getMetadata().getUri(); if (!link.isEmpty()) { links.add(link); } } else { for (ODataEntry entry : (List<ODataEntry>) object) { link = entry.getMetadata().getUri(); if (link != null && link.isEmpty() == false) { links.add(link); } } } return links; } private void modifyLink(final UriInfo uriInfo, final InputStream content, final String requestContentType) throws ODataJPARuntimeException, ODataJPAModelException { try { EdmEntitySet targetEntitySet = uriInfo.getTargetEntitySet(); String targerEntitySetName = targetEntitySet.getName(); EdmNavigationProperty navigationProperty = null; UriInfo getUriInfo = null; if (uriInfo.isLinks()) { getUriInfo = parser.parseLink(targetEntitySet, content, requestContentType); navigationProperty = uriInfo.getNavigationSegments().get(0).getNavigationProperty(); } else { return; } if (!getUriInfo.getTargetEntitySet().getName().equals(targerEntitySetName)) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.RELATIONSHIP_INVALID, null); } targetJPAEntity = jpaProcessor.process((GetEntityUriInfo) getUriInfo); if (targetJPAEntity == null){ throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.RESOURCE_X_NOT_FOUND .addContent(navigationProperty.getName()), null); } if (targetJPAEntity != null && sourceJPAEntity == null) { int index = context.getODataContext().getPathInfo().getODataSegments().size() - 2; getUriInfo = parser.parseURISegment(0, index); sourceJPAEntity = jpaProcessor.process((GetEntityUriInfo) getUriInfo); if (sourceJPAEntity == null) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.RESOURCE_X_NOT_FOUND .addContent(getUriInfo.getTargetEntitySet().getName()), null); } } if (targetJPAEntity != null && sourceJPAEntity != null) { List<Object> targetJPAEntities = new ArrayList<Object>(); targetJPAEntities.add(targetJPAEntity); linkJPAEntities(targetJPAEntities, sourceJPAEntity, navigationProperty); } } catch (IllegalArgumentException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } catch (EdmException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } catch (ODataException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } } private void delinkJPAEntities(final Object jpaEntity, final List<Object> relatedJPAEntities, final EdmNavigationProperty targetNavigationProperty) throws ODataJPARuntimeException { try { JPAEntityParser entityParser = new JPAEntityParser(); Method setMethod = entityParser.getAccessModifier(jpaEntity.getClass(), targetNavigationProperty, JPAEntityParser.ACCESS_MODIFIER_SET); Method getMethod = entityParser.getAccessModifier(jpaEntity.getClass(), targetNavigationProperty, JPAEntityParser.ACCESS_MODIFIER_GET); if (getMethod.getReturnType().getTypeParameters() != null && getMethod.getReturnType().getTypeParameters().length != 0) { setMethod.invoke(jpaEntity, relatedJPAEntities); } else { setMethod.invoke(jpaEntity, (Object) null); } } catch (IllegalAccessException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } catch (InvocationTargetException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } } }
odata2-jpa-processor/jpa-core/src/main/java/org/apache/olingo/odata2/jpa/processor/core/access/data/JPALink.java
/******************************************************************************* * 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.olingo.odata2.jpa.processor.core.access.data; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import javax.persistence.EntityManager; import org.apache.olingo.odata2.api.edm.EdmEntitySet; import org.apache.olingo.odata2.api.edm.EdmException; import org.apache.olingo.odata2.api.edm.EdmNavigationProperty; import org.apache.olingo.odata2.api.edm.EdmSimpleType; import org.apache.olingo.odata2.api.ep.entry.ODataEntry; import org.apache.olingo.odata2.api.exception.ODataException; import org.apache.olingo.odata2.api.uri.KeyPredicate; import org.apache.olingo.odata2.api.uri.NavigationSegment; import org.apache.olingo.odata2.api.uri.UriInfo; import org.apache.olingo.odata2.api.uri.info.DeleteUriInfo; import org.apache.olingo.odata2.api.uri.info.GetEntitySetUriInfo; import org.apache.olingo.odata2.api.uri.info.GetEntityUriInfo; import org.apache.olingo.odata2.api.uri.info.PostUriInfo; import org.apache.olingo.odata2.api.uri.info.PutMergePatchUriInfo; import org.apache.olingo.odata2.jpa.processor.api.ODataJPAContext; import org.apache.olingo.odata2.jpa.processor.api.ODataJPATransaction; import org.apache.olingo.odata2.jpa.processor.api.access.JPAProcessor; import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPAModelException; import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException; import org.apache.olingo.odata2.jpa.processor.api.factory.ODataJPAFactory; import org.apache.olingo.odata2.jpa.processor.core.ODataEntityParser; import org.apache.olingo.odata2.jpa.processor.core.model.JPAEdmMappingImpl; public class JPALink { private static final String SPACE = " "; private static final String ODATA_COMMAND_FILTER = "$filter"; private static final String ODATA_OPERATOR_OR = "or"; private static final String ODATA_OPERATOR_NE = "ne"; private ODataJPAContext context; private JPAProcessor jpaProcessor; private ODataEntityParser parser; private Object targetJPAEntity; private Object sourceJPAEntity; public JPALink(final ODataJPAContext context) { this.context = context; jpaProcessor = ODataJPAFactory.createFactory().getJPAAccessFactory().getJPAProcessor(this.context); parser = new ODataEntityParser(this.context); } public void setSourceJPAEntity(final Object jpaEntity) { sourceJPAEntity = jpaEntity; } public void setTargetJPAEntity(final Object jpaEntity) { targetJPAEntity = jpaEntity; } public Object getTargetJPAEntity() { return targetJPAEntity; } public Object getSourceJPAEntity() { return sourceJPAEntity; } public void create(final PostUriInfo uriInfo, final InputStream content, final String requestContentType, final String contentType) throws ODataJPARuntimeException, ODataJPAModelException { modifyLink((UriInfo) uriInfo, content, requestContentType); } public void update(final PutMergePatchUriInfo putUriInfo, final InputStream content, final String requestContentType, final String contentType) throws ODataJPARuntimeException, ODataJPAModelException { modifyLink((UriInfo) putUriInfo, content, requestContentType); } public void delete(final DeleteUriInfo uriInfo) throws ODataJPARuntimeException { try { int index = context.getODataContext().getPathInfo().getODataSegments().size() - 2; List<String> linkSegments = new ArrayList<String>(); String customLinkSegment = context.getODataContext().getPathInfo().getODataSegments().get(0).getPath(); linkSegments.add(customLinkSegment); customLinkSegment = uriInfo.getNavigationSegments().get(0).getNavigationProperty().getName(); linkSegments.add(customLinkSegment); HashMap<String, String> options = new HashMap<String, String>(); List<KeyPredicate> keyPredicates = uriInfo.getNavigationSegments().get(0).getKeyPredicates(); StringBuffer condition = new StringBuffer(); String literal = null; KeyPredicate keyPredicate = null; int size = keyPredicates.size(); for (int i = 0; i < size; i++) { keyPredicate = keyPredicates.get(i); literal = ((EdmSimpleType) keyPredicate.getProperty().getType()).toUriLiteral(keyPredicate.getLiteral()); condition.append(keyPredicate.getProperty().getName()).append(SPACE); condition.append(ODATA_OPERATOR_NE).append(SPACE); condition.append(literal).append(SPACE); if (i != size - 1) { condition.append(ODATA_OPERATOR_OR).append(SPACE); } } if (condition.length() > 0) { options.put(ODATA_COMMAND_FILTER, condition.toString()); } UriInfo parsedUriInfo = parser.parseLinkSegments(linkSegments, options); List<Object> relatedEntities = jpaProcessor.process((GetEntitySetUriInfo) parsedUriInfo); parsedUriInfo = parser.parseURISegment(0, index); if (parsedUriInfo != null) { targetJPAEntity = jpaProcessor.process((GetEntityUriInfo) parsedUriInfo); if (targetJPAEntity == null) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.RESOURCE_X_NOT_FOUND .addContent(parsedUriInfo.getTargetEntitySet().getName()), null); } NavigationSegment navigationSegment = uriInfo.getNavigationSegments().get(0); EdmNavigationProperty navigationProperty = navigationSegment.getNavigationProperty(); delinkJPAEntities(targetJPAEntity, relatedEntities, navigationProperty); } } catch (EdmException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } catch (ODataException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } } public void save() { EntityManager em = context.getEntityManager(); ODataJPATransaction tx = context.getODataJPATransaction(); boolean isLocalTransaction = false; if (!tx.isActive()) { tx.begin(); isLocalTransaction = true; } if (sourceJPAEntity != null) { em.persist(sourceJPAEntity); } if (targetJPAEntity != null) { em.persist(targetJPAEntity); } if (isLocalTransaction && ((sourceJPAEntity != null && em.contains(sourceJPAEntity)) || (targetJPAEntity != null && em .contains(targetJPAEntity)))) { tx.commit(); } } public void create(final EdmEntitySet entitySet, final ODataEntry oDataEntry, final List<String> navigationPropertyNames) throws ODataJPARuntimeException, ODataJPAModelException { List<Object> targetJPAEntities = new ArrayList<Object>(); try { for (String navPropertyName : navigationPropertyNames) { List<String> links = oDataEntry.getMetadata().getAssociationUris(navPropertyName); if (links == null || links.isEmpty() == true) { links = extractLinkURI(oDataEntry, navPropertyName); } if (links != null && links.isEmpty() == false) { EdmNavigationProperty navProperty = (EdmNavigationProperty) entitySet.getEntityType() .getProperty( navPropertyName); for (String link : links) { UriInfo bindingUriInfo = parser.parseBindingLink(link, new HashMap<String, String>()); targetJPAEntity = jpaProcessor.process((GetEntityUriInfo) bindingUriInfo); if (targetJPAEntity != null) { targetJPAEntities.add(targetJPAEntity); } } if (!targetJPAEntities.isEmpty()) { linkJPAEntities(targetJPAEntities, sourceJPAEntity, navProperty); } targetJPAEntities.clear(); } } } catch (EdmException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } } @SuppressWarnings("unchecked") public static void linkJPAEntities(final Collection<Object> targetJPAEntities, final Object sourceJPAEntity, final EdmNavigationProperty navigationProperty) throws ODataJPARuntimeException { if (targetJPAEntities == null || sourceJPAEntity == null || navigationProperty == null) { return; } try { JPAEntityParser entityParser = new JPAEntityParser(); Method setMethod = entityParser.getAccessModifier(sourceJPAEntity.getClass(), navigationProperty, JPAEntityParser.ACCESS_MODIFIER_SET); JPAEdmMappingImpl jpaEdmMappingImpl = null; if (navigationProperty.getMapping() instanceof JPAEdmMappingImpl) { jpaEdmMappingImpl = (JPAEdmMappingImpl) navigationProperty.getMapping(); } if (jpaEdmMappingImpl != null && jpaEdmMappingImpl.isVirtualAccess()) { setMethod.invoke(sourceJPAEntity, jpaEdmMappingImpl.getInternalName(), targetJPAEntities.iterator().next()); } else { switch (navigationProperty.getMultiplicity()) { case MANY: Method getMethod = entityParser.getAccessModifier(sourceJPAEntity.getClass(), navigationProperty, JPAEntityParser.ACCESS_MODIFIER_GET); Collection<Object> relatedEntities = (Collection<Object>) getMethod.invoke(sourceJPAEntity); if (relatedEntities == null) { throw ODataJPARuntimeException.throwException( ODataJPARuntimeException.ERROR_JPQL_CREATE_REQUEST, null); } relatedEntities.addAll(targetJPAEntities); setMethod.invoke(sourceJPAEntity, relatedEntities); break; case ONE: case ZERO_TO_ONE: setMethod.invoke(sourceJPAEntity, targetJPAEntities.iterator().next()); break; } } } catch (EdmException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } catch (IllegalArgumentException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } catch (IllegalAccessException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } catch (InvocationTargetException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } } @SuppressWarnings("unchecked") private List<String> extractLinkURI(ODataEntry oDataEntry, String navigationPropertyName) { List<String> links = new ArrayList<String>(); String link = null; Object object = oDataEntry.getProperties().get(navigationPropertyName); if (object == null) { return links; } if (object instanceof ODataEntry) { link = ((ODataEntry) object).getMetadata().getUri(); if (!link.isEmpty()) { links.add(link); } } else { for (ODataEntry entry : (List<ODataEntry>) object) { link = entry.getMetadata().getUri(); if (link != null && link.isEmpty() == false) { links.add(link); } } } return links; } private void modifyLink(final UriInfo uriInfo, final InputStream content, final String requestContentType) throws ODataJPARuntimeException, ODataJPAModelException { try { EdmEntitySet targetEntitySet = uriInfo.getTargetEntitySet(); String targerEntitySetName = targetEntitySet.getName(); EdmNavigationProperty navigationProperty = null; UriInfo getUriInfo = null; if (uriInfo.isLinks()) { getUriInfo = parser.parseLink(targetEntitySet, content, requestContentType); navigationProperty = uriInfo.getNavigationSegments().get(0).getNavigationProperty(); } else { return; } if (!getUriInfo.getTargetEntitySet().getName().equals(targerEntitySetName)) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.RELATIONSHIP_INVALID, null); } targetJPAEntity = jpaProcessor.process((GetEntityUriInfo) getUriInfo); if (targetJPAEntity != null && sourceJPAEntity == null) { int index = context.getODataContext().getPathInfo().getODataSegments().size() - 2; getUriInfo = parser.parseURISegment(0, index); sourceJPAEntity = jpaProcessor.process((GetEntityUriInfo) getUriInfo); if (sourceJPAEntity == null) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.RESOURCE_X_NOT_FOUND .addContent(getUriInfo.getTargetEntitySet().getName()), null); } } if (targetJPAEntity != null && sourceJPAEntity != null) { List<Object> targetJPAEntities = new ArrayList<Object>(); targetJPAEntities.add(targetJPAEntity); linkJPAEntities(targetJPAEntities, sourceJPAEntity, navigationProperty); } } catch (IllegalArgumentException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } catch (EdmException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } catch (ODataException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } } private void delinkJPAEntities(final Object jpaEntity, final List<Object> relatedJPAEntities, final EdmNavigationProperty targetNavigationProperty) throws ODataJPARuntimeException { try { JPAEntityParser entityParser = new JPAEntityParser(); Method setMethod = entityParser.getAccessModifier(jpaEntity.getClass(), targetNavigationProperty, JPAEntityParser.ACCESS_MODIFIER_SET); Method getMethod = entityParser.getAccessModifier(jpaEntity.getClass(), targetNavigationProperty, JPAEntityParser.ACCESS_MODIFIER_GET); if (getMethod.getReturnType().getTypeParameters() != null && getMethod.getReturnType().getTypeParameters().length != 0) { setMethod.invoke(jpaEntity, relatedJPAEntities); } else { setMethod.invoke(jpaEntity, (Object) null); } } catch (IllegalAccessException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } catch (InvocationTargetException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } } }
[ODATA-2] JPA silent exit on update
odata2-jpa-processor/jpa-core/src/main/java/org/apache/olingo/odata2/jpa/processor/core/access/data/JPALink.java
[ODATA-2] JPA silent exit on update
<ide><path>data2-jpa-processor/jpa-core/src/main/java/org/apache/olingo/odata2/jpa/processor/core/access/data/JPALink.java <ide> if (targetJPAEntity != null) { <ide> targetJPAEntities.add(targetJPAEntity); <ide> } <add> } <add> if (targetJPAEntity == null){ <add> throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.RESOURCE_X_NOT_FOUND <add> .addContent(navPropertyName), null); <ide> } <ide> if (!targetJPAEntities.isEmpty()) { <ide> linkJPAEntities(targetJPAEntities, sourceJPAEntity, navProperty); <ide> } <ide> <ide> targetJPAEntity = jpaProcessor.process((GetEntityUriInfo) getUriInfo); <add> if (targetJPAEntity == null){ <add> throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.RESOURCE_X_NOT_FOUND <add> .addContent(navigationProperty.getName()), null); <add> } <ide> if (targetJPAEntity != null && sourceJPAEntity == null) { <ide> int index = context.getODataContext().getPathInfo().getODataSegments().size() - 2; <ide> getUriInfo = parser.parseURISegment(0, index);
JavaScript
mit
5dab31ba5c3c131f25dd50c00e62ac334c4454fc
0
david84/flight,Shinchy/flight,icecreamliker/flight,joelbyler/flight,joelbyler/flight,flightjs/flight,Shinchy/flight,margaritis/flight,robertknight/flight,KyawNaingTun/flight,david84/flight,icecreamliker/flight,flightjs/flight,robertknight/flight,KyawNaingTun/flight,giuseppeg/flight
// Karma configuration file // // For all available config options and default values, see: // https://github.com/karma-runner/karma/blob/stable/lib/config.js#L54 module.exports = function(config) { config.set({ // base path, that will be used to resolve files and exclude basePath: '', frameworks: [ 'jasmine' ], // list of files / patterns to load in the browser files: [ // loaded without require 'bower_components/es5-shim/es5-shim.js', 'bower_components/es5-shim/es5-sham.js', 'bower_components/jquery/jquery.js', 'build/flight.js', // hack to load RequireJS after the shim libs 'node_modules/karma-requirejs/lib/require.js', 'node_modules/karma-requirejs/lib/adapter.js', // loaded with require {pattern: 'lib/**/*.js', included: false}, {pattern: 'test/spec/**/*_spec.js', included: false}, 'test/test-main.js' ], // list of files to exclude exclude: [], // use dots reporter, as travis terminal does not support escaping sequences // possible values: 'dots', 'progress' // CLI --reporters progress reporters: ['dots'], // enable / disable watching file and executing tests whenever any file changes // CLI --auto-watch --no-auto-watch autoWatch: true, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) // CLI --browsers Chrome, Firefox, Safari browsers: [ 'Chrome', 'Firefox' ], // If browser does not capture in given timeout [ms], kill it // CLI --capture-timeout 5000 captureTimeout: 20000, // Auto run tests on start (when browsers are captured) and exit // CLI --single-run --no-single-run singleRun: false, plugins: [ 'karma-jasmine', 'karma-requirejs', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-ie-launcher', 'karma-phantomjs-launcher', 'karma-safari-launcher' ] }); };
karma.conf.js
// Karma configuration file // // For all available config options and default values, see: // https://github.com/karma-runner/karma/blob/stable/lib/config.js#L54 module.exports = function(config) { config.set({ // base path, that will be used to resolve files and exclude basePath: '', frameworks: [ 'jasmine' ], // list of files / patterns to load in the browser files: [ // loaded without require 'bower_components/es5-shim/es5-shim.js', 'bower_components/es5-shim/es5-sham.js', 'bower_components/jquery/jquery.js', 'build/flight.js', // hack to load RequireJS after the shim libs 'node_modules/karma-requirejs/lib/require.js', 'node_modules/karma-requirejs/lib/adapter.js', // loaded with require {pattern: 'lib/**/*.js', included: false}, {pattern: 'test/spec/**/*_spec.js', included: false}, 'test/test-main.js' ], // list of files to exclude exclude: [], // use dots reporter, as travis terminal does not support escaping sequences // possible values: 'dots', 'progress' // CLI --reporters progress reporters: ['dots'], // enable / disable watching file and executing tests whenever any file changes // CLI --auto-watch --no-auto-watch autoWatch: true, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) // CLI --browsers Chrome, Firefox, Safari browsers: [ 'Chrome', 'Firefox' ], // If browser does not capture in given timeout [ms], kill it // CLI --capture-timeout 5000 captureTimeout: 20000, // Auto run tests on start (when browsers are captured) and exit // CLI --single-run --no-single-run singleRun: false, plugins: [ 'karma-jasmine', 'karma-requirejs', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-ie-launcher', 'karma-safari-launcher' ] }); };
Load PhantomJS plugin in `karma.conf.js`
karma.conf.js
Load PhantomJS plugin in `karma.conf.js`
<ide><path>arma.conf.js <ide> 'karma-chrome-launcher', <ide> 'karma-firefox-launcher', <ide> 'karma-ie-launcher', <add> 'karma-phantomjs-launcher', <ide> 'karma-safari-launcher' <ide> ] <ide> });
Java
bsd-3-clause
626d5ad886fb7e399b9b40720ad8f60e1c7e6a24
0
Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java
/* * 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.nexrad2; import thredds.catalog.DataFormatType; import ucar.ma2.*; import ucar.nc2.*; import ucar.nc2.constants.*; import ucar.nc2.iosp.AbstractIOServiceProvider; import static ucar.nc2.iosp.nexrad2.Level2Record.*; import ucar.nc2.units.DateFormatter; import ucar.nc2.util.CancelTask; import ucar.unidata.io.RandomAccessFile; import java.io.IOException; import java.util.List; import java.util.ArrayList; import java.util.Date; /** * An IOServiceProvider for NEXRAD level II files. * * @author caron */ public class Nexrad2IOServiceProvider extends AbstractIOServiceProvider { static private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(Nexrad2IOServiceProvider.class); static private final int MISSING_INT = -9999; static private final float MISSING_FLOAT = Float.NaN; public boolean isValidFile( RandomAccessFile raf) throws IOException { try { raf.seek(0); String test = raf.readString(8); return test.equals( Level2VolumeScan.ARCHIVE2) || test.equals( Level2VolumeScan.AR2V0001) || test.equals( Level2VolumeScan.AR2V0003)|| test.equals( Level2VolumeScan.AR2V0004) || test.equals( Level2VolumeScan.AR2V0002) || test.equals( Level2VolumeScan.AR2V0006) || test.equals( Level2VolumeScan.AR2V0007); } catch (IOException ioe) { return false; } } private Level2VolumeScan volScan; // private Dimension radialDim; private double radarRadius; private Variable v0, v1; private DateFormatter formatter = new DateFormatter(); private boolean overMidNight = false; public void open(RandomAccessFile raf, NetcdfFile ncfile, CancelTask cancelTask) throws IOException { NexradStationDB.init(); volScan = new Level2VolumeScan( raf, cancelTask); // note raf may change when compressed this.raf = volScan.raf; if (volScan.hasDifferentDopplarResolutions()) throw new IllegalStateException("volScan.hasDifferentDopplarResolutions"); if( volScan.hasHighResolutions(0)) { if(volScan.getHighResReflectivityGroups() != null) makeVariable2( ncfile, Level2Record.REFLECTIVITY_HIGH, "Reflectivity", "Reflectivity", "R", volScan); if( volScan.getHighResVelocityGroups() != null) makeVariable2( ncfile, Level2Record.VELOCITY_HIGH, "RadialVelocity", "Radial Velocity", "V", volScan); if( volScan.getHighResSpectrumGroups() != null) { List<List<Level2Record>> gps = volScan.getHighResSpectrumGroups(); List<Level2Record> gp = gps.get(0); Level2Record record = gp.get(0); if(v1 != null) makeVariableNoCoords( ncfile, Level2Record.SPECTRUM_WIDTH_HIGH, "SpectrumWidth_HI", "Radial Spectrum_HI", v1, record); if(v0 != null) makeVariableNoCoords( ncfile, Level2Record.SPECTRUM_WIDTH_HIGH, "SpectrumWidth", "Radial Spectrum", v0, record); } } List<List<Level2Record>> gps = volScan.getHighResDiffReflectGroups(); if( gps != null) { makeVariable2( ncfile, Level2Record.DIFF_REFLECTIVITY_HIGH, "DifferentialReflectivity", "Differential Reflectivity", "D", volScan); } gps = volScan.getHighResCoeffocientGroups(); if(gps != null) { makeVariable2( ncfile, Level2Record.CORRELATION_COEFFICIENT, "CorrelationCoefficient", "Correlation Coefficient", "C", volScan); } gps = volScan.getHighResDiffPhaseGroups(); if( gps != null) { makeVariable2( ncfile, Level2Record.DIFF_PHASE, "DifferentialPhase", "Differential Phase", "P", volScan); } gps = volScan.getReflectivityGroups(); if( gps != null) { makeVariable( ncfile, Level2Record.REFLECTIVITY, "Reflectivity", "Reflectivity", "R", volScan.getReflectivityGroups(), 0); int velocity_type = (volScan.getDopplarResolution() == Level2Record.DOPPLER_RESOLUTION_HIGH_CODE) ? Level2Record.VELOCITY_HI : Level2Record.VELOCITY_LOW; Variable v = makeVariable( ncfile, velocity_type, "RadialVelocity", "Radial Velocity", "V", volScan.getVelocityGroups(), 0); gps = volScan.getVelocityGroups(); List<Level2Record> gp = gps.get(0); Level2Record record = gp.get(0); makeVariableNoCoords( ncfile, Level2Record.SPECTRUM_WIDTH, "SpectrumWidth", "Spectrum Width", v, record); } if (volScan.getStationId() != null) { ncfile.addAttribute(null, new Attribute("Station", volScan.getStationId())); ncfile.addAttribute(null, new Attribute("StationName", volScan.getStationName())); ncfile.addAttribute(null, new Attribute("StationLatitude", volScan.getStationLatitude())); ncfile.addAttribute(null, new Attribute("StationLongitude", volScan.getStationLongitude())); ncfile.addAttribute(null, new Attribute("StationElevationInMeters", volScan.getStationElevation())); double latRadiusDegrees = Math.toDegrees( radarRadius / ucar.unidata.geoloc.Earth.getRadius()); ncfile.addAttribute(null, new Attribute("geospatial_lat_min", volScan.getStationLatitude() - latRadiusDegrees)); ncfile.addAttribute(null, new Attribute("geospatial_lat_max", volScan.getStationLatitude() + latRadiusDegrees)); double cosLat = Math.cos( Math.toRadians(volScan.getStationLatitude())); double lonRadiusDegrees = Math.toDegrees( radarRadius / cosLat / ucar.unidata.geoloc.Earth.getRadius()); ncfile.addAttribute(null, new Attribute("geospatial_lon_min", volScan.getStationLongitude() - lonRadiusDegrees)); ncfile.addAttribute(null, new Attribute("geospatial_lon_max", volScan.getStationLongitude() + lonRadiusDegrees)); // add a radial coordinate transform (experimental) /* Variable ct = new Variable(ncfile, null, null, "radialCoordinateTransform"); ct.setDataType(DataType.CHAR); ct.setDimensions(""); // scalar ct.addAttribute( new Attribute("transform_name", "Radial")); ct.addAttribute( new Attribute("center_latitude", volScan.getStationLatitude())); ct.addAttribute( new Attribute("center_longitude", volScan.getStationLongitude())); ct.addAttribute( new Attribute("center_elevation", volScan.getStationElevation())); ct.addAttribute( new Attribute(_Coordinate.TransformType, "Radial")); ct.addAttribute( new Attribute(_Coordinate.AxisTypes, "RadialElevation RadialAzimuth RadialDistance")); Array data = Array.factory(DataType.CHAR.getPrimitiveClassType(), new int[0], new char[] {' '}); ct.setCachedData(data, true); ncfile.addVariable(null, ct); */ } DateFormatter formatter = new DateFormatter(); ncfile.addAttribute(null, new Attribute(CDM.CONVENTIONS, _Coordinate.Convention)); ncfile.addAttribute(null, new Attribute("format", volScan.getDataFormat())); ncfile.addAttribute(null, new Attribute("cdm_data_type", FeatureType.RADIAL.toString())); Date d = getDate(volScan.getTitleJulianDays(), volScan.getTitleMsecs()); ncfile.addAttribute(null, new Attribute("base_date", formatter.toDateOnlyString(d))); ncfile.addAttribute(null, new Attribute("time_coverage_start", formatter.toDateTimeStringISO(d))); ncfile.addAttribute(null, new Attribute("time_coverage_end", formatter.toDateTimeStringISO(volScan.getEndDate()))); ncfile.addAttribute(null, new Attribute(CDM.HISTORY, "Direct read of Nexrad Level 2 file into CDM")); ncfile.addAttribute(null, new Attribute("DataType", "Radial")); ncfile.addAttribute(null, new Attribute("Title", "Nexrad Level 2 Station "+volScan.getStationId()+" from "+ formatter.toDateTimeStringISO(volScan.getStartDate()) + " to " + formatter.toDateTimeStringISO(volScan.getEndDate()))); ncfile.addAttribute(null, new Attribute("Summary", "Weather Surveillance Radar-1988 Doppler (WSR-88D) "+ "Level II data are the three meteorological base data quantities: reflectivity, mean radial velocity, and "+ "spectrum width.")); ncfile.addAttribute(null, new Attribute("keywords", "WSR-88D; NEXRAD; Radar Level II; reflectivity; mean radial velocity; spectrum width")); ncfile.addAttribute(null, new Attribute("VolumeCoveragePatternName", getVolumeCoveragePatternName(volScan.getVCP()))); ncfile.addAttribute(null, new Attribute("VolumeCoveragePattern", volScan.getVCP())); ncfile.addAttribute(null, new Attribute("HorizontalBeamWidthInDegrees", (double) HORIZONTAL_BEAM_WIDTH)); ncfile.finish(); } public void makeVariable2(NetcdfFile ncfile, int datatype, String shortName, String longName, String abbrev, Level2VolumeScan vScan) throws IOException { List<List<Level2Record>> groups = null; if( shortName.startsWith("Reflectivity")) groups = vScan.getHighResReflectivityGroups(); else if( shortName.startsWith("RadialVelocity")) groups = vScan.getHighResVelocityGroups(); else if( shortName.startsWith("DifferentialReflectivity")) groups = vScan.getHighResDiffReflectGroups(); else if( shortName.startsWith("CorrelationCoefficient")) groups = vScan.getHighResCoeffocientGroups(); else if( shortName.startsWith("DifferentialPhase")) groups = vScan.getHighResDiffPhaseGroups(); else throw new IllegalStateException("Bad group: " + shortName); int nscans = groups.size(); if (nscans == 0) { throw new IllegalStateException("No data for "+shortName); } List<List<Level2Record>> firstGroup = new ArrayList<List<Level2Record>>(groups.size()); List<List<Level2Record>> secondGroup = new ArrayList<List<Level2Record>>(groups.size()); for(int i = 0; i < nscans; i++) { List<Level2Record> o = groups.get(i); Level2Record firstRecord = (Level2Record) o.get(0); int ol = o.size(); if(ol >= 720 ) firstGroup.add(o); else if(ol <= 360) secondGroup.add(o); else if( firstRecord.getGateCount(REFLECTIVITY_HIGH) > 500 || firstRecord.getGateCount(VELOCITY_HIGH) > 1000) firstGroup.add(o); else secondGroup.add(o); } if(firstGroup != null && firstGroup.size() > 0) v1 = makeVariable(ncfile, datatype, shortName + "_HI", longName + "_HI", abbrev + "_HI", firstGroup, 1); if(secondGroup != null && secondGroup.size() > 0) v0 = makeVariable(ncfile, datatype, shortName, longName, abbrev, secondGroup, 0); } public int getMaxRadials(List groups) { int maxRadials = 0; for (int i = 0; i < groups.size(); i++) { ArrayList group = (ArrayList) groups.get(i); maxRadials = Math.max(maxRadials, group.size()); } return maxRadials; } public Variable makeVariable(NetcdfFile ncfile, int datatype, String shortName, String longName, String abbrev, List<List<Level2Record>> groups, int rd) throws IOException { int nscans = groups.size(); if (nscans == 0) { throw new IllegalStateException("No data for "+shortName+" file= "+ncfile.getLocation()); } // get representative record List<Level2Record> firstGroup = groups.get(0); Level2Record firstRecord = firstGroup.get(0); int ngates = firstRecord.getGateCount(datatype); String scanDimName = "scan"+abbrev; String gateDimName = "gate"+abbrev; String radialDimName = "radial"+abbrev; Dimension scanDim = new Dimension(scanDimName, nscans); Dimension gateDim = new Dimension(gateDimName, ngates); Dimension radialDim = new Dimension(radialDimName, volScan.getMaxRadials(rd), true); ncfile.addDimension( null, scanDim); ncfile.addDimension( null, gateDim); ncfile.addDimension( null, radialDim); List<Dimension> dims = new ArrayList<Dimension>(); dims.add( scanDim); dims.add( radialDim); dims.add( gateDim); Variable v = new Variable(ncfile, null, null, shortName); if(datatype == DIFF_PHASE){ v.setDataType(DataType.SHORT); } else { v.setDataType(DataType.BYTE); } v.setDimensions(dims); ncfile.addVariable(null, v); v.addAttribute( new Attribute(CDM.UNITS, getDatatypeUnits(datatype))); v.addAttribute( new Attribute(CDM.LONG_NAME, longName)); byte[] b = new byte[2]; b[0] = MISSING_DATA; b[1] = BELOW_THRESHOLD; Array missingArray = Array.factory(DataType.BYTE.getPrimitiveClassType(), new int[] {2}, b); v.addAttribute( new Attribute(CDM.MISSING_VALUE, missingArray)); v.addAttribute( new Attribute("signal_below_threshold", BELOW_THRESHOLD)); v.addAttribute( new Attribute(CDM.SCALE_FACTOR, firstRecord.getDatatypeScaleFactor(datatype))); v.addAttribute( new Attribute(CDM.ADD_OFFSET, firstRecord.getDatatypeAddOffset(datatype))); v.addAttribute( new Attribute(CDM.UNSIGNED, "true")); if(rd == 1) { v.addAttribute( new Attribute("SNR_threshold" ,firstRecord.getDatatypeSNRThreshhold(datatype))); } v.addAttribute( new Attribute("range_folding_threshold" ,firstRecord.getDatatypeRangeFoldingThreshhold(datatype))); List<Dimension> dim2 = new ArrayList<Dimension>(); dim2.add( scanDim); dim2.add( radialDim); // add time coordinate variable String timeCoordName = "time"+abbrev; Variable timeVar = new Variable(ncfile, null, null, timeCoordName); timeVar.setDataType(DataType.INT); timeVar.setDimensions(dim2); ncfile.addVariable(null, timeVar); // int julianDays = volScan.getTitleJulianDays(); // Date d = Level2Record.getDate( julianDays, 0); // Date d = getDate(volScan.getTitleJulianDays(), volScan.getTitleMsecs()); Date d = getDate(volScan.getTitleJulianDays(), 0); // times are msecs from midnight String units = "msecs since "+formatter.toDateTimeStringISO(d); timeVar.addAttribute( new Attribute(CDM.LONG_NAME, "time of each ray")); timeVar.addAttribute( new Attribute(CDM.UNITS, units)); timeVar.addAttribute( new Attribute(CDM.MISSING_VALUE, MISSING_INT)); timeVar.addAttribute( new Attribute(_Coordinate.AxisType, AxisType.Time.toString())); // add elevation coordinate variable String elevCoordName = "elevation"+abbrev; Variable elevVar = new Variable(ncfile, null, null, elevCoordName); elevVar.setDataType(DataType.FLOAT); elevVar.setDimensions(dim2); ncfile.addVariable(null, elevVar); elevVar.addAttribute( new Attribute(CDM.UNITS, "degrees")); elevVar.addAttribute( new Attribute(CDM.LONG_NAME, "elevation angle in degres: 0 = parallel to pedestal base, 90 = perpendicular")); elevVar.addAttribute( new Attribute(CDM.MISSING_VALUE, MISSING_FLOAT)); elevVar.addAttribute( new Attribute(_Coordinate.AxisType, AxisType.RadialElevation.toString())); // add azimuth coordinate variable String aziCoordName = "azimuth"+abbrev; Variable aziVar = new Variable(ncfile, null, null, aziCoordName); aziVar.setDataType(DataType.FLOAT); aziVar.setDimensions(dim2); ncfile.addVariable(null, aziVar); aziVar.addAttribute( new Attribute(CDM.UNITS, "degrees")); aziVar.addAttribute( new Attribute(CDM.LONG_NAME, "azimuth angle in degrees: 0 = true north, 90 = east")); aziVar.addAttribute( new Attribute(CDM.MISSING_VALUE, MISSING_FLOAT)); aziVar.addAttribute( new Attribute(_Coordinate.AxisType, AxisType.RadialAzimuth.toString())); // add gate coordinate variable String gateCoordName = "distance"+abbrev; Variable gateVar = new Variable(ncfile, null, null, gateCoordName); gateVar.setDataType(DataType.FLOAT); gateVar.setDimensions(gateDimName); Array data = Array.makeArray( DataType.FLOAT, ngates, (double) firstRecord.getGateStart(datatype), (double) firstRecord.getGateSize(datatype)); gateVar.setCachedData( data, false); ncfile.addVariable(null, gateVar); radarRadius = firstRecord.getGateStart(datatype) + ngates * firstRecord.getGateSize(datatype); gateVar.addAttribute( new Attribute(CDM.UNITS, "m")); gateVar.addAttribute( new Attribute(CDM.LONG_NAME, "radial distance to start of gate")); gateVar.addAttribute( new Attribute(_Coordinate.AxisType, AxisType.RadialDistance.toString())); // add number of radials variable String nradialsName = "numRadials"+abbrev; Variable nradialsVar = new Variable(ncfile, null, null, nradialsName); nradialsVar.setDataType(DataType.INT); nradialsVar.setDimensions(scanDim.getShortName()); nradialsVar.addAttribute( new Attribute(CDM.LONG_NAME, "number of valid radials in this scan")); ncfile.addVariable(null, nradialsVar); // add number of gates variable String ngateName = "numGates"+abbrev; Variable ngateVar = new Variable(ncfile, null, null, ngateName); ngateVar.setDataType(DataType.INT); ngateVar.setDimensions(scanDim.getShortName()); ngateVar.addAttribute( new Attribute(CDM.LONG_NAME, "number of valid gates in this scan")); ncfile.addVariable(null, ngateVar); makeCoordinateDataWithMissing( datatype, timeVar, elevVar, aziVar, nradialsVar, ngateVar, groups); // back to the data variable String coordinates = timeCoordName+" "+elevCoordName +" "+ aziCoordName+" "+gateCoordName; v.addAttribute( new Attribute(_Coordinate.Axes, coordinates)); // make the record map int nradials = radialDim.getLength(); Level2Record[][] map = new Level2Record[nscans][nradials]; for (int i = 0; i < groups.size(); i++) { Level2Record[] mapScan = map[i]; List<Level2Record> group = groups.get(i); for (Level2Record r : group) { int radial = r.radial_num - 1; mapScan[radial] = r; } } Vgroup vg = new Vgroup(datatype, map); v.setSPobject( vg); return v; } private void makeVariableNoCoords(NetcdfFile ncfile, int datatype, String shortName, String longName, Variable from, Level2Record record) { // get representative record Variable v = new Variable(ncfile, null, null, shortName); v.setDataType(DataType.BYTE); v.setDimensions( from.getDimensions()); ncfile.addVariable(null, v); v.addAttribute( new Attribute(CDM.UNITS, getDatatypeUnits(datatype))); v.addAttribute( new Attribute(CDM.LONG_NAME, longName)); byte[] b = new byte[2]; b[0] = MISSING_DATA; b[1] = BELOW_THRESHOLD; Array missingArray = Array.factory(DataType.BYTE.getPrimitiveClassType(), new int[]{2}, b); v.addAttribute( new Attribute(CDM.MISSING_VALUE, missingArray)); v.addAttribute( new Attribute("signal_below_threshold", BELOW_THRESHOLD)); v.addAttribute( new Attribute(CDM.SCALE_FACTOR, record.getDatatypeScaleFactor(datatype))); v.addAttribute( new Attribute(CDM.ADD_OFFSET, record.getDatatypeAddOffset(datatype))); v.addAttribute( new Attribute(CDM.UNSIGNED, "true")); if(datatype == Level2Record.SPECTRUM_WIDTH_HIGH){ v.addAttribute( new Attribute("SNR_threshold" ,record.getDatatypeSNRThreshhold(datatype))); } v.addAttribute( new Attribute("range_folding_threshold" ,record.getDatatypeRangeFoldingThreshhold(datatype))); Attribute fromAtt = from.findAttribute(_Coordinate.Axes); v.addAttribute( new Attribute(_Coordinate.Axes, fromAtt)); Vgroup vgFrom = (Vgroup) from.getSPobject(); Vgroup vg = new Vgroup(datatype, vgFrom.map); v.setSPobject( vg); } private void makeCoordinateData(int datatype, Variable time, Variable elev, Variable azi, Variable nradialsVar, Variable ngatesVar, List groups) { Array timeData = Array.factory( time.getDataType().getPrimitiveClassType(), time.getShape()); IndexIterator timeDataIter = timeData.getIndexIterator(); Array elevData = Array.factory( elev.getDataType().getPrimitiveClassType(), elev.getShape()); IndexIterator elevDataIter = elevData.getIndexIterator(); Array aziData = Array.factory( azi.getDataType().getPrimitiveClassType(), azi.getShape()); IndexIterator aziDataIter = aziData.getIndexIterator(); Array nradialsData = Array.factory( nradialsVar.getDataType().getPrimitiveClassType(), nradialsVar.getShape()); IndexIterator nradialsIter = nradialsData.getIndexIterator(); Array ngatesData = Array.factory( ngatesVar.getDataType().getPrimitiveClassType(), ngatesVar.getShape()); IndexIterator ngatesIter = ngatesData.getIndexIterator(); int last_msecs = Integer.MIN_VALUE; int nscans = groups.size(); int maxRadials = volScan.getMaxRadials(0); for (int i = 0; i < nscans; i++) { List scanGroup = (List) groups.get(i); int nradials = scanGroup.size(); Level2Record first = null; for (int j = 0; j < nradials; j++) { Level2Record r = (Level2Record) scanGroup.get(j); if (first == null) first = r; timeDataIter.setIntNext( r.data_msecs); elevDataIter.setFloatNext( r.getElevation()); aziDataIter.setFloatNext( r.getAzimuth()); if (r.data_msecs < last_msecs) logger.warn("makeCoordinateData time out of order "+r.data_msecs); last_msecs = r.data_msecs; } for (int j = nradials; j < maxRadials; j++) { timeDataIter.setIntNext( MISSING_INT); elevDataIter.setFloatNext( MISSING_FLOAT); aziDataIter.setFloatNext( MISSING_FLOAT); } nradialsIter.setIntNext( nradials); if (first != null) ngatesIter.setIntNext( first.getGateCount( datatype)); } time.setCachedData( timeData, false); elev.setCachedData( elevData, false); azi.setCachedData( aziData, false); nradialsVar.setCachedData( nradialsData, false); ngatesVar.setCachedData( ngatesData, false); } private void makeCoordinateDataWithMissing(int datatype, Variable time, Variable elev, Variable azi, Variable nradialsVar, Variable ngatesVar, List groups) { Array timeData = Array.factory( time.getDataType().getPrimitiveClassType(), time.getShape()); Index timeIndex = timeData.getIndex(); Array elevData = Array.factory( elev.getDataType().getPrimitiveClassType(), elev.getShape()); Index elevIndex = elevData.getIndex(); Array aziData = Array.factory( azi.getDataType().getPrimitiveClassType(), azi.getShape()); Index aziIndex = aziData.getIndex(); Array nradialsData = Array.factory( nradialsVar.getDataType().getPrimitiveClassType(), nradialsVar.getShape()); IndexIterator nradialsIter = nradialsData.getIndexIterator(); Array ngatesData = Array.factory( ngatesVar.getDataType().getPrimitiveClassType(), ngatesVar.getShape()); IndexIterator ngatesIter = ngatesData.getIndexIterator(); // first fill with missing data IndexIterator ii = timeData.getIndexIterator(); while (ii.hasNext()) ii.setIntNext(MISSING_INT); ii = elevData.getIndexIterator(); while (ii.hasNext()) ii.setFloatNext(MISSING_FLOAT); ii = aziData.getIndexIterator(); while (ii.hasNext()) ii.setFloatNext(MISSING_FLOAT); // now set the coordinate variables from the Level2Record radial int last_msecs = Integer.MIN_VALUE; int nscans = groups.size(); for (int scan = 0; scan < nscans; scan++) { List scanGroup = (List) groups.get(scan); int nradials = scanGroup.size(); Level2Record first = null; for (int j = 0; j < nradials; j++) { Level2Record r = (Level2Record) scanGroup.get(j); if (first == null) first = r; int radial = r.radial_num-1; if(last_msecs != Integer.MIN_VALUE && (last_msecs - r.data_msecs ) > 80000000 ) { overMidNight = true; } if(overMidNight) timeData.setInt( timeIndex.set(scan, radial), r.data_msecs + 24 * 3600 * 1000); else timeData.setInt( timeIndex.set(scan, radial), r.data_msecs); elevData.setFloat( elevIndex.set(scan, radial), r.getElevation()); aziData.setFloat( aziIndex.set(scan, radial), r.getAzimuth()); if (r.data_msecs < last_msecs && !overMidNight) logger.warn("makeCoordinateData time out of order: " + r.data_msecs + " before " + last_msecs); last_msecs = r.data_msecs; } nradialsIter.setIntNext( nradials); if (first != null) ngatesIter.setIntNext( first.getGateCount( datatype)); } time.setCachedData( timeData, false); elev.setCachedData( elevData, false); azi.setCachedData( aziData, false); nradialsVar.setCachedData( nradialsData, false); ngatesVar.setCachedData( ngatesData, false); } public Array readData(Variable v2, Section section) throws IOException, InvalidRangeException { Vgroup vgroup = (Vgroup) v2.getSPobject(); Range scanRange = section.getRange(0); Range radialRange = section.getRange(1); Range gateRange = section.getRange(2); Array data = Array.factory(v2.getDataType().getPrimitiveClassType(), section.getShape()); IndexIterator ii = data.getIndexIterator(); for (int i=scanRange.first(); i<=scanRange.last(); i+= scanRange.stride()) { Level2Record[] mapScan = vgroup.map[i]; readOneScan(mapScan, radialRange, gateRange, vgroup.datatype, ii); } return data; } private void readOneScan(Level2Record[] mapScan, Range radialRange, Range gateRange, int datatype, IndexIterator ii) throws IOException { for (int i=radialRange.first(); i<=radialRange.last(); i+= radialRange.stride()) { Level2Record r = mapScan[i]; readOneRadial(r, datatype, gateRange, ii); } } private void readOneRadial(Level2Record r, int datatype, Range gateRange, IndexIterator ii) throws IOException { if (r == null) { for (int i=gateRange.first(); i<=gateRange.last(); i+= gateRange.stride()) ii.setByteNext( MISSING_DATA); return; } r.readData(volScan.raf, datatype, gateRange, ii); } private class Vgroup { Level2Record[][] map; int datatype; Vgroup( int datatype, Level2Record[][] map) { this.datatype = datatype; this.map = map; } } ///////////////////////////////////////////////////////////////////// public String getFileTypeId() { return DataFormatType.NEXRAD2.toString(); } public String getFileTypeDescription() { return "NEXRAD Level-II Base Data"; } }
cdm/src/main/java/ucar/nc2/iosp/nexrad2/Nexrad2IOServiceProvider.java
/* * 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.nexrad2; import thredds.catalog.DataFormatType; import ucar.ma2.*; import ucar.nc2.*; import ucar.nc2.constants.*; import ucar.nc2.iosp.AbstractIOServiceProvider; import static ucar.nc2.iosp.nexrad2.Level2Record.*; import ucar.nc2.units.DateFormatter; import ucar.nc2.util.CancelTask; import ucar.unidata.io.RandomAccessFile; import java.io.IOException; import java.util.List; import java.util.ArrayList; import java.util.Date; /** * An IOServiceProvider for NEXRAD level II files. * * @author caron */ public class Nexrad2IOServiceProvider extends AbstractIOServiceProvider { static private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(Nexrad2IOServiceProvider.class); static private final int MISSING_INT = -9999; static private final float MISSING_FLOAT = Float.NaN; public boolean isValidFile( RandomAccessFile raf) throws IOException { try { raf.seek(0); String test = raf.readString(8); return test.equals( Level2VolumeScan.ARCHIVE2) || test.equals( Level2VolumeScan.AR2V0001) || test.equals( Level2VolumeScan.AR2V0003)|| test.equals( Level2VolumeScan.AR2V0004) || test.equals( Level2VolumeScan.AR2V0002) || test.equals( Level2VolumeScan.AR2V0006) || test.equals( Level2VolumeScan.AR2V0007); } catch (IOException ioe) { return false; } } private Level2VolumeScan volScan; // private Dimension radialDim; private double radarRadius; private Variable v0, v1; private DateFormatter formatter = new DateFormatter(); private boolean overMidNight = false; public void open(RandomAccessFile raf, NetcdfFile ncfile, CancelTask cancelTask) throws IOException { NexradStationDB.init(); volScan = new Level2VolumeScan( raf, cancelTask); // note raf may change when compressed this.raf = volScan.raf; if (volScan.hasDifferentDopplarResolutions()) throw new IllegalStateException("volScan.hasDifferentDopplarResolutions"); if( volScan.hasHighResolutions(0)) { if(volScan.getHighResReflectivityGroups() != null) makeVariable2( ncfile, Level2Record.REFLECTIVITY_HIGH, "Reflectivity", "Reflectivity", "R", volScan); if( volScan.getHighResVelocityGroups() != null) makeVariable2( ncfile, Level2Record.VELOCITY_HIGH, "RadialVelocity", "Radial Velocity", "V", volScan); if( volScan.getHighResSpectrumGroups() != null) { List<List<Level2Record>> gps = volScan.getHighResSpectrumGroups(); List<Level2Record> gp = gps.get(0); Level2Record record = gp.get(0); if(v1 != null) makeVariableNoCoords( ncfile, Level2Record.SPECTRUM_WIDTH_HIGH, "SpectrumWidth_HI", "Radial Spectrum_HI", v1, record); if(v0 != null) makeVariableNoCoords( ncfile, Level2Record.SPECTRUM_WIDTH_HIGH, "SpectrumWidth", "Radial Spectrum", v0, record); } } List<List<Level2Record>> gps = volScan.getHighResDiffReflectGroups(); if( gps != null) { makeVariable2( ncfile, Level2Record.DIFF_REFLECTIVITY_HIGH, "DifferentialReflectivity", "Differential Reflectivity", "D", volScan); } gps = volScan.getHighResCoeffocientGroups(); if(gps != null) { makeVariable2( ncfile, Level2Record.CORRELATION_COEFFICIENT, "CorrelationCoefficient", "Correlation Coefficient", "C", volScan); } gps = volScan.getHighResDiffPhaseGroups(); if( gps != null) { makeVariable2( ncfile, Level2Record.DIFF_PHASE, "DifferentialPhase", "Differential Phase", "P", volScan); } gps = volScan.getReflectivityGroups(); if( gps != null) { makeVariable( ncfile, Level2Record.REFLECTIVITY, "Reflectivity", "Reflectivity", "R", volScan.getReflectivityGroups(), 0); int velocity_type = (volScan.getDopplarResolution() == Level2Record.DOPPLER_RESOLUTION_HIGH_CODE) ? Level2Record.VELOCITY_HI : Level2Record.VELOCITY_LOW; Variable v = makeVariable( ncfile, velocity_type, "RadialVelocity", "Radial Velocity", "V", volScan.getVelocityGroups(), 0); gps = volScan.getVelocityGroups(); List<Level2Record> gp = gps.get(0); Level2Record record = gp.get(0); makeVariableNoCoords( ncfile, Level2Record.SPECTRUM_WIDTH, "SpectrumWidth", "Spectrum Width", v, record); } if (volScan.getStationId() != null) { ncfile.addAttribute(null, new Attribute("Station", volScan.getStationId())); ncfile.addAttribute(null, new Attribute("StationName", volScan.getStationName())); ncfile.addAttribute(null, new Attribute("StationLatitude", volScan.getStationLatitude())); ncfile.addAttribute(null, new Attribute("StationLongitude", volScan.getStationLongitude())); ncfile.addAttribute(null, new Attribute("StationElevationInMeters", volScan.getStationElevation())); double latRadiusDegrees = Math.toDegrees( radarRadius / ucar.unidata.geoloc.Earth.getRadius()); ncfile.addAttribute(null, new Attribute("geospatial_lat_min", volScan.getStationLatitude() - latRadiusDegrees)); ncfile.addAttribute(null, new Attribute("geospatial_lat_max", volScan.getStationLatitude() + latRadiusDegrees)); double cosLat = Math.cos( Math.toRadians(volScan.getStationLatitude())); double lonRadiusDegrees = Math.toDegrees( radarRadius / cosLat / ucar.unidata.geoloc.Earth.getRadius()); ncfile.addAttribute(null, new Attribute("geospatial_lon_min", volScan.getStationLongitude() - lonRadiusDegrees)); ncfile.addAttribute(null, new Attribute("geospatial_lon_max", volScan.getStationLongitude() + lonRadiusDegrees)); // add a radial coordinate transform (experimental) /* Variable ct = new Variable(ncfile, null, null, "radialCoordinateTransform"); ct.setDataType(DataType.CHAR); ct.setDimensions(""); // scalar ct.addAttribute( new Attribute("transform_name", "Radial")); ct.addAttribute( new Attribute("center_latitude", volScan.getStationLatitude())); ct.addAttribute( new Attribute("center_longitude", volScan.getStationLongitude())); ct.addAttribute( new Attribute("center_elevation", volScan.getStationElevation())); ct.addAttribute( new Attribute(_Coordinate.TransformType, "Radial")); ct.addAttribute( new Attribute(_Coordinate.AxisTypes, "RadialElevation RadialAzimuth RadialDistance")); Array data = Array.factory(DataType.CHAR.getPrimitiveClassType(), new int[0], new char[] {' '}); ct.setCachedData(data, true); ncfile.addVariable(null, ct); */ } DateFormatter formatter = new DateFormatter(); ncfile.addAttribute(null, new Attribute(CDM.CONVENTIONS, _Coordinate.Convention)); ncfile.addAttribute(null, new Attribute("format", volScan.getDataFormat())); ncfile.addAttribute(null, new Attribute("cdm_data_type", FeatureType.RADIAL.toString())); Date d = getDate(volScan.getTitleJulianDays(), volScan.getTitleMsecs()); ncfile.addAttribute(null, new Attribute("base_date", formatter.toDateOnlyString(d))); ncfile.addAttribute(null, new Attribute("time_coverage_start", formatter.toDateTimeStringISO(d))); ncfile.addAttribute(null, new Attribute("time_coverage_end", formatter.toDateTimeStringISO(volScan.getEndDate()))); ncfile.addAttribute(null, new Attribute(CDM.HISTORY, "Direct read of Nexrad Level 2 file into CDM")); ncfile.addAttribute(null, new Attribute("DataType", "Radial")); ncfile.addAttribute(null, new Attribute("Title", "Nexrad Level 2 Station "+volScan.getStationId()+" from "+ formatter.toDateTimeStringISO(volScan.getStartDate()) + " to " + formatter.toDateTimeStringISO(volScan.getEndDate()))); ncfile.addAttribute(null, new Attribute("Summary", "Weather Surveillance Radar-1988 Doppler (WSR-88D) "+ "Level II data are the three meteorological base data quantities: reflectivity, mean radial velocity, and "+ "spectrum width.")); ncfile.addAttribute(null, new Attribute("keywords", "WSR-88D; NEXRAD; Radar Level II; reflectivity; mean radial velocity; spectrum width")); ncfile.addAttribute(null, new Attribute("VolumeCoveragePatternName", getVolumeCoveragePatternName(volScan.getVCP()))); ncfile.addAttribute(null, new Attribute("VolumeCoveragePattern", volScan.getVCP())); ncfile.addAttribute(null, new Attribute("HorizontalBeamWidthInDegrees", (double) HORIZONTAL_BEAM_WIDTH)); ncfile.finish(); } public void makeVariable2(NetcdfFile ncfile, int datatype, String shortName, String longName, String abbrev, Level2VolumeScan vScan) throws IOException { List<List<Level2Record>> groups = null; if( shortName.startsWith("Reflectivity")) groups = vScan.getHighResReflectivityGroups(); else if( shortName.startsWith("RadialVelocity")) groups = vScan.getHighResVelocityGroups(); else if( shortName.startsWith("DifferentialReflectivity")) groups = vScan.getHighResDiffReflectGroups(); else if( shortName.startsWith("CorrelationCoefficient")) groups = vScan.getHighResCoeffocientGroups(); else if( shortName.startsWith("DifferentialPhase")) groups = vScan.getHighResDiffPhaseGroups(); int nscans = groups.size(); if (nscans == 0) { throw new IllegalStateException("No data for "+shortName); } List<List<Level2Record>> firstGroup = new ArrayList<List<Level2Record>>(groups.size()); List<List<Level2Record>> secondGroup = new ArrayList<List<Level2Record>>(groups.size()); for(int i = 0; i < nscans; i++) { List<Level2Record> o = groups.get(i); Level2Record firstRecord = (Level2Record) o.get(0); int ol = o.size(); if(ol >= 720 ) firstGroup.add(o); else if(ol <= 360) secondGroup.add(o); else if( firstRecord.getGateCount(REFLECTIVITY_HIGH) > 500 || firstRecord.getGateCount(VELOCITY_HIGH) > 1000) firstGroup.add(o); else secondGroup.add(o); } if(firstGroup != null && firstGroup.size() > 0) v1 = makeVariable(ncfile, datatype, shortName + "_HI", longName + "_HI", abbrev + "_HI", firstGroup, 1); if(secondGroup != null && secondGroup.size() > 0) v0 = makeVariable(ncfile, datatype, shortName, longName, abbrev, secondGroup, 0); } public int getMaxRadials(List groups) { int maxRadials = 0; for (int i = 0; i < groups.size(); i++) { ArrayList group = (ArrayList) groups.get(i); maxRadials = Math.max(maxRadials, group.size()); } return maxRadials; } public Variable makeVariable(NetcdfFile ncfile, int datatype, String shortName, String longName, String abbrev, List<List<Level2Record>> groups, int rd) throws IOException { int nscans = groups.size(); if (nscans == 0) { throw new IllegalStateException("No data for "+shortName+" file= "+ncfile.getLocation()); } // get representative record List<Level2Record> firstGroup = groups.get(0); Level2Record firstRecord = firstGroup.get(0); int ngates = firstRecord.getGateCount(datatype); String scanDimName = "scan"+abbrev; String gateDimName = "gate"+abbrev; String radialDimName = "radial"+abbrev; Dimension scanDim = new Dimension(scanDimName, nscans); Dimension gateDim = new Dimension(gateDimName, ngates); Dimension radialDim = new Dimension(radialDimName, volScan.getMaxRadials(rd), true); ncfile.addDimension( null, scanDim); ncfile.addDimension( null, gateDim); ncfile.addDimension( null, radialDim); List<Dimension> dims = new ArrayList<Dimension>(); dims.add( scanDim); dims.add( radialDim); dims.add( gateDim); Variable v = new Variable(ncfile, null, null, shortName); if(datatype == DIFF_PHASE){ v.setDataType(DataType.SHORT); } else { v.setDataType(DataType.BYTE); } v.setDimensions(dims); ncfile.addVariable(null, v); v.addAttribute( new Attribute(CDM.UNITS, getDatatypeUnits(datatype))); v.addAttribute( new Attribute(CDM.LONG_NAME, longName)); byte[] b = new byte[2]; b[0] = MISSING_DATA; b[1] = BELOW_THRESHOLD; Array missingArray = Array.factory(DataType.BYTE.getPrimitiveClassType(), new int[] {2}, b); v.addAttribute( new Attribute(CDM.MISSING_VALUE, missingArray)); v.addAttribute( new Attribute("signal_below_threshold", BELOW_THRESHOLD)); v.addAttribute( new Attribute(CDM.SCALE_FACTOR, firstRecord.getDatatypeScaleFactor(datatype))); v.addAttribute( new Attribute(CDM.ADD_OFFSET, firstRecord.getDatatypeAddOffset(datatype))); v.addAttribute( new Attribute(CDM.UNSIGNED, "true")); if(rd == 1) { v.addAttribute( new Attribute("SNR_threshold" ,firstRecord.getDatatypeSNRThreshhold(datatype))); } v.addAttribute( new Attribute("range_folding_threshold" ,firstRecord.getDatatypeRangeFoldingThreshhold(datatype))); List<Dimension> dim2 = new ArrayList<Dimension>(); dim2.add( scanDim); dim2.add( radialDim); // add time coordinate variable String timeCoordName = "time"+abbrev; Variable timeVar = new Variable(ncfile, null, null, timeCoordName); timeVar.setDataType(DataType.INT); timeVar.setDimensions(dim2); ncfile.addVariable(null, timeVar); // int julianDays = volScan.getTitleJulianDays(); // Date d = Level2Record.getDate( julianDays, 0); // Date d = getDate(volScan.getTitleJulianDays(), volScan.getTitleMsecs()); Date d = getDate(volScan.getTitleJulianDays(), 0); // times are msecs from midnight String units = "msecs since "+formatter.toDateTimeStringISO(d); timeVar.addAttribute( new Attribute(CDM.LONG_NAME, "time of each ray")); timeVar.addAttribute( new Attribute(CDM.UNITS, units)); timeVar.addAttribute( new Attribute(CDM.MISSING_VALUE, MISSING_INT)); timeVar.addAttribute( new Attribute(_Coordinate.AxisType, AxisType.Time.toString())); // add elevation coordinate variable String elevCoordName = "elevation"+abbrev; Variable elevVar = new Variable(ncfile, null, null, elevCoordName); elevVar.setDataType(DataType.FLOAT); elevVar.setDimensions(dim2); ncfile.addVariable(null, elevVar); elevVar.addAttribute( new Attribute(CDM.UNITS, "degrees")); elevVar.addAttribute( new Attribute(CDM.LONG_NAME, "elevation angle in degres: 0 = parallel to pedestal base, 90 = perpendicular")); elevVar.addAttribute( new Attribute(CDM.MISSING_VALUE, MISSING_FLOAT)); elevVar.addAttribute( new Attribute(_Coordinate.AxisType, AxisType.RadialElevation.toString())); // add azimuth coordinate variable String aziCoordName = "azimuth"+abbrev; Variable aziVar = new Variable(ncfile, null, null, aziCoordName); aziVar.setDataType(DataType.FLOAT); aziVar.setDimensions(dim2); ncfile.addVariable(null, aziVar); aziVar.addAttribute( new Attribute(CDM.UNITS, "degrees")); aziVar.addAttribute( new Attribute(CDM.LONG_NAME, "azimuth angle in degrees: 0 = true north, 90 = east")); aziVar.addAttribute( new Attribute(CDM.MISSING_VALUE, MISSING_FLOAT)); aziVar.addAttribute( new Attribute(_Coordinate.AxisType, AxisType.RadialAzimuth.toString())); // add gate coordinate variable String gateCoordName = "distance"+abbrev; Variable gateVar = new Variable(ncfile, null, null, gateCoordName); gateVar.setDataType(DataType.FLOAT); gateVar.setDimensions(gateDimName); Array data = Array.makeArray( DataType.FLOAT, ngates, (double) firstRecord.getGateStart(datatype), (double) firstRecord.getGateSize(datatype)); gateVar.setCachedData( data, false); ncfile.addVariable(null, gateVar); radarRadius = firstRecord.getGateStart(datatype) + ngates * firstRecord.getGateSize(datatype); gateVar.addAttribute( new Attribute(CDM.UNITS, "m")); gateVar.addAttribute( new Attribute(CDM.LONG_NAME, "radial distance to start of gate")); gateVar.addAttribute( new Attribute(_Coordinate.AxisType, AxisType.RadialDistance.toString())); // add number of radials variable String nradialsName = "numRadials"+abbrev; Variable nradialsVar = new Variable(ncfile, null, null, nradialsName); nradialsVar.setDataType(DataType.INT); nradialsVar.setDimensions(scanDim.getShortName()); nradialsVar.addAttribute( new Attribute(CDM.LONG_NAME, "number of valid radials in this scan")); ncfile.addVariable(null, nradialsVar); // add number of gates variable String ngateName = "numGates"+abbrev; Variable ngateVar = new Variable(ncfile, null, null, ngateName); ngateVar.setDataType(DataType.INT); ngateVar.setDimensions(scanDim.getShortName()); ngateVar.addAttribute( new Attribute(CDM.LONG_NAME, "number of valid gates in this scan")); ncfile.addVariable(null, ngateVar); makeCoordinateDataWithMissing( datatype, timeVar, elevVar, aziVar, nradialsVar, ngateVar, groups); // back to the data variable String coordinates = timeCoordName+" "+elevCoordName +" "+ aziCoordName+" "+gateCoordName; v.addAttribute( new Attribute(_Coordinate.Axes, coordinates)); // make the record map int nradials = radialDim.getLength(); Level2Record[][] map = new Level2Record[nscans][nradials]; for (int i = 0; i < groups.size(); i++) { Level2Record[] mapScan = map[i]; List<Level2Record> group = groups.get(i); for (Level2Record r : group) { int radial = r.radial_num - 1; mapScan[radial] = r; } } Vgroup vg = new Vgroup(datatype, map); v.setSPobject( vg); return v; } private void makeVariableNoCoords(NetcdfFile ncfile, int datatype, String shortName, String longName, Variable from, Level2Record record) { // get representative record Variable v = new Variable(ncfile, null, null, shortName); v.setDataType(DataType.BYTE); v.setDimensions( from.getDimensions()); ncfile.addVariable(null, v); v.addAttribute( new Attribute(CDM.UNITS, getDatatypeUnits(datatype))); v.addAttribute( new Attribute(CDM.LONG_NAME, longName)); byte[] b = new byte[2]; b[0] = MISSING_DATA; b[1] = BELOW_THRESHOLD; Array missingArray = Array.factory(DataType.BYTE.getPrimitiveClassType(), new int[]{2}, b); v.addAttribute( new Attribute(CDM.MISSING_VALUE, missingArray)); v.addAttribute( new Attribute("signal_below_threshold", BELOW_THRESHOLD)); v.addAttribute( new Attribute(CDM.SCALE_FACTOR, record.getDatatypeScaleFactor(datatype))); v.addAttribute( new Attribute(CDM.ADD_OFFSET, record.getDatatypeAddOffset(datatype))); v.addAttribute( new Attribute(CDM.UNSIGNED, "true")); if(datatype == Level2Record.SPECTRUM_WIDTH_HIGH){ v.addAttribute( new Attribute("SNR_threshold" ,record.getDatatypeSNRThreshhold(datatype))); } v.addAttribute( new Attribute("range_folding_threshold" ,record.getDatatypeRangeFoldingThreshhold(datatype))); Attribute fromAtt = from.findAttribute(_Coordinate.Axes); v.addAttribute( new Attribute(_Coordinate.Axes, fromAtt)); Vgroup vgFrom = (Vgroup) from.getSPobject(); Vgroup vg = new Vgroup(datatype, vgFrom.map); v.setSPobject( vg); } private void makeCoordinateData(int datatype, Variable time, Variable elev, Variable azi, Variable nradialsVar, Variable ngatesVar, List groups) { Array timeData = Array.factory( time.getDataType().getPrimitiveClassType(), time.getShape()); IndexIterator timeDataIter = timeData.getIndexIterator(); Array elevData = Array.factory( elev.getDataType().getPrimitiveClassType(), elev.getShape()); IndexIterator elevDataIter = elevData.getIndexIterator(); Array aziData = Array.factory( azi.getDataType().getPrimitiveClassType(), azi.getShape()); IndexIterator aziDataIter = aziData.getIndexIterator(); Array nradialsData = Array.factory( nradialsVar.getDataType().getPrimitiveClassType(), nradialsVar.getShape()); IndexIterator nradialsIter = nradialsData.getIndexIterator(); Array ngatesData = Array.factory( ngatesVar.getDataType().getPrimitiveClassType(), ngatesVar.getShape()); IndexIterator ngatesIter = ngatesData.getIndexIterator(); int last_msecs = Integer.MIN_VALUE; int nscans = groups.size(); int maxRadials = volScan.getMaxRadials(0); for (int i = 0; i < nscans; i++) { List scanGroup = (List) groups.get(i); int nradials = scanGroup.size(); Level2Record first = null; for (int j = 0; j < nradials; j++) { Level2Record r = (Level2Record) scanGroup.get(j); if (first == null) first = r; timeDataIter.setIntNext( r.data_msecs); elevDataIter.setFloatNext( r.getElevation()); aziDataIter.setFloatNext( r.getAzimuth()); if (r.data_msecs < last_msecs) logger.warn("makeCoordinateData time out of order "+r.data_msecs); last_msecs = r.data_msecs; } for (int j = nradials; j < maxRadials; j++) { timeDataIter.setIntNext( MISSING_INT); elevDataIter.setFloatNext( MISSING_FLOAT); aziDataIter.setFloatNext( MISSING_FLOAT); } nradialsIter.setIntNext( nradials); if (first != null) ngatesIter.setIntNext( first.getGateCount( datatype)); } time.setCachedData( timeData, false); elev.setCachedData( elevData, false); azi.setCachedData( aziData, false); nradialsVar.setCachedData( nradialsData, false); ngatesVar.setCachedData( ngatesData, false); } private void makeCoordinateDataWithMissing(int datatype, Variable time, Variable elev, Variable azi, Variable nradialsVar, Variable ngatesVar, List groups) { Array timeData = Array.factory( time.getDataType().getPrimitiveClassType(), time.getShape()); Index timeIndex = timeData.getIndex(); Array elevData = Array.factory( elev.getDataType().getPrimitiveClassType(), elev.getShape()); Index elevIndex = elevData.getIndex(); Array aziData = Array.factory( azi.getDataType().getPrimitiveClassType(), azi.getShape()); Index aziIndex = aziData.getIndex(); Array nradialsData = Array.factory( nradialsVar.getDataType().getPrimitiveClassType(), nradialsVar.getShape()); IndexIterator nradialsIter = nradialsData.getIndexIterator(); Array ngatesData = Array.factory( ngatesVar.getDataType().getPrimitiveClassType(), ngatesVar.getShape()); IndexIterator ngatesIter = ngatesData.getIndexIterator(); // first fill with missing data IndexIterator ii = timeData.getIndexIterator(); while (ii.hasNext()) ii.setIntNext(MISSING_INT); ii = elevData.getIndexIterator(); while (ii.hasNext()) ii.setFloatNext(MISSING_FLOAT); ii = aziData.getIndexIterator(); while (ii.hasNext()) ii.setFloatNext(MISSING_FLOAT); // now set the coordinate variables from the Level2Record radial int last_msecs = Integer.MIN_VALUE; int nscans = groups.size(); for (int scan = 0; scan < nscans; scan++) { List scanGroup = (List) groups.get(scan); int nradials = scanGroup.size(); Level2Record first = null; for (int j = 0; j < nradials; j++) { Level2Record r = (Level2Record) scanGroup.get(j); if (first == null) first = r; int radial = r.radial_num-1; if(last_msecs != Integer.MIN_VALUE && (last_msecs - r.data_msecs ) > 80000000 ) { overMidNight = true; } if(overMidNight) timeData.setInt( timeIndex.set(scan, radial), r.data_msecs + 24 * 3600 * 1000); else timeData.setInt( timeIndex.set(scan, radial), r.data_msecs); elevData.setFloat( elevIndex.set(scan, radial), r.getElevation()); aziData.setFloat( aziIndex.set(scan, radial), r.getAzimuth()); if (r.data_msecs < last_msecs && !overMidNight) logger.warn("makeCoordinateData time out of order: " + r.data_msecs + " before " + last_msecs); last_msecs = r.data_msecs; } nradialsIter.setIntNext( nradials); if (first != null) ngatesIter.setIntNext( first.getGateCount( datatype)); } time.setCachedData( timeData, false); elev.setCachedData( elevData, false); azi.setCachedData( aziData, false); nradialsVar.setCachedData( nradialsData, false); ngatesVar.setCachedData( ngatesData, false); } public Array readData(Variable v2, Section section) throws IOException, InvalidRangeException { Vgroup vgroup = (Vgroup) v2.getSPobject(); Range scanRange = section.getRange(0); Range radialRange = section.getRange(1); Range gateRange = section.getRange(2); Array data = Array.factory(v2.getDataType().getPrimitiveClassType(), section.getShape()); IndexIterator ii = data.getIndexIterator(); for (int i=scanRange.first(); i<=scanRange.last(); i+= scanRange.stride()) { Level2Record[] mapScan = vgroup.map[i]; readOneScan(mapScan, radialRange, gateRange, vgroup.datatype, ii); } return data; } private void readOneScan(Level2Record[] mapScan, Range radialRange, Range gateRange, int datatype, IndexIterator ii) throws IOException { for (int i=radialRange.first(); i<=radialRange.last(); i+= radialRange.stride()) { Level2Record r = mapScan[i]; readOneRadial(r, datatype, gateRange, ii); } } private void readOneRadial(Level2Record r, int datatype, Range gateRange, IndexIterator ii) throws IOException { if (r == null) { for (int i=gateRange.first(); i<=gateRange.last(); i+= gateRange.stride()) ii.setByteNext( MISSING_DATA); return; } r.readData(volScan.raf, datatype, gateRange, ii); } private class Vgroup { Level2Record[][] map; int datatype; Vgroup( int datatype, Level2Record[][] map) { this.datatype = datatype; this.map = map; } } ///////////////////////////////////////////////////////////////////// public String getFileTypeId() { return DataFormatType.NEXRAD2.toString(); } public String getFileTypeDescription() { return "NEXRAD Level-II Base Data"; } }
Handle bad group name. Found by Coverity.
cdm/src/main/java/ucar/nc2/iosp/nexrad2/Nexrad2IOServiceProvider.java
Handle bad group name.
<ide><path>dm/src/main/java/ucar/nc2/iosp/nexrad2/Nexrad2IOServiceProvider.java <ide> groups = vScan.getHighResCoeffocientGroups(); <ide> else if( shortName.startsWith("DifferentialPhase")) <ide> groups = vScan.getHighResDiffPhaseGroups(); <add> else <add> throw new IllegalStateException("Bad group: " + shortName); <ide> <ide> int nscans = groups.size(); <ide>
Java
apache-2.0
f06a1b95c4568997295e987b9617be799c517845
0
mohanaraosv/commons-cli,pplatek/commons-cli,apache/commons-cli,pplatek/commons-cli,pplatek/commons-cli,pplatek/commons-cli,mohanaraosv/commons-cli,apache/commons-cli,mohanaraosv/commons-cli,mohanaraosv/commons-cli,apache/commons-cli,apache/commons-cli
/* * 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.cli.bug; import java.io.PrintWriter; import java.io.StringWriter; import java.sql.ParameterMetaData; import java.sql.Types; import junit.framework.TestCase; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; public class BugCLI162Test extends TestCase { /** Constant for the line separator.*/ private static final String CR = System.getProperty("line.separator"); public void testInfiniteLoop() { Options options = new Options(); options.addOption("h", "help", false, "This is a looooong description"); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(20); formatter.printHelp("app", options); // used to hang & crash } public void testPrintHelpLongLines() { // Constants used for options final String OPT = "-"; final String OPT_COLUMN_NAMES = "l"; final String OPT_CONNECTION = "c"; final String OPT_DESCRIPTION = "e"; final String OPT_DRIVER = "d"; final String OPT_DRIVER_INFO = "n"; final String OPT_FILE_BINDING = "b"; final String OPT_FILE_JDBC = "j"; final String OPT_FILE_SFMD = "f"; final String OPT_HELP = "h"; final String OPT_HELP_ = "help"; final String OPT_INTERACTIVE = "i"; final String OPT_JDBC_TO_SFMD = "2"; final String OPT_JDBC_TO_SFMD_L = "jdbc2sfmd"; final String OPT_METADATA = "m"; final String OPT_PARAM_MODES_INT = "o"; final String OPT_PARAM_MODES_NAME = "O"; final String OPT_PARAM_NAMES = "a"; final String OPT_PARAM_TYPES_INT = "y"; final String OPT_PARAM_TYPES_NAME = "Y"; final String OPT_PASSWORD = "p"; final String OPT_PASSWORD_L = "password"; final String OPT_SQL = "s"; final String OPT_SQL_L = "sql"; final String OPT_SQL_SPLIT_DEFAULT = "###"; final String OPT_SQL_SPLIT_L = "splitSql"; final String OPT_STACK_TRACE = "t"; final String OPT_TIMING = "g"; final String OPT_TRIM_L = "trim"; final String OPT_USER = "u"; final String OPT_WRITE_TO_FILE = "w"; final String _PMODE_IN = "IN"; final String _PMODE_INOUT = "INOUT"; final String _PMODE_OUT = "OUT"; final String _PMODE_UNK = "Unknown"; final String PMODES = _PMODE_IN + ", " + _PMODE_INOUT + ", " + _PMODE_OUT + ", " + _PMODE_UNK; // Options build Options commandLineOptions; commandLineOptions = new Options(); commandLineOptions.addOption(OPT_HELP, OPT_HELP_, false, "Prints help and quits"); commandLineOptions.addOption(OPT_DRIVER, "driver", true, "JDBC driver class name"); commandLineOptions.addOption(OPT_DRIVER_INFO, "info", false, "Prints driver information and properties. If " + OPT + OPT_CONNECTION + " is not specified, all drivers on the classpath are displayed."); commandLineOptions.addOption(OPT_CONNECTION, "url", true, "Connection URL"); commandLineOptions.addOption(OPT_USER, "user", true, "A database user name"); commandLineOptions .addOption( OPT_PASSWORD, OPT_PASSWORD_L, true, "The database password for the user specified with the " + OPT + OPT_USER + " option. You can obfuscate the password with org.mortbay.jetty.security.Password, see http://docs.codehaus.org/display/JETTY/Securing+Passwords"); commandLineOptions.addOption(OPT_SQL, OPT_SQL_L, true, "Runs SQL or {call stored_procedure(?, ?)} or {?=call function(?, ?)}"); commandLineOptions.addOption(OPT_FILE_SFMD, "sfmd", true, "Writes a SFMD file for the given SQL"); commandLineOptions.addOption(OPT_FILE_BINDING, "jdbc", true, "Writes a JDBC binding node file for the given SQL"); commandLineOptions.addOption(OPT_FILE_JDBC, "node", true, "Writes a JDBC node file for the given SQL (internal debugging)"); commandLineOptions.addOption(OPT_WRITE_TO_FILE, "outfile", true, "Writes the SQL output to the given file"); commandLineOptions.addOption(OPT_DESCRIPTION, "description", true, "SFMD description. A default description is used if omited. Example: " + OPT + OPT_DESCRIPTION + " \"Runs such and such\""); commandLineOptions.addOption(OPT_INTERACTIVE, "interactive", false, "Runs in interactive mode, reading and writing from the console, 'go' or '/' sends a statement"); commandLineOptions.addOption(OPT_TIMING, "printTiming", false, "Prints timing information"); commandLineOptions.addOption(OPT_METADATA, "printMetaData", false, "Prints metadata information"); commandLineOptions.addOption(OPT_STACK_TRACE, "printStack", false, "Prints stack traces on errors"); Option option = new Option(OPT_COLUMN_NAMES, "columnNames", true, "Column XML names; default names column labels. Example: " + OPT + OPT_COLUMN_NAMES + " \"cname1 cname2\""); commandLineOptions.addOption(option); option = new Option(OPT_PARAM_NAMES, "paramNames", true, "Parameter XML names; default names are param1, param2, etc. Example: " + OPT + OPT_PARAM_NAMES + " \"pname1 pname2\""); commandLineOptions.addOption(option); // OptionGroup pOutTypesOptionGroup = new OptionGroup(); String pOutTypesOptionGroupDoc = OPT + OPT_PARAM_TYPES_INT + " and " + OPT + OPT_PARAM_TYPES_NAME + " are mutually exclusive."; final String typesClassName = Types.class.getName(); option = new Option(OPT_PARAM_TYPES_INT, "paramTypes", true, "Parameter types from " + typesClassName + ". " + pOutTypesOptionGroupDoc + " Example: " + OPT + OPT_PARAM_TYPES_INT + " \"-10 12\""); commandLineOptions.addOption(option); option = new Option(OPT_PARAM_TYPES_NAME, "paramTypeNames", true, "Parameter " + typesClassName + " names. " + pOutTypesOptionGroupDoc + " Example: " + OPT + OPT_PARAM_TYPES_NAME + " \"CURSOR VARCHAR\""); commandLineOptions.addOption(option); commandLineOptions.addOptionGroup(pOutTypesOptionGroup); // OptionGroup modesOptionGroup = new OptionGroup(); String modesOptionGroupDoc = OPT + OPT_PARAM_MODES_INT + " and " + OPT + OPT_PARAM_MODES_NAME + " are mutually exclusive."; option = new Option(OPT_PARAM_MODES_INT, "paramModes", true, "Parameters modes (" + ParameterMetaData.parameterModeIn + "=IN, " + ParameterMetaData.parameterModeInOut + "=INOUT, " + ParameterMetaData.parameterModeOut + "=OUT, " + ParameterMetaData.parameterModeUnknown + "=Unknown" + "). " + modesOptionGroupDoc + " Example for 2 parameters, OUT and IN: " + OPT + OPT_PARAM_MODES_INT + " \"" + ParameterMetaData.parameterModeOut + " " + ParameterMetaData.parameterModeIn + "\""); modesOptionGroup.addOption(option); option = new Option(OPT_PARAM_MODES_NAME, "paramModeNames", true, "Parameters mode names (" + PMODES + "). " + modesOptionGroupDoc + " Example for 2 parameters, OUT and IN: " + OPT + OPT_PARAM_MODES_NAME + " \"" + _PMODE_OUT + " " + _PMODE_IN + "\""); modesOptionGroup.addOption(option); commandLineOptions.addOptionGroup(modesOptionGroup); option = new Option(null, OPT_TRIM_L, true, "Trims leading and trailing spaces from all column values. Column XML names can be optionally specified to set which columns to trim."); option.setOptionalArg(true); commandLineOptions.addOption(option); option = new Option(OPT_JDBC_TO_SFMD, OPT_JDBC_TO_SFMD_L, true, "Converts the JDBC file in the first argument to an SMFD file specified in the second argument."); option.setArgs(2); commandLineOptions.addOption(option); new HelpFormatter().printHelp(this.getClass().getName(), commandLineOptions); } public void testLongLineChunking() { Options options = new Options(); options.addOption("x", "extralongarg", false, "This description has ReallyLongValuesThatAreLongerThanTheWidthOfTheColumns " + "and also other ReallyLongValuesThatAreHugerAndBiggerThanTheWidthOfTheColumnsBob, " + "yes. "); HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); formatter.printHelp(new PrintWriter(sw), 35, this.getClass().getName(), "Header", options, 0, 5, "Footer"); String expected = "usage:" + CR + " org.apache.commons.cli.bug.B" + CR + " ugCLI162Test" + CR + "Header" + CR + "-x,--extralongarg This" + CR + " description" + CR + " has" + CR + " ReallyLongVal" + CR + " uesThatAreLon" + CR + " gerThanTheWid" + CR + " thOfTheColumn" + CR + " s and also" + CR + " other" + CR + " ReallyLongVal" + CR + " uesThatAreHug" + CR + " erAndBiggerTh" + CR + " anTheWidthOfT" + CR + " heColumnsBob," + CR + " yes." + CR + "Footer" + CR; assertEquals( "Long arguments did not split as expected", expected, sw.toString() ); } public void testLongLineChunkingIndentIgnored() { Options options = new Options(); options.addOption("x", "extralongarg", false, "This description is Long." ); HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); formatter.printHelp(new PrintWriter(sw), 22, this.getClass().getName(), "Header", options, 0, 5, "Footer"); System.err.println(sw.toString()); String expected = "usage:" + CR + " org.apache.comm" + CR + " ons.cli.bug.Bug" + CR + " CLI162Test" + CR + "Header" + CR + "-x,--extralongarg" + CR + " This description is" + CR + " Long." + CR + "Footer" + CR; assertEquals( "Long arguments did not split as expected", expected, sw.toString() ); } }
src/test/java/org/apache/commons/cli/bug/BugCLI162Test.java
/* * 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.cli.bug; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.sql.ParameterMetaData; import java.sql.Types; import junit.framework.TestCase; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; public class BugCLI162Test extends TestCase { /** Constant for the line separator.*/ private static final String CR = System.getProperty("line.separator"); public void testInfiniteLoop() { Options options = new Options(); options.addOption("h", "help", false, "This is a looooong description"); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(20); formatter.printHelp("app", options); // used to hang & crash } public void testPrintHelpLongLines() throws ParseException, IOException { // Constants used for options final String OPT = "-"; final String OPT_COLUMN_NAMES = "l"; final String OPT_CONNECTION = "c"; final String OPT_DESCRIPTION = "e"; final String OPT_DRIVER = "d"; final String OPT_DRIVER_INFO = "n"; final String OPT_FILE_BINDING = "b"; final String OPT_FILE_JDBC = "j"; final String OPT_FILE_SFMD = "f"; final String OPT_HELP = "h"; final String OPT_HELP_ = "help"; final String OPT_INTERACTIVE = "i"; final String OPT_JDBC_TO_SFMD = "2"; final String OPT_JDBC_TO_SFMD_L = "jdbc2sfmd"; final String OPT_METADATA = "m"; final String OPT_PARAM_MODES_INT = "o"; final String OPT_PARAM_MODES_NAME = "O"; final String OPT_PARAM_NAMES = "a"; final String OPT_PARAM_TYPES_INT = "y"; final String OPT_PARAM_TYPES_NAME = "Y"; final String OPT_PASSWORD = "p"; final String OPT_PASSWORD_L = "password"; final String OPT_SQL = "s"; final String OPT_SQL_L = "sql"; final String OPT_SQL_SPLIT_DEFAULT = "###"; final String OPT_SQL_SPLIT_L = "splitSql"; final String OPT_STACK_TRACE = "t"; final String OPT_TIMING = "g"; final String OPT_TRIM_L = "trim"; final String OPT_USER = "u"; final String OPT_WRITE_TO_FILE = "w"; final String _PMODE_IN = "IN"; final String _PMODE_INOUT = "INOUT"; final String _PMODE_OUT = "OUT"; final String _PMODE_UNK = "Unknown"; final String PMODES = _PMODE_IN + ", " + _PMODE_INOUT + ", " + _PMODE_OUT + ", " + _PMODE_UNK; // Options build Options commandLineOptions; commandLineOptions = new Options(); commandLineOptions.addOption(OPT_HELP, OPT_HELP_, false, "Prints help and quits"); commandLineOptions.addOption(OPT_DRIVER, "driver", true, "JDBC driver class name"); commandLineOptions.addOption(OPT_DRIVER_INFO, "info", false, "Prints driver information and properties. If " + OPT + OPT_CONNECTION + " is not specified, all drivers on the classpath are displayed."); commandLineOptions.addOption(OPT_CONNECTION, "url", true, "Connection URL"); commandLineOptions.addOption(OPT_USER, "user", true, "A database user name"); commandLineOptions .addOption( OPT_PASSWORD, OPT_PASSWORD_L, true, "The database password for the user specified with the " + OPT + OPT_USER + " option. You can obfuscate the password with org.mortbay.jetty.security.Password, see http://docs.codehaus.org/display/JETTY/Securing+Passwords"); commandLineOptions.addOption(OPT_SQL, OPT_SQL_L, true, "Runs SQL or {call stored_procedure(?, ?)} or {?=call function(?, ?)}"); commandLineOptions.addOption(OPT_FILE_SFMD, "sfmd", true, "Writes a SFMD file for the given SQL"); commandLineOptions.addOption(OPT_FILE_BINDING, "jdbc", true, "Writes a JDBC binding node file for the given SQL"); commandLineOptions.addOption(OPT_FILE_JDBC, "node", true, "Writes a JDBC node file for the given SQL (internal debugging)"); commandLineOptions.addOption(OPT_WRITE_TO_FILE, "outfile", true, "Writes the SQL output to the given file"); commandLineOptions.addOption(OPT_DESCRIPTION, "description", true, "SFMD description. A default description is used if omited. Example: " + OPT + OPT_DESCRIPTION + " \"Runs such and such\""); commandLineOptions.addOption(OPT_INTERACTIVE, "interactive", false, "Runs in interactive mode, reading and writing from the console, 'go' or '/' sends a statement"); commandLineOptions.addOption(OPT_TIMING, "printTiming", false, "Prints timing information"); commandLineOptions.addOption(OPT_METADATA, "printMetaData", false, "Prints metadata information"); commandLineOptions.addOption(OPT_STACK_TRACE, "printStack", false, "Prints stack traces on errors"); Option option = new Option(OPT_COLUMN_NAMES, "columnNames", true, "Column XML names; default names column labels. Example: " + OPT + OPT_COLUMN_NAMES + " \"cname1 cname2\""); commandLineOptions.addOption(option); option = new Option(OPT_PARAM_NAMES, "paramNames", true, "Parameter XML names; default names are param1, param2, etc. Example: " + OPT + OPT_PARAM_NAMES + " \"pname1 pname2\""); commandLineOptions.addOption(option); // OptionGroup pOutTypesOptionGroup = new OptionGroup(); String pOutTypesOptionGroupDoc = OPT + OPT_PARAM_TYPES_INT + " and " + OPT + OPT_PARAM_TYPES_NAME + " are mutually exclusive."; final String typesClassName = Types.class.getName(); option = new Option(OPT_PARAM_TYPES_INT, "paramTypes", true, "Parameter types from " + typesClassName + ". " + pOutTypesOptionGroupDoc + " Example: " + OPT + OPT_PARAM_TYPES_INT + " \"-10 12\""); commandLineOptions.addOption(option); option = new Option(OPT_PARAM_TYPES_NAME, "paramTypeNames", true, "Parameter " + typesClassName + " names. " + pOutTypesOptionGroupDoc + " Example: " + OPT + OPT_PARAM_TYPES_NAME + " \"CURSOR VARCHAR\""); commandLineOptions.addOption(option); commandLineOptions.addOptionGroup(pOutTypesOptionGroup); // OptionGroup modesOptionGroup = new OptionGroup(); String modesOptionGroupDoc = OPT + OPT_PARAM_MODES_INT + " and " + OPT + OPT_PARAM_MODES_NAME + " are mutually exclusive."; option = new Option(OPT_PARAM_MODES_INT, "paramModes", true, "Parameters modes (" + ParameterMetaData.parameterModeIn + "=IN, " + ParameterMetaData.parameterModeInOut + "=INOUT, " + ParameterMetaData.parameterModeOut + "=OUT, " + ParameterMetaData.parameterModeUnknown + "=Unknown" + "). " + modesOptionGroupDoc + " Example for 2 parameters, OUT and IN: " + OPT + OPT_PARAM_MODES_INT + " \"" + ParameterMetaData.parameterModeOut + " " + ParameterMetaData.parameterModeIn + "\""); modesOptionGroup.addOption(option); option = new Option(OPT_PARAM_MODES_NAME, "paramModeNames", true, "Parameters mode names (" + PMODES + "). " + modesOptionGroupDoc + " Example for 2 parameters, OUT and IN: " + OPT + OPT_PARAM_MODES_NAME + " \"" + _PMODE_OUT + " " + _PMODE_IN + "\""); modesOptionGroup.addOption(option); commandLineOptions.addOptionGroup(modesOptionGroup); option = new Option(null, OPT_TRIM_L, true, "Trims leading and trailing spaces from all column values. Column XML names can be optionally specified to set which columns to trim."); option.setOptionalArg(true); commandLineOptions.addOption(option); option = new Option(OPT_JDBC_TO_SFMD, OPT_JDBC_TO_SFMD_L, true, "Converts the JDBC file in the first argument to an SMFD file specified in the second argument."); option.setArgs(2); commandLineOptions.addOption(option); new HelpFormatter().printHelp(this.getClass().getName(), commandLineOptions); } public void testLongLineChunking() throws ParseException, IOException { Options options = new Options(); options.addOption("x", "extralongarg", false, "This description has ReallyLongValuesThatAreLongerThanTheWidthOfTheColumns " + "and also other ReallyLongValuesThatAreHugerAndBiggerThanTheWidthOfTheColumnsBob, " + "yes. "); HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); formatter.printHelp(new PrintWriter(sw), 35, this.getClass().getName(), "Header", options, 0, 5, "Footer"); String expected = "usage:" + CR + " org.apache.commons.cli.bug.B" + CR + " ugCLI162Test" + CR + "Header" + CR + "-x,--extralongarg This" + CR + " description" + CR + " has" + CR + " ReallyLongVal" + CR + " uesThatAreLon" + CR + " gerThanTheWid" + CR + " thOfTheColumn" + CR + " s and also" + CR + " other" + CR + " ReallyLongVal" + CR + " uesThatAreHug" + CR + " erAndBiggerTh" + CR + " anTheWidthOfT" + CR + " heColumnsBob," + CR + " yes." + CR + "Footer" + CR; assertEquals( "Long arguments did not split as expected", expected, sw.toString() ); } public void testLongLineChunkingIndentIgnored() throws ParseException, IOException { Options options = new Options(); options.addOption("x", "extralongarg", false, "This description is Long." ); HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); formatter.printHelp(new PrintWriter(sw), 22, this.getClass().getName(), "Header", options, 0, 5, "Footer"); System.err.println(sw.toString()); String expected = "usage:" + CR + " org.apache.comm" + CR + " ons.cli.bug.Bug" + CR + " CLI162Test" + CR + "Header" + CR + "-x,--extralongarg" + CR + " This description is" + CR + " Long." + CR + "Footer" + CR; assertEquals( "Long arguments did not split as expected", expected, sw.toString() ); } }
Exceptions not thrown git-svn-id: 0504523afcbcb96d4685eab89810948fa7b5e19d@1440534 13f79535-47bb-0310-9956-ffa450edef68
src/test/java/org/apache/commons/cli/bug/BugCLI162Test.java
Exceptions not thrown
<ide><path>rc/test/java/org/apache/commons/cli/bug/BugCLI162Test.java <ide> <ide> package org.apache.commons.cli.bug; <ide> <del>import java.io.IOException; <ide> import java.io.PrintWriter; <ide> import java.io.StringWriter; <ide> import java.sql.ParameterMetaData; <ide> import org.apache.commons.cli.Option; <ide> import org.apache.commons.cli.OptionGroup; <ide> import org.apache.commons.cli.Options; <del>import org.apache.commons.cli.ParseException; <ide> <ide> public class BugCLI162Test extends TestCase { <ide> /** Constant for the line separator.*/ <ide> formatter.printHelp("app", options); // used to hang & crash <ide> } <ide> <del> public void testPrintHelpLongLines() throws ParseException, IOException { <add> public void testPrintHelpLongLines() { <ide> // Constants used for options <ide> final String OPT = "-"; <ide> <ide> new HelpFormatter().printHelp(this.getClass().getName(), commandLineOptions); <ide> } <ide> <del> public void testLongLineChunking() throws ParseException, IOException { <add> public void testLongLineChunking() { <ide> Options options = new Options(); <ide> options.addOption("x", "extralongarg", false, <ide> "This description has ReallyLongValuesThatAreLongerThanTheWidthOfTheColumns " + <ide> assertEquals( "Long arguments did not split as expected", expected, sw.toString() ); <ide> } <ide> <del> public void testLongLineChunkingIndentIgnored() throws ParseException, IOException { <add> public void testLongLineChunkingIndentIgnored() { <ide> Options options = new Options(); <ide> options.addOption("x", "extralongarg", false, "This description is Long." ); <ide> HelpFormatter formatter = new HelpFormatter();
Java
apache-2.0
fd69ad6b9fd510588d858e4e06a31dee1fb59199
0
apache/felix-dev,apache/felix-dev,apache/felix-dev,apache/felix-dev
/* * 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.felix.framework; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.*; import org.apache.felix.framework.util.MapToDictionary; import org.apache.felix.framework.util.StringMap; import org.apache.felix.framework.util.Util; import org.apache.felix.moduleloader.IModule; import org.apache.felix.moduleloader.IWire; import org.osgi.framework.*; class ServiceRegistrationImpl implements ServiceRegistration { // Service registry. private final ServiceRegistry m_registry; // Bundle implementing the service. private final Bundle m_bundle; // Interfaces associated with the service object. private final String[] m_classes; // Service Id associated with the service object. private final Long m_serviceId; // Service object. private volatile Object m_svcObj; // Service factory interface. private volatile ServiceFactory m_factory; // Associated property dictionary. private volatile Map m_propMap = new StringMap(false); // Re-usable service reference. private final ServiceReferenceImpl m_ref; // Flag indicating that we are unregistering. private volatile boolean m_isUnregistering = false; public ServiceRegistrationImpl( ServiceRegistry registry, Bundle bundle, String[] classes, Long serviceId, Object svcObj, Dictionary dict) { m_registry = registry; m_bundle = bundle; m_classes = classes; m_serviceId = serviceId; m_svcObj = svcObj; m_factory = (m_svcObj instanceof ServiceFactory) ? (ServiceFactory) m_svcObj : null; initializeProperties(dict); // This reference is the "standard" reference for this // service and will always be returned by getReference(). // Since all reference to this service are supposed to // be equal, we use the hashcode of this reference for // a references to this service in ServiceReference. m_ref = new ServiceReferenceImpl(); } protected synchronized boolean isValid() { return (m_svcObj != null); } protected synchronized void invalidate() { m_svcObj = null; } public synchronized ServiceReference getReference() { // Make sure registration is valid. if (!isValid()) { throw new IllegalStateException( "The service registration is no longer valid."); } return m_ref; } public void setProperties(Dictionary dict) { Map oldProps; synchronized (this) { // Make sure registration is valid. if (!isValid()) { throw new IllegalStateException( "The service registration is no longer valid."); } // Remember old properties. oldProps = m_propMap; // Set the properties. initializeProperties(dict); } // Tell registry about it. m_registry.servicePropertiesModified(this, new MapToDictionary(oldProps)); } public void unregister() { synchronized (this) { if (!isValid() || m_isUnregistering) { throw new IllegalStateException("Service already unregistered."); } m_isUnregistering = true; } m_registry.unregisterService(m_bundle, this); synchronized (this) { m_svcObj = null; m_factory = null; } } // // Utility methods. // /** * This method determines if the class loader of the service object * has access to the specified class. * @param clazz the class to test for reachability. * @return <tt>true</tt> if the specified class is reachable from the * service object's class loader, <tt>false</tt> otherwise. **/ private boolean isClassAccessible(Class clazz) { try { // Try to load from the service object or service factory class. Class sourceClass = (m_factory != null) ? m_factory.getClass() : m_svcObj.getClass(); Class targetClass = Util.loadClassUsingClass(sourceClass, clazz.getName()); return (targetClass == clazz); } catch (Exception ex) { // Ignore this and return false. } return false; } Object getProperty(String key) { return m_propMap.get(key); } private String[] getPropertyKeys() { Set s = m_propMap.keySet(); return (String[]) s.toArray(new String[s.size()]); } private Bundle[] getUsingBundles() { return m_registry.getUsingBundles(m_ref); } /** * This method provides direct access to the associated service object; * it generally should not be used by anyone other than the service registry * itself. * @return The service object associated with the registration. **/ Object getService() { return m_svcObj; } Object getService(Bundle acqBundle) { // If the service object is a service factory, then // let it create the service object. if (m_factory != null) { Object svcObj = null; try { if (System.getSecurityManager() != null) { svcObj = AccessController.doPrivileged( new ServiceFactoryPrivileged(acqBundle, null)); } else { svcObj = getFactoryUnchecked(acqBundle); } } catch (PrivilegedActionException ex) { if (ex.getException() instanceof ServiceException) { throw (ServiceException) ex.getException(); } else { throw new ServiceException( "Service factory exception: " + ex.getException().getMessage(), ServiceException.FACTORY_EXCEPTION, ex.getException()); } } return svcObj; } else { return m_svcObj; } } void ungetService(Bundle relBundle, Object svcObj) { // If the service object is a service factory, then // let it release the service object. if (m_factory != null) { try { if (System.getSecurityManager() != null) { AccessController.doPrivileged( new ServiceFactoryPrivileged(relBundle, svcObj)); } else { ungetFactoryUnchecked(relBundle, svcObj); } } catch (Exception ex) { m_registry.getLogger().log( Logger.LOG_ERROR, "ServiceRegistrationImpl: Error ungetting service.", ex); } } } private void initializeProperties(Dictionary dict) { // Create a case-insensitive map for the properties. Map props = new StringMap(false); if (dict != null) { // Make sure there are no duplicate keys. Enumeration keys = dict.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (props.get(key) == null) { props.put(key, dict.get(key)); } else { throw new IllegalArgumentException("Duplicate service property: " + key); } } } // Add the framework assigned properties. props.put(Constants.OBJECTCLASS, m_classes); props.put(Constants.SERVICE_ID, m_serviceId); // Update the service property map. m_propMap = props; } private Object getFactoryUnchecked(Bundle bundle) { Object svcObj = null; try { svcObj = m_factory.getService(bundle, this); } catch (Throwable th) { throw new ServiceException( "Service factory exception: " + th.getMessage(), ServiceException.FACTORY_EXCEPTION, th); } if (svcObj != null) { for (int i = 0; i < m_classes.length; i++) { Class clazz = Util.loadClassUsingClass(svcObj.getClass(), m_classes[i]); if ((clazz == null) || !clazz.isAssignableFrom(svcObj.getClass())) { if (clazz == null) { throw new ServiceException( "Service cannot be cast due to missing class: " + m_classes[i], ServiceException.FACTORY_ERROR); } else { throw new ServiceException( "Service cannot be cast: " + m_classes[i], ServiceException.FACTORY_ERROR); } } } } else { throw new ServiceException( "Service factory returned null.", ServiceException.FACTORY_ERROR); } return svcObj; } private void ungetFactoryUnchecked(Bundle bundle, Object svcObj) { m_factory.ungetService(bundle, this, svcObj); } /** * This simple class is used to ensure that when a service factory * is called, that no other classes on the call stack interferes * with the permissions of the factory itself. **/ private class ServiceFactoryPrivileged implements PrivilegedExceptionAction { private Bundle m_bundle = null; private Object m_svcObj = null; public ServiceFactoryPrivileged(Bundle bundle, Object svcObj) { m_bundle = bundle; m_svcObj = svcObj; } public Object run() throws Exception { if (m_svcObj == null) { return getFactoryUnchecked(m_bundle); } else { ungetFactoryUnchecked(m_bundle, m_svcObj); } return null; } } class ServiceReferenceImpl implements ServiceReference { private ServiceReferenceImpl() {} ServiceRegistrationImpl getRegistration() { return ServiceRegistrationImpl.this; } public Object getProperty(String s) { return ServiceRegistrationImpl.this.getProperty(s); } public String[] getPropertyKeys() { return ServiceRegistrationImpl.this.getPropertyKeys(); } public Bundle getBundle() { // The spec says that this should return null if // the service is unregistered. return (isValid()) ? m_bundle : null; } public Bundle[] getUsingBundles() { return ServiceRegistrationImpl.this.getUsingBundles(); } public String toString() { String[] ocs = (String[]) getProperty("objectClass"); String oc = "["; for(int i = 0; i < ocs.length; i++) { oc = oc + ocs[i]; if (i < ocs.length - 1) oc = oc + ", "; } oc = oc + "]"; return oc; } public boolean isAssignableTo(Bundle requester, String className) { // Always return true if the requester is the same as the provider. if (requester == m_bundle) { return true; } // Boolean flag. boolean allow = true; // Get the package. String pkgName = Util.getClassPackage(className); IModule requesterModule = ((BundleImpl) requester).getCurrentModule(); // Get package wiring from service requester. IWire requesterWire = Util.getWire(requesterModule, pkgName); // Get package wiring from service provider. IModule providerModule = ((BundleImpl) m_bundle).getCurrentModule(); IWire providerWire = Util.getWire(providerModule, pkgName); // There are four situations that may occur here: // 1. Neither the requester, nor provider have a wire for // the package. // 2. The requester does not have a wire for the package. // 3. The provider does not have a wire for the package. // 4. Both have a wire for the package. // For case 1, we return true if the providing module is the same // as the requesting module, otherwise we return false. // For case 2, we only filter the service reference if the requester // has private acess to the class and its not the same class as the // registering bundle's class; for other situations we assume the // requester is doing some sort of reflection-based lookup. For // case 3, we have to try to load the class from the class loader // of the service object and then compare the class loaders to // determine if we should filter the service reference. For case 4, // we simply compare the exporting modules from the package wiring // to determine if we need to filter the service reference. // Case 1: Only include if modules are equals. if ((requesterWire == null) && (providerWire == null)) { allow = requesterModule.equals(providerModule); } // Case 2: Always include service reference. else if (requesterWire == null) { try { Class requestClass = requesterModule.getClassByDelegation(className); allow = getRegistration().isClassAccessible(requestClass); } catch (Exception ex) { allow = true; } } // Case 3: Only include service reference if the service // object uses the same class as the requester. else if (providerWire == null) { // If the provider is not the exporter of the requester's package, // then try to use the service registration to see if the requester's // class is accessible. if (!((BundleImpl) m_bundle).hasModule(requesterWire.getExporter())) { try { // Load the class from the requesting bundle. Class requestClass = requesterModule.getClassByDelegation(className); // Get the service registration and ask it to check // if the service object is assignable to the requesting // bundle's class. allow = getRegistration().isClassAccessible(requestClass); } catch (Exception ex) { // This should not happen, filter to be safe. allow = false; } } else { // O.k. the provider is the exporter of the requester's package, now check // if the requester is wired to the latest version of the provider, if so // then allow else don't (the provider has been updated but not refreshed). allow = providerModule == requesterWire.getExporter(); } } // Case 4: Include service reference if the wires have the // same source module. else { allow = providerWire.getExporter().equals(requesterWire.getExporter()); } return allow; } public int compareTo(Object reference) { ServiceReference other = (ServiceReference) reference; Long id = (Long) getProperty(Constants.SERVICE_ID); Long otherId = (Long) other.getProperty(Constants.SERVICE_ID); if (id.equals(otherId)) { return 0; // same service } Object rankObj = getProperty(Constants.SERVICE_RANKING); Object otherRankObj = other.getProperty(Constants.SERVICE_RANKING); // If no rank, then spec says it defaults to zero. rankObj = (rankObj == null) ? new Integer(0) : rankObj; otherRankObj = (otherRankObj == null) ? new Integer(0) : otherRankObj; // If rank is not Integer, then spec says it defaults to zero. Integer rank = (rankObj instanceof Integer) ? (Integer) rankObj : new Integer(0); Integer otherRank = (otherRankObj instanceof Integer) ? (Integer) otherRankObj : new Integer(0); // Sort by rank in ascending order. if (rank.compareTo(otherRank) < 0) { return -1; // lower rank } else if (rank.compareTo(otherRank) > 0) { return 1; // higher rank } // If ranks are equal, then sort by service id in descending order. return (id.compareTo(otherId) < 0) ? 1 : -1; } } }
framework/src/main/java/org/apache/felix/framework/ServiceRegistrationImpl.java
/* * 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.felix.framework; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.*; import org.apache.felix.framework.util.MapToDictionary; import org.apache.felix.framework.util.StringMap; import org.apache.felix.framework.util.Util; import org.apache.felix.moduleloader.IModule; import org.apache.felix.moduleloader.IWire; import org.osgi.framework.*; class ServiceRegistrationImpl implements ServiceRegistration { // Service registry. private final ServiceRegistry m_registry; // Bundle implementing the service. private final Bundle m_bundle; // Interfaces associated with the service object. private final String[] m_classes; // Service Id associated with the service object. private final Long m_serviceId; // Service object. private volatile Object m_svcObj; // Service factory interface. private volatile ServiceFactory m_factory; // Associated property dictionary. private volatile Map m_propMap = new StringMap(false); // Re-usable service reference. private final ServiceReferenceImpl m_ref; // Flag indicating that we are unregistering. private volatile boolean m_isUnregistering = false; public ServiceRegistrationImpl( ServiceRegistry registry, Bundle bundle, String[] classes, Long serviceId, Object svcObj, Dictionary dict) { m_registry = registry; m_bundle = bundle; m_classes = classes; m_serviceId = serviceId; m_svcObj = svcObj; m_factory = (m_svcObj instanceof ServiceFactory) ? (ServiceFactory) m_svcObj : null; initializeProperties(dict); // This reference is the "standard" reference for this // service and will always be returned by getReference(). // Since all reference to this service are supposed to // be equal, we use the hashcode of this reference for // a references to this service in ServiceReference. m_ref = new ServiceReferenceImpl(); } protected synchronized boolean isValid() { return (m_svcObj != null); } protected synchronized void invalidate() { m_svcObj = null; } public synchronized ServiceReference getReference() { // Make sure registration is valid. if (!isValid()) { throw new IllegalStateException( "The service registration is no longer valid."); } return m_ref; } public void setProperties(Dictionary dict) { Map oldProps; synchronized (this) { // Make sure registration is valid. if (!isValid()) { throw new IllegalStateException( "The service registration is no longer valid."); } // Remember old properties. oldProps = m_propMap; // Set the properties. initializeProperties(dict); } // Tell registry about it. m_registry.servicePropertiesModified(this, new MapToDictionary(oldProps)); } public void unregister() { synchronized (this) { if (!isValid() || m_isUnregistering) { throw new IllegalStateException("Service already unregistered."); } m_isUnregistering = true; } m_registry.unregisterService(m_bundle, this); synchronized (this) { m_svcObj = null; m_factory = null; } } // // Utility methods. // /** * This method determines if the class loader of the service object * has access to the specified class. * @param clazz the class to test for reachability. * @return <tt>true</tt> if the specified class is reachable from the * service object's class loader, <tt>false</tt> otherwise. **/ private boolean isClassAccessible(Class clazz) { try { // Try to load from the service object or service factory class. Class sourceClass = (m_factory != null) ? m_factory.getClass() : m_svcObj.getClass(); Class targetClass = Util.loadClassUsingClass(sourceClass, clazz.getName()); return (targetClass == clazz); } catch (Exception ex) { // Ignore this and return false. } return false; } Object getProperty(String key) { return m_propMap.get(key); } private String[] getPropertyKeys() { Set s = m_propMap.keySet(); return (String[]) s.toArray(new String[s.size()]); } private Bundle[] getUsingBundles() { return m_registry.getUsingBundles(m_ref); } /** * This method provides direct access to the associated service object; * it generally should not be used by anyone other than the service registry * itself. * @return The service object associated with the registration. **/ Object getService() { return m_svcObj; } Object getService(Bundle acqBundle) { // If the service object is a service factory, then // let it create the service object. if (m_factory != null) { Object svcObj = null; try { if (System.getSecurityManager() != null) { svcObj = AccessController.doPrivileged( new ServiceFactoryPrivileged(acqBundle, null)); } else { svcObj = getFactoryUnchecked(acqBundle); } } catch (PrivilegedActionException ex) { if (ex.getException() instanceof ServiceException) { throw (ServiceException) ex.getException(); } else { throw new ServiceException( "Service factory exception: " + ex.getException().getMessage(), ServiceException.FACTORY_EXCEPTION, ex.getException()); } } return svcObj; } else { return m_svcObj; } } void ungetService(Bundle relBundle, Object svcObj) { // If the service object is a service factory, then // let it release the service object. if (m_factory != null) { try { if (System.getSecurityManager() != null) { AccessController.doPrivileged( new ServiceFactoryPrivileged(relBundle, svcObj)); } else { ungetFactoryUnchecked(relBundle, svcObj); } } catch (Exception ex) { m_registry.getLogger().log( Logger.LOG_ERROR, "ServiceRegistrationImpl: Error ungetting service.", ex); } } } private void initializeProperties(Dictionary dict) { // Create a case-insensitive map for the properties. Map props = new StringMap(false); if (dict != null) { // Make sure there are no duplicate keys. Enumeration keys = dict.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (props.get(key) == null) { props.put(key, dict.get(key)); } else { throw new IllegalArgumentException("Duplicate service property: " + key); } } } // Add the framework assigned properties. props.put(Constants.OBJECTCLASS, m_classes); props.put(Constants.SERVICE_ID, m_serviceId); // Update the service property map. m_propMap = props; } private Object getFactoryUnchecked(Bundle bundle) { Object svcObj = null; try { svcObj = m_factory.getService(bundle, this); } catch (Throwable th) { throw new ServiceException( "Service factory exception: " + th.getMessage(), ServiceException.FACTORY_EXCEPTION, th); } if (svcObj != null) { for (int i = 0; i < m_classes.length; i++) { Class clazz = Util.loadClassUsingClass(svcObj.getClass(), m_classes[i]); if ((clazz == null) || !clazz.isAssignableFrom(svcObj.getClass())) { if (clazz == null) { throw new ServiceException( "Service cannot be cast due to missing class: " + m_classes[i], ServiceException.FACTORY_ERROR); } else { throw new ServiceException( "Service cannot be cast: " + m_classes[i], ServiceException.FACTORY_ERROR); } } } } else { throw new ServiceException( "Service factory returned null.", ServiceException.FACTORY_ERROR); } return svcObj; } private void ungetFactoryUnchecked(Bundle bundle, Object svcObj) { m_factory.ungetService(bundle, this, svcObj); } /** * This simple class is used to ensure that when a service factory * is called, that no other classes on the call stack interferes * with the permissions of the factory itself. **/ private class ServiceFactoryPrivileged implements PrivilegedExceptionAction { private Bundle m_bundle = null; private Object m_svcObj = null; public ServiceFactoryPrivileged(Bundle bundle, Object svcObj) { m_bundle = bundle; m_svcObj = svcObj; } public Object run() throws Exception { if (m_svcObj == null) { return getFactoryUnchecked(m_bundle); } else { ungetFactoryUnchecked(m_bundle, m_svcObj); } return null; } } class ServiceReferenceImpl implements ServiceReference { private ServiceReferenceImpl() {} ServiceRegistrationImpl getRegistration() { return ServiceRegistrationImpl.this; } public Object getProperty(String s) { return ServiceRegistrationImpl.this.getProperty(s); } public String[] getPropertyKeys() { return ServiceRegistrationImpl.this.getPropertyKeys(); } public Bundle getBundle() { // The spec says that this should return null if // the service is unregistered. return (isValid()) ? m_bundle : null; } public Bundle[] getUsingBundles() { return ServiceRegistrationImpl.this.getUsingBundles(); } public String toString() { String[] ocs = (String[]) getProperty("objectClass"); String oc = "["; for(int i = 0; i < ocs.length; i++) { oc = oc + ocs[i]; if (i < ocs.length - 1) oc = oc + ", "; } oc = oc + "]"; return oc; } public boolean isAssignableTo(Bundle requester, String className) { // Always return true if the requester is the same as the provider. if (requester == m_bundle) { return true; } // Boolean flag. boolean allow = true; // Get the package. String pkgName = Util.getClassPackage(className); IModule requesterModule = ((BundleImpl) requester).getCurrentModule(); // Get package wiring from service requester. IWire requesterWire = Util.getWire(requesterModule, pkgName); // Get package wiring from service provider. IModule providerModule = ((BundleImpl) m_bundle).getCurrentModule(); IWire providerWire = Util.getWire(providerModule, pkgName); // There are four situations that may occur here: // 1. Neither the requester, nor provider have a wire for // the package. // 2. The requester does not have a wire for the package. // 3. The provider does not have a wire for the package. // 4. Both have a wire for the package. // For case 1, we return true if the providing module is the same // as the requesting module, otherwise we return false. // For case 2, we do not filter the service reference since we // assume that the requesting bundle is using reflection or that // it won't use that class at all since it does not import it. // For case 3, we have to try to load the class from the class // loader of the service object and then compare the class // loaders to determine if we should filter the service // reference. In case 4, we simply compare the exporting // modules from the package wiring to determine if we need // to filter the service reference. // Case 1: Only include if modules are equals. if ((requesterWire == null) && (providerWire == null)) { allow = requesterModule.equals(providerModule); } // Case 2: Always include service reference. else if (requesterWire == null) { allow = true; } // Case 3: Only include service reference if the service // object uses the same class as the requester. else if (providerWire == null) { // If the provider is not the exporter of the requester's package, // then try to use the service registration to see if the requester's // class is accessible. if (!((BundleImpl) m_bundle).hasModule(requesterWire.getExporter())) { try { // Load the class from the requesting bundle. Class requestClass = requesterModule.getClassByDelegation(className); // Get the service registration and ask it to check // if the service object is assignable to the requesting // bundle's class. allow = getRegistration().isClassAccessible(requestClass); } catch (Exception ex) { // This should not happen, filter to be safe. allow = false; } } else { // O.k. the provider is the exporter of the requester's package, now check // if the requester is wired to the latest version of the provider, if so // then allow else don't (the provider has been updated but not refreshed). allow = providerModule == requesterWire.getExporter(); } } // Case 4: Include service reference if the wires have the // same source module. else { allow = providerWire.getExporter().equals(requesterWire.getExporter()); } return allow; } public int compareTo(Object reference) { ServiceReference other = (ServiceReference) reference; Long id = (Long) getProperty(Constants.SERVICE_ID); Long otherId = (Long) other.getProperty(Constants.SERVICE_ID); if (id.equals(otherId)) { return 0; // same service } Object rankObj = getProperty(Constants.SERVICE_RANKING); Object otherRankObj = other.getProperty(Constants.SERVICE_RANKING); // If no rank, then spec says it defaults to zero. rankObj = (rankObj == null) ? new Integer(0) : rankObj; otherRankObj = (otherRankObj == null) ? new Integer(0) : otherRankObj; // If rank is not Integer, then spec says it defaults to zero. Integer rank = (rankObj instanceof Integer) ? (Integer) rankObj : new Integer(0); Integer otherRank = (otherRankObj instanceof Integer) ? (Integer) otherRankObj : new Integer(0); // Sort by rank in ascending order. if (rank.compareTo(otherRank) < 0) { return -1; // lower rank } else if (rank.compareTo(otherRank) > 0) { return 1; // higher rank } // If ranks are equal, then sort by service id in descending order. return (id.compareTo(otherId) < 0) ? 1 : -1; } } }
Try to refine ServiceReference.isAssignableTo() to handle case where requester has private copy of service interface. (FELIX-1600) git-svn-id: e057f57e93a604d3b43d277ae69bde5ebf332112@818210 13f79535-47bb-0310-9956-ffa450edef68
framework/src/main/java/org/apache/felix/framework/ServiceRegistrationImpl.java
Try to refine ServiceReference.isAssignableTo() to handle case where requester has private copy of service interface. (FELIX-1600)
<ide><path>ramework/src/main/java/org/apache/felix/framework/ServiceRegistrationImpl.java <ide> // 4. Both have a wire for the package. <ide> // For case 1, we return true if the providing module is the same <ide> // as the requesting module, otherwise we return false. <del> // For case 2, we do not filter the service reference since we <del> // assume that the requesting bundle is using reflection or that <del> // it won't use that class at all since it does not import it. <del> // For case 3, we have to try to load the class from the class <del> // loader of the service object and then compare the class <del> // loaders to determine if we should filter the service <del> // reference. In case 4, we simply compare the exporting <del> // modules from the package wiring to determine if we need <del> // to filter the service reference. <add> // For case 2, we only filter the service reference if the requester <add> // has private acess to the class and its not the same class as the <add> // registering bundle's class; for other situations we assume the <add> // requester is doing some sort of reflection-based lookup. For <add> // case 3, we have to try to load the class from the class loader <add> // of the service object and then compare the class loaders to <add> // determine if we should filter the service reference. For case 4, <add> // we simply compare the exporting modules from the package wiring <add> // to determine if we need to filter the service reference. <ide> <ide> // Case 1: Only include if modules are equals. <ide> if ((requesterWire == null) && (providerWire == null)) <ide> // Case 2: Always include service reference. <ide> else if (requesterWire == null) <ide> { <del> allow = true; <add> try <add> { <add> Class requestClass = requesterModule.getClassByDelegation(className); <add> allow = getRegistration().isClassAccessible(requestClass); <add> } <add> catch (Exception ex) <add> { <add> allow = true; <add> } <ide> } <ide> <ide> // Case 3: Only include service reference if the service
JavaScript
mit
45390e9ad18a61d0570682d656204b4f25823307
0
sebascontre/bootscreen3ds,sebascontre/bootscreen3ds
/* global $ */ $.jCanvas.defaults.fromCenter = false; /* .getCanvasImage() don't work on Google Chrome if the page is served from a file URL (file://). This is a limitation of Google Chrome’s sandboxing architecture, and therefore cannot be fixed */ if (window.location.protocol == 'file:' && window.navigator.vendor == "Google Inc.") { $('#offline_warning').show(); $('select[name=type] option[value=menuhax2015]', "#settings").prop('disabled', true); $('select[name=type] option[value=menuhax2016]', "#settings").prop('disabled', true); } /* jCanvas has an option for write full strings but don't have a option for control letter spacing. The font has a letter spacing of 2px, and the generator needs a spacing of 1px. This function allows to write character by character with only 1px of spacing. */ var write = function(x, y, text, color = 'gray') { var letter = text.substr(0,1); /* Search for specials characters */ if (letter == '_') { text = text.substr(1); letter = text.substr(0,1); if (color == 'gray') color = 'white'; else if (color == 'white') color = 'gray'; } /* Draw 1 character */ $('#topscreen').drawText({ fillStyle: color, x: x+2, y: y, fontSize: 16, fontFamily: 'PerfectDOSVGA437Win', align: 'left', text: letter }); /* Remove the character writed from the string, and if itn't empty, continue recursive */ text = text.substr(1); if (text != '') write(x+8, y, text, color); } /* This draw the entire splash screen with any change on the form */ $("#settings input, #settings select").on('change', function() { var $topscreen = $('#topscreen'); var model = $('input[name=model]:checked', "#settings").val(); var region = $('select[name=region] option:selected', "#settings").val(); var sd = $('select[name=sd] option:selected', "#settings").val(); var type = $('select[name=type] option:selected', "#settings").val(); var line1 = $('select[name=type] option:selected', "#settings").text(); var line2 = ''; var processor = 0; var use_bootinput = false; var use_auxinput = false; if ($('select[name=boottool] option:selected', "#settings").val() == 'custom') { $('input[name=boottool]', "#settings").show(); $('select[name=boottool]', "#settings").hide(); use_bootinput = true; } if ($('select[name=secondTool] option:selected', "#settings").val() == 'custom') { $('input[name=secondTool]', "#settings").show(); $('select[name=secondTool]', "#settings").hide(); use_auxinput = true; } switch(type) { case 'luma2016': $topscreen.attr('width', 400); line2 = 'Copyright(C) 2016, AuroraWright'; break; case 'luma2017': $topscreen.attr('width', 400); line2 = 'Copyright(C) 2017, AuroraWright'; break; case 'menuhax2015': $topscreen.attr('width', 800); line2 = 'Copyright(C) 2015, yellow8'; break; case 'menuhax2016': $topscreen.attr('width', 800); line2 = 'Copyright(C) 2016, yellow8'; break; } $topscreen.clearCanvas().drawRect({ fillStyle: 'black', x: 0, y: 0, width: 400, height: 240 }).drawImage({ source: 'images/symbols.png', x: 1, y: 16, sWidth: 21, sHeight: 29, sx: 40, sy: 10 }); switch ($('select[name=logoOptions] option:selected', "#settings").val()) { case 'energyStar': $topscreen.drawImage({ source: 'images/symbols.png', x: 266, y: 16, sWidth: 133, sHeight: 84, sx: 0, sy: 0 }).drawRect({ fillStyle: 'black', x: 306, y: 26, width: 21, height: 29 }); break; case 'energyLuma': $topscreen.drawImage({ source: 'images/symbols.png', x: 266, y: 16, sWidth: 133, sHeight: 84, sx: 0, sy: 84 }); break; case 'lumaIcon': $topscreen.drawImage({ source: 'images/symbols.png', x: 266, y: 8, sWidth: 133, sHeight: 84, sx: 0, sy: 84*2 }); break; } write(24, 16*1, line1); write(24, 16*2, line2); switch(model) { case '3DS': write(0, 16*5, 'Nintendo 3DS CTR-001('+region+')'); processor = 2; sd += ' SD' break; case '3DSXL': if (region == 'JPN') write(0, 16*5, 'Nintendo 3DS LL SPR-001('+region+')'); else write(0, 16*5, 'Nintendo 3DS XL SPR-001('+region+')'); processor = 2; sd += ' SD' break; case '2DS': write(0, 16*5, 'Nintendo 2DS FTR-001('+region+')'); processor = 2; sd += ' SD' break; case 'n3DS': write(0, 16*5, 'New Nintendo 3DS KTR-001('+region+')'); processor = 4; sd += ' microSD' break; case 'n3DSXL': if (region == 'JPN') write(0, 16*5, 'New Nintendo 3DS LL RED-001('+region+')'); else write(0, 16*5, 'New Nintendo 3DS XL RED-001('+region+')'); processor = 4; sd += ' microSD' break; } switch(processor) { case 2: write(0, 16*7, 'Main Processor : Dual-core ARM11 MPCore'); write(0, 16*8, 'Memory Testing : 131072K OK'); break; case 4: write(0, 16*7, 'Main Processor : Quad-core ARM11 MPCore'); write(0, 16*8, 'Memory Testing : 262144K OK'); break; } write(0, 16*9, 'Detecting Primary Master ... '+ processor/2 +'G Internal Memory'); write(0, 16*10, 'Detecting Primary Slave ... '+ sd +' Card'); if (!use_bootinput) $('input[name=boottool]', "#settings").val($('select[name=boottool] option:selected', "#settings").text()); if (!use_auxinput) $('input[name=secondTool]', "#settings").val($('select[name=secondTool] option:selected', "#settings").text()); var boot_bool = $('input[name=hold]', "#settings").is(':checked'); var boot_keys = $('select[name=onboot] option:selected', "#settings").val(); var boot_tool = $('input[name=boottool]', "#settings").val(); var boot_text = '_Hold ' + boot_keys + ' '+ $('select[name=firstTime] option:selected').text() +'_ to enter _' + boot_tool + '_.'; var aux_bool = $('input[name=secondLine]', "#settings").is(':checked'); var aux_keys = $('select[name=secondButton] option:selected').val(); var aux_tool = $('input[name=secondTool]').val(); var aux_text = '_Hold ' + aux_keys + ' '+ $('select[name=secondTime] option:selected').text() +'_ to enter _' + aux_tool + '_.'; if (boot_bool && !aux_bool) write(0, 16*14, boot_text); else if (boot_bool) write(0, 16*13, boot_text); if (aux_bool) write(0, 16*14, aux_text); if ($topscreen.width() == 800) { $topscreen.drawImage({ source: $topscreen.getCanvasImage(), x: 400, y: 0 }); } }); window.onload = function() { $('canvas').drawImage({ source: 'images/symbols.png', x: 0, y: 0, load: function() { $("select[name=region]", "#settings").trigger('change'); if ($('#offline_warning').is(':hidden')) $('#downloadPNG, #downloadBIN').removeClass('disabled'); } }); }; $('input[name=boottool]', "#settings").keyup(function() { $("#settings input").trigger('change'); }); $('input[name=auxtool]', "#settings").keyup(function() { $("#settings input").trigger('change'); }); /* Create a PNG downloadable of the canvas */ /* global download */ $('#downloadPNG').click(function() { if (!$(this).hasClass('disabled')) { var filename = ($('#topscreen').width() == 400) ? 'splash.png' : 'imagedisplay.png'; var filedata = $('#topscreen').getCanvasImage(); download(filedata, filename, "image/png"); } }); $('#downloadBIN').click(function() { if (!$(this).hasClass('disabled')) { var filename = ($('#topscreen').width() == 400) ? 'splash.bin' : 'menuhax_imagedisplay.bin'; var width = $('#topscreen').height(); var height = $('#topscreen').width(); var $canvas = $('<canvas/>').css({ position: 'absolute', top: 0, left: -1*width }).appendTo('body'); $canvas.attr('width', width).attr('height', height); $canvas.drawImage({ source: $('#topscreen').getCanvasImage(), x: width/2, y: height/2, fromCenter: true, rotate: 90 }); var canvasdata = $canvas.get(0).getContext('2d').getImageData(0, 0, width, height).data; var filedata = ''; for(var i = 0; i < canvasdata.length; i += 4) filedata += String.fromCharCode(canvasdata[i+2], canvasdata[i+1], canvasdata[i]); $canvas.remove(); download('data:application/octet-stream;base64,' + window.btoa(filedata), filename); } });
scripts.js
/* global $ */ $.jCanvas.defaults.fromCenter = false; /* .getCanvasImage() don't work on Google Chrome if the page is served from a file URL (file://). This is a limitation of Google Chrome’s sandboxing architecture, and therefore cannot be fixed */ if (window.location.protocol == 'file:' && window.navigator.vendor == "Google Inc.") { $('#offline_warning').show(); $('select[name=type] option[value=menuhax2015]', "#settings").prop('disabled', true); $('select[name=type] option[value=menuhax2016]', "#settings").prop('disabled', true); } /* jCanvas has an option for write full strings but don't have a option for control letter spacing. The font has a letter spacing of 2px, and the generator needs a spacing of 1px. This function allows to write character by character with only 1px of spacing. */ var write = function(x, y, text, color = 'gray') { var letter = text.substr(0,1); /* Search for specials characters */ if (letter == '_') { text = text.substr(1); letter = text.substr(0,1); if (color == 'gray') color = 'white'; else if (color == 'white') color = 'gray'; } /* Draw 1 character */ $('#topscreen').drawText({ fillStyle: color, x: x+2, y: y, fontSize: 16, fontFamily: 'PerfectDOSVGA437Win', align: 'left', text: letter }); /* Remove the character writed from the string, and if itn't empty, continue recursive */ text = text.substr(1); if (text != '') write(x+8, y, text, color); } /* This draw the entire splash screen with any change on the form */ $("#settings input, #settings select").on('change', function() { var $topscreen = $('#topscreen'); var model = $('input[name=model]:checked', "#settings").val(); var region = $('select[name=region] option:selected', "#settings").val(); var sd = $('select[name=sd] option:selected', "#settings").val(); var type = $('select[name=type] option:selected', "#settings").val(); var line1 = $('select[name=type] option:selected', "#settings").text(); var line2 = ''; var processor = 0; var use_bootinput = false; var use_auxinput = false; if ($('select[name=boottool] option:selected', "#settings").val() == 'custom') { $('input[name=boottool]', "#settings").show(); $('select[name=boottool]', "#settings").hide(); use_bootinput = true; } if ($('select[name=secondTool] option:selected', "#settings").val() == 'custom') { $('input[name=secondTool]', "#settings").show(); $('select[name=secondTool]', "#settings").hide(); use_auxinput = true; } switch(type) { case 'luma2016': $topscreen.attr('width', 400); line2 = 'Copyright(C) 2016, AuroraWright'; break; case 'luma2017': $topscreen.attr('width', 400); line2 = 'Copyright(C) 2017, AuroraWright'; break; case 'menuhax2015': $topscreen.attr('width', 800); line2 = 'Copyright(C) 2015, yellow8'; break; case 'menuhax2016': $topscreen.attr('width', 800); line2 = 'Copyright(C) 2016, yellow8'; break; } $topscreen.clearCanvas().drawRect({ fillStyle: 'black', x: 0, y: 0, width: 400, height: 240 }).drawImage({ source: 'images/symbols.png', x: 1, y: 16, sWidth: 21, sHeight: 29, sx: 40, sy: 10 }); switch ($('select[name=logoOptions] option:selected', "#settings").val()) { case 'energyStar': $topscreen.drawImage({ source: 'images/symbols.png', x: 266, y: 16, sWidth: 133, sHeight: 84, sx: 0, sy: 0 }).drawRect({ fillStyle: 'black', x: 306, y: 26, width: 21, height: 29 }); break; case 'energyLuma': $topscreen.drawImage({ source: 'images/symbols.png', x: 266, y: 16, sWidth: 133, sHeight: 84, sx: 0, sy: 84 }); break; case 'lumaIcon': $topscreen.drawImage({ source: 'images/symbols.png', x: 266, y: 8, sWidth: 133, sHeight: 84, sx: 0, sy: 84*2 }); break; } write(24, 16*1, line1); write(24, 16*2, line2); switch(model) { case '3DS': write(0, 16*5, 'Nintendo 3DS CTR-001('+region+')'); processor = 2; sd += ' SD' break; case '3DSXL': if (region == 'JPN') write(0, 16*5, 'Nintendo 3DS LL SPR-001('+region+')'); else write(0, 16*5, 'Nintendo 3DS XL SPR-001('+region+')'); processor = 2; sd += ' SD' break; case '2DS': write(0, 16*5, 'Nintendo 2DS FTR-001('+region+')'); processor = 2; sd += ' SD' break; case 'n3DS': write(0, 16*5, 'New Nintendo 3DS KTR-001('+region+')'); processor = 4; sd += ' microSD' break; case 'n3DSXL': if (region == 'JPN') write(0, 16*5, 'New Nintendo 3DS LL RED-001('+region+')'); else write(0, 16*5, 'New Nintendo 3DS XL RED-001('+region+')'); processor = 4; sd += ' microSD' break; } switch(processor) { case 2: write(0, 16*7, 'Main Processor : Dual-core ARM11 MPCore'); write(0, 16*8, 'Memory Testing : 131072K OK'); break; case 4: write(0, 16*7, 'Main Processor : Quad-core ARM11 MPCore'); write(0, 16*8, 'Memory Testing : 262144K OK'); break; } write(0, 16*9, 'Detecting Primary Master ... '+ processor/2 +'G Internal Memory'); write(0, 16*10, 'Detecting Primary Slave ... '+ sd +' Card'); if (!use_bootinput) $('input[name=boottool]', "#settings").val($('select[name=boottool] option:selected', "#settings").text()); if (!use_auxinput) $('input[name=secondTool]', "#settings").val($('select[name=secondTool] option:selected', "#settings").text()); var boot_bool = $('input[name=hold]', "#settings").is(':checked'); var boot_keys = $('select[name=onboot] option:selected', "#settings").val(); var boot_tool = $('input[name=boottool]', "#settings").val(); var boot_text = '_Hold ' + boot_keys + ' '+ $('select[name=firstTime] option:selected').text() +'_ to enter _' + boot_tool + '_.'; var aux_bool = $('input[name=secondLine]', "#settings").is(':checked'); var aux_keys = $('select[name=secondButton] option:selected').val(); var aux_tool = $('input[name=secondTool]').val(); var aux_text = '_Hold ' + aux_keys + ' '+ $('select[name=secondTime] option:selected').text() +'_ to enter _' + aux_tool + '_.'; if (boot_bool && !aux_bool) write(0, 16*14, boot_text); else if (boot_bool) write(0, 16*13, boot_text); if (aux_bool) write(0, 16*14, aux_text); if ($topscreen.width() == 800) { $topscreen.drawImage({ source: $topscreen.getCanvasImage(), x: 400, y: 0 }); } }); $(window).load(function() { $('canvas').drawImage({ source: 'images/symbols.png', x: 0, y: 0, load: function() { $("select[name=region]", "#settings").trigger('change'); if ($('#offline_warning').is(':hidden')) $('#downloadPNG, #downloadBIN').removeClass('disabled'); } }); }); $('input[name=boottool]', "#settings").keyup(function() { $("#settings input").trigger('change'); }); $('input[name=auxtool]', "#settings").keyup(function() { $("#settings input").trigger('change'); }); /* Create a PNG downloadable of the canvas */ /* global download */ $('#downloadPNG').click(function() { if (!$(this).hasClass('disabled')) { var filename = ($('#topscreen').width() == 400) ? 'splash.png' : 'imagedisplay.png'; var filedata = $('#topscreen').getCanvasImage(); download(filedata, filename, "image/png"); } }); $('#downloadBIN').click(function() { if (!$(this).hasClass('disabled')) { var filename = ($('#topscreen').width() == 400) ? 'splash.bin' : 'menuhax_imagedisplay.bin'; var width = $('#topscreen').height(); var height = $('#topscreen').width(); var $canvas = $('<canvas/>').css({ position: 'absolute', top: 0, left: -1*width }).appendTo('body'); $canvas.attr('width', width).attr('height', height); $canvas.drawImage({ source: $('#topscreen').getCanvasImage(), x: width/2, y: height/2, fromCenter: true, rotate: 90 }); var canvasdata = $canvas.get(0).getContext('2d').getImageData(0, 0, width, height).data; var filedata = ''; for(var i = 0; i < canvasdata.length; i += 4) filedata += String.fromCharCode(canvasdata[i+2], canvasdata[i+1], canvasdata[i]); $canvas.remove(); download('data:application/octet-stream;base64,' + window.btoa(filedata), filename); } });
Fix typo
scripts.js
Fix typo
<ide><path>cripts.js <ide> <ide> }); <ide> <del>$(window).load(function() { <add>window.onload = function() { <ide> <ide> $('canvas').drawImage({ <ide> source: 'images/symbols.png', <ide> } <ide> }); <ide> <del>}); <add>}; <ide> <ide> $('input[name=boottool]', "#settings").keyup(function() { $("#settings input").trigger('change'); }); <ide> $('input[name=auxtool]', "#settings").keyup(function() { $("#settings input").trigger('change'); });
Java
apache-2.0
a105c91dabbf4056363c3c02a854ae5d8b8a88f8
0
gusai-francelabs/datafari,francelabs/datafari,gusai-francelabs/datafari,svanschalkwyk/datafari,svanschalkwyk/datafari,francelabs/datafari,gusai-francelabs/datafari,svanschalkwyk/datafari,svanschalkwyk/datafari,svanschalkwyk/datafari,gusai-francelabs/datafari,gusai-francelabs/datafari,svanschalkwyk/datafari,svanschalkwyk/datafari,francelabs/datafari,gusai-francelabs/datafari,gusai-francelabs/datafari,svanschalkwyk/datafari,gusai-francelabs/datafari,francelabs/datafari,gusai-francelabs/datafari,francelabs/datafari,svanschalkwyk/datafari,gusai-francelabs/datafari,svanschalkwyk/datafari,gusai-francelabs/datafari,svanschalkwyk/datafari,gusai-francelabs/datafari,svanschalkwyk/datafari
package com.francelabs.datafari.servlets.admin; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; import com.francelabs.datafari.utils.*; import com.francelabs.datafari.servlets.admin.StringsDatafariProperties.*; /** * Servlet implementation class ConfigDeduplication */ @WebServlet("/ConfigDeduplication") public class ConfigDeduplication extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(ConfigDeduplication.class.getName()); /** * @see HttpServlet#HttpServlet() */ public ConfigDeduplication() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BasicConfigurator.configure(); JSONObject jsonResponse = new JSONObject(); if (request.getParameter("id")!=null){ int id = Integer.parseInt(request.getParameter("id")); String enable = request.getParameter("enable"); request.setCharacterEncoding("utf8"); response.setContentType("application/json"); boolean error=false; if (id==1){ if (enable!=null){ if (enable.equals("true")){ error = CorePropertiesConfiguration.setProperty(StringsDatafariProperties.DEDUPLICATION, "true"); } else error = CorePropertiesConfiguration.setProperty(StringsDatafariProperties.DEDUPLICATION, "false"); } }else if (id==2){ if (enable!=null){ if (enable.equals("true")) error = CorePropertiesConfiguration.setProperty(StringsDatafariProperties.DEDUPLICATION_FACTORY, "true"); else error = CorePropertiesConfiguration.setProperty(StringsDatafariProperties.DEDUPLICATION_FACTORY, "false"); } } try { if (error){ jsonResponse.put("code",-1); }else{ jsonResponse.put("code",0); } } catch (JSONException e) { // TODO Auto-generated catch block logger.error(e); } }else if (request.getParameter("initiate")!=null){ String checked,checked_factory; if (CorePropertiesConfiguration.getProperty(StringsDatafariProperties.DEDUPLICATION)!=null && CorePropertiesConfiguration.getProperty(StringsDatafariProperties.DEDUPLICATION).equals("true") ){ checked="checked"; }else{ checked=""; } if (CorePropertiesConfiguration.getProperty(StringsDatafariProperties.DEDUPLICATION_FACTORY)!=null && CorePropertiesConfiguration.getProperty(StringsDatafariProperties.DEDUPLICATION_FACTORY).equals("true") ){ checked_factory="checked"; }else{ checked_factory=""; } try { jsonResponse.put("code",0); jsonResponse.put("checked", checked); jsonResponse.put("checked_factory", checked_factory); } catch (JSONException e) { logger.error(e); } } PrintWriter out = response.getWriter(); out.print(jsonResponse); } }
src/com/francelabs/datafari/servlets/admin/ConfigDeduplication.java
package com.francelabs.datafari.servlets.admin; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; import com.francelabs.datafari.utils.*; import com.francelabs.datafari.servlets.admin.StringsDatafariProperties.*; /** * Servlet implementation class ConfigDeduplication */ @WebServlet("/ConfigDeduplication") public class ConfigDeduplication extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(ConfigDeduplication.class.getName()); /** * @see HttpServlet#HttpServlet() */ public ConfigDeduplication() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BasicConfigurator.configure(); JSONObject jsonResponse = new JSONObject(); if (request.getParameter("id")!=null){ int id = Integer.parseInt(request.getParameter("id")); String enable = request.getParameter("enable"); request.setCharacterEncoding("utf8"); response.setContentType("application/json"); boolean error=false; if (id==1){ if (enable!=null){ if (enable.equals("true")){ error = ScriptConfiguration.setProperty(StringsDatafariProperties.DEDUPLICATION, "true"); } else error = ScriptConfiguration.setProperty(StringsDatafariProperties.DEDUPLICATION, "false"); } }else if (id==2){ if (enable!=null){ if (enable.equals("true")) error = ScriptConfiguration.setProperty(StringsDatafariProperties.DEDUPLICATION_FACTORY, "true"); else error = ScriptConfiguration.setProperty(StringsDatafariProperties.DEDUPLICATION_FACTORY, "false"); } } try { if (error){ jsonResponse.put("code",-1); }else{ jsonResponse.put("code",0); } } catch (JSONException e) { // TODO Auto-generated catch block logger.error(e); } }else if (request.getParameter("initiate")!=null){ String checked,checked_factory; if (ScriptConfiguration.getProperty(StringsDatafariProperties.DEDUPLICATION)!=null && ScriptConfiguration.getProperty(StringsDatafariProperties.DEDUPLICATION).equals("true") ){ checked="checked"; }else{ checked=""; } if (ScriptConfiguration.getProperty(StringsDatafariProperties.DEDUPLICATION_FACTORY)!=null && ScriptConfiguration.getProperty(StringsDatafariProperties.DEDUPLICATION_FACTORY).equals("true") ){ checked_factory="checked"; }else{ checked_factory=""; } try { jsonResponse.put("code",0); jsonResponse.put("checked", checked); jsonResponse.put("checked_factory", checked_factory); } catch (JSONException e) { logger.error(e); } } PrintWriter out = response.getWriter(); out.print(jsonResponse); } }
Deduplication by solr core properties (code deleted by previous commit)
src/com/francelabs/datafari/servlets/admin/ConfigDeduplication.java
Deduplication by solr core properties (code deleted by previous commit)
<ide><path>rc/com/francelabs/datafari/servlets/admin/ConfigDeduplication.java <ide> if (id==1){ <ide> if (enable!=null){ <ide> if (enable.equals("true")){ <del> error = ScriptConfiguration.setProperty(StringsDatafariProperties.DEDUPLICATION, "true"); <add> error = CorePropertiesConfiguration.setProperty(StringsDatafariProperties.DEDUPLICATION, "true"); <ide> } <ide> else <del> error = ScriptConfiguration.setProperty(StringsDatafariProperties.DEDUPLICATION, "false"); <add> error = CorePropertiesConfiguration.setProperty(StringsDatafariProperties.DEDUPLICATION, "false"); <ide> } <ide> <ide> }else if (id==2){ <ide> if (enable!=null){ <ide> if (enable.equals("true")) <ide> <del> error = ScriptConfiguration.setProperty(StringsDatafariProperties.DEDUPLICATION_FACTORY, "true"); <add> error = CorePropertiesConfiguration.setProperty(StringsDatafariProperties.DEDUPLICATION_FACTORY, "true"); <ide> else <del> error = ScriptConfiguration.setProperty(StringsDatafariProperties.DEDUPLICATION_FACTORY, "false"); <add> error = CorePropertiesConfiguration.setProperty(StringsDatafariProperties.DEDUPLICATION_FACTORY, "false"); <ide> } <ide> } <ide> try { <ide> } <ide> }else if (request.getParameter("initiate")!=null){ <ide> String checked,checked_factory; <del> if (ScriptConfiguration.getProperty(StringsDatafariProperties.DEDUPLICATION)!=null && ScriptConfiguration.getProperty(StringsDatafariProperties.DEDUPLICATION).equals("true") ){ <add> if (CorePropertiesConfiguration.getProperty(StringsDatafariProperties.DEDUPLICATION)!=null && CorePropertiesConfiguration.getProperty(StringsDatafariProperties.DEDUPLICATION).equals("true") ){ <ide> checked="checked"; <ide> }else{ <ide> checked=""; <ide> } <ide> <del> if (ScriptConfiguration.getProperty(StringsDatafariProperties.DEDUPLICATION_FACTORY)!=null && ScriptConfiguration.getProperty(StringsDatafariProperties.DEDUPLICATION_FACTORY).equals("true") ){ <add> if (CorePropertiesConfiguration.getProperty(StringsDatafariProperties.DEDUPLICATION_FACTORY)!=null && CorePropertiesConfiguration.getProperty(StringsDatafariProperties.DEDUPLICATION_FACTORY).equals("true") ){ <ide> checked_factory="checked"; <ide> }else{ <ide> checked_factory="";
Java
apache-2.0
3592d44e2c626272a10aedef4f2bf23fc892725c
0
ronsigal/xerces,RackerWilliams/xercesj,ronsigal/xerces,RackerWilliams/xercesj,ronsigal/xerces,RackerWilliams/xercesj,jimma/xerces,jimma/xerces,jimma/xerces
/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999,2000 The Apache Software Foundation. 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 the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xerces.readers; import org.apache.xerces.framework.XMLErrorReporter; import org.apache.xerces.utils.QName; import org.apache.xerces.utils.StringPool; import org.apache.xerces.utils.SymbolCache; import org.apache.xerces.utils.UTF8DataChunk; import org.apache.xerces.utils.XMLCharacterProperties; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.LocatorImpl; import java.io.InputStream; import java.util.Vector; /** * This is the primary reader used for UTF-8 encoded byte streams. * <p> * This reader processes requests from the scanners against the * underlying UTF-8 byte stream, avoiding when possible any up-front * transcoding. When the StringPool handle interfaces are used, * the information in the data stream will be added to the string * pool and lazy-evaluated until asked for. * <p> * We use the SymbolCache to match expected names (element types in * end tags) and walk the data structures of that class directly. * <p> * There is a significant amount of hand-inlining and some blatant * voilation of good object oriented programming rules, ignoring * boundaries of modularity, etc., in the name of good performance. * <p> * There are also some places where the code here frequently crashes * the SUN java runtime compiler (JIT) and the code here has been * carefully "crafted" to avoid those problems. * * @version $Id$ */ final class UTF8Reader extends XMLEntityReader { // // // private final static boolean USE_OUT_OF_LINE_LOAD_NEXT_BYTE = false; private final static boolean USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE = true; // // // public UTF8Reader(XMLEntityHandler entityHandler, XMLErrorReporter errorReporter, boolean sendCharDataAsCharArray, InputStream dataStream, StringPool stringPool) throws Exception { super(entityHandler, errorReporter, sendCharDataAsCharArray); fInputStream = dataStream; fStringPool = stringPool; fCharArrayRange = fStringPool.createCharArrayRange(); fCurrentChunk = UTF8DataChunk.createChunk(fStringPool, null); fillCurrentChunk(); } /** * */ public int addString(int offset, int length) { if (length == 0) return 0; return fCurrentChunk.addString(offset, length); } /** * */ public int addSymbol(int offset, int length) { if (length == 0) return 0; return fCurrentChunk.addSymbol(offset, length, 0); } /** * */ private int addSymbol(int offset, int length, int hashcode) { if (length == 0) return 0; return fCurrentChunk.addSymbol(offset, length, hashcode); } /** * */ public void append(XMLEntityHandler.CharBuffer charBuffer, int offset, int length) { fCurrentChunk.append(charBuffer, offset, length); } // // // private int slowLoadNextByte() throws Exception { fCallClearPreviousChunk = true; if (fCurrentChunk.nextChunk() != null) { fCurrentChunk = fCurrentChunk.nextChunk(); fCurrentIndex = 0; fMostRecentData = fCurrentChunk.toByteArray(); return(fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } else { fCurrentChunk = UTF8DataChunk.createChunk(fStringPool, fCurrentChunk); return fillCurrentChunk(); } } private int loadNextByte() throws Exception { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; return fMostRecentByte; } catch (ArrayIndexOutOfBoundsException ex) { return slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) return slowLoadNextByte(); else return(fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } // // // private boolean atEOF(int offset) { return(offset > fLength); } // // // public XMLEntityHandler.EntityReader changeReaders() throws Exception { XMLEntityHandler.EntityReader nextReader = super.changeReaders(); fCurrentChunk.releaseChunk(); fCurrentChunk = null; fMostRecentData = null; fMostRecentByte = 0; return nextReader; } // // // public boolean lookingAtChar(char ch, boolean skipPastChar) throws Exception { int b0 = fMostRecentByte; if (b0 != ch) { if (b0 == 0) { if (atEOF(fCurrentOffset + 1)) { return changeReaders().lookingAtChar(ch, skipPastChar); } } if (ch == 0x0A && b0 == 0x0D) { if (skipPastChar) { fCarriageReturnCounter++; fCharacterCounter = 1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; b0 = fMostRecentByte; } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (b0 == 0x0A) { fLinefeedCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } } } return true; } return false; } if (ch == 0x0D) return false; if (skipPastChar) { fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } } return true; } // // // public boolean lookingAtValidChar(boolean skipPastChar) throws Exception { int b0 = fMostRecentByte; if (b0 < 0x80) { // 0xxxxxxx if (b0 >= 0x20 || b0 == 0x09) { if (skipPastChar) { fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } } return true; } if (b0 == 0x0A) { if (skipPastChar) { fLinefeedCounter++; fCharacterCounter = 1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } } return true; } if (b0 == 0x0D) { if (skipPastChar) { fCarriageReturnCounter++; fCharacterCounter = 1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; b0 = fMostRecentByte; } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (b0 == 0x0A) { fLinefeedCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } } } return true; } if (b0 == 0) { if (atEOF(fCurrentOffset + 1)) { return changeReaders().lookingAtValidChar(skipPastChar); } } return false; } // // REVISIT - optimize this with in-buffer lookahead. // UTF8DataChunk saveChunk = fCurrentChunk; int saveIndex = fCurrentIndex; int saveOffset = fCurrentOffset; int b1 = loadNextByte(); if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx (0x80 to 0x7ff) if (skipPastChar) { fCharacterCounter++; loadNextByte(); } else { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; } return true; // [#x20-#xD7FF] } int b2 = loadNextByte(); if ((0xf0 & b0) == 0xe0) { // 1110zzzz 10yyyyyy 10xxxxxx // ch = ((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2); // zzzz yyyy yyxx xxxx (0x800 to 0xffff) // if (!((ch >= 0xD800 && ch <= 0xDFFF) || ch >= 0xFFFE)) // if ((ch <= 0xD7FF) || (ch >= 0xE000 && ch <= 0xFFFD)) boolean result = false; if (!((b0 == 0xED && b1 >= 0xA0) || (b0 == 0xEF && b1 == 0xBF && b2 >= 0xBE))) { // [#x20-#xD7FF] | [#xE000-#xFFFD] if (skipPastChar) { fCharacterCounter++; loadNextByte(); return true; } result = true; } fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return result; } int b3 = loadNextByte(); // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx // ch = ((0x0f & b0)<<18) + ((0x3f & b1)<<12) + ((0x3f & b2)<<6) + (0x3f & b3); // u uuuu zzzz yyyy yyxx xxxx (0x10000 to 0x1ffff) // if (ch >= 0x110000) boolean result = false; //if (( 0xf8 & b0 ) == 0xf0 ) { //if (!(b0 > 0xF4 || (b0 == 0xF4 && b1 >= 0x90))) { // [#x10000-#x10FFFF] if( ((b0&0xf8) == 0xf0) && ((b1&0xc0)==0x80) && ((b2&0xc0) == 0x80) && ((b3&0xc0)==0x80)){ if (skipPastChar) { fCharacterCounter++; loadNextByte(); return true; } result = true; //} fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return result; } else{ fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return result; } } // // // public boolean lookingAtSpace(boolean skipPastChar) throws Exception { int ch = fMostRecentByte; if (ch > 0x20) return false; if (ch == 0x20 || ch == 0x09) { if (!skipPastChar) return true; fCharacterCounter++; } else if (ch == 0x0A) { if (!skipPastChar) return true; fLinefeedCounter++; fCharacterCounter = 1; } else if (ch == 0x0D) { if (!skipPastChar) return true; fCarriageReturnCounter++; fCharacterCounter = 1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; ch = fMostRecentByte; } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (ch != 0x0A) return true; fLinefeedCounter++; } else { if (ch == 0) { // REVISIT - should we be checking this here ? if (atEOF(fCurrentOffset + 1)) { return changeReaders().lookingAtSpace(skipPastChar); } } return false; } if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } return true; } // // // public void skipToChar(char ch) throws Exception { // // REVISIT - this will skip invalid characters without reporting them. // int b0 = fMostRecentByte; while (true) { if (b0 == ch) // ch will always be an ascii character return; if (b0 == 0) { if (atEOF(fCurrentOffset + 1)) { changeReaders().skipToChar(ch); return; } fCharacterCounter++; } else if (b0 == 0x0A) { fLinefeedCounter++; fCharacterCounter = 1; } else if (b0 == 0x0D) { fCarriageReturnCounter++; fCharacterCounter = 1; b0 = loadNextByte(); if (b0 != 0x0A) continue; fLinefeedCounter++; } else if (b0 < 0x80) { // 0xxxxxxx fCharacterCounter++; } else { fCharacterCounter++; if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx loadNextByte(); } else if ((0xf0 & b0) == 0xe0) { // 1110zzzz 10yyyyyy 10xxxxxx loadNextByte(); loadNextByte(); } else { // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx loadNextByte(); loadNextByte(); loadNextByte(); } } b0 = loadNextByte(); } } // // // public void skipPastSpaces() throws Exception { int ch = fMostRecentByte; while (true) { if (ch == 0x20 || ch == 0x09) { fCharacterCounter++; } else if (ch == 0x0A) { fLinefeedCounter++; fCharacterCounter = 1; } else if (ch == 0x0D) { fCarriageReturnCounter++; fCharacterCounter = 1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; ch = fMostRecentByte; } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (ch != 0x0A) continue; fLinefeedCounter++; } else { if (ch == 0 && atEOF(fCurrentOffset + 1)) changeReaders().skipPastSpaces(); return; } if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; ch = fMostRecentByte; } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } } } // // // protected boolean skippedMultiByteCharWithFlag(int b0, int flag) throws Exception { UTF8DataChunk saveChunk = fCurrentChunk; int saveOffset = fCurrentOffset; int saveIndex = fCurrentIndex; if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } int b1 = loadNextByte(); if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx if ((XMLCharacterProperties.fgCharFlags[((0x1f & b0)<<6) + (0x3f & b1)] & flag) == 0) { // yyy yyxx xxxx (0x80 to 0x7ff) fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } return true; } int b2 = loadNextByte(); if ((0xf0 & b0) == 0xe0) { // 1110zzzz 10yyyyyy 10xxxxxx // if ((ch >= 0xD800 && ch <= 0xDFFF) || ch >= 0xFFFE) if ((b0 == 0xED && b1 >= 0xA0) || (b0 == 0xEF && b1 == 0xBF && b2 >= 0xBE)) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } if ((XMLCharacterProperties.fgCharFlags[((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2)] & flag) == 0) { // zzzz yyyy yyxx xxxx (0x800 to 0xffff) fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } return true; } else { // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } } public void skipPastName(char fastcheck) throws Exception { int b0 = fMostRecentByte; if (b0 < 0x80) { if (XMLCharacterProperties.fgAsciiInitialNameChar[b0] == 0) return; } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } if (!skippedMultiByteCharWithFlag(b0, XMLCharacterProperties.E_InitialNameCharFlag)) return; } while (true) { fCharacterCounter++; b0 = loadNextByte(); if (fastcheck == b0) return; if (b0 < 0x80) { if (XMLCharacterProperties.fgAsciiNameChar[b0] == 0) return; } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } if (!skippedMultiByteCharWithFlag(b0, XMLCharacterProperties.E_NameCharFlag)) return; } } } // // // public void skipPastNmtoken(char fastcheck) throws Exception { int b0 = fMostRecentByte; while (true) { if (fastcheck == b0) return; if (b0 < 0x80) { if (XMLCharacterProperties.fgAsciiNameChar[b0] == 0) return; } else { if (!skippedMultiByteCharWithFlag(b0, XMLCharacterProperties.E_NameCharFlag)) return; } fCharacterCounter++; b0 = loadNextByte(); } } // // // public boolean skippedString(char[] s) throws Exception { int length = s.length; byte[] data = fMostRecentData; int index = fCurrentIndex + length; int sindex = length; try { while (sindex-- > 0) { if (data[--index] != s[sindex]) return false; } fCurrentIndex += length; } catch (ArrayIndexOutOfBoundsException ex) { int i = 0; index = fCurrentIndex; while (index < UTF8DataChunk.CHUNK_SIZE) { if (data[index++] != s[i++]) return false; } UTF8DataChunk dataChunk = fCurrentChunk; int savedOffset = fCurrentOffset; int savedIndex = fCurrentIndex; slowLoadNextByte(); data = fMostRecentData; index = 0; while (i < length) { if (data[index++] != s[i++]) { fCurrentChunk = dataChunk; fCurrentIndex = savedIndex; fCurrentOffset = savedOffset; fMostRecentData = fCurrentChunk.toByteArray(); fMostRecentByte = fMostRecentData[savedIndex] & 0xFF; return false; } } fCurrentIndex = index; } fCharacterCounter += length; fCurrentOffset += length; try { fMostRecentByte = data[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } return true; } // // // public int scanInvalidChar() throws Exception { int b0 = fMostRecentByte; int ch = b0; if (ch == 0x0A) { fLinefeedCounter++; fCharacterCounter = 1; } else if (ch == 0x0D) { fCarriageReturnCounter++; fCharacterCounter = 1; ch = loadNextByte(); if (ch != 0x0A) return 0x0A; fLinefeedCounter++; } else if (ch == 0) { if (atEOF(fCurrentOffset + 1)) { return changeReaders().scanInvalidChar(); } fCharacterCounter++; } else if (b0 >= 0x80) { fCharacterCounter++; int b1 = loadNextByte(); int b2 = 0; if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx ch = ((0x1f & b0)<<6) + (0x3f & b1); } else if( (0xf0 & b0) == 0xe0 ) { b2 = loadNextByte(); ch = ((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2); } else if(( 0xf8 & b0 ) == 0xf0 ){ b2 = loadNextByte(); int b3 = loadNextByte(); // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx ch = ((0x0f & b0)<<18) + ((0x3f & b1)<<12) + ((0x3f & b2)<<6) + (0x3f & b3); } } loadNextByte(); return ch; } // // // public int scanCharRef(boolean hex) throws Exception { int ch = fMostRecentByte; if (ch == 0) { if (atEOF(fCurrentOffset + 1)) { return changeReaders().scanCharRef(hex); } return XMLEntityHandler.CHARREF_RESULT_INVALID_CHAR; } int num = 0; if (hex) { if (ch > 'f' || XMLCharacterProperties.fgAsciiXDigitChar[ch] == 0) return XMLEntityHandler.CHARREF_RESULT_INVALID_CHAR; num = ch - (ch < 'A' ? '0' : (ch < 'a' ? 'A' : 'a') - 10); } else { if (ch < '0' || ch > '9') return XMLEntityHandler.CHARREF_RESULT_INVALID_CHAR; num = ch - '0'; } fCharacterCounter++; loadNextByte(); boolean toobig = false; while (true) { ch = fMostRecentByte; if (ch == 0) break; if (hex) { if (ch > 'f' || XMLCharacterProperties.fgAsciiXDigitChar[ch] == 0) break; } else { if (ch < '0' || ch > '9') break; } fCharacterCounter++; loadNextByte(); if (hex) { int dig = ch - (ch < 'A' ? '0' : (ch < 'a' ? 'A' : 'a') - 10); num = (num << 4) + dig; } else { int dig = ch - '0'; num = (num * 10) + dig; } if (num > 0x10FFFF) { toobig = true; num = 0; } } if (ch != ';') return XMLEntityHandler.CHARREF_RESULT_SEMICOLON_REQUIRED; fCharacterCounter++; loadNextByte(); if (toobig) return XMLEntityHandler.CHARREF_RESULT_OUT_OF_RANGE; return num; } // // // public int scanStringLiteral() throws Exception { boolean single; if (!(single = lookingAtChar('\'', true)) && !lookingAtChar('\"', true)) { return XMLEntityHandler.STRINGLIT_RESULT_QUOTE_REQUIRED; } int offset = fCurrentOffset; char qchar = single ? '\'' : '\"'; while (!lookingAtChar(qchar, false)) { if (!lookingAtValidChar(true)) { return XMLEntityHandler.STRINGLIT_RESULT_INVALID_CHAR; } } int stringIndex = fCurrentChunk.addString(offset, fCurrentOffset - offset); lookingAtChar(qchar, true); // move past qchar return stringIndex; } // // [10] AttValue ::= '"' ([^<&"] | Reference)* '"' // | "'" ([^<&'] | Reference)* "'" // // The values in the following table are defined as: // // 0 - not special // 1 - quote character // 2 - complex // 3 - less than // 4 - invalid // public static final byte fgAsciiAttValueChar[] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 4, 4, 2, 4, 4, // tab is 0x09, LF is 0x0A, CR is 0x0D 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 1, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, // '\"' is 0x22, '&' is 0x26, '\'' is 0x27 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, // '<' is 0x3C 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public int scanAttValue(char qchar, boolean asSymbol) throws Exception { int offset = fCurrentOffset; int b0 = fMostRecentByte; while (true) { if (b0 < 0x80) { switch (fgAsciiAttValueChar[b0]) { case 1: // quote char if (b0 == qchar) { int length = fCurrentOffset - offset; int result = length == 0 ? StringPool.EMPTY_STRING : (asSymbol ? fCurrentChunk.addSymbol(offset, length, 0) : fCurrentChunk.addString(offset, length)); fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } return result; } // the other quote character is not special // fall through case 0: // non-special char fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } continue; case 2: // complex return XMLEntityHandler.ATTVALUE_RESULT_COMPLEX; case 3: // less than return XMLEntityHandler.ATTVALUE_RESULT_LESSTHAN; case 4: // invalid return XMLEntityHandler.ATTVALUE_RESULT_INVALID_CHAR; } } else { if (!skipMultiByteCharData(b0)) return XMLEntityHandler.ATTVALUE_RESULT_INVALID_CHAR; b0 = fMostRecentByte; } } } // // [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"' // | "'" ([^%&'] | PEReference | Reference)* "'" // // The values in the following table are defined as: // // 0 - not special // 1 - quote character // 2 - reference // 3 - peref // 4 - invalid // 5 - linefeed // 6 - carriage-return // 7 - end of input // public static final byte fgAsciiEntityValueChar[] = { 7, 4, 4, 4, 4, 4, 4, 4, 4, 0, 5, 4, 4, 6, 4, 4, // tab is 0x09, LF is 0x0A, CR is 0x0D 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 1, 0, 0, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, // '\"', '%', '&', '\'' 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public int scanEntityValue(int qchar, boolean createString) throws Exception { int offset = fCurrentOffset; int b0 = fMostRecentByte; while (true) { if (b0 < 0x80) { switch (fgAsciiEntityValueChar[b0]) { case 1: // quote char if (b0 == qchar) { if (!createString) return XMLEntityHandler.ENTITYVALUE_RESULT_FINISHED; int length = fCurrentOffset - offset; int result = length == 0 ? StringPool.EMPTY_STRING : fCurrentChunk.addString(offset, length); fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } return result; } // the other quote character is not special // fall through case 0: // non-special char fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } continue; case 5: // linefeed fLinefeedCounter++; fCharacterCounter = 1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } continue; case 6: // carriage-return fCarriageReturnCounter++; fCharacterCounter = 1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (b0 != 0x0A) { continue; } fLinefeedCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } continue; case 2: // reference return XMLEntityHandler.ENTITYVALUE_RESULT_REFERENCE; case 3: // peref return XMLEntityHandler.ENTITYVALUE_RESULT_PEREF; case 7: if (atEOF(fCurrentOffset + 1)) { changeReaders(); // do not call next reader, our caller may need to change the parameters return XMLEntityHandler.ENTITYVALUE_RESULT_END_OF_INPUT; } // fall into... case 4: // invalid return XMLEntityHandler.ENTITYVALUE_RESULT_INVALID_CHAR; } } else { if (!skipMultiByteCharData(b0)) return XMLEntityHandler.ENTITYVALUE_RESULT_INVALID_CHAR; b0 = fMostRecentByte; } } } // // // public boolean scanExpectedName(char fastcheck, StringPool.CharArrayRange expectedName) throws Exception { char[] expected = expectedName.chars; int offset = expectedName.offset; int len = expectedName.length; int b0 = fMostRecentByte; int ch = 0; int i = 0; while (true) { if (b0 < 0x80) { ch = b0; if (i == len) break; if (ch != expected[offset]) { skipPastNmtoken(fastcheck); return false; } } else { // // REVISIT - optimize this with in-buffer lookahead. // UTF8DataChunk saveChunk = fCurrentChunk; int saveIndex = fCurrentIndex; int saveOffset = fCurrentOffset; int b1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b1 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b1 = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { b1 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b1 = slowLoadNextByte(); else b1 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx ch = ((0x1f & b0)<<6) + (0x3f & b1); if (i == len) break; if (ch != expected[offset]) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; skipPastNmtoken(fastcheck); return false; } } else { int b2; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b2 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b2 = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { b2 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b2 = slowLoadNextByte(); else b2 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if ((0xf0 & b0) == 0xe0) { // 1110zzzz 10yyyyyy 10xxxxxx // if ((ch >= 0xD800 && ch <= 0xDFFF) || ch >= 0xFFFE) if ((b0 == 0xED && b1 >= 0xA0) || (b0 == 0xEF && b1 == 0xBF && b2 >= 0xBE)) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } ch = ((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2); if (i == len) break; if (ch != expected[offset]) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; skipPastNmtoken(fastcheck); return false; } } else { // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } } } i++; offset++; fCharacterCounter++; fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (ch == fastcheck) return true; if (ch < 0x80) { if (XMLCharacterProperties.fgAsciiNameChar[ch] == 0) return true; } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) return true; } skipPastNmtoken(fastcheck); return false; } public void scanQName(char fastcheck, QName qname) throws Exception { int offset = fCurrentOffset; int ch = fMostRecentByte; if (ch < 0x80) { if (XMLCharacterProperties.fgAsciiInitialNameChar[ch] == 0) { qname.clear(); return; } if (ch == ':') { qname.clear(); return; } } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } ch = getMultiByteSymbolChar(ch); fCurrentIndex--; fCurrentOffset--; if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) { qname.clear(); return; } } int index = fCurrentIndex; byte[] data = fMostRecentData; int prefixend = -1; while (true) { fCharacterCounter++; fCurrentOffset++; index++; try { ch = data[index] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); index = 0; data = fMostRecentData; } if (fastcheck == ch) break; if (ch < 0x80) { if (XMLCharacterProperties.fgAsciiNameChar[ch] == 0) break; if (ch == ':') { if (prefixend != -1) break; prefixend = fCurrentOffset; // // We need to peek ahead one character. If the next character is not a // valid initial name character, or is another colon, then we cannot meet // both the Prefix and LocalPart productions for the QName production, // which means that there is no Prefix and we need to terminate the QName // at the first colon. // try { ch = data[index + 1] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { UTF8DataChunk savedChunk = fCurrentChunk; int savedOffset = fCurrentOffset; ch = slowLoadNextByte(); fCurrentChunk = savedChunk; fCurrentOffset = savedOffset; fMostRecentData = fCurrentChunk.toByteArray(); } boolean lpok = true; if (ch < 0x80) { if (XMLCharacterProperties.fgAsciiInitialNameChar[ch] == 0 || ch == ':') lpok = false; } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) lpok = false; } ch = ':'; if (!lpok) { prefixend = -1; break; } } } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } fCurrentIndex = index; fMostRecentByte = ch; ch = getMultiByteSymbolChar(ch); fCurrentIndex--; fCurrentOffset--; index = fCurrentIndex; if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) break; } } fCurrentIndex = index; fMostRecentByte = ch; int length = fCurrentOffset - offset; qname.rawname = addSymbol(offset, length); qname.prefix = prefixend == -1 ? -1 : addSymbol(offset, prefixend - offset); qname.localpart = prefixend == -1 ? qname.rawname : addSymbol(prefixend + 1, fCurrentOffset - (prefixend + 1)); qname.uri = -1; } // scanQName(char,QName) private int getMultiByteSymbolChar(int b0) throws Exception { // // REVISIT - optimize this with in-buffer lookahead. // UTF8DataChunk saveChunk = fCurrentChunk; int saveIndex = fCurrentIndex; int saveOffset = fCurrentOffset; if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } int b1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b1 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b1 = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { b1 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b1 = slowLoadNextByte(); else b1 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx int ch = ((0x1f & b0)<<6) + (0x3f & b1); if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) { // yyy yyxx xxxx (0x80 to 0x7ff) fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return -1; } loadNextByte(); return ch; } int b2; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b2 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b2 = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { b2 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b2 = slowLoadNextByte(); else b2 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if ((0xf0 & b0) == 0xe0) { // 1110zzzz 10yyyyyy 10xxxxxx // if ((ch >= 0xD800 && ch <= 0xDFFF) || ch >= 0xFFFE) if ((b0 == 0xED && b1 >= 0xA0) || (b0 == 0xEF && b1 == 0xBF && b2 >= 0xBE)) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return -1; } int ch = ((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2); if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) { // zzzz yyyy yyxx xxxx (0x800 to 0xffff) fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return -1; } loadNextByte(); return ch; } // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return -1; } public int scanName(char fastcheck) throws Exception { int b0 = fMostRecentByte; int ch; if (b0 < 0x80) { if (XMLCharacterProperties.fgAsciiInitialNameChar[b0] == 0) { if (b0 == 0 && atEOF(fCurrentOffset + 1)) { return changeReaders().scanName(fastcheck); } return -1; } ch = b0; } else { // // REVISIT - optimize this with in-buffer lookahead. // UTF8DataChunk saveChunk = fCurrentChunk; int saveIndex = fCurrentIndex; int saveOffset = fCurrentOffset; if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } int b1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b1 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b1 = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { b1 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b1 = slowLoadNextByte(); else b1 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx ch = ((0x1f & b0)<<6) + (0x3f & b1); if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) { // yyy yyxx xxxx (0x80 to 0x7ff) fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return -1; } } else { int b2; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b2 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b2 = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { b2 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b2 = slowLoadNextByte(); else b2 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if ((0xf0 & b0) == 0xe0) { // 1110zzzz 10yyyyyy 10xxxxxx // if ((ch >= 0xD800 && ch <= 0xDFFF) || ch >= 0xFFFE) if ((b0 == 0xED && b1 >= 0xA0) || (b0 == 0xEF && b1 == 0xBF && b2 >= 0xBE)) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return -1; } ch = ((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2); if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) { // zzzz yyyy yyxx xxxx (0x800 to 0xffff) fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return -1; } } else { // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return -1; } } } fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } return scanMatchingName(ch, b0, fastcheck); } private int scanMatchingName(int ch, int b0, int fastcheck) throws Exception { SymbolCache cache = fStringPool.getSymbolCache(); int[][] cacheLines = cache.fCacheLines; char[] symbolChars = cache.fSymbolChars; boolean lengthOfOne = fastcheck == fMostRecentByte; int startOffset = cache.fSymbolCharsOffset; int entry = 0; int[] entries = cacheLines[entry]; int offset = 1 + ((entries[0] - 1) * SymbolCache.CACHE_RECORD_SIZE); int totalMisses = 0; if (lengthOfOne) { while (offset > 0) { if (entries[offset + SymbolCache.CHAR_OFFSET] == ch) { if (entries[offset + SymbolCache.INDEX_OFFSET] != -1) { int symbolIndex = entries[offset + SymbolCache.INDEX_OFFSET]; if (totalMisses > 3) fStringPool.updateCacheLine(symbolIndex, totalMisses, 1); return symbolIndex; } break; } offset -= SymbolCache.CACHE_RECORD_SIZE; totalMisses++; } try { symbolChars[cache.fSymbolCharsOffset] = (char)ch; } catch (ArrayIndexOutOfBoundsException ex) { symbolChars = new char[cache.fSymbolCharsOffset * 2]; System.arraycopy(cache.fSymbolChars, 0, symbolChars, 0, cache.fSymbolCharsOffset); cache.fSymbolChars = symbolChars; symbolChars[cache.fSymbolCharsOffset] = (char)ch; } cache.fSymbolCharsOffset++; if (offset < 0) { offset = 1 + (entries[0] * SymbolCache.CACHE_RECORD_SIZE); entries[0]++; try { entries[offset + SymbolCache.CHAR_OFFSET] = ch; } catch (ArrayIndexOutOfBoundsException ex) { int newSize = 1 + ((offset - 1) * 2); entries = new int[newSize]; System.arraycopy(cacheLines[entry], 0, entries, 0, offset); cacheLines[entry] = entries; entries[offset + SymbolCache.CHAR_OFFSET] = ch; } entries[offset + SymbolCache.NEXT_OFFSET] = -1; } int result = fStringPool.createNonMatchingSymbol(startOffset, entry, entries, offset); return result; } try { symbolChars[cache.fSymbolCharsOffset] = (char)ch; } catch (ArrayIndexOutOfBoundsException ex) { symbolChars = new char[cache.fSymbolCharsOffset * 2]; System.arraycopy(cache.fSymbolChars, 0, symbolChars, 0, cache.fSymbolCharsOffset); cache.fSymbolChars = symbolChars; symbolChars[cache.fSymbolCharsOffset] = (char)ch; } cache.fSymbolCharsOffset++; int depth = 1; while (true) { if (offset < 0) break; if (entries[offset + SymbolCache.CHAR_OFFSET] != ch) { offset -= SymbolCache.CACHE_RECORD_SIZE; totalMisses++; continue; } if (b0 >= 0x80) { ch = getMultiByteSymbolChar(b0); b0 = fMostRecentByte; } else if (b0 == fastcheck || XMLCharacterProperties.fgAsciiNameChar[b0] == 0) { ch = -1; } else { ch = b0; fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } } if (ch == -1) { if (entries[offset + SymbolCache.INDEX_OFFSET] == -1) { return fStringPool.createNonMatchingSymbol(startOffset, entry, entries, offset); } cache.fSymbolCharsOffset = startOffset; int symbolIndex = entries[offset + SymbolCache.INDEX_OFFSET]; if (totalMisses > (depth * 3)) fStringPool.updateCacheLine(symbolIndex, totalMisses, depth); return symbolIndex; } try { symbolChars[cache.fSymbolCharsOffset] = (char)ch; } catch (ArrayIndexOutOfBoundsException ex) { symbolChars = new char[cache.fSymbolCharsOffset * 2]; System.arraycopy(cache.fSymbolChars, 0, symbolChars, 0, cache.fSymbolCharsOffset); cache.fSymbolChars = symbolChars; symbolChars[cache.fSymbolCharsOffset] = (char)ch; } cache.fSymbolCharsOffset++; entry = entries[offset + SymbolCache.NEXT_OFFSET]; try { entries = cacheLines[entry]; } catch (ArrayIndexOutOfBoundsException ex) { if (entry == -1) { entry = cache.fCacheLineCount++; entries[offset + SymbolCache.NEXT_OFFSET] = entry; entries = new int[1+(SymbolCache.INITIAL_CACHE_RECORD_COUNT*SymbolCache.CACHE_RECORD_SIZE)]; try { cacheLines[entry] = entries; } catch (ArrayIndexOutOfBoundsException ex2) { cacheLines = new int[entry * 2][]; System.arraycopy(cache.fCacheLines, 0, cacheLines, 0, entry); cache.fCacheLines = cacheLines; cacheLines[entry] = entries; } } else { entries = cacheLines[entry]; throw new RuntimeException("RDR001 untested"); // REVISIT } } offset = 1 + ((entries[0] - 1) * SymbolCache.CACHE_RECORD_SIZE); depth++; } if (offset < 0) offset = 1 + (entries[0] * SymbolCache.CACHE_RECORD_SIZE); while (true) { entries[0]++; try { entries[offset + SymbolCache.CHAR_OFFSET] = ch; } catch (ArrayIndexOutOfBoundsException ex) { int newSize = 1 + ((offset - 1) * 2); entries = new int[newSize]; System.arraycopy(cacheLines[entry], 0, entries, 0, offset); cacheLines[entry] = entries; entries[offset + SymbolCache.CHAR_OFFSET] = ch; } if (b0 >= 0x80) { ch = getMultiByteSymbolChar(b0); b0 = fMostRecentByte; } else if (b0 == fastcheck || XMLCharacterProperties.fgAsciiNameChar[b0] == 0) { ch = -1; } else { ch = b0; fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } } if (ch == -1) { entries[offset + SymbolCache.NEXT_OFFSET] = -1; break; } entry = cache.fCacheLineCount++; entries[offset + SymbolCache.INDEX_OFFSET] = -1; entries[offset + SymbolCache.NEXT_OFFSET] = entry; entries = new int[1+(SymbolCache.INITIAL_CACHE_RECORD_COUNT*SymbolCache.CACHE_RECORD_SIZE)]; try { cacheLines[entry] = entries; } catch (ArrayIndexOutOfBoundsException ex) { cacheLines = new int[entry * 2][]; System.arraycopy(cache.fCacheLines, 0, cacheLines, 0, entry); cache.fCacheLines = cacheLines; cacheLines[entry] = entries; } offset = 1; try { symbolChars[cache.fSymbolCharsOffset] = (char)ch; } catch (ArrayIndexOutOfBoundsException ex) { symbolChars = new char[cache.fSymbolCharsOffset * 2]; System.arraycopy(cache.fSymbolChars, 0, symbolChars, 0, cache.fSymbolCharsOffset); cache.fSymbolChars = symbolChars; symbolChars[cache.fSymbolCharsOffset] = (char)ch; } cache.fSymbolCharsOffset++; } int result = fStringPool.createNonMatchingSymbol(startOffset, entry, entries, offset); return result; } // // [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*) // private int recognizeMarkup(int b0, QName element) throws Exception { switch (b0) { case 0: return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; case '?': fCharacterCounter++; loadNextByte(); return XMLEntityHandler.CONTENT_RESULT_START_OF_PI; case '!': fCharacterCounter++; b0 = loadNextByte(); if (b0 == 0) { fCharacterCounter--; fCurrentOffset--; return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; } if (b0 == '-') { fCharacterCounter++; b0 = loadNextByte(); if (b0 == 0) { fCharacterCounter -= 2; fCurrentOffset -= 2; return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; } if (b0 == '-') { fCharacterCounter++; b0 = loadNextByte(); return XMLEntityHandler.CONTENT_RESULT_START_OF_COMMENT; } break; } if (b0 == '[') { for (int i = 0; i < 6; i++) { fCharacterCounter++; b0 = loadNextByte(); if (b0 == 0) { fCharacterCounter -= (2 + i); fCurrentOffset -= (2 + i); return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; } if (b0 != cdata_string[i]) { return XMLEntityHandler.CONTENT_RESULT_MARKUP_NOT_RECOGNIZED; } } fCharacterCounter++; loadNextByte(); return XMLEntityHandler.CONTENT_RESULT_START_OF_CDSECT; } break; case '/': fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } int expectedName = element.rawname; fStringPool.getCharArrayRange(expectedName, fCharArrayRange); char[] expected = fCharArrayRange.chars; int offset = fCharArrayRange.offset; int len = fCharArrayRange.length; // // DEFECT !! - needs UTF8 multibyte support... // if (b0 == expected[offset++]) { UTF8DataChunk savedChunk = fCurrentChunk; int savedIndex = fCurrentIndex; int savedOffset = fCurrentOffset; for (int i = 1; i < len; i++) { if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } // // DEFECT !! - needs UTF8 multibyte support... // if (b0 != expected[offset++]) { fCurrentChunk = savedChunk; fCurrentIndex = savedIndex; fCurrentOffset = savedOffset; fMostRecentData = fCurrentChunk.toByteArray(); fMostRecentByte = fMostRecentData[savedIndex] & 0xFF; return XMLEntityHandler.CONTENT_RESULT_START_OF_ETAG; } } fCharacterCounter += len; // REVISIT - double check this... fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (b0 == '>') { fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } return XMLEntityHandler.CONTENT_RESULT_MATCHING_ETAG; } while (b0 == 0x20 || b0 == 0x09 || b0 == 0x0A || b0 == 0x0D) { if (b0 == 0x0A) { fLinefeedCounter++; fCharacterCounter = 1; b0 = loadNextByte(); } else if (b0 == 0x0D) { fCarriageReturnCounter++; fCharacterCounter = 1; b0 = loadNextByte(); if (b0 == 0x0A) { fLinefeedCounter++; b0 = loadNextByte(); } } else { fCharacterCounter++; b0 = loadNextByte(); } if (b0 == '>') { fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } return XMLEntityHandler.CONTENT_RESULT_MATCHING_ETAG; } } fCurrentChunk = savedChunk; fCurrentIndex = savedIndex; fCurrentOffset = savedOffset; fMostRecentData = fCurrentChunk.toByteArray(); fMostRecentByte = fMostRecentData[savedIndex] & 0xFF; } return XMLEntityHandler.CONTENT_RESULT_START_OF_ETAG; default: return XMLEntityHandler.CONTENT_RESULT_START_OF_ELEMENT; } return XMLEntityHandler.CONTENT_RESULT_MARKUP_NOT_RECOGNIZED; } private int recognizeReference(int ch) throws Exception { if (ch == 0) { return XMLEntityHandler.CONTENT_RESULT_REFERENCE_END_OF_INPUT; } // // [67] Reference ::= EntityRef | CharRef // [68] EntityRef ::= '&' Name ';' // [66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';' // if (ch == '#') { fCharacterCounter++; loadNextByte(); return XMLEntityHandler.CONTENT_RESULT_START_OF_CHARREF; } else { return XMLEntityHandler.CONTENT_RESULT_START_OF_ENTITYREF; } } public int scanContent(QName element) throws Exception { if (fCallClearPreviousChunk && fCurrentChunk.clearPreviousChunk()) fCallClearPreviousChunk = false; fCharDataLength = 0; int charDataOffset = fCurrentOffset; int ch = fMostRecentByte; if (ch < 0x80) { switch (XMLCharacterProperties.fgAsciiWSCharData[ch]) { case 0: if (fSendCharDataAsCharArray) { try { fCharacters[fCharDataLength] = (char)ch; fCharDataLength++; } catch (ArrayIndexOutOfBoundsException ex) { slowAppendCharData(ch); } } fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } break; case 1: // '<' fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (!fInCDSect) { return recognizeMarkup(ch, element); } if (fSendCharDataAsCharArray) appendCharData('<'); break; case 2: // '&' fCharacterCounter++; ch = loadNextByte(); if (!fInCDSect) { return recognizeReference(ch); } if (fSendCharDataAsCharArray) appendCharData('&'); break; case 3: // ']' fCharacterCounter++; ch = loadNextByte(); if (ch != ']') { if (fSendCharDataAsCharArray) appendCharData(']'); break; } if (fCurrentIndex + 1 == UTF8DataChunk.CHUNK_SIZE) { UTF8DataChunk saveChunk = fCurrentChunk; int saveIndex = fCurrentIndex; int saveOffset = fCurrentOffset; if (loadNextByte() != '>') { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = fCurrentChunk.toByteArray(); fMostRecentByte = ']'; if (fSendCharDataAsCharArray) appendCharData(']'); break; } } else { if (fMostRecentData[fCurrentIndex + 1] != '>') { if (fSendCharDataAsCharArray) appendCharData(']'); break; } fCurrentIndex++; fCurrentOffset++; } loadNextByte(); fCharacterCounter += 2; return XMLEntityHandler.CONTENT_RESULT_END_OF_CDSECT; case 4: // invalid char if (ch == 0 && atEOF(fCurrentOffset + 1)) { changeReaders(); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; // REVISIT - not quite... } return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; case 5: do { if (ch == 0x0A) { fLinefeedCounter++; fCharacterCounter = 1; } else if (ch == 0x0D) { fCarriageReturnCounter++; fCharacterCounter = 1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (ch != 0x0A) { if (fSendCharDataAsCharArray) appendCharData(0x0A); if (ch == 0x20 || ch == 0x09 || ch == 0x0D) continue; break; } fLinefeedCounter++; } else { fCharacterCounter++; } if (fSendCharDataAsCharArray) { try { fCharacters[fCharDataLength] = (char)ch; fCharDataLength++; } catch (ArrayIndexOutOfBoundsException ex) { slowAppendCharData(ch); } } if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } } while (ch == 0x20 || ch == 0x09 || ch == 0x0A || ch == 0x0D); if (ch < 0x80) { switch (XMLCharacterProperties.fgAsciiCharData[ch]) { case 0: if (fSendCharDataAsCharArray) appendCharData(ch); fCharacterCounter++; ch = loadNextByte(); break; case 1: // '<' if (!fInCDSect) { if (fSendCharDataAsCharArray) { fCharDataHandler.processWhitespace(fCharacters, 0, fCharDataLength); } else { int stringIndex = addString(charDataOffset, fCurrentOffset - charDataOffset); fCharDataHandler.processWhitespace(stringIndex); } fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } return recognizeMarkup(ch, element); } if (fSendCharDataAsCharArray) appendCharData('<'); fCharacterCounter++; ch = loadNextByte(); break; case 2: // '&' if (!fInCDSect) { whitespace(charDataOffset, fCurrentOffset); fCharacterCounter++; ch = loadNextByte(); return recognizeReference(ch); } if (fSendCharDataAsCharArray) appendCharData('&'); fCharacterCounter++; ch = loadNextByte(); break; case 3: // ']' int endOffset = fCurrentOffset; ch = loadNextByte(); if (ch != ']') { fCharacterCounter++; if (fSendCharDataAsCharArray) appendCharData(']'); break; } if (fCurrentIndex + 1 == UTF8DataChunk.CHUNK_SIZE) { UTF8DataChunk saveChunk = fCurrentChunk; int saveIndex = fCurrentIndex; int saveOffset = fCurrentOffset; if (loadNextByte() != '>') { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = fCurrentChunk.toByteArray(); fMostRecentByte = ']'; fCharacterCounter++; if (fSendCharDataAsCharArray) appendCharData(']'); break; } } else { if (fMostRecentData[fCurrentIndex + 1] != '>') { fCharacterCounter++; if (fSendCharDataAsCharArray) appendCharData(']'); break; } fCurrentIndex++; fCurrentOffset++; } loadNextByte(); whitespace(charDataOffset, endOffset); fCharacterCounter += 3; return XMLEntityHandler.CONTENT_RESULT_END_OF_CDSECT; case 4: // invalid char whitespace(charDataOffset, fCurrentOffset); if (ch == 0 && atEOF(fCurrentOffset + 1)) { changeReaders(); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; // REVISIT - not quite... } return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } else { if (fSendCharDataAsCharArray) { if (!copyMultiByteCharData(ch)) { whitespace(charDataOffset, fCurrentOffset); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } else if (!skipMultiByteCharData(ch)) { whitespace(charDataOffset, fCurrentOffset); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } break; } } else { if (fSendCharDataAsCharArray) { if (!copyMultiByteCharData(ch)) { return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } else { if (!skipMultiByteCharData(ch)) { return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } } if (fSendCharDataAsCharArray) ch = copyAsciiCharData(); else ch = skipAsciiCharData(); while (true) { if (ch < 0x80) { switch (XMLCharacterProperties.fgAsciiCharData[ch]) { case 0: if (fSendCharDataAsCharArray) appendCharData(ch); fCharacterCounter++; ch = loadNextByte(); break; case 1: // '<' if (!fInCDSect) { if (fSendCharDataAsCharArray) { fCharDataHandler.processCharacters(fCharacters, 0, fCharDataLength); } else { int stringIndex = addString(charDataOffset, fCurrentOffset - charDataOffset); fCharDataHandler.processCharacters(stringIndex); } fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } return recognizeMarkup(ch, element); } if (fSendCharDataAsCharArray) appendCharData('<'); fCharacterCounter++; ch = loadNextByte(); break; case 2: // '&' if (!fInCDSect) { characters(charDataOffset, fCurrentOffset); fCharacterCounter++; ch = loadNextByte(); return recognizeReference(ch); } if (fSendCharDataAsCharArray) appendCharData('&'); fCharacterCounter++; ch = loadNextByte(); break; case 3: // ']' int endOffset = fCurrentOffset; ch = loadNextByte(); if (ch != ']') { fCharacterCounter++; if (fSendCharDataAsCharArray) appendCharData(']'); break; } if (fCurrentIndex + 1 == UTF8DataChunk.CHUNK_SIZE) { UTF8DataChunk saveChunk = fCurrentChunk; int saveIndex = fCurrentIndex; int saveOffset = fCurrentOffset; if (loadNextByte() != '>') { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = fCurrentChunk.toByteArray(); fMostRecentByte = ']'; fCharacterCounter++; if (fSendCharDataAsCharArray) appendCharData(']'); break; } } else { if (fMostRecentData[fCurrentIndex + 1] != '>') { fCharacterCounter++; if (fSendCharDataAsCharArray) appendCharData(']'); break; } fCurrentIndex++; fCurrentOffset++; } loadNextByte(); characters(charDataOffset, endOffset); fCharacterCounter += 3; return XMLEntityHandler.CONTENT_RESULT_END_OF_CDSECT; case 4: // invalid char if (ch == 0x0A) { if (fSendCharDataAsCharArray) appendCharData(ch); fLinefeedCounter++; fCharacterCounter = 1; ch = loadNextByte(); break; } if (ch == 0x0D) { if (fSendCharDataAsCharArray) appendCharData(0x0A); fCarriageReturnCounter++; fCharacterCounter = 1; ch = loadNextByte(); if (ch == 0x0A) { fLinefeedCounter++; ch = loadNextByte(); } break; } characters(charDataOffset, fCurrentOffset); if (ch == 0 && atEOF(fCurrentOffset + 1)) { changeReaders(); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; // REVISIT - not quite... } return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } else { if (fSendCharDataAsCharArray) { if (!copyMultiByteCharData(ch)) { characters(charDataOffset, fCurrentOffset); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } else if (!skipMultiByteCharData(ch)) { characters(charDataOffset, fCurrentOffset); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } ch = fMostRecentByte; } } } private boolean copyMultiByteCharData(int b0) throws Exception { UTF8DataChunk saveChunk = fCurrentChunk; int saveOffset = fCurrentOffset; int saveIndex = fCurrentIndex; int b1 = loadNextByte(); if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx (0x80 to 0x7ff) int ch = ((0x1f & b0)<<6) + (0x3f & b1); appendCharData(ch); // yyy yyxx xxxx (0x80 to 0x7ff) loadNextByte(); return true; } int b2 = loadNextByte(); if ((0xf0 & b0) == 0xe0) { // 1110zzzz 10yyyyyy 10xxxxxx // ch = ((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2); // zzzz yyyy yyxx xxxx (0x800 to 0xffff) // if ((ch >= 0xD800 && ch <= 0xDFFF) || ch >= 0xFFFE) if ((b0 == 0xED && b1 >= 0xA0) || (b0 == 0xEF && b1 == 0xBF && b2 >= 0xBE)) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } int ch = ((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2); appendCharData(ch); // zzzz yyyy yyxx xxxx (0x800 to 0xffff) loadNextByte(); return true; } int b3 = loadNextByte(); // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx // ch = ((0x0f & b0)<<18) + ((0x3f & b1)<<12) + ((0x3f & b2)<<6) + (0x3f & b3); // u uuuu zzzz yyyy yyxx xxxx (0x10000 to 0x1ffff) // if (ch >= 0x110000) if (( 0xf8 & b0 ) == 0xf0 ) { if (b0 > 0xF4 || (b0 == 0xF4 && b1 >= 0x90)) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } int ch = ((0x0f & b0)<<18) + ((0x3f & b1)<<12) + ((0x3f & b2)<<6) + (0x3f & b3); if (ch < 0x10000) { appendCharData(ch); } else { appendCharData(((ch-0x00010000)>>10)+0xd800); appendCharData(((ch-0x00010000)&0x3ff)+0xdc00); } loadNextByte(); return true; } else { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } } private boolean skipMultiByteCharData(int b0) throws Exception { UTF8DataChunk saveChunk = fCurrentChunk; int saveOffset = fCurrentOffset; int saveIndex = fCurrentIndex; int b1 = loadNextByte(); if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx (0x80 to 0x7ff) loadNextByte(); return true; } int b2 = loadNextByte(); if ((0xf0 & b0) == 0xe0) { // 1110zzzz 10yyyyyy 10xxxxxx // ch = ((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2); // zzzz yyyy yyxx xxxx (0x800 to 0xffff) // if ((ch >= 0xD800 && ch <= 0xDFFF) || ch >= 0xFFFE) if ((b0 == 0xED && b1 >= 0xA0) || (b0 == 0xEF && b1 == 0xBF && b2 >= 0xBE)) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } loadNextByte(); return true; } int b3 = loadNextByte(); // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx // ch = ((0x0f & b0)<<18) + ((0x3f & b1)<<12) + ((0x3f & b2)<<6) + (0x3f & b3); // u uuuu zzzz yyyy yyxx xxxx (0x10000 to 0x1ffff) // if (ch >= 0x110000) if (b0 > 0xF4 || (b0 == 0xF4 && b1 >= 0x90)) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } loadNextByte(); return true; } private int copyAsciiCharData() throws Exception { int srcIndex = fCurrentIndex; int offset = fCurrentOffset - srcIndex; byte[] data = fMostRecentData; int dstIndex = fCharDataLength; boolean skiplf = false; while (true) { int ch; try { ch = data[srcIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { offset += srcIndex; slowLoadNextByte(); srcIndex = 0; data = fMostRecentData; ch = data[srcIndex] & 0xFF; } if (ch >= 0x80) { fCurrentOffset = offset + srcIndex; fCurrentIndex = srcIndex; fMostRecentByte = ch; return ch; } if (XMLCharacterProperties.fgAsciiCharData[ch] == 0) { fCharacterCounter++; skiplf = false; } else if (ch == 0x0A) { fLinefeedCounter++; if (skiplf) { skiplf = false; srcIndex++; continue; } fCharacterCounter = 1; } else if (ch == 0x0D) { fCarriageReturnCounter++; fCharacterCounter = 1; skiplf = true; ch = 0x0A; } else { fCurrentOffset = offset + srcIndex; fCurrentIndex = srcIndex; fMostRecentByte = ch; return ch; } srcIndex++; try { fCharacters[fCharDataLength] = (char)ch; fCharDataLength++; } catch (ArrayIndexOutOfBoundsException ex) { slowAppendCharData(ch); } } } private int skipAsciiCharData() throws Exception { int srcIndex = fCurrentIndex; int offset = fCurrentOffset - srcIndex; byte[] data = fMostRecentData; while (true) { int ch; try { ch = data[srcIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { offset += srcIndex; slowLoadNextByte(); srcIndex = 0; data = fMostRecentData; ch = data[srcIndex] & 0xFF; } if (ch >= 0x80) { fCurrentOffset = offset + srcIndex; fCurrentIndex = srcIndex; fMostRecentByte = ch; return ch; } if (XMLCharacterProperties.fgAsciiCharData[ch] == 0) { fCharacterCounter++; } else if (ch == 0x0A) { fLinefeedCounter++; fCharacterCounter = 1; } else if (ch == 0x0D) { fCarriageReturnCounter++; fCharacterCounter = 1; } else { fCurrentOffset = offset + srcIndex; fCurrentIndex = srcIndex; fMostRecentByte = ch; return ch; } srcIndex++; } } private char[] fCharacters = new char[UTF8DataChunk.CHUNK_SIZE]; private int fCharDataLength = 0; private void appendCharData(int ch) throws Exception { try { fCharacters[fCharDataLength] = (char)ch; fCharDataLength++; } catch (ArrayIndexOutOfBoundsException ex) { slowAppendCharData(ch); } } private void slowAppendCharData(int ch) throws Exception { // flush the buffer... characters(0, fCharDataLength); /* DEFECT !! whitespace this long is unlikely, but possible */ fCharDataLength = 0; fCharacters[fCharDataLength++] = (char)ch; } private void characters(int offset, int endOffset) throws Exception { // // REVISIT - need more up front bounds checking code of params... // if (!fSendCharDataAsCharArray) { int stringIndex = addString(offset, endOffset - offset); fCharDataHandler.processCharacters(stringIndex); return; } fCharDataHandler.processCharacters(fCharacters, 0, fCharDataLength); } private void whitespace(int offset, int endOffset) throws Exception { // // REVISIT - need more up front bounds checking code of params... // if (!fSendCharDataAsCharArray) { int stringIndex = addString(offset, endOffset - offset); fCharDataHandler.processWhitespace(stringIndex); return; } fCharDataHandler.processWhitespace(fCharacters, 0, fCharDataLength); } // // // private static final char[] cdata_string = { 'C','D','A','T','A','['}; private StringPool.CharArrayRange fCharArrayRange = null; private InputStream fInputStream = null; private StringPool fStringPool = null; private UTF8DataChunk fCurrentChunk = null; private int fCurrentIndex = 0; private byte[] fMostRecentData = null; private int fMostRecentByte = 0; private int fLength = 0; private boolean fCalledCharPropInit = false; private boolean fCallClearPreviousChunk = true; // // // private int fillCurrentChunk() throws Exception { byte[] buf = fCurrentChunk.toByteArray(); if (fInputStream == null) { if (buf == null) buf = new byte[1]; buf[0] = 0; fMostRecentData = buf; fCurrentIndex = 0; fCurrentChunk.setByteArray(fMostRecentData); return(fMostRecentByte = fMostRecentData[0] & 0xFF); } if (buf == null) buf = new byte[UTF8DataChunk.CHUNK_SIZE]; int offset = 0; int capacity = UTF8DataChunk.CHUNK_SIZE; int result = 0; do { try { result = fInputStream.read(buf, offset, capacity); } catch (java.io.IOException ex) { result = -1; } if (result == -1) { // // We have reached the end of the stream. // fInputStream.close(); fInputStream = null; try { buf[offset] = 0; } catch (ArrayIndexOutOfBoundsException ex) { } break; } if (result > 0) { offset += result; capacity -= result; } } while (capacity > 0); fMostRecentData = buf; fLength += offset; fCurrentIndex = 0; fCurrentChunk.setByteArray(fMostRecentData); return(fMostRecentByte = fMostRecentData[0] & 0xFF); } }
src/org/apache/xerces/readers/UTF8Reader.java
/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999,2000 The Apache Software Foundation. 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 the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xerces.readers; import org.apache.xerces.framework.XMLErrorReporter; import org.apache.xerces.utils.QName; import org.apache.xerces.utils.StringPool; import org.apache.xerces.utils.SymbolCache; import org.apache.xerces.utils.UTF8DataChunk; import org.apache.xerces.utils.XMLCharacterProperties; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.LocatorImpl; import java.io.InputStream; import java.util.Vector; /** * This is the primary reader used for UTF-8 encoded byte streams. * <p> * This reader processes requests from the scanners against the * underlying UTF-8 byte stream, avoiding when possible any up-front * transcoding. When the StringPool handle interfaces are used, * the information in the data stream will be added to the string * pool and lazy-evaluated until asked for. * <p> * We use the SymbolCache to match expected names (element types in * end tags) and walk the data structures of that class directly. * <p> * There is a significant amount of hand-inlining and some blatant * voilation of good object oriented programming rules, ignoring * boundaries of modularity, etc., in the name of good performance. * <p> * There are also some places where the code here frequently crashes * the SUN java runtime compiler (JIT) and the code here has been * carefully "crafted" to avoid those problems. * * @version $Id$ */ final class UTF8Reader extends XMLEntityReader { // // // private final static boolean USE_OUT_OF_LINE_LOAD_NEXT_BYTE = false; private final static boolean USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE = true; // // // public UTF8Reader(XMLEntityHandler entityHandler, XMLErrorReporter errorReporter, boolean sendCharDataAsCharArray, InputStream dataStream, StringPool stringPool) throws Exception { super(entityHandler, errorReporter, sendCharDataAsCharArray); fInputStream = dataStream; fStringPool = stringPool; fCharArrayRange = fStringPool.createCharArrayRange(); fCurrentChunk = UTF8DataChunk.createChunk(fStringPool, null); fillCurrentChunk(); } /** * */ public int addString(int offset, int length) { if (length == 0) return 0; return fCurrentChunk.addString(offset, length); } /** * */ public int addSymbol(int offset, int length) { if (length == 0) return 0; return fCurrentChunk.addSymbol(offset, length, 0); } /** * */ private int addSymbol(int offset, int length, int hashcode) { if (length == 0) return 0; return fCurrentChunk.addSymbol(offset, length, hashcode); } /** * */ public void append(XMLEntityHandler.CharBuffer charBuffer, int offset, int length) { fCurrentChunk.append(charBuffer, offset, length); } // // // private int slowLoadNextByte() throws Exception { fCallClearPreviousChunk = true; if (fCurrentChunk.nextChunk() != null) { fCurrentChunk = fCurrentChunk.nextChunk(); fCurrentIndex = 0; fMostRecentData = fCurrentChunk.toByteArray(); return(fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } else { fCurrentChunk = UTF8DataChunk.createChunk(fStringPool, fCurrentChunk); return fillCurrentChunk(); } } private int loadNextByte() throws Exception { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; return fMostRecentByte; } catch (ArrayIndexOutOfBoundsException ex) { return slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) return slowLoadNextByte(); else return(fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } // // // private boolean atEOF(int offset) { return(offset > fLength); } // // // public XMLEntityHandler.EntityReader changeReaders() throws Exception { XMLEntityHandler.EntityReader nextReader = super.changeReaders(); fCurrentChunk.releaseChunk(); fCurrentChunk = null; fMostRecentData = null; fMostRecentByte = 0; return nextReader; } // // // public boolean lookingAtChar(char ch, boolean skipPastChar) throws Exception { int b0 = fMostRecentByte; if (b0 != ch) { if (b0 == 0) { if (atEOF(fCurrentOffset + 1)) { return changeReaders().lookingAtChar(ch, skipPastChar); } } if (ch == 0x0A && b0 == 0x0D) { if (skipPastChar) { fCarriageReturnCounter++; fCharacterCounter = 1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; b0 = fMostRecentByte; } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (b0 == 0x0A) { fLinefeedCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } } } return true; } return false; } if (ch == 0x0D) return false; if (skipPastChar) { fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } } return true; } // // // public boolean lookingAtValidChar(boolean skipPastChar) throws Exception { int b0 = fMostRecentByte; if (b0 < 0x80) { // 0xxxxxxx if (b0 >= 0x20 || b0 == 0x09) { if (skipPastChar) { fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } } return true; } if (b0 == 0x0A) { if (skipPastChar) { fLinefeedCounter++; fCharacterCounter = 1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } } return true; } if (b0 == 0x0D) { if (skipPastChar) { fCarriageReturnCounter++; fCharacterCounter = 1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; b0 = fMostRecentByte; } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (b0 == 0x0A) { fLinefeedCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } } } return true; } if (b0 == 0) { if (atEOF(fCurrentOffset + 1)) { return changeReaders().lookingAtValidChar(skipPastChar); } } return false; } // // REVISIT - optimize this with in-buffer lookahead. // UTF8DataChunk saveChunk = fCurrentChunk; int saveIndex = fCurrentIndex; int saveOffset = fCurrentOffset; int b1 = loadNextByte(); if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx (0x80 to 0x7ff) if (skipPastChar) { fCharacterCounter++; loadNextByte(); } else { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; } return true; // [#x20-#xD7FF] } int b2 = loadNextByte(); if ((0xf0 & b0) == 0xe0) { // 1110zzzz 10yyyyyy 10xxxxxx // ch = ((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2); // zzzz yyyy yyxx xxxx (0x800 to 0xffff) // if (!((ch >= 0xD800 && ch <= 0xDFFF) || ch >= 0xFFFE)) // if ((ch <= 0xD7FF) || (ch >= 0xE000 && ch <= 0xFFFD)) boolean result = false; if (!((b0 == 0xED && b1 >= 0xA0) || (b0 == 0xEF && b1 == 0xBF && b2 >= 0xBE))) { // [#x20-#xD7FF] | [#xE000-#xFFFD] if (skipPastChar) { fCharacterCounter++; loadNextByte(); return true; } result = true; } fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return result; } int b3 = loadNextByte(); // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx // ch = ((0x0f & b0)<<18) + ((0x3f & b1)<<12) + ((0x3f & b2)<<6) + (0x3f & b3); // u uuuu zzzz yyyy yyxx xxxx (0x10000 to 0x1ffff) // if (ch >= 0x110000) boolean result = false; //if (( 0xf8 & b0 ) == 0xf0 ) { //if (!(b0 > 0xF4 || (b0 == 0xF4 && b1 >= 0x90))) { // [#x10000-#x10FFFF] if( ((b0&0xf8) == 0xf0) && ((b1&0xc0)==0x80) && ((b2&0xc0) == 0x80) && ((b3&0xc0)==0x80)){ if (skipPastChar) { fCharacterCounter++; loadNextByte(); return true; } result = true; //} fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return result; } else{ fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return result; } } // // // public boolean lookingAtSpace(boolean skipPastChar) throws Exception { int ch = fMostRecentByte; if (ch > 0x20) return false; if (ch == 0x20 || ch == 0x09) { if (!skipPastChar) return true; fCharacterCounter++; } else if (ch == 0x0A) { if (!skipPastChar) return true; fLinefeedCounter++; fCharacterCounter = 1; } else if (ch == 0x0D) { if (!skipPastChar) return true; fCarriageReturnCounter++; fCharacterCounter = 1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; ch = fMostRecentByte; } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (ch != 0x0A) return true; fLinefeedCounter++; } else { if (ch == 0) { // REVISIT - should we be checking this here ? if (atEOF(fCurrentOffset + 1)) { return changeReaders().lookingAtSpace(skipPastChar); } } return false; } if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } return true; } // // // public void skipToChar(char ch) throws Exception { // // REVISIT - this will skip invalid characters without reporting them. // int b0 = fMostRecentByte; while (true) { if (b0 == ch) // ch will always be an ascii character return; if (b0 == 0) { if (atEOF(fCurrentOffset + 1)) { changeReaders().skipToChar(ch); return; } fCharacterCounter++; } else if (b0 == 0x0A) { fLinefeedCounter++; fCharacterCounter = 1; } else if (b0 == 0x0D) { fCarriageReturnCounter++; fCharacterCounter = 1; b0 = loadNextByte(); if (b0 != 0x0A) continue; fLinefeedCounter++; } else if (b0 < 0x80) { // 0xxxxxxx fCharacterCounter++; } else { fCharacterCounter++; if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx loadNextByte(); } else if ((0xf0 & b0) == 0xe0) { // 1110zzzz 10yyyyyy 10xxxxxx loadNextByte(); loadNextByte(); } else { // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx loadNextByte(); loadNextByte(); loadNextByte(); } } b0 = loadNextByte(); } } // // // public void skipPastSpaces() throws Exception { int ch = fMostRecentByte; while (true) { if (ch == 0x20 || ch == 0x09) { fCharacterCounter++; } else if (ch == 0x0A) { fLinefeedCounter++; fCharacterCounter = 1; } else if (ch == 0x0D) { fCarriageReturnCounter++; fCharacterCounter = 1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; ch = fMostRecentByte; } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (ch != 0x0A) continue; fLinefeedCounter++; } else { if (ch == 0 && atEOF(fCurrentOffset + 1)) changeReaders().skipPastSpaces(); return; } if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; ch = fMostRecentByte; } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } } } // // // protected boolean skippedMultiByteCharWithFlag(int b0, int flag) throws Exception { UTF8DataChunk saveChunk = fCurrentChunk; int saveOffset = fCurrentOffset; int saveIndex = fCurrentIndex; if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } int b1 = loadNextByte(); if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx if ((XMLCharacterProperties.fgCharFlags[((0x1f & b0)<<6) + (0x3f & b1)] & flag) == 0) { // yyy yyxx xxxx (0x80 to 0x7ff) fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } return true; } int b2 = loadNextByte(); if ((0xf0 & b0) == 0xe0) { // 1110zzzz 10yyyyyy 10xxxxxx // if ((ch >= 0xD800 && ch <= 0xDFFF) || ch >= 0xFFFE) if ((b0 == 0xED && b1 >= 0xA0) || (b0 == 0xEF && b1 == 0xBF && b2 >= 0xBE)) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } if ((XMLCharacterProperties.fgCharFlags[((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2)] & flag) == 0) { // zzzz yyyy yyxx xxxx (0x800 to 0xffff) fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } return true; } else { // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } } public void skipPastName(char fastcheck) throws Exception { int b0 = fMostRecentByte; if (b0 < 0x80) { if (XMLCharacterProperties.fgAsciiInitialNameChar[b0] == 0) return; } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } if (!skippedMultiByteCharWithFlag(b0, XMLCharacterProperties.E_InitialNameCharFlag)) return; } while (true) { fCharacterCounter++; b0 = loadNextByte(); if (fastcheck == b0) return; if (b0 < 0x80) { if (XMLCharacterProperties.fgAsciiNameChar[b0] == 0) return; } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } if (!skippedMultiByteCharWithFlag(b0, XMLCharacterProperties.E_NameCharFlag)) return; } } } // // // public void skipPastNmtoken(char fastcheck) throws Exception { int b0 = fMostRecentByte; while (true) { if (fastcheck == b0) return; if (b0 < 0x80) { if (XMLCharacterProperties.fgAsciiNameChar[b0] == 0) return; } else { if (!skippedMultiByteCharWithFlag(b0, XMLCharacterProperties.E_NameCharFlag)) return; } fCharacterCounter++; b0 = loadNextByte(); } } // // // public boolean skippedString(char[] s) throws Exception { int length = s.length; byte[] data = fMostRecentData; int index = fCurrentIndex + length; int sindex = length; try { while (sindex-- > 0) { if (data[--index] != s[sindex]) return false; } fCurrentIndex += length; } catch (ArrayIndexOutOfBoundsException ex) { int i = 0; index = fCurrentIndex; while (index < UTF8DataChunk.CHUNK_SIZE) { if (data[index++] != s[i++]) return false; } UTF8DataChunk dataChunk = fCurrentChunk; int savedOffset = fCurrentOffset; int savedIndex = fCurrentIndex; slowLoadNextByte(); data = fMostRecentData; index = 0; while (i < length) { if (data[index++] != s[i++]) { fCurrentChunk = dataChunk; fCurrentIndex = savedIndex; fCurrentOffset = savedOffset; fMostRecentData = fCurrentChunk.toByteArray(); fMostRecentByte = fMostRecentData[savedIndex] & 0xFF; return false; } } fCurrentIndex = index; } fCharacterCounter += length; fCurrentOffset += length; try { fMostRecentByte = data[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } return true; } // // // public int scanInvalidChar() throws Exception { int b0 = fMostRecentByte; int ch = b0; if (ch == 0x0A) { fLinefeedCounter++; fCharacterCounter = 1; } else if (ch == 0x0D) { fCarriageReturnCounter++; fCharacterCounter = 1; ch = loadNextByte(); if (ch != 0x0A) return 0x0A; fLinefeedCounter++; } else if (ch == 0) { if (atEOF(fCurrentOffset + 1)) { return changeReaders().scanInvalidChar(); } fCharacterCounter++; } else if (b0 >= 0x80) { fCharacterCounter++; int b1 = loadNextByte(); int b2 = 0; if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx ch = ((0x1f & b0)<<6) + (0x3f & b1); } else if( (0xf0 & b0) == 0xe0 ) { b2 = loadNextByte(); ch = ((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2); } else if(( 0xf8 & b0 ) == 0xf0 ){ b2 = loadNextByte(); int b3 = loadNextByte(); // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx ch = ((0x0f & b0)<<18) + ((0x3f & b1)<<12) + ((0x3f & b2)<<6) + (0x3f & b3); } } loadNextByte(); return ch; } // // // public int scanCharRef(boolean hex) throws Exception { int ch = fMostRecentByte; if (ch == 0) { if (atEOF(fCurrentOffset + 1)) { return changeReaders().scanCharRef(hex); } return XMLEntityHandler.CHARREF_RESULT_INVALID_CHAR; } int num = 0; if (hex) { if (ch > 'f' || XMLCharacterProperties.fgAsciiXDigitChar[ch] == 0) return XMLEntityHandler.CHARREF_RESULT_INVALID_CHAR; num = ch - (ch < 'A' ? '0' : (ch < 'a' ? 'A' : 'a') - 10); } else { if (ch < '0' || ch > '9') return XMLEntityHandler.CHARREF_RESULT_INVALID_CHAR; num = ch - '0'; } fCharacterCounter++; loadNextByte(); boolean toobig = false; while (true) { ch = fMostRecentByte; if (ch == 0) break; if (hex) { if (ch > 'f' || XMLCharacterProperties.fgAsciiXDigitChar[ch] == 0) break; } else { if (ch < '0' || ch > '9') break; } fCharacterCounter++; loadNextByte(); if (hex) { int dig = ch - (ch < 'A' ? '0' : (ch < 'a' ? 'A' : 'a') - 10); num = (num << 4) + dig; } else { int dig = ch - '0'; num = (num * 10) + dig; } if (num > 0x10FFFF) { toobig = true; num = 0; } } if (ch != ';') return XMLEntityHandler.CHARREF_RESULT_SEMICOLON_REQUIRED; fCharacterCounter++; loadNextByte(); if (toobig) return XMLEntityHandler.CHARREF_RESULT_OUT_OF_RANGE; return num; } // // // public int scanStringLiteral() throws Exception { boolean single; if (!(single = lookingAtChar('\'', true)) && !lookingAtChar('\"', true)) { return XMLEntityHandler.STRINGLIT_RESULT_QUOTE_REQUIRED; } int offset = fCurrentOffset; char qchar = single ? '\'' : '\"'; while (!lookingAtChar(qchar, false)) { if (!lookingAtValidChar(true)) { return XMLEntityHandler.STRINGLIT_RESULT_INVALID_CHAR; } } int stringIndex = fCurrentChunk.addString(offset, fCurrentOffset - offset); lookingAtChar(qchar, true); // move past qchar return stringIndex; } // // [10] AttValue ::= '"' ([^<&"] | Reference)* '"' // | "'" ([^<&'] | Reference)* "'" // // The values in the following table are defined as: // // 0 - not special // 1 - quote character // 2 - complex // 3 - less than // 4 - invalid // public static final byte fgAsciiAttValueChar[] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 4, 4, 2, 4, 4, // tab is 0x09, LF is 0x0A, CR is 0x0D 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 1, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, // '\"' is 0x22, '&' is 0x26, '\'' is 0x27 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, // '<' is 0x3C 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public int scanAttValue(char qchar, boolean asSymbol) throws Exception { int offset = fCurrentOffset; int b0 = fMostRecentByte; while (true) { if (b0 < 0x80) { switch (fgAsciiAttValueChar[b0]) { case 1: // quote char if (b0 == qchar) { int length = fCurrentOffset - offset; int result = length == 0 ? StringPool.EMPTY_STRING : (asSymbol ? fCurrentChunk.addSymbol(offset, length, 0) : fCurrentChunk.addString(offset, length)); fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } return result; } // the other quote character is not special // fall through case 0: // non-special char fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } continue; case 2: // complex return XMLEntityHandler.ATTVALUE_RESULT_COMPLEX; case 3: // less than return XMLEntityHandler.ATTVALUE_RESULT_LESSTHAN; case 4: // invalid return XMLEntityHandler.ATTVALUE_RESULT_INVALID_CHAR; } } else { if (!skipMultiByteCharData(b0)) return XMLEntityHandler.ATTVALUE_RESULT_INVALID_CHAR; b0 = fMostRecentByte; } } } // // [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"' // | "'" ([^%&'] | PEReference | Reference)* "'" // // The values in the following table are defined as: // // 0 - not special // 1 - quote character // 2 - reference // 3 - peref // 4 - invalid // 5 - linefeed // 6 - carriage-return // 7 - end of input // public static final byte fgAsciiEntityValueChar[] = { 7, 4, 4, 4, 4, 4, 4, 4, 4, 0, 5, 4, 4, 6, 4, 4, // tab is 0x09, LF is 0x0A, CR is 0x0D 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 1, 0, 0, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, // '\"', '%', '&', '\'' 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public int scanEntityValue(int qchar, boolean createString) throws Exception { int offset = fCurrentOffset; int b0 = fMostRecentByte; while (true) { if (b0 < 0x80) { switch (fgAsciiEntityValueChar[b0]) { case 1: // quote char if (b0 == qchar) { if (!createString) return XMLEntityHandler.ENTITYVALUE_RESULT_FINISHED; int length = fCurrentOffset - offset; int result = length == 0 ? StringPool.EMPTY_STRING : fCurrentChunk.addString(offset, length); fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } return result; } // the other quote character is not special // fall through case 0: // non-special char fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } continue; case 5: // linefeed fLinefeedCounter++; fCharacterCounter = 1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } continue; case 6: // carriage-return fCarriageReturnCounter++; fCharacterCounter = 1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (b0 != 0x0A) { continue; } fLinefeedCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } continue; case 2: // reference return XMLEntityHandler.ENTITYVALUE_RESULT_REFERENCE; case 3: // peref return XMLEntityHandler.ENTITYVALUE_RESULT_PEREF; case 7: if (atEOF(fCurrentOffset + 1)) { changeReaders(); // do not call next reader, our caller may need to change the parameters return XMLEntityHandler.ENTITYVALUE_RESULT_END_OF_INPUT; } // fall into... case 4: // invalid return XMLEntityHandler.ENTITYVALUE_RESULT_INVALID_CHAR; } } else { if (!skipMultiByteCharData(b0)) return XMLEntityHandler.ENTITYVALUE_RESULT_INVALID_CHAR; b0 = fMostRecentByte; } } } // // // public boolean scanExpectedName(char fastcheck, StringPool.CharArrayRange expectedName) throws Exception { char[] expected = expectedName.chars; int offset = expectedName.offset; int len = expectedName.length; int b0 = fMostRecentByte; int ch = 0; int i = 0; while (true) { if (b0 < 0x80) { ch = b0; if (i == len) break; if (ch != expected[offset]) { skipPastNmtoken(fastcheck); return false; } } else { // // REVISIT - optimize this with in-buffer lookahead. // UTF8DataChunk saveChunk = fCurrentChunk; int saveIndex = fCurrentIndex; int saveOffset = fCurrentOffset; int b1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b1 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b1 = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { b1 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b1 = slowLoadNextByte(); else b1 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx ch = ((0x1f & b0)<<6) + (0x3f & b1); if (i == len) break; if (ch != expected[offset]) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; skipPastNmtoken(fastcheck); return false; } } else { int b2; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b2 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b2 = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { b2 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b2 = slowLoadNextByte(); else b2 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if ((0xf0 & b0) == 0xe0) { // 1110zzzz 10yyyyyy 10xxxxxx // if ((ch >= 0xD800 && ch <= 0xDFFF) || ch >= 0xFFFE) if ((b0 == 0xED && b1 >= 0xA0) || (b0 == 0xEF && b1 == 0xBF && b2 >= 0xBE)) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } ch = ((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2); if (i == len) break; if (ch != expected[offset]) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; skipPastNmtoken(fastcheck); return false; } } else { // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } } } i++; offset++; fCharacterCounter++; fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (ch == fastcheck) return true; if (ch < 0x80) { if (XMLCharacterProperties.fgAsciiNameChar[ch] == 0) return true; } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) return true; } skipPastNmtoken(fastcheck); return false; } public void scanQName(char fastcheck, QName qname) throws Exception { int ch = fMostRecentByte; if (ch < 0x80) { if (XMLCharacterProperties.fgAsciiInitialNameChar[ch] == 0) { qname.clear(); return; } if (ch == ':') { qname.clear(); return; } } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) { qname.clear(); return; } } int offset = fCurrentOffset; int index = fCurrentIndex; byte[] data = fMostRecentData; int prefixend = -1; while (true) { fCharacterCounter++; fCurrentOffset++; index++; try { ch = data[index] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); index = 0; data = fMostRecentData; } if (fastcheck == ch) break; if (ch < 0x80) { if (XMLCharacterProperties.fgAsciiNameChar[ch] == 0) break; if (ch == ':') { if (prefixend != -1) break; prefixend = fCurrentOffset; // // We need to peek ahead one character. If the next character is not a // valid initial name character, or is another colon, then we cannot meet // both the Prefix and LocalPart productions for the QName production, // which means that there is no Prefix and we need to terminate the QName // at the first colon. // try { ch = data[index + 1] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { UTF8DataChunk savedChunk = fCurrentChunk; int savedOffset = fCurrentOffset; ch = slowLoadNextByte(); fCurrentChunk = savedChunk; fCurrentOffset = savedOffset; fMostRecentData = fCurrentChunk.toByteArray(); } boolean lpok = true; if (ch < 0x80) { if (XMLCharacterProperties.fgAsciiInitialNameChar[ch] == 0 || ch == ':') lpok = false; } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) lpok = false; } ch = ':'; if (!lpok) { prefixend = -1; break; } } } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) break; } } fCurrentIndex = index; fMostRecentByte = ch; int length = fCurrentOffset - offset; qname.rawname = addSymbol(offset, length); qname.prefix = prefixend == -1 ? -1 : addSymbol(offset, prefixend - offset); qname.localpart = prefixend == -1 ? qname.rawname : addSymbol(prefixend + 1, fCurrentOffset - (prefixend + 1)); qname.uri = -1; } // scanQName(char,QName) private int getMultiByteSymbolChar(int b0) throws Exception { // // REVISIT - optimize this with in-buffer lookahead. // UTF8DataChunk saveChunk = fCurrentChunk; int saveIndex = fCurrentIndex; int saveOffset = fCurrentOffset; if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } int b1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b1 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b1 = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { b1 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b1 = slowLoadNextByte(); else b1 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx int ch = ((0x1f & b0)<<6) + (0x3f & b1); if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) { // yyy yyxx xxxx (0x80 to 0x7ff) fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return -1; } loadNextByte(); return ch; } int b2; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b2 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b2 = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { b2 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b2 = slowLoadNextByte(); else b2 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if ((0xf0 & b0) == 0xe0) { // 1110zzzz 10yyyyyy 10xxxxxx // if ((ch >= 0xD800 && ch <= 0xDFFF) || ch >= 0xFFFE) if ((b0 == 0xED && b1 >= 0xA0) || (b0 == 0xEF && b1 == 0xBF && b2 >= 0xBE)) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return -1; } int ch = ((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2); if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) { // zzzz yyyy yyxx xxxx (0x800 to 0xffff) fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return -1; } loadNextByte(); return ch; } // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return -1; } public int scanName(char fastcheck) throws Exception { int b0 = fMostRecentByte; int ch; if (b0 < 0x80) { if (XMLCharacterProperties.fgAsciiInitialNameChar[b0] == 0) { if (b0 == 0 && atEOF(fCurrentOffset + 1)) { return changeReaders().scanName(fastcheck); } return -1; } ch = b0; } else { // // REVISIT - optimize this with in-buffer lookahead. // UTF8DataChunk saveChunk = fCurrentChunk; int saveIndex = fCurrentIndex; int saveOffset = fCurrentOffset; if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } int b1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b1 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b1 = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { b1 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b1 = slowLoadNextByte(); else b1 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx ch = ((0x1f & b0)<<6) + (0x3f & b1); if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) { // yyy yyxx xxxx (0x80 to 0x7ff) fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return -1; } } else { int b2; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b2 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b2 = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { b2 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b2 = slowLoadNextByte(); else b2 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if ((0xf0 & b0) == 0xe0) { // 1110zzzz 10yyyyyy 10xxxxxx // if ((ch >= 0xD800 && ch <= 0xDFFF) || ch >= 0xFFFE) if ((b0 == 0xED && b1 >= 0xA0) || (b0 == 0xEF && b1 == 0xBF && b2 >= 0xBE)) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return -1; } ch = ((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2); if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) { // zzzz yyyy yyxx xxxx (0x800 to 0xffff) fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return -1; } } else { // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return -1; } } } fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } return scanMatchingName(ch, b0, fastcheck); } private int scanMatchingName(int ch, int b0, int fastcheck) throws Exception { SymbolCache cache = fStringPool.getSymbolCache(); int[][] cacheLines = cache.fCacheLines; char[] symbolChars = cache.fSymbolChars; boolean lengthOfOne = fastcheck == fMostRecentByte; int startOffset = cache.fSymbolCharsOffset; int entry = 0; int[] entries = cacheLines[entry]; int offset = 1 + ((entries[0] - 1) * SymbolCache.CACHE_RECORD_SIZE); int totalMisses = 0; if (lengthOfOne) { while (offset > 0) { if (entries[offset + SymbolCache.CHAR_OFFSET] == ch) { if (entries[offset + SymbolCache.INDEX_OFFSET] != -1) { int symbolIndex = entries[offset + SymbolCache.INDEX_OFFSET]; if (totalMisses > 3) fStringPool.updateCacheLine(symbolIndex, totalMisses, 1); return symbolIndex; } break; } offset -= SymbolCache.CACHE_RECORD_SIZE; totalMisses++; } try { symbolChars[cache.fSymbolCharsOffset] = (char)ch; } catch (ArrayIndexOutOfBoundsException ex) { symbolChars = new char[cache.fSymbolCharsOffset * 2]; System.arraycopy(cache.fSymbolChars, 0, symbolChars, 0, cache.fSymbolCharsOffset); cache.fSymbolChars = symbolChars; symbolChars[cache.fSymbolCharsOffset] = (char)ch; } cache.fSymbolCharsOffset++; if (offset < 0) { offset = 1 + (entries[0] * SymbolCache.CACHE_RECORD_SIZE); entries[0]++; try { entries[offset + SymbolCache.CHAR_OFFSET] = ch; } catch (ArrayIndexOutOfBoundsException ex) { int newSize = 1 + ((offset - 1) * 2); entries = new int[newSize]; System.arraycopy(cacheLines[entry], 0, entries, 0, offset); cacheLines[entry] = entries; entries[offset + SymbolCache.CHAR_OFFSET] = ch; } entries[offset + SymbolCache.NEXT_OFFSET] = -1; } int result = fStringPool.createNonMatchingSymbol(startOffset, entry, entries, offset); return result; } try { symbolChars[cache.fSymbolCharsOffset] = (char)ch; } catch (ArrayIndexOutOfBoundsException ex) { symbolChars = new char[cache.fSymbolCharsOffset * 2]; System.arraycopy(cache.fSymbolChars, 0, symbolChars, 0, cache.fSymbolCharsOffset); cache.fSymbolChars = symbolChars; symbolChars[cache.fSymbolCharsOffset] = (char)ch; } cache.fSymbolCharsOffset++; int depth = 1; while (true) { if (offset < 0) break; if (entries[offset + SymbolCache.CHAR_OFFSET] != ch) { offset -= SymbolCache.CACHE_RECORD_SIZE; totalMisses++; continue; } if (b0 >= 0x80) { ch = getMultiByteSymbolChar(b0); b0 = fMostRecentByte; } else if (b0 == fastcheck || XMLCharacterProperties.fgAsciiNameChar[b0] == 0) { ch = -1; } else { ch = b0; fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } } if (ch == -1) { if (entries[offset + SymbolCache.INDEX_OFFSET] == -1) { return fStringPool.createNonMatchingSymbol(startOffset, entry, entries, offset); } cache.fSymbolCharsOffset = startOffset; int symbolIndex = entries[offset + SymbolCache.INDEX_OFFSET]; if (totalMisses > (depth * 3)) fStringPool.updateCacheLine(symbolIndex, totalMisses, depth); return symbolIndex; } try { symbolChars[cache.fSymbolCharsOffset] = (char)ch; } catch (ArrayIndexOutOfBoundsException ex) { symbolChars = new char[cache.fSymbolCharsOffset * 2]; System.arraycopy(cache.fSymbolChars, 0, symbolChars, 0, cache.fSymbolCharsOffset); cache.fSymbolChars = symbolChars; symbolChars[cache.fSymbolCharsOffset] = (char)ch; } cache.fSymbolCharsOffset++; entry = entries[offset + SymbolCache.NEXT_OFFSET]; try { entries = cacheLines[entry]; } catch (ArrayIndexOutOfBoundsException ex) { if (entry == -1) { entry = cache.fCacheLineCount++; entries[offset + SymbolCache.NEXT_OFFSET] = entry; entries = new int[1+(SymbolCache.INITIAL_CACHE_RECORD_COUNT*SymbolCache.CACHE_RECORD_SIZE)]; try { cacheLines[entry] = entries; } catch (ArrayIndexOutOfBoundsException ex2) { cacheLines = new int[entry * 2][]; System.arraycopy(cache.fCacheLines, 0, cacheLines, 0, entry); cache.fCacheLines = cacheLines; cacheLines[entry] = entries; } } else { entries = cacheLines[entry]; throw new RuntimeException("RDR001 untested"); // REVISIT } } offset = 1 + ((entries[0] - 1) * SymbolCache.CACHE_RECORD_SIZE); depth++; } if (offset < 0) offset = 1 + (entries[0] * SymbolCache.CACHE_RECORD_SIZE); while (true) { entries[0]++; try { entries[offset + SymbolCache.CHAR_OFFSET] = ch; } catch (ArrayIndexOutOfBoundsException ex) { int newSize = 1 + ((offset - 1) * 2); entries = new int[newSize]; System.arraycopy(cacheLines[entry], 0, entries, 0, offset); cacheLines[entry] = entries; entries[offset + SymbolCache.CHAR_OFFSET] = ch; } if (b0 >= 0x80) { ch = getMultiByteSymbolChar(b0); b0 = fMostRecentByte; } else if (b0 == fastcheck || XMLCharacterProperties.fgAsciiNameChar[b0] == 0) { ch = -1; } else { ch = b0; fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } } if (ch == -1) { entries[offset + SymbolCache.NEXT_OFFSET] = -1; break; } entry = cache.fCacheLineCount++; entries[offset + SymbolCache.INDEX_OFFSET] = -1; entries[offset + SymbolCache.NEXT_OFFSET] = entry; entries = new int[1+(SymbolCache.INITIAL_CACHE_RECORD_COUNT*SymbolCache.CACHE_RECORD_SIZE)]; try { cacheLines[entry] = entries; } catch (ArrayIndexOutOfBoundsException ex) { cacheLines = new int[entry * 2][]; System.arraycopy(cache.fCacheLines, 0, cacheLines, 0, entry); cache.fCacheLines = cacheLines; cacheLines[entry] = entries; } offset = 1; try { symbolChars[cache.fSymbolCharsOffset] = (char)ch; } catch (ArrayIndexOutOfBoundsException ex) { symbolChars = new char[cache.fSymbolCharsOffset * 2]; System.arraycopy(cache.fSymbolChars, 0, symbolChars, 0, cache.fSymbolCharsOffset); cache.fSymbolChars = symbolChars; symbolChars[cache.fSymbolCharsOffset] = (char)ch; } cache.fSymbolCharsOffset++; } int result = fStringPool.createNonMatchingSymbol(startOffset, entry, entries, offset); return result; } // // [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*) // private int recognizeMarkup(int b0, QName element) throws Exception { switch (b0) { case 0: return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; case '?': fCharacterCounter++; loadNextByte(); return XMLEntityHandler.CONTENT_RESULT_START_OF_PI; case '!': fCharacterCounter++; b0 = loadNextByte(); if (b0 == 0) { fCharacterCounter--; fCurrentOffset--; return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; } if (b0 == '-') { fCharacterCounter++; b0 = loadNextByte(); if (b0 == 0) { fCharacterCounter -= 2; fCurrentOffset -= 2; return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; } if (b0 == '-') { fCharacterCounter++; b0 = loadNextByte(); return XMLEntityHandler.CONTENT_RESULT_START_OF_COMMENT; } break; } if (b0 == '[') { for (int i = 0; i < 6; i++) { fCharacterCounter++; b0 = loadNextByte(); if (b0 == 0) { fCharacterCounter -= (2 + i); fCurrentOffset -= (2 + i); return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; } if (b0 != cdata_string[i]) { return XMLEntityHandler.CONTENT_RESULT_MARKUP_NOT_RECOGNIZED; } } fCharacterCounter++; loadNextByte(); return XMLEntityHandler.CONTENT_RESULT_START_OF_CDSECT; } break; case '/': fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } int expectedName = element.rawname; fStringPool.getCharArrayRange(expectedName, fCharArrayRange); char[] expected = fCharArrayRange.chars; int offset = fCharArrayRange.offset; int len = fCharArrayRange.length; // // DEFECT !! - needs UTF8 multibyte support... // if (b0 == expected[offset++]) { UTF8DataChunk savedChunk = fCurrentChunk; int savedIndex = fCurrentIndex; int savedOffset = fCurrentOffset; for (int i = 1; i < len; i++) { if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } // // DEFECT !! - needs UTF8 multibyte support... // if (b0 != expected[offset++]) { fCurrentChunk = savedChunk; fCurrentIndex = savedIndex; fCurrentOffset = savedOffset; fMostRecentData = fCurrentChunk.toByteArray(); fMostRecentByte = fMostRecentData[savedIndex] & 0xFF; return XMLEntityHandler.CONTENT_RESULT_START_OF_ETAG; } } fCharacterCounter += len; // REVISIT - double check this... fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { b0 = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { b0 = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) b0 = slowLoadNextByte(); else b0 = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (b0 == '>') { fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } return XMLEntityHandler.CONTENT_RESULT_MATCHING_ETAG; } while (b0 == 0x20 || b0 == 0x09 || b0 == 0x0A || b0 == 0x0D) { if (b0 == 0x0A) { fLinefeedCounter++; fCharacterCounter = 1; b0 = loadNextByte(); } else if (b0 == 0x0D) { fCarriageReturnCounter++; fCharacterCounter = 1; b0 = loadNextByte(); if (b0 == 0x0A) { fLinefeedCounter++; b0 = loadNextByte(); } } else { fCharacterCounter++; b0 = loadNextByte(); } if (b0 == '>') { fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) slowLoadNextByte(); else fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF; } } return XMLEntityHandler.CONTENT_RESULT_MATCHING_ETAG; } } fCurrentChunk = savedChunk; fCurrentIndex = savedIndex; fCurrentOffset = savedOffset; fMostRecentData = fCurrentChunk.toByteArray(); fMostRecentByte = fMostRecentData[savedIndex] & 0xFF; } return XMLEntityHandler.CONTENT_RESULT_START_OF_ETAG; default: return XMLEntityHandler.CONTENT_RESULT_START_OF_ELEMENT; } return XMLEntityHandler.CONTENT_RESULT_MARKUP_NOT_RECOGNIZED; } private int recognizeReference(int ch) throws Exception { if (ch == 0) { return XMLEntityHandler.CONTENT_RESULT_REFERENCE_END_OF_INPUT; } // // [67] Reference ::= EntityRef | CharRef // [68] EntityRef ::= '&' Name ';' // [66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';' // if (ch == '#') { fCharacterCounter++; loadNextByte(); return XMLEntityHandler.CONTENT_RESULT_START_OF_CHARREF; } else { return XMLEntityHandler.CONTENT_RESULT_START_OF_ENTITYREF; } } public int scanContent(QName element) throws Exception { if (fCallClearPreviousChunk && fCurrentChunk.clearPreviousChunk()) fCallClearPreviousChunk = false; fCharDataLength = 0; int charDataOffset = fCurrentOffset; int ch = fMostRecentByte; if (ch < 0x80) { switch (XMLCharacterProperties.fgAsciiWSCharData[ch]) { case 0: if (fSendCharDataAsCharArray) { try { fCharacters[fCharDataLength] = (char)ch; fCharDataLength++; } catch (ArrayIndexOutOfBoundsException ex) { slowAppendCharData(ch); } } fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } break; case 1: // '<' fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (!fInCDSect) { return recognizeMarkup(ch, element); } if (fSendCharDataAsCharArray) appendCharData('<'); break; case 2: // '&' fCharacterCounter++; ch = loadNextByte(); if (!fInCDSect) { return recognizeReference(ch); } if (fSendCharDataAsCharArray) appendCharData('&'); break; case 3: // ']' fCharacterCounter++; ch = loadNextByte(); if (ch != ']') { if (fSendCharDataAsCharArray) appendCharData(']'); break; } if (fCurrentIndex + 1 == UTF8DataChunk.CHUNK_SIZE) { UTF8DataChunk saveChunk = fCurrentChunk; int saveIndex = fCurrentIndex; int saveOffset = fCurrentOffset; if (loadNextByte() != '>') { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = fCurrentChunk.toByteArray(); fMostRecentByte = ']'; if (fSendCharDataAsCharArray) appendCharData(']'); break; } } else { if (fMostRecentData[fCurrentIndex + 1] != '>') { if (fSendCharDataAsCharArray) appendCharData(']'); break; } fCurrentIndex++; fCurrentOffset++; } loadNextByte(); fCharacterCounter += 2; return XMLEntityHandler.CONTENT_RESULT_END_OF_CDSECT; case 4: // invalid char if (ch == 0 && atEOF(fCurrentOffset + 1)) { changeReaders(); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; // REVISIT - not quite... } return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; case 5: do { if (ch == 0x0A) { fLinefeedCounter++; fCharacterCounter = 1; } else if (ch == 0x0D) { fCarriageReturnCounter++; fCharacterCounter = 1; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } if (ch != 0x0A) { if (fSendCharDataAsCharArray) appendCharData(0x0A); if (ch == 0x20 || ch == 0x09 || ch == 0x0D) continue; break; } fLinefeedCounter++; } else { fCharacterCounter++; } if (fSendCharDataAsCharArray) { try { fCharacters[fCharDataLength] = (char)ch; fCharDataLength++; } catch (ArrayIndexOutOfBoundsException ex) { slowAppendCharData(ch); } } if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } } while (ch == 0x20 || ch == 0x09 || ch == 0x0A || ch == 0x0D); if (ch < 0x80) { switch (XMLCharacterProperties.fgAsciiCharData[ch]) { case 0: if (fSendCharDataAsCharArray) appendCharData(ch); fCharacterCounter++; ch = loadNextByte(); break; case 1: // '<' if (!fInCDSect) { if (fSendCharDataAsCharArray) { fCharDataHandler.processWhitespace(fCharacters, 0, fCharDataLength); } else { int stringIndex = addString(charDataOffset, fCurrentOffset - charDataOffset); fCharDataHandler.processWhitespace(stringIndex); } fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } return recognizeMarkup(ch, element); } if (fSendCharDataAsCharArray) appendCharData('<'); fCharacterCounter++; ch = loadNextByte(); break; case 2: // '&' if (!fInCDSect) { whitespace(charDataOffset, fCurrentOffset); fCharacterCounter++; ch = loadNextByte(); return recognizeReference(ch); } if (fSendCharDataAsCharArray) appendCharData('&'); fCharacterCounter++; ch = loadNextByte(); break; case 3: // ']' int endOffset = fCurrentOffset; ch = loadNextByte(); if (ch != ']') { fCharacterCounter++; if (fSendCharDataAsCharArray) appendCharData(']'); break; } if (fCurrentIndex + 1 == UTF8DataChunk.CHUNK_SIZE) { UTF8DataChunk saveChunk = fCurrentChunk; int saveIndex = fCurrentIndex; int saveOffset = fCurrentOffset; if (loadNextByte() != '>') { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = fCurrentChunk.toByteArray(); fMostRecentByte = ']'; fCharacterCounter++; if (fSendCharDataAsCharArray) appendCharData(']'); break; } } else { if (fMostRecentData[fCurrentIndex + 1] != '>') { fCharacterCounter++; if (fSendCharDataAsCharArray) appendCharData(']'); break; } fCurrentIndex++; fCurrentOffset++; } loadNextByte(); whitespace(charDataOffset, endOffset); fCharacterCounter += 3; return XMLEntityHandler.CONTENT_RESULT_END_OF_CDSECT; case 4: // invalid char whitespace(charDataOffset, fCurrentOffset); if (ch == 0 && atEOF(fCurrentOffset + 1)) { changeReaders(); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; // REVISIT - not quite... } return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } else { if (fSendCharDataAsCharArray) { if (!copyMultiByteCharData(ch)) { whitespace(charDataOffset, fCurrentOffset); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } else if (!skipMultiByteCharData(ch)) { whitespace(charDataOffset, fCurrentOffset); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } break; } } else { if (fSendCharDataAsCharArray) { if (!copyMultiByteCharData(ch)) { return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } else { if (!skipMultiByteCharData(ch)) { return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } } if (fSendCharDataAsCharArray) ch = copyAsciiCharData(); else ch = skipAsciiCharData(); while (true) { if (ch < 0x80) { switch (XMLCharacterProperties.fgAsciiCharData[ch]) { case 0: if (fSendCharDataAsCharArray) appendCharData(ch); fCharacterCounter++; ch = loadNextByte(); break; case 1: // '<' if (!fInCDSect) { if (fSendCharDataAsCharArray) { fCharDataHandler.processCharacters(fCharacters, 0, fCharDataLength); } else { int stringIndex = addString(charDataOffset, fCurrentOffset - charDataOffset); fCharDataHandler.processCharacters(stringIndex); } fCharacterCounter++; if (USE_OUT_OF_LINE_LOAD_NEXT_BYTE) { ch = loadNextByte(); } else { fCurrentOffset++; if (USE_TRY_CATCH_FOR_LOAD_NEXT_BYTE) { fCurrentIndex++; try { ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } catch (ArrayIndexOutOfBoundsException ex) { ch = slowLoadNextByte(); } } else { if (++fCurrentIndex == UTF8DataChunk.CHUNK_SIZE) ch = slowLoadNextByte(); else ch = (fMostRecentByte = fMostRecentData[fCurrentIndex] & 0xFF); } } return recognizeMarkup(ch, element); } if (fSendCharDataAsCharArray) appendCharData('<'); fCharacterCounter++; ch = loadNextByte(); break; case 2: // '&' if (!fInCDSect) { characters(charDataOffset, fCurrentOffset); fCharacterCounter++; ch = loadNextByte(); return recognizeReference(ch); } if (fSendCharDataAsCharArray) appendCharData('&'); fCharacterCounter++; ch = loadNextByte(); break; case 3: // ']' int endOffset = fCurrentOffset; ch = loadNextByte(); if (ch != ']') { fCharacterCounter++; if (fSendCharDataAsCharArray) appendCharData(']'); break; } if (fCurrentIndex + 1 == UTF8DataChunk.CHUNK_SIZE) { UTF8DataChunk saveChunk = fCurrentChunk; int saveIndex = fCurrentIndex; int saveOffset = fCurrentOffset; if (loadNextByte() != '>') { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = fCurrentChunk.toByteArray(); fMostRecentByte = ']'; fCharacterCounter++; if (fSendCharDataAsCharArray) appendCharData(']'); break; } } else { if (fMostRecentData[fCurrentIndex + 1] != '>') { fCharacterCounter++; if (fSendCharDataAsCharArray) appendCharData(']'); break; } fCurrentIndex++; fCurrentOffset++; } loadNextByte(); characters(charDataOffset, endOffset); fCharacterCounter += 3; return XMLEntityHandler.CONTENT_RESULT_END_OF_CDSECT; case 4: // invalid char if (ch == 0x0A) { if (fSendCharDataAsCharArray) appendCharData(ch); fLinefeedCounter++; fCharacterCounter = 1; ch = loadNextByte(); break; } if (ch == 0x0D) { if (fSendCharDataAsCharArray) appendCharData(0x0A); fCarriageReturnCounter++; fCharacterCounter = 1; ch = loadNextByte(); if (ch == 0x0A) { fLinefeedCounter++; ch = loadNextByte(); } break; } characters(charDataOffset, fCurrentOffset); if (ch == 0 && atEOF(fCurrentOffset + 1)) { changeReaders(); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; // REVISIT - not quite... } return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } else { if (fSendCharDataAsCharArray) { if (!copyMultiByteCharData(ch)) { characters(charDataOffset, fCurrentOffset); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } else if (!skipMultiByteCharData(ch)) { characters(charDataOffset, fCurrentOffset); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } ch = fMostRecentByte; } } } private boolean copyMultiByteCharData(int b0) throws Exception { UTF8DataChunk saveChunk = fCurrentChunk; int saveOffset = fCurrentOffset; int saveIndex = fCurrentIndex; int b1 = loadNextByte(); if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx (0x80 to 0x7ff) int ch = ((0x1f & b0)<<6) + (0x3f & b1); appendCharData(ch); // yyy yyxx xxxx (0x80 to 0x7ff) loadNextByte(); return true; } int b2 = loadNextByte(); if ((0xf0 & b0) == 0xe0) { // 1110zzzz 10yyyyyy 10xxxxxx // ch = ((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2); // zzzz yyyy yyxx xxxx (0x800 to 0xffff) // if ((ch >= 0xD800 && ch <= 0xDFFF) || ch >= 0xFFFE) if ((b0 == 0xED && b1 >= 0xA0) || (b0 == 0xEF && b1 == 0xBF && b2 >= 0xBE)) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } int ch = ((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2); appendCharData(ch); // zzzz yyyy yyxx xxxx (0x800 to 0xffff) loadNextByte(); return true; } int b3 = loadNextByte(); // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx // ch = ((0x0f & b0)<<18) + ((0x3f & b1)<<12) + ((0x3f & b2)<<6) + (0x3f & b3); // u uuuu zzzz yyyy yyxx xxxx (0x10000 to 0x1ffff) // if (ch >= 0x110000) if (( 0xf8 & b0 ) == 0xf0 ) { if (b0 > 0xF4 || (b0 == 0xF4 && b1 >= 0x90)) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } int ch = ((0x0f & b0)<<18) + ((0x3f & b1)<<12) + ((0x3f & b2)<<6) + (0x3f & b3); if (ch < 0x10000) { appendCharData(ch); } else { appendCharData(((ch-0x00010000)>>10)+0xd800); appendCharData(((ch-0x00010000)&0x3ff)+0xdc00); } loadNextByte(); return true; } else { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } } private boolean skipMultiByteCharData(int b0) throws Exception { UTF8DataChunk saveChunk = fCurrentChunk; int saveOffset = fCurrentOffset; int saveIndex = fCurrentIndex; int b1 = loadNextByte(); if ((0xe0 & b0) == 0xc0) { // 110yyyyy 10xxxxxx (0x80 to 0x7ff) loadNextByte(); return true; } int b2 = loadNextByte(); if ((0xf0 & b0) == 0xe0) { // 1110zzzz 10yyyyyy 10xxxxxx // ch = ((0x0f & b0)<<12) + ((0x3f & b1)<<6) + (0x3f & b2); // zzzz yyyy yyxx xxxx (0x800 to 0xffff) // if ((ch >= 0xD800 && ch <= 0xDFFF) || ch >= 0xFFFE) if ((b0 == 0xED && b1 >= 0xA0) || (b0 == 0xEF && b1 == 0xBF && b2 >= 0xBE)) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } loadNextByte(); return true; } int b3 = loadNextByte(); // 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx // ch = ((0x0f & b0)<<18) + ((0x3f & b1)<<12) + ((0x3f & b2)<<6) + (0x3f & b3); // u uuuu zzzz yyyy yyxx xxxx (0x10000 to 0x1ffff) // if (ch >= 0x110000) if (b0 > 0xF4 || (b0 == 0xF4 && b1 >= 0x90)) { fCurrentChunk = saveChunk; fCurrentIndex = saveIndex; fCurrentOffset = saveOffset; fMostRecentData = saveChunk.toByteArray(); fMostRecentByte = b0; return false; } loadNextByte(); return true; } private int copyAsciiCharData() throws Exception { int srcIndex = fCurrentIndex; int offset = fCurrentOffset - srcIndex; byte[] data = fMostRecentData; int dstIndex = fCharDataLength; boolean skiplf = false; while (true) { int ch; try { ch = data[srcIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { offset += srcIndex; slowLoadNextByte(); srcIndex = 0; data = fMostRecentData; ch = data[srcIndex] & 0xFF; } if (ch >= 0x80) { fCurrentOffset = offset + srcIndex; fCurrentIndex = srcIndex; fMostRecentByte = ch; return ch; } if (XMLCharacterProperties.fgAsciiCharData[ch] == 0) { fCharacterCounter++; skiplf = false; } else if (ch == 0x0A) { fLinefeedCounter++; if (skiplf) { skiplf = false; srcIndex++; continue; } fCharacterCounter = 1; } else if (ch == 0x0D) { fCarriageReturnCounter++; fCharacterCounter = 1; skiplf = true; ch = 0x0A; } else { fCurrentOffset = offset + srcIndex; fCurrentIndex = srcIndex; fMostRecentByte = ch; return ch; } srcIndex++; try { fCharacters[fCharDataLength] = (char)ch; fCharDataLength++; } catch (ArrayIndexOutOfBoundsException ex) { slowAppendCharData(ch); } } } private int skipAsciiCharData() throws Exception { int srcIndex = fCurrentIndex; int offset = fCurrentOffset - srcIndex; byte[] data = fMostRecentData; while (true) { int ch; try { ch = data[srcIndex] & 0xFF; } catch (ArrayIndexOutOfBoundsException ex) { offset += srcIndex; slowLoadNextByte(); srcIndex = 0; data = fMostRecentData; ch = data[srcIndex] & 0xFF; } if (ch >= 0x80) { fCurrentOffset = offset + srcIndex; fCurrentIndex = srcIndex; fMostRecentByte = ch; return ch; } if (XMLCharacterProperties.fgAsciiCharData[ch] == 0) { fCharacterCounter++; } else if (ch == 0x0A) { fLinefeedCounter++; fCharacterCounter = 1; } else if (ch == 0x0D) { fCarriageReturnCounter++; fCharacterCounter = 1; } else { fCurrentOffset = offset + srcIndex; fCurrentIndex = srcIndex; fMostRecentByte = ch; return ch; } srcIndex++; } } private char[] fCharacters = new char[UTF8DataChunk.CHUNK_SIZE]; private int fCharDataLength = 0; private void appendCharData(int ch) throws Exception { try { fCharacters[fCharDataLength] = (char)ch; fCharDataLength++; } catch (ArrayIndexOutOfBoundsException ex) { slowAppendCharData(ch); } } private void slowAppendCharData(int ch) throws Exception { // flush the buffer... characters(0, fCharDataLength); /* DEFECT !! whitespace this long is unlikely, but possible */ fCharDataLength = 0; fCharacters[fCharDataLength++] = (char)ch; } private void characters(int offset, int endOffset) throws Exception { // // REVISIT - need more up front bounds checking code of params... // if (!fSendCharDataAsCharArray) { int stringIndex = addString(offset, endOffset - offset); fCharDataHandler.processCharacters(stringIndex); return; } fCharDataHandler.processCharacters(fCharacters, 0, fCharDataLength); } private void whitespace(int offset, int endOffset) throws Exception { // // REVISIT - need more up front bounds checking code of params... // if (!fSendCharDataAsCharArray) { int stringIndex = addString(offset, endOffset - offset); fCharDataHandler.processWhitespace(stringIndex); return; } fCharDataHandler.processWhitespace(fCharacters, 0, fCharDataLength); } // // // private static final char[] cdata_string = { 'C','D','A','T','A','['}; private StringPool.CharArrayRange fCharArrayRange = null; private InputStream fInputStream = null; private StringPool fStringPool = null; private UTF8DataChunk fCurrentChunk = null; private int fCurrentIndex = 0; private byte[] fMostRecentData = null; private int fMostRecentByte = 0; private int fLength = 0; private boolean fCalledCharPropInit = false; private boolean fCallClearPreviousChunk = true; // // // private int fillCurrentChunk() throws Exception { byte[] buf = fCurrentChunk.toByteArray(); if (fInputStream == null) { if (buf == null) buf = new byte[1]; buf[0] = 0; fMostRecentData = buf; fCurrentIndex = 0; fCurrentChunk.setByteArray(fMostRecentData); return(fMostRecentByte = fMostRecentData[0] & 0xFF); } if (buf == null) buf = new byte[UTF8DataChunk.CHUNK_SIZE]; int offset = 0; int capacity = UTF8DataChunk.CHUNK_SIZE; int result = 0; do { try { result = fInputStream.read(buf, offset, capacity); } catch (java.io.IOException ex) { result = -1; } if (result == -1) { // // We have reached the end of the stream. // fInputStream.close(); fInputStream = null; try { buf[offset] = 0; } catch (ArrayIndexOutOfBoundsException ex) { } break; } if (result > 0) { offset += result; capacity -= result; } } while (capacity > 0); fMostRecentData = buf; fLength += offset; fCurrentIndex = 0; fCurrentChunk.setByteArray(fMostRecentData); return(fMostRecentByte = fMostRecentData[0] & 0xFF); } }
Applied patch from Kent Tamura. PR: Obtained from: Submitted by: Reviewed by: git-svn-id: 21df804813e9d3638e43477f308dd0be51e5f30f@316111 13f79535-47bb-0310-9956-ffa450edef68
src/org/apache/xerces/readers/UTF8Reader.java
Applied patch from Kent Tamura.
<ide><path>rc/org/apache/xerces/readers/UTF8Reader.java <ide> } <ide> <ide> public void scanQName(char fastcheck, QName qname) throws Exception { <del> <add> int offset = fCurrentOffset; <ide> int ch = fMostRecentByte; <ide> if (ch < 0x80) { <ide> if (XMLCharacterProperties.fgAsciiInitialNameChar[ch] == 0) { <ide> XMLCharacterProperties.initCharFlags(); <ide> fCalledCharPropInit = true; <ide> } <add> ch = getMultiByteSymbolChar(ch); <add> fCurrentIndex--; <add> fCurrentOffset--; <ide> if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) { <ide> qname.clear(); <ide> return; <ide> } <ide> } <del> int offset = fCurrentOffset; <ide> int index = fCurrentIndex; <ide> byte[] data = fMostRecentData; <ide> int prefixend = -1; <ide> XMLCharacterProperties.initCharFlags(); <ide> fCalledCharPropInit = true; <ide> } <add> fCurrentIndex = index; <add> fMostRecentByte = ch; <add> ch = getMultiByteSymbolChar(ch); <add> fCurrentIndex--; <add> fCurrentOffset--; <add> index = fCurrentIndex; <ide> if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) <ide> break; <ide> }
Java
agpl-3.0
d00c0ec1963ea1c90ee9dd6e085eb665088187c5
0
clintonhealthaccess/lmis-moz-mobile,clintonhealthaccess/lmis-moz-mobile,clintonhealthaccess/lmis-moz-mobile,clintonhealthaccess/lmis-moz-mobile
/* * This program is part of the OpenLMIS logistics management information * system platform software. * * Copyright © 2015 ThoughtWorks, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. 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 Affero General Public License for more details. You should * have received a copy of the GNU Affero General Public License along with * this program. If not, see http://www.gnu.org/licenses. For additional * information contact [email protected] */ package org.openlmis.core.view.fragment; import android.app.Activity; import android.app.DialogFragment; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.Button; import android.widget.EditText; import android.widget.ScrollView; import android.widget.TextView; import com.google.inject.Inject; import org.openlmis.core.R; import org.openlmis.core.exceptions.LMISException; import org.openlmis.core.model.RnRForm; import org.openlmis.core.presenter.MMIARequisitionPresenter; import org.openlmis.core.presenter.Presenter; import org.openlmis.core.utils.Constants; import org.openlmis.core.utils.DateUtil; import org.openlmis.core.utils.ToastUtil; import org.openlmis.core.utils.ViewUtil; import org.openlmis.core.view.activity.BaseActivity; import org.openlmis.core.view.widget.MMIAInfoList; import org.openlmis.core.view.widget.MMIARegimeList; import org.openlmis.core.view.widget.MMIARnrForm; import org.openlmis.core.view.widget.RnrFormHorizontalScrollView; import org.openlmis.core.view.widget.SignatureDialog; import java.util.ArrayList; import roboguice.inject.InjectView; public class MMIARequisitionFragment extends BaseFragment implements MMIARequisitionPresenter.MMIARequisitionView, View.OnClickListener, SimpleDialogFragment.MsgDialogCallBack { @InjectView(R.id.rnr_form_list) protected MMIARnrForm rnrFormList; @InjectView(R.id.regime_list) protected MMIARegimeList regimeListView; @InjectView(R.id.mmia_info_list) protected MMIAInfoList mmiaInfoListView; @InjectView(R.id.btn_complete) protected Button btnComplete; @InjectView(R.id.tv_regime_total) protected TextView tvRegimeTotal; @InjectView(R.id.et_comment) protected TextView etComment; @InjectView(R.id.scrollview) protected ScrollView scrollView; @InjectView(R.id.btn_save) protected View btnSave; @InjectView(R.id.tv_total_mismatch) protected TextView tvMismatch; @InjectView(R.id.action_panel) protected View bottomView; @InjectView(R.id.mmia_rnr_items_header_freeze) protected ViewGroup rnrItemsHeaderFreeze; @InjectView(R.id.mmia_rnr_items_header_freeze_left) protected ViewGroup rnrItemsHeaderFreezeLeft; @InjectView(R.id.mmia_rnr_items_header_freeze_right) protected ViewGroup rnrItemsHeaderFreezeRight; @Inject MMIARequisitionPresenter presenter; private Boolean hasDataChanged; private boolean commentHasChanged = false; private boolean isHistoryForm; private long formId; protected View containerView; protected static final String TAG_BACK_PRESSED = "onBackPressed"; private static final String TAG_MISMATCH = "mismatch"; private static final String TAG_SHOW_MESSAGE_NOTIFY_DIALOG = "showMessageNotifyDialog"; protected int actionBarHeight; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); formId = getActivity().getIntent().getLongExtra(Constants.PARAM_FORM_ID, 0); isHistoryForm = formId != 0; } @Override public Presenter initPresenter() { return presenter; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { containerView = inflater.inflate(R.layout.fragment_mmia_requisition, container, false); return containerView; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initUI(); presenter.loadData(formId); } protected void initUI() { scrollView.setVisibility(View.INVISIBLE); if (isHistoryForm) { scrollView.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); bottomView.setVisibility(View.GONE); etComment.setEnabled(false); } else { scrollView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); bottomView.setVisibility(View.VISIBLE); etComment.setEnabled(true); } disableFreezeHeaderScroll(); initActionBarHeight(); } private void disableFreezeHeaderScroll() { rnrItemsHeaderFreezeRight.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); } @Override public void refreshRequisitionForm(RnRForm form) { scrollView.setVisibility(View.VISIBLE); rnrFormList.initView(new ArrayList<>(form.getRnrFormItemListWrapper())); regimeListView.initView(form.getRegimenItemListWrapper(), tvRegimeTotal); mmiaInfoListView.initView(form.getBaseInfoItemListWrapper()); InflateFreezeHeaderView(); getActivity().setTitle(getString(R.string.label_mmia_title, DateUtil.formatDateWithoutYear(form.getPeriodBegin()), DateUtil.formatDateWithoutYear(form.getPeriodEnd()))); highlightTotalDifference(); etComment.setText(form.getComments()); bindListeners(); } private void InflateFreezeHeaderView() { final View leftHeaderView = rnrFormList.getLeftHeaderView(); rnrItemsHeaderFreezeLeft.addView(leftHeaderView); final ViewGroup rightHeaderView = rnrFormList.getRightHeaderView(); rnrItemsHeaderFreezeRight.addView(rightHeaderView); rnrFormList.post(new Runnable() { @Override public void run() { ViewUtil.syncViewHeight(leftHeaderView, rightHeaderView); } }); } @Override public void setProcessButtonName(String name) { btnComplete.setText(name); } protected void bindListeners() { etComment.post(new Runnable() { @Override public void run() { etComment.addTextChangedListener(commentTextWatcher); } }); tvRegimeTotal.post(new Runnable() { @Override public void run() { tvRegimeTotal.addTextChangedListener(totalTextWatcher); } }); final EditText patientTotalView = mmiaInfoListView.getPatientTotalView(); patientTotalView.post(new Runnable() { @Override public void run() { patientTotalView.addTextChangedListener(totalTextWatcher); } }); btnSave.setOnClickListener(this); btnComplete.setOnClickListener(this); scrollView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { clearEditErrorFocus(); if (getActivity() != null) { ((BaseActivity) getActivity()).hideImm(); } return false; } }); bindFreezeHeaderListener(); } private void bindFreezeHeaderListener() { ViewTreeObserver verticalViewTreeObserver = scrollView.getViewTreeObserver(); verticalViewTreeObserver.addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { hideOrDisplayRnrItemsHeader(); } }); rnrFormList.getRnrItemsHorizontalScrollView().setOnScrollChangedListener(new RnrFormHorizontalScrollView.OnScrollChangedListener() { @Override public void onScrollChanged(int l, int t, int oldl, int oldt) { rnrItemsHeaderFreezeRight.scrollBy(l - oldl, 0); } }); } private void initActionBarHeight() { containerView.post(new Runnable() { @Override public void run() { int[] initialTopLocationOfRnrForm = new int[2]; containerView.getLocationOnScreen(initialTopLocationOfRnrForm); actionBarHeight = initialTopLocationOfRnrForm[1]; } }); } protected void hideOrDisplayRnrItemsHeader() { if (isNeedHideFreezeHeader()) { rnrItemsHeaderFreeze.setVisibility(View.INVISIBLE); } else { rnrItemsHeaderFreeze.setVisibility(View.VISIBLE); } } private boolean isNeedHideFreezeHeader() { int[] rnrItemsViewLocation = new int[2]; rnrFormList.getLocationOnScreen(rnrItemsViewLocation); final int rnrFormY = rnrItemsViewLocation[1]; int lastItemHeight = rnrFormList.getRightViewGroup().getChildAt(rnrFormList.getRightViewGroup().getChildCount() - 1).getHeight(); final int offsetY = -rnrFormY + rnrItemsHeaderFreeze.getHeight() + actionBarHeight; final int hiddenThresholdY = rnrFormList.getHeight() - lastItemHeight; return offsetY > hiddenThresholdY; } private void clearEditErrorFocus() { scrollView.requestFocus(); } TextWatcher commentTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { commentHasChanged = true; highlightTotalDifference(); try { presenter.getRnrForm(formId).setComments(s.toString()); } catch (LMISException e) { e.reportToFabric(); } } }; TextWatcher totalTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { highlightTotalDifference(); } }; private void highlightTotalDifference() { if (isHistoryForm || hasEmptyColumn() || isTotalEqual() || etComment.getText().toString().length() >= 5) { regimeListView.deHighLightTotal(); mmiaInfoListView.deHighLightTotal(); tvMismatch.setVisibility(View.INVISIBLE); } else { regimeListView.highLightTotal(); mmiaInfoListView.highLightTotal(); tvMismatch.setVisibility(View.VISIBLE); } } private boolean hasEmptyColumn() { return regimeListView.hasEmptyField() || mmiaInfoListView.hasEmptyField(); } public void onBackPressed() { if (getResources().getBoolean(R.bool.feature_show_pop_up_even_no_data_changed_418)) { if (presenter.getRnrFormStatus() == RnRForm.STATUS.DRAFT) { hasDataChanged = true; } } if (hasDataChanged()) { SimpleDialogFragment dialogFragment = SimpleDialogFragment.newInstance( null, getString(R.string.msg_mmia_onback_confirm), getString(R.string.btn_positive), getString(R.string.btn_negative), TAG_BACK_PRESSED); dialogFragment.show(getActivity().getFragmentManager(), "back_confirm_dialog"); dialogFragment.setCallBackListener(this); } else { finish(); } } private void removeTempForm() { if (!isHistoryForm) { try { presenter.removeRequisition(); } catch (LMISException e) { ToastUtil.show("Delete Failed"); e.reportToFabric(); } } } private boolean hasDataChanged() { if (hasDataChanged == null) { hasDataChanged = regimeListView.hasDataChanged() || mmiaInfoListView.hasDataChanged() || commentHasChanged; } return hasDataChanged; } private void finish() { getActivity().setResult(Activity.RESULT_OK); getActivity().finish(); } @Override public void showValidationAlert() { DialogFragment dialogFragment = SimpleDialogFragment.newInstance(null, getString(R.string.msg_regime_total_and_patient_total_not_match), getString(R.string.btn_ok), TAG_MISMATCH); dialogFragment.show(getFragmentManager(), "not_match_dialog"); } @Override public void showErrorMessage(String msg) { ToastUtil.show(msg); } @Override public void showSaveErrorMessage() { ToastUtil.show(getString(R.string.hint_save_mmia_failed)); } @Override public void showCompleteErrorMessage() { ToastUtil.show(getString(R.string.hint_mmia_complete_failed)); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_save: onSaveBtnClick(); break; case R.id.btn_complete: onProcessButtonClick(); break; default: break; } } private void onProcessButtonClick() { if (regimeListView.isCompleted() && mmiaInfoListView.isCompleted()) { presenter.processRequisition(regimeListView.getDataList(), mmiaInfoListView.getDataList(), etComment.getText().toString()); } } @Override public void completeSuccess() { ToastUtil.showForLongTime(R.string.msg_mmia_submit_tip); finish(); } @Override public void saveSuccess() { finish(); } @Override public void showSignDialog(boolean isFormStatusDraft) { SignatureDialog signatureDialog = new SignatureDialog(); String signatureDialogTitle = isFormStatusDraft ? getResources().getString(R.string.msg_mmia_submit_signature) : getResources().getString(R.string.msg_approve_signature); signatureDialog.setArguments(SignatureDialog.getBundleToMe(signatureDialogTitle)); signatureDialog.setDelegate(signatureDialogDelegate); signatureDialog.show(this.getFragmentManager()); } protected SignatureDialog.DialogDelegate signatureDialogDelegate = new SignatureDialog.DialogDelegate() { @Override public void onCancel() { } @Override public void onSign(String sign) { presenter.processSign(sign, presenter.getRnRForm()); } }; @Override public void showMessageNotifyDialog() { DialogFragment dialogFragment = SimpleDialogFragment.newInstance(null, getString(R.string.msg_requisition_signature_message_notify), getString(R.string.btn_continue), null, TAG_SHOW_MESSAGE_NOTIFY_DIALOG); dialogFragment.show(this.getFragmentManager(), TAG_SHOW_MESSAGE_NOTIFY_DIALOG); } private boolean isTotalEqual() { return regimeListView.getTotal() == mmiaInfoListView.getTotal(); } private void onSaveBtnClick() { presenter.saveMMIAForm(regimeListView.getDataList(), mmiaInfoListView.getDataList(), etComment.getText().toString()); } @Override public void positiveClick(String tag) { if (tag.equals(TAG_BACK_PRESSED)) { removeTempForm(); finish(); } } @Override public void negativeClick(String tag) { } }
app/src/main/java/org/openlmis/core/view/fragment/MMIARequisitionFragment.java
/* * This program is part of the OpenLMIS logistics management information * system platform software. * * Copyright © 2015 ThoughtWorks, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. 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 Affero General Public License for more details. You should * have received a copy of the GNU Affero General Public License along with * this program. If not, see http://www.gnu.org/licenses. For additional * information contact [email protected] */ package org.openlmis.core.view.fragment; import android.app.Activity; import android.app.DialogFragment; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.Button; import android.widget.EditText; import android.widget.ScrollView; import android.widget.TextView; import com.google.inject.Inject; import org.openlmis.core.R; import org.openlmis.core.exceptions.LMISException; import org.openlmis.core.model.RnRForm; import org.openlmis.core.presenter.MMIARequisitionPresenter; import org.openlmis.core.presenter.Presenter; import org.openlmis.core.utils.Constants; import org.openlmis.core.utils.DateUtil; import org.openlmis.core.utils.ToastUtil; import org.openlmis.core.utils.ViewUtil; import org.openlmis.core.view.activity.BaseActivity; import org.openlmis.core.view.widget.MMIAInfoList; import org.openlmis.core.view.widget.MMIARegimeList; import org.openlmis.core.view.widget.MMIARnrForm; import org.openlmis.core.view.widget.RnrFormHorizontalScrollView; import org.openlmis.core.view.widget.SignatureDialog; import java.util.ArrayList; import roboguice.inject.InjectView; public class MMIARequisitionFragment extends BaseFragment implements MMIARequisitionPresenter.MMIARequisitionView, View.OnClickListener, SimpleDialogFragment.MsgDialogCallBack { @InjectView(R.id.rnr_form_list) protected MMIARnrForm rnrFormList; @InjectView(R.id.regime_list) protected MMIARegimeList regimeListView; @InjectView(R.id.mmia_info_list) protected MMIAInfoList mmiaInfoListView; @InjectView(R.id.btn_complete) protected Button btnComplete; @InjectView(R.id.tv_regime_total) protected TextView tvRegimeTotal; @InjectView(R.id.et_comment) protected TextView etComment; @InjectView(R.id.scrollview) protected ScrollView scrollView; @InjectView(R.id.btn_save) protected View btnSave; @InjectView(R.id.tv_total_mismatch) protected TextView tvMismatch; @InjectView(R.id.action_panel) protected View bottomView; @InjectView(R.id.mmia_rnr_items_header_freeze) protected ViewGroup rnrItemsHeaderFreeze; @InjectView(R.id.mmia_rnr_items_header_freeze_left) protected ViewGroup rnrItemsHeaderFreezeLeft; @InjectView(R.id.mmia_rnr_items_header_freeze_right) protected ViewGroup rnrItemsHeaderFreezeRight; @Inject MMIARequisitionPresenter presenter; private Boolean hasDataChanged; private boolean commentHasChanged = false; private boolean isHistoryForm; private long formId; protected View containerView; protected static final String TAG_BACK_PRESSED = "onBackPressed"; private static final String TAG_MISMATCH = "mismatch"; private static final String TAG_SHOW_MESSAGE_NOTIFY_DIALOG = "showMessageNotifyDialog"; protected int actionBarHeight; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); formId = getActivity().getIntent().getLongExtra(Constants.PARAM_FORM_ID, 0); isHistoryForm = formId != 0; } @Override public Presenter initPresenter() { return presenter; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { containerView = inflater.inflate(R.layout.fragment_mmia_requisition, container, false); return containerView; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initUI(); presenter.loadData(formId); } protected void initUI() { scrollView.setVisibility(View.INVISIBLE); if (isHistoryForm) { scrollView.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); bottomView.setVisibility(View.GONE); } else { scrollView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); bottomView.setVisibility(View.VISIBLE); } disableFreezeHeaderScroll(); initActionBarHeight(); } private void disableFreezeHeaderScroll() { rnrItemsHeaderFreezeRight.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); } @Override public void refreshRequisitionForm(RnRForm form) { scrollView.setVisibility(View.VISIBLE); rnrFormList.initView(new ArrayList<>(form.getRnrFormItemListWrapper())); regimeListView.initView(form.getRegimenItemListWrapper(), tvRegimeTotal); mmiaInfoListView.initView(form.getBaseInfoItemListWrapper()); InflateFreezeHeaderView(); getActivity().setTitle(getString(R.string.label_mmia_title, DateUtil.formatDateWithoutYear(form.getPeriodBegin()), DateUtil.formatDateWithoutYear(form.getPeriodEnd()))); highlightTotalDifference(); etComment.setText(form.getComments()); bindListeners(); } private void InflateFreezeHeaderView() { final View leftHeaderView = rnrFormList.getLeftHeaderView(); rnrItemsHeaderFreezeLeft.addView(leftHeaderView); final ViewGroup rightHeaderView = rnrFormList.getRightHeaderView(); rnrItemsHeaderFreezeRight.addView(rightHeaderView); rnrFormList.post(new Runnable() { @Override public void run() { ViewUtil.syncViewHeight(leftHeaderView, rightHeaderView); } }); } @Override public void setProcessButtonName(String name) { btnComplete.setText(name); } protected void bindListeners() { etComment.post(new Runnable() { @Override public void run() { etComment.addTextChangedListener(commentTextWatcher); } }); tvRegimeTotal.post(new Runnable() { @Override public void run() { tvRegimeTotal.addTextChangedListener(totalTextWatcher); } }); final EditText patientTotalView = mmiaInfoListView.getPatientTotalView(); patientTotalView.post(new Runnable() { @Override public void run() { patientTotalView.addTextChangedListener(totalTextWatcher); } }); btnSave.setOnClickListener(this); btnComplete.setOnClickListener(this); scrollView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { clearEditErrorFocus(); if (getActivity() != null) { ((BaseActivity) getActivity()).hideImm(); } return false; } }); bindFreezeHeaderListener(); } private void bindFreezeHeaderListener() { ViewTreeObserver verticalViewTreeObserver = scrollView.getViewTreeObserver(); verticalViewTreeObserver.addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { hideOrDisplayRnrItemsHeader(); } }); rnrFormList.getRnrItemsHorizontalScrollView().setOnScrollChangedListener(new RnrFormHorizontalScrollView.OnScrollChangedListener() { @Override public void onScrollChanged(int l, int t, int oldl, int oldt) { rnrItemsHeaderFreezeRight.scrollBy(l - oldl, 0); } }); } private void initActionBarHeight() { containerView.post(new Runnable() { @Override public void run() { int[] initialTopLocationOfRnrForm = new int[2]; containerView.getLocationOnScreen(initialTopLocationOfRnrForm); actionBarHeight = initialTopLocationOfRnrForm[1]; } }); } protected void hideOrDisplayRnrItemsHeader() { if (isNeedHideFreezeHeader()) { rnrItemsHeaderFreeze.setVisibility(View.INVISIBLE); } else { rnrItemsHeaderFreeze.setVisibility(View.VISIBLE); } } private boolean isNeedHideFreezeHeader() { int[] rnrItemsViewLocation = new int[2]; rnrFormList.getLocationOnScreen(rnrItemsViewLocation); final int rnrFormY = rnrItemsViewLocation[1]; int lastItemHeight = rnrFormList.getRightViewGroup().getChildAt(rnrFormList.getRightViewGroup().getChildCount() - 1).getHeight(); final int offsetY = -rnrFormY + rnrItemsHeaderFreeze.getHeight() + actionBarHeight; final int hiddenThresholdY = rnrFormList.getHeight() - lastItemHeight; return offsetY > hiddenThresholdY; } private void clearEditErrorFocus() { scrollView.requestFocus(); } TextWatcher commentTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { commentHasChanged = true; highlightTotalDifference(); try { presenter.getRnrForm(formId).setComments(s.toString()); } catch (LMISException e) { e.reportToFabric(); } } }; TextWatcher totalTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { highlightTotalDifference(); } }; private void highlightTotalDifference() { if (hasEmptyColumn() || isTotalEqual() || etComment.getText().toString().length() >= 5) { regimeListView.deHighLightTotal(); mmiaInfoListView.deHighLightTotal(); tvMismatch.setVisibility(View.INVISIBLE); } else { regimeListView.highLightTotal(); mmiaInfoListView.highLightTotal(); tvMismatch.setVisibility(View.VISIBLE); } } private boolean hasEmptyColumn() { return regimeListView.hasEmptyField() || mmiaInfoListView.hasEmptyField(); } public void onBackPressed() { if (getResources().getBoolean(R.bool.feature_show_pop_up_even_no_data_changed_418)) { if (presenter.getRnrFormStatus() == RnRForm.STATUS.DRAFT) { hasDataChanged = true; } } if (hasDataChanged()) { SimpleDialogFragment dialogFragment = SimpleDialogFragment.newInstance( null, getString(R.string.msg_mmia_onback_confirm), getString(R.string.btn_positive), getString(R.string.btn_negative), TAG_BACK_PRESSED); dialogFragment.show(getActivity().getFragmentManager(), "back_confirm_dialog"); dialogFragment.setCallBackListener(this); } else { finish(); } } private void removeTempForm() { if (!isHistoryForm) { try { presenter.removeRequisition(); } catch (LMISException e) { ToastUtil.show("Delete Failed"); e.reportToFabric(); } } } private boolean hasDataChanged() { if (hasDataChanged == null) { hasDataChanged = regimeListView.hasDataChanged() || mmiaInfoListView.hasDataChanged() || commentHasChanged; } return hasDataChanged; } private void finish() { getActivity().setResult(Activity.RESULT_OK); getActivity().finish(); } @Override public void showValidationAlert() { DialogFragment dialogFragment = SimpleDialogFragment.newInstance(null, getString(R.string.msg_regime_total_and_patient_total_not_match), getString(R.string.btn_ok), TAG_MISMATCH); dialogFragment.show(getFragmentManager(), "not_match_dialog"); } @Override public void showErrorMessage(String msg) { ToastUtil.show(msg); } @Override public void showSaveErrorMessage() { ToastUtil.show(getString(R.string.hint_save_mmia_failed)); } @Override public void showCompleteErrorMessage() { ToastUtil.show(getString(R.string.hint_mmia_complete_failed)); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_save: onSaveBtnClick(); break; case R.id.btn_complete: onProcessButtonClick(); break; default: break; } } private void onProcessButtonClick() { if (regimeListView.isCompleted() && mmiaInfoListView.isCompleted()) { presenter.processRequisition(regimeListView.getDataList(), mmiaInfoListView.getDataList(), etComment.getText().toString()); } } @Override public void completeSuccess() { ToastUtil.showForLongTime(R.string.msg_mmia_submit_tip); finish(); } @Override public void saveSuccess() { finish(); } @Override public void showSignDialog(boolean isFormStatusDraft) { SignatureDialog signatureDialog = new SignatureDialog(); String signatureDialogTitle = isFormStatusDraft ? getResources().getString(R.string.msg_mmia_submit_signature) : getResources().getString(R.string.msg_approve_signature); signatureDialog.setArguments(SignatureDialog.getBundleToMe(signatureDialogTitle)); signatureDialog.setDelegate(signatureDialogDelegate); signatureDialog.show(this.getFragmentManager()); } protected SignatureDialog.DialogDelegate signatureDialogDelegate = new SignatureDialog.DialogDelegate() { @Override public void onCancel() { } @Override public void onSign(String sign) { presenter.processSign(sign, presenter.getRnRForm()); } }; @Override public void showMessageNotifyDialog() { DialogFragment dialogFragment = SimpleDialogFragment.newInstance(null, getString(R.string.msg_requisition_signature_message_notify), getString(R.string.btn_continue), null, TAG_SHOW_MESSAGE_NOTIFY_DIALOG); dialogFragment.show(this.getFragmentManager(), TAG_SHOW_MESSAGE_NOTIFY_DIALOG); } private boolean isTotalEqual() { return regimeListView.getTotal() == mmiaInfoListView.getTotal(); } private void onSaveBtnClick() { presenter.saveMMIAForm(regimeListView.getDataList(), mmiaInfoListView.getDataList(), etComment.getText().toString()); } @Override public void positiveClick(String tag) { if (tag.equals(TAG_BACK_PRESSED)) { removeTempForm(); finish(); } } @Override public void negativeClick(String tag) { } }
MG - #000 - Do not show the mismatch label and highlight EditText in Requisition history page
app/src/main/java/org/openlmis/core/view/fragment/MMIARequisitionFragment.java
MG - #000 - Do not show the mismatch label and highlight EditText in Requisition history page
<ide><path>pp/src/main/java/org/openlmis/core/view/fragment/MMIARequisitionFragment.java <ide> if (isHistoryForm) { <ide> scrollView.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); <ide> bottomView.setVisibility(View.GONE); <add> etComment.setEnabled(false); <ide> } else { <ide> scrollView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); <ide> bottomView.setVisibility(View.VISIBLE); <add> etComment.setEnabled(true); <ide> } <ide> disableFreezeHeaderScroll(); <ide> initActionBarHeight(); <ide> }; <ide> <ide> private void highlightTotalDifference() { <del> if (hasEmptyColumn() || isTotalEqual() || etComment.getText().toString().length() >= 5) { <add> if (isHistoryForm || hasEmptyColumn() || isTotalEqual() || etComment.getText().toString().length() >= 5) { <ide> regimeListView.deHighLightTotal(); <ide> mmiaInfoListView.deHighLightTotal(); <ide> tvMismatch.setVisibility(View.INVISIBLE);
Java
apache-2.0
80ee6c1a9184754bdf431cf45470747237b3b86c
0
synaptek/cordova-android,rakuco/crosswalk-cordova-android,archananaik/cordova-amazon-fireos-old,mleoking/cordova-android,wikimedia/incubator-cordova-android,MetSystem/cordova-android,bso-intel/cordova-android,vionescu/cordova-android,Icenium/cordova-android,macdonst/cordova-android,polyvi/xface-android,crosswalk-project/crosswalk-cordova-android,Philzen/cordova-android-multitouch-polyfill,jfrumar/cordova-android,forcedotcom/incubator-cordova-android,tony--/cordova-android,mokelab/cordova-android,jasongin/cordova-android,rakuco/crosswalk-cordova-android,chengxiaole/crosswalk-cordova-android,ogoguel/cordova-android,alsorokin/cordova-android,CrandellWS/cordova-android,csantanapr/cordova-android,revolunet/cordova-android,matb33/cordova-android,honger05/cordova-android,awesome-niu/crosswalk-cordova-android,lvrookie/cordova-android,net19880504/cordova-android,devgeeks/cordova-android,CrandellWS/cordova-android,mleoking/cordova-android,grigorkh/cordova-android,jfrumar/cordova-android,bso-intel/cordova-android,0359xiaodong/cordova-android,manuelbrand/cordova-android,xandroidx/cordova-android,imhotep/incubator-cordova-android,hgl888/crosswalk-cordova-android,mmig/cordova-android,rakuco/crosswalk-cordova-android,vionescu/cordova-android,chengxiaole/crosswalk-cordova-android,leixinstar/cordova-android,cesine/cordova-android,rohngonnarock/cordova-android,lybvinci/cordova-android,infil00p/cordova-android,0359xiaodong/cordova-android,honger05/cordova-android,revolunet/cordova-android,corimf/cordova-android,hgl888/cordova-android-chromeview,lvrookie/cordova-android,GroupAhead/cordova-android,Icenium/cordova-android,egirshov/cordova-android,mmig/cordova-android,jfrumar/cordova-android,apache/cordova-android,thedracle/cordova-android-chromeview,macdonst/cordova-android,cesine/cordova-android,honger05/cordova-android,lybvinci/cordova-android,askyheller/testgithub,crosswalk-project/crosswalk-cordova-android,GroupAhead/cordova-android,hgl888/cordova-android-chromeview,egirshov/cordova-android,GroupAhead/cordova-android,ecit241/cordova-android,ttiurani/cordova-android,alpache/cordova-android,net19880504/cordova-android,mokelab/cordova-android,thedracle/cordova-android-chromeview,hgl888/crosswalk-cordova-android,corimf/cordova-android,mleoking/cordova-android,ogoguel/cordova-android,matb33/cordova-android,alpache/cordova-android,cesine/cordova-android,hgl888/cordova-android,alsorokin/cordova-android,askyheller/testgithub,vionescu/cordova-android,MetSystem/cordova-android,ogoguel/cordova-android,MetSystem/cordova-android,infil00p/cordova-android,devgeeks/cordova-android,corimf/cordova-android,dpogue/cordova-android,forcedotcom/incubator-cordova-android,leixinstar/cordova-android,mokelab/cordova-android,hgl888/cordova-android-chromeview,hgl888/cordova-android-chromeview,lybvinci/cordova-android,hgl888/crosswalk-cordova-android,wikimedia/incubator-cordova-android,askyheller/testgithub,Philzen/cordova-android-multitouch-polyfill,ttiurani/cordova-android,filmaj/cordova-android,matb33/cordova-android,alpache/cordova-android,polyvi/xface-android,sxagan/cordova-android,infil00p/cordova-android,wikimedia/incubator-cordova-android,adobe-marketing-cloud-mobile/aemm-android,awesome-niu/crosswalk-cordova-android,adobe-marketing-cloud-mobile/aemm-android,macdonst/cordova-android,dpogue/cordova-android,tony--/cordova-android,jasongin/cordova-android,Icenium/cordova-android,apache/cordova-android,archananaik/cordova-amazon-fireos-old,CrandellWS/cordova-android,leixinstar/cordova-android,polyvi/xface-android,manuelbrand/cordova-android,imhotep/incubator-cordova-android,jasongin/cordova-android,lvrookie/cordova-android,rohngonnarock/cordova-android,synaptek/cordova-android,bso-intel/cordova-android,imhotep/incubator-cordova-android,CloudCom/cordova-android,devgeeks/cordova-android,chengxiaole/crosswalk-cordova-android,rohngonnarock/cordova-android,hgl888/cordova-android,filmaj/cordova-android,CloudCom/cordova-android,grigorkh/cordova-android,awesome-niu/crosswalk-cordova-android,revolunet/cordova-android,net19880504/cordova-android,grigorkh/cordova-android,csantanapr/cordova-android,synaptek/cordova-android,sxagan/cordova-android,crosswalk-project/crosswalk-cordova-android,egirshov/cordova-android,thedracle/cordova-android-chromeview,filmaj/cordova-android,ecit241/cordova-android,dpogue/cordova-android,xandroidx/cordova-android,0359xiaodong/cordova-android,ecit241/cordova-android,ttiurani/cordova-android,apache/cordova-android,manuelbrand/cordova-android,Philzen/cordova-android-multitouch-polyfill,adobe-marketing-cloud-mobile/aemm-android,forcedotcom/incubator-cordova-android,CloudCom/cordova-android,mmig/cordova-android,sxagan/cordova-android,archananaik/cordova-amazon-fireos-old,alsorokin/cordova-android,xandroidx/cordova-android,grigorkh/cordova-android,hgl888/cordova-android,csantanapr/cordova-android,tony--/cordova-android
/* 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.cordova; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.cordova.PreferenceNode; import org.apache.cordova.PreferenceSet; import org.apache.cordova.api.IPlugin; import org.apache.cordova.api.LOG; import org.apache.cordova.api.CordovaInterface; import org.apache.cordova.api.PluginManager; import org.xmlpull.v1.XmlPullParserException; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.content.res.XmlResourceParser; import android.graphics.Color; import android.media.AudioManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.view.Display; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebSettings.LayoutAlgorithm; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.LinearLayout; /** * This class is the main Android activity that represents the Cordova * application. It should be extended by the user to load the specific * html file that contains the application. * * As an example: * * package org.apache.cordova.examples; * import android.app.Activity; * import android.os.Bundle; * import org.apache.cordova.*; * * public class Examples extends DroidGap { * @Override * public void onCreate(Bundle savedInstanceState) { * super.onCreate(savedInstanceState); * * // Set properties for activity * super.setStringProperty("loadingDialog", "Title,Message"); // show loading dialog * super.setStringProperty("errorUrl", "file:///android_asset/www/error.html"); // if error loading file in super.loadUrl(). * * // Initialize activity * super.init(); * * // Clear cache if you want * super.appView.clearCache(true); * * // Load your application * super.setIntegerProperty("splashscreen", R.drawable.splash); // load splash.jpg image from the resource drawable directory * super.loadUrl("file:///android_asset/www/index.html", 3000); // show splash screen 3 sec before loading app * } * } * * Properties: The application can be configured using the following properties: * * // Display a native loading dialog when loading app. Format for value = "Title,Message". * // (String - default=null) * super.setStringProperty("loadingDialog", "Wait,Loading Demo..."); * * // Display a native loading dialog when loading sub-pages. Format for value = "Title,Message". * // (String - default=null) * super.setStringProperty("loadingPageDialog", "Loading page..."); * * // Load a splash screen image from the resource drawable directory. * // (Integer - default=0) * super.setIntegerProperty("splashscreen", R.drawable.splash); * * // Set the background color. * // (Integer - default=0 or BLACK) * super.setIntegerProperty("backgroundColor", Color.WHITE); * * // Time in msec to wait before triggering a timeout error when loading * // with super.loadUrl(). (Integer - default=20000) * super.setIntegerProperty("loadUrlTimeoutValue", 60000); * * // URL to load if there's an error loading specified URL with loadUrl(). * // Should be a local URL starting with file://. (String - default=null) * super.setStringProperty("errorUrl", "file:///android_asset/www/error.html"); * * // Enable app to keep running in background. (Boolean - default=true) * super.setBooleanProperty("keepRunning", false); * * Cordova.xml configuration: * Cordova uses a configuration file at res/xml/cordova.xml to specify the following settings. * * Approved list of URLs that can be loaded into DroidGap * <access origin="http://server regexp" subdomains="true" /> * Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR) * <log level="DEBUG" /> * * Cordova plugins: * Cordova uses a file at res/xml/plugins.xml to list all plugins that are installed. * Before using a new plugin, a new element must be added to the file. * name attribute is the service name passed to Cordova.exec() in JavaScript * value attribute is the Java class name to call. * * <plugins> * <plugin name="App" value="org.apache.cordova.App"/> * ... * </plugins> */ public class DroidGap extends Activity implements CordovaInterface { public static String TAG = "DroidGap"; // The webview for our app protected WebView appView; protected WebViewClient webViewClient; private ArrayList<Pattern> whiteList = new ArrayList<Pattern>(); private HashMap<String, Boolean> whiteListCache = new HashMap<String,Boolean>(); protected LinearLayout root; public boolean bound = false; public CallbackServer callbackServer; protected PluginManager pluginManager; protected boolean cancelLoadUrl = false; protected ProgressDialog spinnerDialog = null; // The initial URL for our app // ie http://server/path/index.html#abc?query private String url = null; private Stack<String> urls = new Stack<String>(); // Url was specified from extras (activity was started programmatically) private String initUrl = null; private static int ACTIVITY_STARTING = 0; private static int ACTIVITY_RUNNING = 1; private static int ACTIVITY_EXITING = 2; private int activityState = 0; // 0=starting, 1=running (after 1st resume), 2=shutting down // The base of the initial URL for our app. // Does not include file name. Ends with / // ie http://server/path/ String baseUrl = null; // Plugin to call when activity result is received protected IPlugin activityResultCallback = null; protected boolean activityResultKeepRunning; // Flag indicates that a loadUrl timeout occurred int loadUrlTimeout = 0; // Default background color for activity // (this is not the color for the webview, which is set in HTML) private int backgroundColor = Color.BLACK; /** The authorization tokens. */ private Hashtable<String, AuthenticationToken> authenticationTokens = new Hashtable<String, AuthenticationToken>(); /* * The variables below are used to cache some of the activity properties. */ // Draw a splash screen using an image located in the drawable resource directory. // This is not the same as calling super.loadSplashscreen(url) protected int splashscreen = 0; // LoadUrl timeout value in msec (default of 20 sec) protected int loadUrlTimeoutValue = 20000; // Keep app running when pause is received. (default = true) // If true, then the JavaScript and native code continue to run in the background // when another application (activity) is started. protected boolean keepRunning = true; // preferences read from cordova.xml protected PreferenceSet preferences; /** * Sets the authentication token. * * @param authenticationToken * the authentication token * @param host * the host * @param realm * the realm */ public void setAuthenticationToken(AuthenticationToken authenticationToken, String host, String realm) { if(host == null) { host = ""; } if(realm == null) { realm = ""; } authenticationTokens.put(host.concat(realm), authenticationToken); } /** * Removes the authentication token. * * @param host * the host * @param realm * the realm * @return the authentication token or null if did not exist */ public AuthenticationToken removeAuthenticationToken(String host, String realm) { return authenticationTokens.remove(host.concat(realm)); } /** * Gets the authentication token. * * In order it tries: * 1- host + realm * 2- host * 3- realm * 4- no host, no realm * * @param host * the host * @param realm * the realm * @return the authentication token */ public AuthenticationToken getAuthenticationToken(String host, String realm) { AuthenticationToken token = null; token = authenticationTokens.get(host.concat(realm)); if(token == null) { // try with just the host token = authenticationTokens.get(host); // Try the realm if(token == null) { token = authenticationTokens.get(realm); } // if no host found, just query for default if(token == null) { token = authenticationTokens.get(""); } } return token; } /** * Clear all authentication tokens. */ public void clearAuthenticationTokens() { authenticationTokens.clear(); } /** * Called when the activity is first created. * * @param savedInstanceState */ @Override public void onCreate(Bundle savedInstanceState) { preferences = new PreferenceSet(); // Load Cordova configuration: // white list of allowed URLs // debug setting this.loadConfiguration(); LOG.d(TAG, "DroidGap.onCreate()"); super.onCreate(savedInstanceState); if (!preferences.prefMatches("showTitle", "true")) { getWindow().requestFeature(Window.FEATURE_NO_TITLE); } if (preferences.prefMatches("fullscreen","true")) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); } // This builds the view. We could probably get away with NOT having a LinearLayout, but I like having a bucket! Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); root = new LinearLayoutSoftKeyboardDetect(this, width, height); root.setOrientation(LinearLayout.VERTICAL); root.setBackgroundColor(this.backgroundColor); root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 0.0F)); // If url was passed in to intent, then init webview, which will load the url Bundle bundle = this.getIntent().getExtras(); if (bundle != null) { String url = bundle.getString("url"); if (url != null) { this.initUrl = url; } } // Setup the hardware volume controls to handle volume control setVolumeControlStream(AudioManager.STREAM_MUSIC); } /** * Create and initialize web container with default web view objects. */ public void init() { this.init(new WebView(DroidGap.this), new CordovaWebViewClient(this), new CordovaChromeClient(DroidGap.this)); } /** * Initialize web container with web view objects. * * @param webView * @param webViewClient * @param webChromeClient */ public void init(WebView webView, WebViewClient webViewClient, WebChromeClient webChromeClient) { LOG.d(TAG, "DroidGap.init()"); // Set up web container this.appView = webView; this.appView.setId(100); this.appView.setLayoutParams(new LinearLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 1.0F)); this.appView.setWebChromeClient(webChromeClient); this.setWebViewClient(this.appView, webViewClient); this.appView.setInitialScale(0); this.appView.setVerticalScrollBarEnabled(false); this.appView.requestFocusFromTouch(); // Enable JavaScript WebSettings settings = this.appView.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL); //Set the nav dump for HTC settings.setNavDump(true); // Enable database settings.setDatabaseEnabled(true); String databasePath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); settings.setDatabasePath(databasePath); // Enable DOM storage settings.setDomStorageEnabled(true); // Enable built-in geolocation settings.setGeolocationEnabled(true); // Add web view but make it invisible while loading URL this.appView.setVisibility(View.INVISIBLE); root.addView(this.appView); setContentView(root); // Clear cancel flag this.cancelLoadUrl = false; // Create plugin manager this.pluginManager = new PluginManager(this.appView, this); } /** * Set the WebViewClient. * * @param appView * @param client */ protected void setWebViewClient(WebView appView, WebViewClient client) { this.webViewClient = client; appView.setWebViewClient(client); } /** * Look at activity parameters and process them. * This must be called from the main UI thread. */ private void handleActivityParameters() { // If backgroundColor this.backgroundColor = this.getIntegerProperty("backgroundColor", Color.BLACK); this.root.setBackgroundColor(this.backgroundColor); // If spashscreen this.splashscreen = this.getIntegerProperty("splashscreen", 0); // If loadUrlTimeoutValue int timeout = this.getIntegerProperty("loadUrlTimeoutValue", 0); if (timeout > 0) { this.loadUrlTimeoutValue = timeout; } // If keepRunning this.keepRunning = this.getBooleanProperty("keepRunning", true); } /** * Load the url into the webview. * * @param url */ public void loadUrl(String url) { // If first page of app, then set URL to load to be the one passed in if (this.initUrl == null || (this.urls.size() > 0)) { this.loadUrlIntoView(url); } // Otherwise use the URL specified in the activity's extras bundle else { this.loadUrlIntoView(this.initUrl); } } /** * Load the url into the webview. * * @param url */ private void loadUrlIntoView(final String url) { if (!url.startsWith("javascript:")) { LOG.d(TAG, "DroidGap.loadUrl(%s)", url); } this.url = url; if (this.baseUrl == null) { int i = url.lastIndexOf('/'); if (i > 0) { this.baseUrl = url.substring(0, i+1); } else { this.baseUrl = this.url + "/"; } } if (!url.startsWith("javascript:")) { LOG.d(TAG, "DroidGap: url=%s baseUrl=%s", url, baseUrl); } // Load URL on UI thread final DroidGap me = this; this.runOnUiThread(new Runnable() { public void run() { // Init web view if not already done if (me.appView == null) { me.init(); } // Handle activity parameters me.handleActivityParameters(); // Track URLs loaded instead of using appView history me.urls.push(url); me.appView.clearHistory(); // Create callback server and plugin manager if (me.callbackServer == null) { me.callbackServer = new CallbackServer(); me.callbackServer.init(url); } else { me.callbackServer.reinit(url); } me.pluginManager.init(); // If loadingDialog property, then show the App loading dialog for first page of app String loading = null; if (me.urls.size() == 1) { loading = me.getStringProperty("loadingDialog", null); } else { loading = me.getStringProperty("loadingPageDialog", null); } if (loading != null) { String title = ""; String message = "Loading Application..."; if (loading.length() > 0) { int comma = loading.indexOf(','); if (comma > 0) { title = loading.substring(0, comma); message = loading.substring(comma+1); } else { title = ""; message = loading; } } me.spinnerStart(title, message); } // Create a timeout timer for loadUrl final int currentLoadUrlTimeout = me.loadUrlTimeout; Runnable runnable = new Runnable() { public void run() { try { synchronized(this) { wait(me.loadUrlTimeoutValue); } } catch (InterruptedException e) { e.printStackTrace(); } // If timeout, then stop loading and handle error if (me.loadUrlTimeout == currentLoadUrlTimeout) { me.appView.stopLoading(); LOG.e(TAG, "DroidGap: TIMEOUT ERROR! - calling webViewClient"); me.webViewClient.onReceivedError(me.appView, -6, "The connection to the server was unsuccessful.", url); } } }; Thread thread = new Thread(runnable); thread.start(); me.appView.loadUrl(url); } }); } /** * Load the url into the webview after waiting for period of time. * This is used to display the splashscreen for certain amount of time. * * @param url * @param time The number of ms to wait before loading webview */ public void loadUrl(final String url, int time) { // If first page of app, then set URL to load to be the one passed in if (this.initUrl == null || (this.urls.size() > 0)) { this.loadUrlIntoView(url, time); } // Otherwise use the URL specified in the activity's extras bundle else { this.loadUrlIntoView(this.initUrl); } } /** * Load the url into the webview after waiting for period of time. * This is used to display the splashscreen for certain amount of time. * * @param url * @param time The number of ms to wait before loading webview */ private void loadUrlIntoView(final String url, final int time) { // Clear cancel flag this.cancelLoadUrl = false; // If not first page of app, then load immediately if (this.urls.size() > 0) { this.loadUrlIntoView(url); } if (!url.startsWith("javascript:")) { LOG.d(TAG, "DroidGap.loadUrl(%s, %d)", url, time); } this.handleActivityParameters(); if (this.splashscreen != 0) { this.showSplashScreen(time); } this.loadUrlIntoView(url); } /** * Cancel loadUrl before it has been loaded. */ public void cancelLoadUrl() { this.cancelLoadUrl = true; } /** * Clear the resource cache. */ public void clearCache() { if (this.appView == null) { this.init(); } this.appView.clearCache(true); } /** * Clear web history in this web view. */ public void clearHistory() { this.urls.clear(); this.appView.clearHistory(); // Leave current url on history stack if (this.url != null) { this.urls.push(this.url); } } /** * Go to previous page in history. (We manage our own history) * * @return true if we went back, false if we are already at top */ public boolean backHistory() { // Check webview first to see if there is a history // This is needed to support curPage#diffLink, since they are added to appView's history, but not our history url array (JQMobile behavior) if (this.appView.canGoBack()) { this.appView.goBack(); return true; } // If our managed history has prev url if (this.urls.size() > 1) { this.urls.pop(); // Pop current url String url = this.urls.pop(); // Pop prev url that we want to load, since it will be added back by loadUrl() this.loadUrl(url); return true; } return false; } @Override /** * Called by the system when the device configuration changes while your activity is running. * * @param Configuration newConfig */ public void onConfigurationChanged(Configuration newConfig) { //don't reload the current page when the orientation is changed super.onConfigurationChanged(newConfig); } /** * Get boolean property for activity. * * @param name * @param defaultValue * @return */ public boolean getBooleanProperty(String name, boolean defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } Boolean p = (Boolean)bundle.get(name); if (p == null) { return defaultValue; } return p.booleanValue(); } /** * Get int property for activity. * * @param name * @param defaultValue * @return */ public int getIntegerProperty(String name, int defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } Integer p = (Integer)bundle.get(name); if (p == null) { return defaultValue; } return p.intValue(); } /** * Get string property for activity. * * @param name * @param defaultValue * @return */ public String getStringProperty(String name, String defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } String p = bundle.getString(name); if (p == null) { return defaultValue; } return p; } /** * Get double property for activity. * * @param name * @param defaultValue * @return */ public double getDoubleProperty(String name, double defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } Double p = (Double)bundle.get(name); if (p == null) { return defaultValue; } return p.doubleValue(); } /** * Set boolean property on activity. * * @param name * @param value */ public void setBooleanProperty(String name, boolean value) { this.getIntent().putExtra(name, value); } /** * Set int property on activity. * * @param name * @param value */ public void setIntegerProperty(String name, int value) { this.getIntent().putExtra(name, value); } /** * Set string property on activity. * * @param name * @param value */ public void setStringProperty(String name, String value) { this.getIntent().putExtra(name, value); } /** * Set double property on activity. * * @param name * @param value */ public void setDoubleProperty(String name, double value) { this.getIntent().putExtra(name, value); } @Override /** * Called when the system is about to start resuming a previous activity. */ protected void onPause() { super.onPause(); // Don't process pause if shutting down, since onDestroy() will be called if (this.activityState == ACTIVITY_EXITING) { return; } if (this.appView == null) { return; } // Send pause event to JavaScript this.appView.loadUrl("javascript:try{cordova.fireDocumentEvent('pause');}catch(e){console.log('exception firing pause event from native');};"); // Forward to plugins if (this.pluginManager != null) { this.pluginManager.onPause(this.keepRunning); } // If app doesn't want to run in background if (!this.keepRunning) { // Pause JavaScript timers (including setInterval) this.appView.pauseTimers(); } } @Override /** * Called when the activity receives a new intent **/ protected void onNewIntent(Intent intent) { super.onNewIntent(intent); //Forward to plugins if (this.pluginManager != null) { this.pluginManager.onNewIntent(intent); } } @Override /** * Called when the activity will start interacting with the user. */ protected void onResume() { super.onResume(); if (this.activityState == ACTIVITY_STARTING) { this.activityState = ACTIVITY_RUNNING; return; } if (this.appView == null) { return; } // Send resume event to JavaScript this.appView.loadUrl("javascript:try{cordova.fireDocumentEvent('resume');}catch(e){console.log('exception firing resume event from native');};"); // Forward to plugins if (this.pluginManager != null) { this.pluginManager.onResume(this.keepRunning || this.activityResultKeepRunning); } // If app doesn't want to run in background if (!this.keepRunning || this.activityResultKeepRunning) { // Restore multitasking state if (this.activityResultKeepRunning) { this.keepRunning = this.activityResultKeepRunning; this.activityResultKeepRunning = false; } // Resume JavaScript timers (including setInterval) this.appView.resumeTimers(); } } @Override /** * The final call you receive before your activity is destroyed. */ public void onDestroy() { super.onDestroy(); if (this.appView != null) { // Send destroy event to JavaScript this.appView.loadUrl("javascript:try{cordova.require('cordova/channel').onDestroy.fire();}catch(e){console.log('exception firing destroy event from native');};"); // Load blank page so that JavaScript onunload is called this.appView.loadUrl("about:blank"); // Forward to plugins if (this.pluginManager != null) { this.pluginManager.onDestroy(); } } else { this.endActivity(); } } /** * Send a message to all plugins. * * @param id The message id * @param data The message data */ public void postMessage(String id, Object data) { // Forward to plugins if (this.pluginManager != null) { this.pluginManager.postMessage(id, data); } } /** * @deprecated * Add services to res/xml/plugins.xml instead. * * Add a class that implements a service. * * @param serviceType * @param className */ @Deprecated public void addService(String serviceType, String className) { if (this.pluginManager != null) { this.pluginManager.addService(serviceType, className); } } /** * Send JavaScript statement back to JavaScript. * (This is a convenience method) * * @param message */ public void sendJavascript(String statement) { //We need to check for the null case on the Kindle Fire beacuse it changes the width and height on load if(this.callbackServer != null) this.callbackServer.sendJavascript(statement); } /** * Load the specified URL in the Cordova webview or a new browser instance. * * NOTE: If openExternal is false, only URLs listed in whitelist can be loaded. * * @param url The url to load. * @param openExternal Load url in browser instead of Cordova webview. * @param clearHistory Clear the history stack, so new page becomes top of history * @param params DroidGap parameters for new app */ public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) { //throws android.content.ActivityNotFoundException { LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap", url, openExternal, clearHistory); // If clearing history if (clearHistory) { this.clearHistory(); } // If loading into our webview if (!openExternal) { // Make sure url is in whitelist if (url.startsWith("file://") || url.indexOf(this.baseUrl) == 0 || isUrlWhiteListed(url)) { // TODO: What about params? // Clear out current url from history, since it will be replacing it if (clearHistory) { this.urls.clear(); } // Load new URL this.loadUrl(url); } // Load in default viewer if not else { LOG.w(TAG, "showWebPage: Cannot load URL into webview since it is not in white list. Loading into browser instead. (URL="+url+")"); try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); this.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } // Load in default view intent else { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); this.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } /** * Show the spinner. Must be called from the UI thread. * * @param title Title of the dialog * @param message The message of the dialog */ public void spinnerStart(final String title, final String message) { if (this.spinnerDialog != null) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } final DroidGap me = this; this.spinnerDialog = ProgressDialog.show(DroidGap.this, title , message, true, true, new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { me.spinnerDialog = null; } }); } /** * Stop spinner. */ public void spinnerStop() { if (this.spinnerDialog != null) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } } /** * End this activity by calling finish for activity */ public void endActivity() { this.activityState = ACTIVITY_EXITING; this.finish(); } /** * Called when a key is de-pressed. (Key UP) * * @param keyCode * @param event */ @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (this.appView == null) { return super.onKeyUp(keyCode, event); } // If back key if (keyCode == KeyEvent.KEYCODE_BACK) { // If back key is bound, then send event to JavaScript if (this.bound) { this.appView.loadUrl("javascript:cordova.fireDocumentEvent('backbutton');"); return true; } else { // If not bound // Go to previous page in webview if it is possible to go back if (this.backHistory()) { return true; } // If not, then invoke behavior of super class else { this.activityState = ACTIVITY_EXITING; return super.onKeyUp(keyCode, event); } } } // If menu key else if (keyCode == KeyEvent.KEYCODE_MENU) { this.appView.loadUrl("javascript:cordova.fireDocumentEvent('menubutton');"); return super.onKeyUp(keyCode, event); } // If search key else if (keyCode == KeyEvent.KEYCODE_SEARCH) { this.appView.loadUrl("javascript:cordova.fireDocumentEvent('searchbutton');"); return true; } return false; } /** * Any calls to Activity.startActivityForResult must use method below, so * the result can be routed to them correctly. * * This is done to eliminate the need to modify DroidGap.java to receive activity results. * * @param intent The intent to start * @param requestCode Identifies who to send the result to * * @throws RuntimeException */ @Override public void startActivityForResult(Intent intent, int requestCode) throws RuntimeException { LOG.d(TAG, "DroidGap.startActivityForResult(intent,%d)", requestCode); super.startActivityForResult(intent, requestCode); } /** * Launch an activity for which you would like a result when it finished. When this activity exits, * your onActivityResult() method will be called. * * @param command The command object * @param intent The intent to start * @param requestCode The request code that is passed to callback to identify the activity */ public void startActivityForResult(IPlugin command, Intent intent, int requestCode) { this.activityResultCallback = command; this.activityResultKeepRunning = this.keepRunning; // If multitasking turned on, then disable it for activities that return results if (command != null) { this.keepRunning = false; } // Start activity super.startActivityForResult(intent, requestCode); } @Override /** * Called when an activity you launched exits, giving you the requestCode you started it with, * the resultCode it returned, and any additional data from it. * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). */ protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); IPlugin callback = this.activityResultCallback; if (callback != null) { callback.onActivityResult(requestCode, resultCode, intent); } } public void setActivityResultCallback(IPlugin plugin) { this.activityResultCallback = plugin; } /** * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). * The errorCode parameter corresponds to one of the ERROR_* constants. * * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. */ public void onReceivedError(final int errorCode, final String description, final String failingUrl) { final DroidGap me = this; // If errorUrl specified, then load it final String errorUrl = me.getStringProperty("errorUrl", null); if ((errorUrl != null) && (errorUrl.startsWith("file://") || errorUrl.indexOf(me.baseUrl) == 0 || isUrlWhiteListed(errorUrl)) && (!failingUrl.equals(errorUrl))) { // Load URL on UI thread me.runOnUiThread(new Runnable() { public void run() { me.showWebPage(errorUrl, false, true, null); } }); } // If not, then display error dialog else { final boolean exit = !(errorCode == WebViewClient.ERROR_HOST_LOOKUP); me.runOnUiThread(new Runnable() { public void run() { if(exit) { me.appView.setVisibility(View.GONE); me.displayError("Application Error", description + " ("+failingUrl+")", "OK", exit); } } }); } } /** * Display an error dialog and optionally exit application. * * @param title * @param message * @param button * @param exit */ public void displayError(final String title, final String message, final String button, final boolean exit) { final DroidGap me = this; me.runOnUiThread(new Runnable() { public void run() { AlertDialog.Builder dlg = new AlertDialog.Builder(me); dlg.setMessage(message); dlg.setTitle(title); dlg.setCancelable(false); dlg.setPositiveButton(button, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (exit) { me.endActivity(); } } }); dlg.create(); dlg.show(); } }); } /** * Load Cordova configuration from res/xml/cordova.xml. * Approved list of URLs that can be loaded into DroidGap * <access origin="http://server regexp" subdomains="true" /> * Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR) * <log level="DEBUG" /> */ private void loadConfiguration() { int id = getResources().getIdentifier("cordova", "xml", getPackageName()); if (id == 0) { LOG.i("CordovaLog", "cordova.xml missing. Ignoring..."); return; } XmlResourceParser xml = getResources().getXml(id); int eventType = -1; while (eventType != XmlResourceParser.END_DOCUMENT) { if (eventType == XmlResourceParser.START_TAG) { String strNode = xml.getName(); if (strNode.equals("access")) { String origin = xml.getAttributeValue(null, "origin"); String subdomains = xml.getAttributeValue(null, "subdomains"); if (origin != null) { this.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0)); } } else if (strNode.equals("log")) { String level = xml.getAttributeValue(null, "level"); LOG.i("CordovaLog", "Found log level %s", level); if (level != null) { LOG.setLogLevel(level); } } else if (strNode.equals("preference")) { String name = xml.getAttributeValue(null, "name"); String value = xml.getAttributeValue(null, "value"); String readonlyString = xml.getAttributeValue(null, "readonly"); boolean readonly = (readonlyString != null && readonlyString.equals("true")); LOG.i("CordovaLog", "Found preference for %s", name); preferences.add(new PreferenceNode(name, value, readonly)); } } try { eventType = xml.next(); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } /** * Add entry to approved list of URLs (whitelist) * * @param origin URL regular expression to allow * @param subdomains T=include all subdomains under origin */ private void addWhiteListEntry(String origin, boolean subdomains) { try { // Unlimited access to network resources if(origin.compareTo("*") == 0) { LOG.d(TAG, "Unlimited access to network resources"); whiteList.add(Pattern.compile(".*")); } else { // specific access // check if subdomains should be included // TODO: we should not add more domains if * has already been added if (subdomains) { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://(.*\\.)?"))); } else { whiteList.add(Pattern.compile("^https?://(.*\\.)?"+origin)); } LOG.d(TAG, "Origin to allow with subdomains: %s", origin); } else { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://"))); } else { whiteList.add(Pattern.compile("^https?://"+origin)); } LOG.d(TAG, "Origin to allow: %s", origin); } } } catch(Exception e) { LOG.d(TAG, "Failed to add origin %s", origin); } } /** * Determine if URL is in approved list of URLs to load. * * @param url * @return */ public boolean isUrlWhiteListed(String url) { // Check to see if we have matched url previously if (whiteListCache.get(url) != null) { return true; } // Look for match in white list Iterator<Pattern> pit = whiteList.iterator(); while (pit.hasNext()) { Pattern p = pit.next(); Matcher m = p.matcher(url); // If match found, then cache it to speed up subsequent comparisons if (m.find()) { whiteListCache.put(url, true); return true; } } return false; } /* * URL stack manipulators */ /** * Returns the top url on the stack without removing it from * the stack. */ public String peekAtUrlStack() { if (urls.size() > 0) { return urls.peek(); } return ""; } /** * Add a url to the stack * * @param url */ public void pushUrl(String url) { urls.push(url); } /* * Hook in DroidGap for menu plugins * */ @Override public boolean onCreateOptionsMenu(Menu menu) { this.postMessage("onCreateOptionsMenu", menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { this.postMessage("onPrepareOptionsMenu", menu); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { this.postMessage("onOptionsItemSelected", item); return true; } public Context getContext() { return this; } public void bindBackButton(boolean override) { // TODO Auto-generated method stub this.bound = override; } public boolean isBackButtonBound() { // TODO Auto-generated method stub return this.bound; } protected Dialog splashDialog; /** * Removes the Dialog that displays the splash screen */ public void removeSplashScreen() { if (splashDialog != null) { splashDialog.dismiss(); splashDialog = null; } } /** * Shows the splash screen over the full Activity */ protected void showSplashScreen(int time) { // Get reference to display Display display = getWindowManager().getDefaultDisplay(); // Create the layout for the dialog LinearLayout root = new LinearLayout(this); root.setMinimumHeight(display.getHeight()); root.setMinimumWidth(display.getWidth()); root.setOrientation(LinearLayout.VERTICAL); root.setBackgroundColor(this.getIntegerProperty("backgroundColor", Color.BLACK)); root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 0.0F)); root.setBackgroundResource(this.splashscreen); // Create and show the dialog splashDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar); splashDialog.setContentView(root); splashDialog.setCancelable(false); splashDialog.show(); // Set Runnable to remove splash screen just in case final Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { removeSplashScreen(); } }, time); } }
framework/src/org/apache/cordova/DroidGap.java
/* 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.cordova; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.cordova.PreferenceNode; import org.apache.cordova.PreferenceSet; import org.apache.cordova.api.IPlugin; import org.apache.cordova.api.LOG; import org.apache.cordova.api.CordovaInterface; import org.apache.cordova.api.PluginManager; import org.xmlpull.v1.XmlPullParserException; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.content.res.XmlResourceParser; import android.graphics.Color; import android.media.AudioManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.view.Display; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebSettings.LayoutAlgorithm; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.LinearLayout; /** * This class is the main Android activity that represents the Cordova * application. It should be extended by the user to load the specific * html file that contains the application. * * As an example: * * package org.apache.cordova.examples; * import android.app.Activity; * import android.os.Bundle; * import org.apache.cordova.*; * * public class Examples extends DroidGap { * @Override * public void onCreate(Bundle savedInstanceState) { * super.onCreate(savedInstanceState); * * // Set properties for activity * super.setStringProperty("loadingDialog", "Title,Message"); // show loading dialog * super.setStringProperty("errorUrl", "file:///android_asset/www/error.html"); // if error loading file in super.loadUrl(). * * // Initialize activity * super.init(); * * // Clear cache if you want * super.appView.clearCache(true); * * // Load your application * super.setIntegerProperty("splashscreen", R.drawable.splash); // load splash.jpg image from the resource drawable directory * super.loadUrl("file:///android_asset/www/index.html", 3000); // show splash screen 3 sec before loading app * } * } * * Properties: The application can be configured using the following properties: * * // Display a native loading dialog when loading app. Format for value = "Title,Message". * // (String - default=null) * super.setStringProperty("loadingDialog", "Wait,Loading Demo..."); * * // Display a native loading dialog when loading sub-pages. Format for value = "Title,Message". * // (String - default=null) * super.setStringProperty("loadingPageDialog", "Loading page..."); * * // Load a splash screen image from the resource drawable directory. * // (Integer - default=0) * super.setIntegerProperty("splashscreen", R.drawable.splash); * * // Set the background color. * // (Integer - default=0 or BLACK) * super.setIntegerProperty("backgroundColor", Color.WHITE); * * // Time in msec to wait before triggering a timeout error when loading * // with super.loadUrl(). (Integer - default=20000) * super.setIntegerProperty("loadUrlTimeoutValue", 60000); * * // URL to load if there's an error loading specified URL with loadUrl(). * // Should be a local URL starting with file://. (String - default=null) * super.setStringProperty("errorUrl", "file:///android_asset/www/error.html"); * * // Enable app to keep running in background. (Boolean - default=true) * super.setBooleanProperty("keepRunning", false); * * Cordova.xml configuration: * Cordova uses a configuration file at res/xml/cordova.xml to specify the following settings. * * Approved list of URLs that can be loaded into DroidGap * <access origin="http://server regexp" subdomains="true" /> * Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR) * <log level="DEBUG" /> * * Cordova plugins: * Cordova uses a file at res/xml/plugins.xml to list all plugins that are installed. * Before using a new plugin, a new element must be added to the file. * name attribute is the service name passed to Cordova.exec() in JavaScript * value attribute is the Java class name to call. * * <plugins> * <plugin name="App" value="org.apache.cordova.App"/> * ... * </plugins> */ public class DroidGap extends Activity implements CordovaInterface { public static String TAG = "DroidGap"; // The webview for our app protected WebView appView; protected WebViewClient webViewClient; private ArrayList<Pattern> whiteList = new ArrayList<Pattern>(); private HashMap<String, Boolean> whiteListCache = new HashMap<String,Boolean>(); protected LinearLayout root; public boolean bound = false; public CallbackServer callbackServer; protected PluginManager pluginManager; protected boolean cancelLoadUrl = false; protected ProgressDialog spinnerDialog = null; // The initial URL for our app // ie http://server/path/index.html#abc?query private String url = null; private Stack<String> urls = new Stack<String>(); // Url was specified from extras (activity was started programmatically) private String initUrl = null; private static int ACTIVITY_STARTING = 0; private static int ACTIVITY_RUNNING = 1; private static int ACTIVITY_EXITING = 2; private int activityState = 0; // 0=starting, 1=running (after 1st resume), 2=shutting down // The base of the initial URL for our app. // Does not include file name. Ends with / // ie http://server/path/ String baseUrl = null; // Plugin to call when activity result is received protected IPlugin activityResultCallback = null; protected boolean activityResultKeepRunning; // Flag indicates that a loadUrl timeout occurred int loadUrlTimeout = 0; // Default background color for activity // (this is not the color for the webview, which is set in HTML) private int backgroundColor = Color.BLACK; /** The authorization tokens. */ private Hashtable<String, AuthenticationToken> authenticationTokens = new Hashtable<String, AuthenticationToken>(); /* * The variables below are used to cache some of the activity properties. */ // Draw a splash screen using an image located in the drawable resource directory. // This is not the same as calling super.loadSplashscreen(url) protected int splashscreen = 0; // LoadUrl timeout value in msec (default of 20 sec) protected int loadUrlTimeoutValue = 20000; // Keep app running when pause is received. (default = true) // If true, then the JavaScript and native code continue to run in the background // when another application (activity) is started. protected boolean keepRunning = true; // preferences read from cordova.xml protected PreferenceSet preferences; /** * Sets the authentication token. * * @param authenticationToken * the authentication token * @param host * the host * @param realm * the realm */ public void setAuthenticationToken(AuthenticationToken authenticationToken, String host, String realm) { if(host == null) { host = ""; } if(realm == null) { realm = ""; } authenticationTokens.put(host.concat(realm), authenticationToken); } /** * Removes the authentication token. * * @param host * the host * @param realm * the realm * @return the authentication token or null if did not exist */ public AuthenticationToken removeAuthenticationToken(String host, String realm) { return authenticationTokens.remove(host.concat(realm)); } /** * Gets the authentication token. * * In order it tries: * 1- host + realm * 2- host * 3- realm * 4- no host, no realm * * @param host * the host * @param realm * the realm * @return the authentication token */ public AuthenticationToken getAuthenticationToken(String host, String realm) { AuthenticationToken token = null; token = authenticationTokens.get(host.concat(realm)); if(token == null) { // try with just the host token = authenticationTokens.get(host); // Try the realm if(token == null) { token = authenticationTokens.get(realm); } // if no host found, just query for default if(token == null) { token = authenticationTokens.get(""); } } return token; } /** * Clear all authentication tokens. */ public void clearAuthenticationTokens() { authenticationTokens.clear(); } /** * Called when the activity is first created. * * @param savedInstanceState */ @Override public void onCreate(Bundle savedInstanceState) { preferences = new PreferenceSet(); // Load Cordova configuration: // white list of allowed URLs // debug setting this.loadConfiguration(); LOG.d(TAG, "DroidGap.onCreate()"); super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_NO_TITLE); if (preferences.prefMatches("fullscreen","true")) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); } // This builds the view. We could probably get away with NOT having a LinearLayout, but I like having a bucket! Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); root = new LinearLayoutSoftKeyboardDetect(this, width, height); root.setOrientation(LinearLayout.VERTICAL); root.setBackgroundColor(this.backgroundColor); root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 0.0F)); // If url was passed in to intent, then init webview, which will load the url Bundle bundle = this.getIntent().getExtras(); if (bundle != null) { String url = bundle.getString("url"); if (url != null) { this.initUrl = url; } } // Setup the hardware volume controls to handle volume control setVolumeControlStream(AudioManager.STREAM_MUSIC); } /** * Create and initialize web container with default web view objects. */ public void init() { this.init(new WebView(DroidGap.this), new CordovaWebViewClient(this), new CordovaChromeClient(DroidGap.this)); } /** * Initialize web container with web view objects. * * @param webView * @param webViewClient * @param webChromeClient */ public void init(WebView webView, WebViewClient webViewClient, WebChromeClient webChromeClient) { LOG.d(TAG, "DroidGap.init()"); // Set up web container this.appView = webView; this.appView.setId(100); this.appView.setLayoutParams(new LinearLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 1.0F)); this.appView.setWebChromeClient(webChromeClient); this.setWebViewClient(this.appView, webViewClient); this.appView.setInitialScale(0); this.appView.setVerticalScrollBarEnabled(false); this.appView.requestFocusFromTouch(); // Enable JavaScript WebSettings settings = this.appView.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL); //Set the nav dump for HTC settings.setNavDump(true); // Enable database settings.setDatabaseEnabled(true); String databasePath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); settings.setDatabasePath(databasePath); // Enable DOM storage settings.setDomStorageEnabled(true); // Enable built-in geolocation settings.setGeolocationEnabled(true); // Add web view but make it invisible while loading URL this.appView.setVisibility(View.INVISIBLE); root.addView(this.appView); setContentView(root); // Clear cancel flag this.cancelLoadUrl = false; // Create plugin manager this.pluginManager = new PluginManager(this.appView, this); } /** * Set the WebViewClient. * * @param appView * @param client */ protected void setWebViewClient(WebView appView, WebViewClient client) { this.webViewClient = client; appView.setWebViewClient(client); } /** * Look at activity parameters and process them. * This must be called from the main UI thread. */ private void handleActivityParameters() { // If backgroundColor this.backgroundColor = this.getIntegerProperty("backgroundColor", Color.BLACK); this.root.setBackgroundColor(this.backgroundColor); // If spashscreen this.splashscreen = this.getIntegerProperty("splashscreen", 0); // If loadUrlTimeoutValue int timeout = this.getIntegerProperty("loadUrlTimeoutValue", 0); if (timeout > 0) { this.loadUrlTimeoutValue = timeout; } // If keepRunning this.keepRunning = this.getBooleanProperty("keepRunning", true); } /** * Load the url into the webview. * * @param url */ public void loadUrl(String url) { // If first page of app, then set URL to load to be the one passed in if (this.initUrl == null || (this.urls.size() > 0)) { this.loadUrlIntoView(url); } // Otherwise use the URL specified in the activity's extras bundle else { this.loadUrlIntoView(this.initUrl); } } /** * Load the url into the webview. * * @param url */ private void loadUrlIntoView(final String url) { if (!url.startsWith("javascript:")) { LOG.d(TAG, "DroidGap.loadUrl(%s)", url); } this.url = url; if (this.baseUrl == null) { int i = url.lastIndexOf('/'); if (i > 0) { this.baseUrl = url.substring(0, i+1); } else { this.baseUrl = this.url + "/"; } } if (!url.startsWith("javascript:")) { LOG.d(TAG, "DroidGap: url=%s baseUrl=%s", url, baseUrl); } // Load URL on UI thread final DroidGap me = this; this.runOnUiThread(new Runnable() { public void run() { // Init web view if not already done if (me.appView == null) { me.init(); } // Handle activity parameters me.handleActivityParameters(); // Track URLs loaded instead of using appView history me.urls.push(url); me.appView.clearHistory(); // Create callback server and plugin manager if (me.callbackServer == null) { me.callbackServer = new CallbackServer(); me.callbackServer.init(url); } else { me.callbackServer.reinit(url); } me.pluginManager.init(); // If loadingDialog property, then show the App loading dialog for first page of app String loading = null; if (me.urls.size() == 1) { loading = me.getStringProperty("loadingDialog", null); } else { loading = me.getStringProperty("loadingPageDialog", null); } if (loading != null) { String title = ""; String message = "Loading Application..."; if (loading.length() > 0) { int comma = loading.indexOf(','); if (comma > 0) { title = loading.substring(0, comma); message = loading.substring(comma+1); } else { title = ""; message = loading; } } me.spinnerStart(title, message); } // Create a timeout timer for loadUrl final int currentLoadUrlTimeout = me.loadUrlTimeout; Runnable runnable = new Runnable() { public void run() { try { synchronized(this) { wait(me.loadUrlTimeoutValue); } } catch (InterruptedException e) { e.printStackTrace(); } // If timeout, then stop loading and handle error if (me.loadUrlTimeout == currentLoadUrlTimeout) { me.appView.stopLoading(); LOG.e(TAG, "DroidGap: TIMEOUT ERROR! - calling webViewClient"); me.webViewClient.onReceivedError(me.appView, -6, "The connection to the server was unsuccessful.", url); } } }; Thread thread = new Thread(runnable); thread.start(); me.appView.loadUrl(url); } }); } /** * Load the url into the webview after waiting for period of time. * This is used to display the splashscreen for certain amount of time. * * @param url * @param time The number of ms to wait before loading webview */ public void loadUrl(final String url, int time) { // If first page of app, then set URL to load to be the one passed in if (this.initUrl == null || (this.urls.size() > 0)) { this.loadUrlIntoView(url, time); } // Otherwise use the URL specified in the activity's extras bundle else { this.loadUrlIntoView(this.initUrl); } } /** * Load the url into the webview after waiting for period of time. * This is used to display the splashscreen for certain amount of time. * * @param url * @param time The number of ms to wait before loading webview */ private void loadUrlIntoView(final String url, final int time) { // Clear cancel flag this.cancelLoadUrl = false; // If not first page of app, then load immediately if (this.urls.size() > 0) { this.loadUrlIntoView(url); } if (!url.startsWith("javascript:")) { LOG.d(TAG, "DroidGap.loadUrl(%s, %d)", url, time); } this.handleActivityParameters(); if (this.splashscreen != 0) { this.showSplashScreen(time); } this.loadUrlIntoView(url); } /** * Cancel loadUrl before it has been loaded. */ public void cancelLoadUrl() { this.cancelLoadUrl = true; } /** * Clear the resource cache. */ public void clearCache() { if (this.appView == null) { this.init(); } this.appView.clearCache(true); } /** * Clear web history in this web view. */ public void clearHistory() { this.urls.clear(); this.appView.clearHistory(); // Leave current url on history stack if (this.url != null) { this.urls.push(this.url); } } /** * Go to previous page in history. (We manage our own history) * * @return true if we went back, false if we are already at top */ public boolean backHistory() { // Check webview first to see if there is a history // This is needed to support curPage#diffLink, since they are added to appView's history, but not our history url array (JQMobile behavior) if (this.appView.canGoBack()) { this.appView.goBack(); return true; } // If our managed history has prev url if (this.urls.size() > 1) { this.urls.pop(); // Pop current url String url = this.urls.pop(); // Pop prev url that we want to load, since it will be added back by loadUrl() this.loadUrl(url); return true; } return false; } @Override /** * Called by the system when the device configuration changes while your activity is running. * * @param Configuration newConfig */ public void onConfigurationChanged(Configuration newConfig) { //don't reload the current page when the orientation is changed super.onConfigurationChanged(newConfig); } /** * Get boolean property for activity. * * @param name * @param defaultValue * @return */ public boolean getBooleanProperty(String name, boolean defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } Boolean p = (Boolean)bundle.get(name); if (p == null) { return defaultValue; } return p.booleanValue(); } /** * Get int property for activity. * * @param name * @param defaultValue * @return */ public int getIntegerProperty(String name, int defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } Integer p = (Integer)bundle.get(name); if (p == null) { return defaultValue; } return p.intValue(); } /** * Get string property for activity. * * @param name * @param defaultValue * @return */ public String getStringProperty(String name, String defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } String p = bundle.getString(name); if (p == null) { return defaultValue; } return p; } /** * Get double property for activity. * * @param name * @param defaultValue * @return */ public double getDoubleProperty(String name, double defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } Double p = (Double)bundle.get(name); if (p == null) { return defaultValue; } return p.doubleValue(); } /** * Set boolean property on activity. * * @param name * @param value */ public void setBooleanProperty(String name, boolean value) { this.getIntent().putExtra(name, value); } /** * Set int property on activity. * * @param name * @param value */ public void setIntegerProperty(String name, int value) { this.getIntent().putExtra(name, value); } /** * Set string property on activity. * * @param name * @param value */ public void setStringProperty(String name, String value) { this.getIntent().putExtra(name, value); } /** * Set double property on activity. * * @param name * @param value */ public void setDoubleProperty(String name, double value) { this.getIntent().putExtra(name, value); } @Override /** * Called when the system is about to start resuming a previous activity. */ protected void onPause() { super.onPause(); // Don't process pause if shutting down, since onDestroy() will be called if (this.activityState == ACTIVITY_EXITING) { return; } if (this.appView == null) { return; } // Send pause event to JavaScript this.appView.loadUrl("javascript:try{cordova.fireDocumentEvent('pause');}catch(e){console.log('exception firing pause event from native');};"); // Forward to plugins if (this.pluginManager != null) { this.pluginManager.onPause(this.keepRunning); } // If app doesn't want to run in background if (!this.keepRunning) { // Pause JavaScript timers (including setInterval) this.appView.pauseTimers(); } } @Override /** * Called when the activity receives a new intent **/ protected void onNewIntent(Intent intent) { super.onNewIntent(intent); //Forward to plugins if (this.pluginManager != null) { this.pluginManager.onNewIntent(intent); } } @Override /** * Called when the activity will start interacting with the user. */ protected void onResume() { super.onResume(); if (this.activityState == ACTIVITY_STARTING) { this.activityState = ACTIVITY_RUNNING; return; } if (this.appView == null) { return; } // Send resume event to JavaScript this.appView.loadUrl("javascript:try{cordova.fireDocumentEvent('resume');}catch(e){console.log('exception firing resume event from native');};"); // Forward to plugins if (this.pluginManager != null) { this.pluginManager.onResume(this.keepRunning || this.activityResultKeepRunning); } // If app doesn't want to run in background if (!this.keepRunning || this.activityResultKeepRunning) { // Restore multitasking state if (this.activityResultKeepRunning) { this.keepRunning = this.activityResultKeepRunning; this.activityResultKeepRunning = false; } // Resume JavaScript timers (including setInterval) this.appView.resumeTimers(); } } @Override /** * The final call you receive before your activity is destroyed. */ public void onDestroy() { super.onDestroy(); if (this.appView != null) { // Send destroy event to JavaScript this.appView.loadUrl("javascript:try{cordova.require('cordova/channel').onDestroy.fire();}catch(e){console.log('exception firing destroy event from native');};"); // Load blank page so that JavaScript onunload is called this.appView.loadUrl("about:blank"); // Forward to plugins if (this.pluginManager != null) { this.pluginManager.onDestroy(); } } else { this.endActivity(); } } /** * Send a message to all plugins. * * @param id The message id * @param data The message data */ public void postMessage(String id, Object data) { // Forward to plugins if (this.pluginManager != null) { this.pluginManager.postMessage(id, data); } } /** * @deprecated * Add services to res/xml/plugins.xml instead. * * Add a class that implements a service. * * @param serviceType * @param className */ @Deprecated public void addService(String serviceType, String className) { if (this.pluginManager != null) { this.pluginManager.addService(serviceType, className); } } /** * Send JavaScript statement back to JavaScript. * (This is a convenience method) * * @param message */ public void sendJavascript(String statement) { //We need to check for the null case on the Kindle Fire beacuse it changes the width and height on load if(this.callbackServer != null) this.callbackServer.sendJavascript(statement); } /** * Load the specified URL in the Cordova webview or a new browser instance. * * NOTE: If openExternal is false, only URLs listed in whitelist can be loaded. * * @param url The url to load. * @param openExternal Load url in browser instead of Cordova webview. * @param clearHistory Clear the history stack, so new page becomes top of history * @param params DroidGap parameters for new app */ public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) { //throws android.content.ActivityNotFoundException { LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap", url, openExternal, clearHistory); // If clearing history if (clearHistory) { this.clearHistory(); } // If loading into our webview if (!openExternal) { // Make sure url is in whitelist if (url.startsWith("file://") || url.indexOf(this.baseUrl) == 0 || isUrlWhiteListed(url)) { // TODO: What about params? // Clear out current url from history, since it will be replacing it if (clearHistory) { this.urls.clear(); } // Load new URL this.loadUrl(url); } // Load in default viewer if not else { LOG.w(TAG, "showWebPage: Cannot load URL into webview since it is not in white list. Loading into browser instead. (URL="+url+")"); try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); this.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } // Load in default view intent else { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); this.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } /** * Show the spinner. Must be called from the UI thread. * * @param title Title of the dialog * @param message The message of the dialog */ public void spinnerStart(final String title, final String message) { if (this.spinnerDialog != null) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } final DroidGap me = this; this.spinnerDialog = ProgressDialog.show(DroidGap.this, title , message, true, true, new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { me.spinnerDialog = null; } }); } /** * Stop spinner. */ public void spinnerStop() { if (this.spinnerDialog != null) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } } /** * End this activity by calling finish for activity */ public void endActivity() { this.activityState = ACTIVITY_EXITING; this.finish(); } /** * Called when a key is de-pressed. (Key UP) * * @param keyCode * @param event */ @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (this.appView == null) { return super.onKeyUp(keyCode, event); } // If back key if (keyCode == KeyEvent.KEYCODE_BACK) { // If back key is bound, then send event to JavaScript if (this.bound) { this.appView.loadUrl("javascript:cordova.fireDocumentEvent('backbutton');"); return true; } else { // If not bound // Go to previous page in webview if it is possible to go back if (this.backHistory()) { return true; } // If not, then invoke behavior of super class else { this.activityState = ACTIVITY_EXITING; return super.onKeyUp(keyCode, event); } } } // If menu key else if (keyCode == KeyEvent.KEYCODE_MENU) { this.appView.loadUrl("javascript:cordova.fireDocumentEvent('menubutton');"); return super.onKeyUp(keyCode, event); } // If search key else if (keyCode == KeyEvent.KEYCODE_SEARCH) { this.appView.loadUrl("javascript:cordova.fireDocumentEvent('searchbutton');"); return true; } return false; } /** * Any calls to Activity.startActivityForResult must use method below, so * the result can be routed to them correctly. * * This is done to eliminate the need to modify DroidGap.java to receive activity results. * * @param intent The intent to start * @param requestCode Identifies who to send the result to * * @throws RuntimeException */ @Override public void startActivityForResult(Intent intent, int requestCode) throws RuntimeException { LOG.d(TAG, "DroidGap.startActivityForResult(intent,%d)", requestCode); super.startActivityForResult(intent, requestCode); } /** * Launch an activity for which you would like a result when it finished. When this activity exits, * your onActivityResult() method will be called. * * @param command The command object * @param intent The intent to start * @param requestCode The request code that is passed to callback to identify the activity */ public void startActivityForResult(IPlugin command, Intent intent, int requestCode) { this.activityResultCallback = command; this.activityResultKeepRunning = this.keepRunning; // If multitasking turned on, then disable it for activities that return results if (command != null) { this.keepRunning = false; } // Start activity super.startActivityForResult(intent, requestCode); } @Override /** * Called when an activity you launched exits, giving you the requestCode you started it with, * the resultCode it returned, and any additional data from it. * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). */ protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); IPlugin callback = this.activityResultCallback; if (callback != null) { callback.onActivityResult(requestCode, resultCode, intent); } } public void setActivityResultCallback(IPlugin plugin) { this.activityResultCallback = plugin; } /** * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). * The errorCode parameter corresponds to one of the ERROR_* constants. * * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. */ public void onReceivedError(final int errorCode, final String description, final String failingUrl) { final DroidGap me = this; // If errorUrl specified, then load it final String errorUrl = me.getStringProperty("errorUrl", null); if ((errorUrl != null) && (errorUrl.startsWith("file://") || errorUrl.indexOf(me.baseUrl) == 0 || isUrlWhiteListed(errorUrl)) && (!failingUrl.equals(errorUrl))) { // Load URL on UI thread me.runOnUiThread(new Runnable() { public void run() { me.showWebPage(errorUrl, false, true, null); } }); } // If not, then display error dialog else { final boolean exit = !(errorCode == WebViewClient.ERROR_HOST_LOOKUP); me.runOnUiThread(new Runnable() { public void run() { if(exit) { me.appView.setVisibility(View.GONE); me.displayError("Application Error", description + " ("+failingUrl+")", "OK", exit); } } }); } } /** * Display an error dialog and optionally exit application. * * @param title * @param message * @param button * @param exit */ public void displayError(final String title, final String message, final String button, final boolean exit) { final DroidGap me = this; me.runOnUiThread(new Runnable() { public void run() { AlertDialog.Builder dlg = new AlertDialog.Builder(me); dlg.setMessage(message); dlg.setTitle(title); dlg.setCancelable(false); dlg.setPositiveButton(button, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (exit) { me.endActivity(); } } }); dlg.create(); dlg.show(); } }); } /** * Load Cordova configuration from res/xml/cordova.xml. * Approved list of URLs that can be loaded into DroidGap * <access origin="http://server regexp" subdomains="true" /> * Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR) * <log level="DEBUG" /> */ private void loadConfiguration() { int id = getResources().getIdentifier("cordova", "xml", getPackageName()); if (id == 0) { LOG.i("CordovaLog", "cordova.xml missing. Ignoring..."); return; } XmlResourceParser xml = getResources().getXml(id); int eventType = -1; while (eventType != XmlResourceParser.END_DOCUMENT) { if (eventType == XmlResourceParser.START_TAG) { String strNode = xml.getName(); if (strNode.equals("access")) { String origin = xml.getAttributeValue(null, "origin"); String subdomains = xml.getAttributeValue(null, "subdomains"); if (origin != null) { this.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0)); } } else if (strNode.equals("log")) { String level = xml.getAttributeValue(null, "level"); LOG.i("CordovaLog", "Found log level %s", level); if (level != null) { LOG.setLogLevel(level); } } else if (strNode.equals("preference")) { String name = xml.getAttributeValue(null, "name"); String value = xml.getAttributeValue(null, "value"); String readonlyString = xml.getAttributeValue(null, "readonly"); boolean readonly = (readonlyString != null && readonlyString.equals("true")); LOG.i("CordovaLog", "Found preference for %s", name); preferences.add(new PreferenceNode(name, value, readonly)); } } try { eventType = xml.next(); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } /** * Add entry to approved list of URLs (whitelist) * * @param origin URL regular expression to allow * @param subdomains T=include all subdomains under origin */ private void addWhiteListEntry(String origin, boolean subdomains) { try { // Unlimited access to network resources if(origin.compareTo("*") == 0) { LOG.d(TAG, "Unlimited access to network resources"); whiteList.add(Pattern.compile(".*")); } else { // specific access // check if subdomains should be included // TODO: we should not add more domains if * has already been added if (subdomains) { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://(.*\\.)?"))); } else { whiteList.add(Pattern.compile("^https?://(.*\\.)?"+origin)); } LOG.d(TAG, "Origin to allow with subdomains: %s", origin); } else { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://"))); } else { whiteList.add(Pattern.compile("^https?://"+origin)); } LOG.d(TAG, "Origin to allow: %s", origin); } } } catch(Exception e) { LOG.d(TAG, "Failed to add origin %s", origin); } } /** * Determine if URL is in approved list of URLs to load. * * @param url * @return */ public boolean isUrlWhiteListed(String url) { // Check to see if we have matched url previously if (whiteListCache.get(url) != null) { return true; } // Look for match in white list Iterator<Pattern> pit = whiteList.iterator(); while (pit.hasNext()) { Pattern p = pit.next(); Matcher m = p.matcher(url); // If match found, then cache it to speed up subsequent comparisons if (m.find()) { whiteListCache.put(url, true); return true; } } return false; } /* * URL stack manipulators */ /** * Returns the top url on the stack without removing it from * the stack. */ public String peekAtUrlStack() { if (urls.size() > 0) { return urls.peek(); } return ""; } /** * Add a url to the stack * * @param url */ public void pushUrl(String url) { urls.push(url); } /* * Hook in DroidGap for menu plugins * */ @Override public boolean onCreateOptionsMenu(Menu menu) { this.postMessage("onCreateOptionsMenu", menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { this.postMessage("onPrepareOptionsMenu", menu); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { this.postMessage("onOptionsItemSelected", item); return true; } public Context getContext() { return this; } public void bindBackButton(boolean override) { // TODO Auto-generated method stub this.bound = override; } public boolean isBackButtonBound() { // TODO Auto-generated method stub return this.bound; } protected Dialog splashDialog; /** * Removes the Dialog that displays the splash screen */ public void removeSplashScreen() { if (splashDialog != null) { splashDialog.dismiss(); splashDialog = null; } } /** * Shows the splash screen over the full Activity */ protected void showSplashScreen(int time) { // Get reference to display Display display = getWindowManager().getDefaultDisplay(); // Create the layout for the dialog LinearLayout root = new LinearLayout(this); root.setMinimumHeight(display.getHeight()); root.setMinimumWidth(display.getWidth()); root.setOrientation(LinearLayout.VERTICAL); root.setBackgroundColor(this.getIntegerProperty("backgroundColor", Color.BLACK)); root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 0.0F)); root.setBackgroundResource(this.splashscreen); // Create and show the dialog splashDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar); splashDialog.setContentView(root); splashDialog.setCancelable(false); splashDialog.show(); // Set Runnable to remove splash screen just in case final Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { removeSplashScreen(); } }, time); } }
Support showing the app title bar through a preference. This does not change the default behaviour, and will only show the title bar when the showTitle preference is true. This allows apps to show and make use of the ActionBar in Android 3.x and 4.0.
framework/src/org/apache/cordova/DroidGap.java
Support showing the app title bar through a preference.
<ide><path>ramework/src/org/apache/cordova/DroidGap.java <ide> LOG.d(TAG, "DroidGap.onCreate()"); <ide> super.onCreate(savedInstanceState); <ide> <del> getWindow().requestFeature(Window.FEATURE_NO_TITLE); <add> if (!preferences.prefMatches("showTitle", "true")) { <add> getWindow().requestFeature(Window.FEATURE_NO_TITLE); <add> } <ide> <ide> if (preferences.prefMatches("fullscreen","true")) { <ide> getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
Java
apache-2.0
9b37565d4047f60a3b7824b831d77ecb10c3854b
0
sourcepit/common-utils
/** * Copyright (c) 2011 Sourcepit.org contributors and others. All rights reserved. This program and the accompanying * materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.sourcepit.common.utils.xml; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public final class XmlUtils { private XmlUtils() { super(); } public static String getEncoding(InputStream inputStream) { return SAXEncodingDetector.parse(inputStream); } public static Document newDocument() { final DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); final DocumentBuilder docBuilder; try { docBuilder = dbfac.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } final Document document = docBuilder.newDocument(); document.setXmlStandalone(true); return document; } public static Document readXml(InputStream inputStream) { try { Document document = newDocumentBuilder().parse(inputStream); document.setXmlStandalone(true); return document; } catch (IOException e) { throw new IllegalArgumentException(e); } catch (SAXException e) { throw new IllegalArgumentException(e); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } } public static Document readXml(File xmlFile) throws IllegalArgumentException { try { Document document = newDocumentBuilder().parse(xmlFile); document.setXmlStandalone(true); return document; } catch (IOException e) { throw new IllegalArgumentException(e); } catch (SAXException e) { throw new IllegalArgumentException(e); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } } private static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(false); factory.setIgnoringElementContentWhitespace(true); return factory.newDocumentBuilder(); } public static void writeXml(Document doc, OutputStream outputStream) { try { // Prepare the DOM document for writing Source source = new DOMSource(doc); // Prepare the output file Result result = new StreamResult(outputStream); // Write the DOM document to the file Transformer xformer = TransformerFactory.newInstance().newTransformer(); try { xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3"); } catch (IllegalArgumentException e) { // ignore } try { xformer.setOutputProperty(OutputKeys.INDENT, "yes"); } catch (IllegalArgumentException e) { // ignore } xformer.transform(source, result); } catch (TransformerConfigurationException e) { throw new IllegalStateException(e); } catch (TransformerException e) { throw new IllegalStateException(e); } } // This method writes a DOM document to a file public static void writeXml(Document doc, File file) { try { // Prepare the DOM document for writing Source source = new DOMSource(doc); // Prepare the output file Result result = new StreamResult(file); // Write the DOM document to the file Transformer xformer = TransformerFactory.newInstance().newTransformer(); try { xformer.setOutputProperty(OutputKeys.INDENT, "yes"); } catch (IllegalArgumentException e) { // ignore } xformer.transform(source, result); } catch (TransformerConfigurationException e) { throw new IllegalStateException(e); } catch (TransformerException e) { throw new IllegalStateException(e); } } public static Iterable<Node> queryNodes(Document document, String xPath) { return toIterable(queryNodeList(document, xPath)); } public static Node queryNode(Document document, String xPath) { try { XPathExpression expr = XPathFactory.newInstance().newXPath().compile(xPath); return (Node) expr.evaluate(document, XPathConstants.NODE); } catch (XPathExpressionException e) { throw new IllegalArgumentException(e); } } public static NodeList queryNodeList(Document document, String xPath) { try { XPathExpression expr = XPathFactory.newInstance().newXPath().compile(xPath); return (NodeList) expr.evaluate(document, XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new IllegalArgumentException(e); } } public static Iterable<Node> toIterable(NodeList nodeList) { return nodeList == null ? DomIterable.EMPTY_ITERABLE : new DomIterable(nodeList); } public static String queryText(Document document, String xPath) { try { XPathExpression expr = XPathFactory.newInstance().newXPath().compile(xPath); return (String) expr.evaluate(document, XPathConstants.STRING); } catch (XPathExpressionException e) { throw new IllegalArgumentException(e); } } public static class DomIterable implements Iterable<Node> { private static final DomIterable EMPTY_ITERABLE = new DomIterable(new NodeList() { public Node item(int index) { return null; } public int getLength() { return 0; } }); private final NodeList nodeList; public DomIterable(NodeList nodeList) { this.nodeList = nodeList; } public static Iterable<Node> newIterable(Element element, String tagName) { return new DomIterable(element.getElementsByTagName(tagName)); } public static Iterable<Node> newIterable(Document document, String tagName) { return new DomIterable(document.getElementsByTagName(tagName)); } public static Iterable<Node> newIterable(Node node, String tagName) { if (node instanceof Element) { return newIterable((Element) node, tagName); } else if (node instanceof Document) { return newIterable((Document) node, tagName); } return EMPTY_ITERABLE; } public Iterator<Node> iterator() { return new NodeIterator(nodeList); } } private static class NodeIterator implements Iterator<Node>, Iterable<Node> { private final NodeList nodeList; private int i = 0; public NodeIterator(NodeList nodeList) { this.nodeList = nodeList; } public boolean hasNext() { return nodeList.getLength() > i; } public Node next() { return nodeList.item(i++); } public void remove() { throw new UnsupportedOperationException(); } public Iterator<Node> iterator() { return this; } } }
src/main/java/org/sourcepit/common/utils/xml/XmlUtils.java
/** * Copyright (c) 2011 Sourcepit.org contributors and others. All rights reserved. This program and the accompanying * materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.sourcepit.common.utils.xml; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public final class XmlUtils { private XmlUtils() { super(); } public static String getEncoding(InputStream inputStream) { return SAXEncodingDetector.parse(inputStream); } public static Document newDocument() { final DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); final DocumentBuilder docBuilder; try { docBuilder = dbfac.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } return docBuilder.newDocument(); } public static Document readXml(InputStream inputStream) { try { return newDocumentBuilder().parse(inputStream); } catch (IOException e) { throw new IllegalArgumentException(e); } catch (SAXException e) { throw new IllegalArgumentException(e); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } } public static Document readXml(File xmlFile) throws IllegalArgumentException { try { return newDocumentBuilder().parse(xmlFile); } catch (IOException e) { throw new IllegalArgumentException(e); } catch (SAXException e) { throw new IllegalArgumentException(e); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } } private static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(false); factory.setIgnoringElementContentWhitespace(true); return factory.newDocumentBuilder(); } public static void writeXml(Document doc, OutputStream outputStream) { try { // Prepare the DOM document for writing Source source = new DOMSource(doc); // Prepare the output file Result result = new StreamResult(outputStream); // Write the DOM document to the file Transformer xformer = TransformerFactory.newInstance().newTransformer(); try { xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3"); } catch (IllegalArgumentException e) { // ignore } try { xformer.setOutputProperty(OutputKeys.INDENT, "yes"); } catch (IllegalArgumentException e) { // ignore } xformer.transform(source, result); } catch (TransformerConfigurationException e) { throw new IllegalStateException(e); } catch (TransformerException e) { throw new IllegalStateException(e); } } // This method writes a DOM document to a file public static void writeXml(Document doc, File file) { try { // Prepare the DOM document for writing Source source = new DOMSource(doc); // Prepare the output file Result result = new StreamResult(file); // Write the DOM document to the file Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(source, result); } catch (TransformerConfigurationException e) { throw new IllegalStateException(e); } catch (TransformerException e) { throw new IllegalStateException(e); } } public static Iterable<Node> queryNodes(Document document, String xPath) { return toIterable(queryNodeList(document, xPath)); } public static Node queryNode(Document document, String xPath) { try { XPathExpression expr = XPathFactory.newInstance().newXPath().compile(xPath); return (Node) expr.evaluate(document, XPathConstants.NODE); } catch (XPathExpressionException e) { throw new IllegalArgumentException(e); } } public static NodeList queryNodeList(Document document, String xPath) { try { XPathExpression expr = XPathFactory.newInstance().newXPath().compile(xPath); return (NodeList) expr.evaluate(document, XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new IllegalArgumentException(e); } } public static Iterable<Node> toIterable(NodeList nodeList) { return nodeList == null ? DomIterable.EMPTY_ITERABLE : new DomIterable(nodeList); } public static String queryText(Document document, String xPath) { try { XPathExpression expr = XPathFactory.newInstance().newXPath().compile(xPath); return (String) expr.evaluate(document, XPathConstants.STRING); } catch (XPathExpressionException e) { throw new IllegalArgumentException(e); } } public static class DomIterable implements Iterable<Node> { private static final DomIterable EMPTY_ITERABLE = new DomIterable(new NodeList() { public Node item(int index) { return null; } public int getLength() { return 0; } }); private final NodeList nodeList; public DomIterable(NodeList nodeList) { this.nodeList = nodeList; } public static Iterable<Node> newIterable(Element element, String tagName) { return new DomIterable(element.getElementsByTagName(tagName)); } public static Iterable<Node> newIterable(Document document, String tagName) { return new DomIterable(document.getElementsByTagName(tagName)); } public static Iterable<Node> newIterable(Node node, String tagName) { if (node instanceof Element) { return newIterable((Element) node, tagName); } else if (node instanceof Document) { return newIterable((Document) node, tagName); } return EMPTY_ITERABLE; } public Iterator<Node> iterator() { return new NodeIterator(nodeList); } } private static class NodeIterator implements Iterator<Node>, Iterable<Node> { private final NodeList nodeList; private int i = 0; public NodeIterator(NodeList nodeList) { this.nodeList = nodeList; } public boolean hasNext() { return nodeList.getLength() > i; } public Node next() { return nodeList.item(i++); } public void remove() { throw new UnsupportedOperationException(); } public Iterator<Node> iterator() { return this; } } }
Improved XmlUtils (ident on write, xml doc standalone 'yes')
src/main/java/org/sourcepit/common/utils/xml/XmlUtils.java
Improved XmlUtils (ident on write, xml doc standalone 'yes')
<ide><path>rc/main/java/org/sourcepit/common/utils/xml/XmlUtils.java <ide> { <ide> throw new IllegalStateException(e); <ide> } <del> return docBuilder.newDocument(); <add> final Document document = docBuilder.newDocument(); <add> document.setXmlStandalone(true); <add> return document; <ide> } <ide> <ide> public static Document readXml(InputStream inputStream) <ide> { <ide> try <ide> { <del> return newDocumentBuilder().parse(inputStream); <add> Document document = newDocumentBuilder().parse(inputStream); <add> document.setXmlStandalone(true); <add> return document; <ide> } <ide> catch (IOException e) <ide> { <ide> { <ide> try <ide> { <del> return newDocumentBuilder().parse(xmlFile); <add> Document document = newDocumentBuilder().parse(xmlFile); <add> document.setXmlStandalone(true); <add> return document; <ide> } <ide> catch (IOException e) <ide> { <ide> <ide> // Write the DOM document to the file <ide> Transformer xformer = TransformerFactory.newInstance().newTransformer(); <add> <add> try <add> { <add> xformer.setOutputProperty(OutputKeys.INDENT, "yes"); <add> } <add> catch (IllegalArgumentException e) <add> { // ignore <add> } <add> <ide> xformer.transform(source, result); <ide> } <ide> catch (TransformerConfigurationException e)
Java
apache-2.0
d1ba2ca5619f27b2f76210d65ce79bbb69e1b818
0
timlevett/uPortal,apetro/uPortal,doodelicious/uPortal,GIP-RECIA/esco-portail,kole9273/uPortal,GIP-RECIA/esup-uportal,ASU-Capstone/uPortal-Forked,stalele/uPortal,jameswennmacher/uPortal,chasegawa/uPortal,joansmith/uPortal,kole9273/uPortal,vbonamy/esup-uportal,doodelicious/uPortal,cousquer/uPortal,Jasig/uPortal-start,apetro/uPortal,EdiaEducationTechnology/uPortal,Mines-Albi/esup-uportal,stalele/uPortal,Jasig/SSP-Platform,EsupPortail/esup-uportal,vbonamy/esup-uportal,jhelmer-unicon/uPortal,pspaude/uPortal,joansmith/uPortal,EdiaEducationTechnology/uPortal,ASU-Capstone/uPortal,drewwills/uPortal,chasegawa/uPortal,bjagg/uPortal,ASU-Capstone/uPortal,drewwills/uPortal,drewwills/uPortal,pspaude/uPortal,andrewstuart/uPortal,GIP-RECIA/esup-uportal,phillips1021/uPortal,groybal/uPortal,joansmith/uPortal,GIP-RECIA/esco-portail,ASU-Capstone/uPortal,andrewstuart/uPortal,Jasig/uPortal-start,jonathanmtran/uPortal,doodelicious/uPortal,jonathanmtran/uPortal,EsupPortail/esup-uportal,andrewstuart/uPortal,Jasig/uPortal,joansmith/uPortal,groybal/uPortal,jhelmer-unicon/uPortal,Mines-Albi/esup-uportal,stalele/uPortal,jameswennmacher/uPortal,MichaelVose2/uPortal,ASU-Capstone/uPortal,drewwills/uPortal,phillips1021/uPortal,jl1955/uPortal5,cousquer/uPortal,bjagg/uPortal,andrewstuart/uPortal,vertein/uPortal,Jasig/SSP-Platform,andrewstuart/uPortal,jl1955/uPortal5,jl1955/uPortal5,vertein/uPortal,mgillian/uPortal,doodelicious/uPortal,ASU-Capstone/uPortal-Forked,phillips1021/uPortal,chasegawa/uPortal,vbonamy/esup-uportal,Mines-Albi/esup-uportal,GIP-RECIA/esup-uportal,groybal/uPortal,ASU-Capstone/uPortal-Forked,groybal/uPortal,stalele/uPortal,kole9273/uPortal,jameswennmacher/uPortal,GIP-RECIA/esup-uportal,Jasig/SSP-Platform,doodelicious/uPortal,stalele/uPortal,jhelmer-unicon/uPortal,pspaude/uPortal,ASU-Capstone/uPortal,vertein/uPortal,ChristianMurphy/uPortal,apetro/uPortal,jl1955/uPortal5,jl1955/uPortal5,jhelmer-unicon/uPortal,Jasig/SSP-Platform,ASU-Capstone/uPortal-Forked,mgillian/uPortal,Jasig/SSP-Platform,kole9273/uPortal,apetro/uPortal,ChristianMurphy/uPortal,mgillian/uPortal,jonathanmtran/uPortal,kole9273/uPortal,cousquer/uPortal,EdiaEducationTechnology/uPortal,jameswennmacher/uPortal,jameswennmacher/uPortal,bjagg/uPortal,chasegawa/uPortal,joansmith/uPortal,jhelmer-unicon/uPortal,Jasig/uPortal,timlevett/uPortal,GIP-RECIA/esco-portail,Jasig/uPortal,EsupPortail/esup-uportal,pspaude/uPortal,vbonamy/esup-uportal,phillips1021/uPortal,timlevett/uPortal,EsupPortail/esup-uportal,Mines-Albi/esup-uportal,MichaelVose2/uPortal,MichaelVose2/uPortal,Mines-Albi/esup-uportal,ASU-Capstone/uPortal-Forked,GIP-RECIA/esup-uportal,apetro/uPortal,groybal/uPortal,EsupPortail/esup-uportal,MichaelVose2/uPortal,chasegawa/uPortal,timlevett/uPortal,EdiaEducationTechnology/uPortal,MichaelVose2/uPortal,ChristianMurphy/uPortal,phillips1021/uPortal,vertein/uPortal,vbonamy/esup-uportal
/* Copyright 2004 The JA-SIG Collaborative. All rights reserved. * See license distributed with this file and * available online at http://www.uportal.org/license.html */ package org.jasig.portal.services.persondir.support; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * @author Eric Dalquist <a href="mailto:[email protected]">[email protected]</a> * @version $Revision$ $Date$ * @since uPortal 2.5 */ public final class MultivaluedPersonAttributeUtils { /** * Translate from a more flexible Attribute to Attribute mapping format to a Map * from String to Set of Strings. * * The point of the map is to map from attribute names in the underlying data store * (e.g., JDBC column names, LDAP attribute names) to uPortal attribute names. * Any given underlying data store attribute might map to zero uPortal * attributes (not appear in the map at all), map to exactly one uPortal attribute * (appear in the Map as a mapping from a String to a String or as a mapping * from a String to a Set containing just one String), or map to several uPortal * attribute names (appear in the Map as a mapping from a String to a Set * of Strings). * * This method takes as its argument a {@link Map} that must have keys of * type {@link String} and values of type {@link String} or {@link Set} of * {@link String}s. The argument must not be null and must have no null * keys or null values. It must contain no keys other than Strings and no * values other than Strings or Sets of Strings. This method will throw * IllegalArgumentException if the method argument doesn't meet these * requirements. * * This method returns a Map equivalent to its argument except whereever there * was a String value in the Map there will instead be an immutable Set containing * the String value. That is, the return value is normalized to be a Map from * String to Set (of String). * * @param mapping {@link Map} from String names of attributes in the underlying store * to uP attribute names or Sets of such names. * @return a Map from String to Set of Strings * @throws IllegalArgumentException If the {@link Map} doesn't follow the rules stated above. */ static Map parseAttributeToAttributeMapping(final Map mapping) { //null is assumed to be an empty map if (mapping == null) { return Collections.EMPTY_MAP; } //do a defenisve copy of the map final Map mappedAttributesBuilder = new HashMap(); for (final Iterator sourceAttrNameItr = mapping.keySet().iterator(); sourceAttrNameItr.hasNext(); ) { final Object key = sourceAttrNameItr.next(); //The key must exist if (key == null) { throw new IllegalArgumentException("The map from attribute names to attributes must not have any null keys."); } // the key must be of type String if (! (key instanceof String)) { throw new IllegalArgumentException("The map from attribute names to attributes must only have String keys. Encountered a key of class [" + key.getClass().getName() + "]"); } final String sourceAttrName = (String) key; final Object mappedAttribute = mapping.get(sourceAttrName); //mapping cannot be null if (mappedAttribute == null) throw new IllegalArgumentException("Values in the map cannot be null. key='" + sourceAttrName + "'"); //Create a single item set for the string mapping if (mappedAttribute instanceof String) { final Set mappedSet = Collections.singleton(mappedAttribute); mappedAttributesBuilder.put(sourceAttrName, mappedSet); } //Create a defenisve copy of the mapped set & verify its contents are strings else if (mappedAttribute instanceof Set) { final Set sourceSet = (Set)mappedAttribute; final Set mappedSet = new HashSet(); for (final Iterator sourceSetItr = sourceSet.iterator(); sourceSetItr.hasNext(); ) { final Object mappedAttributeName = sourceSetItr.next(); if (mappedAttributeName instanceof String) { mappedSet.add(mappedAttributeName); } else { throw new IllegalArgumentException("Invalid mapped type. key='" + sourceAttrName + "', value type='" + mappedAttribute.getClass().getName() + "', sub value type='" + mappedAttributeName.getClass().getName() + "'"); } } mappedAttributesBuilder.put(sourceAttrName, Collections.unmodifiableSet(mappedSet)); } //Not a valid type for the mapping else { throw new IllegalArgumentException("Invalid mapped type. key='" + sourceAttrName + "', value type='" + mappedAttribute.getClass().getName() + "'"); } } return Collections.unmodifiableMap(mappedAttributesBuilder); } /** * Adds a key/value pair to the specified {@link Map}, creating multi-valued * values when appropriate. * <br> * Since multi-valued attributes end up with a value of type * {@link List}, passing in a {@link List} of any type will * cause its contents to be added to the <code>results</code> * {@link Map} directly under the specified <code>key</code> * * @param results The {@link Map} to modify. * @param key The key to add the value for. * @param value The value to add for the key. * @throws IllegalArgumentException if any argument is null */ static void addResult(final Map results, final Object key, final Object value) { if (results == null) { throw new IllegalArgumentException("Cannot add a result to a null map."); } if (key == null) { throw new IllegalArgumentException("Cannot add a result with a null key."); } if (value == null) { throw new IllegalArgumentException("Cannot add a result with a null value."); } final Object currentValue = results.get(key); //Key doesn't have a value yet, add the value if (currentValue == null) { results.put(key, value); } //Set of values else if (value instanceof List) { final List newValues = (List)value; //Key exists with List, add to it if (currentValue instanceof List) { final List values = (List)currentValue; values.addAll(newValues); results.put(key, values); } //Key exists with a single value, create a List else { final List values = new ArrayList(newValues.size() + 1); values.add(currentValue); values.addAll(newValues); results.put(key, values); } } //Standard value else { //Key exists with List, add to it if (currentValue instanceof List) { final List values = (List)currentValue; values.add(value); results.put(key, values); } //Key exists with a single value, create a List else { final List values = new ArrayList(2); values.add(currentValue); values.add(value); results.put(key, values); } } } /** * Takes a {@link Collection} and creates a flattened {@link Collection} out * of it. * * @param source The {@link Collection} to flatten. * @return A flattened {@link Collection} that contains all entries from all levels of <code>source</code>. */ static Collection flattenCollection(final Collection source) { if (source == null) { throw new IllegalArgumentException("Cannot flatten a null collection."); } final Collection result = new LinkedList(); for (final Iterator setItr = source.iterator(); setItr.hasNext();) { final Object value = setItr.next(); if (value instanceof Collection) { final Collection flatCollection = flattenCollection((Collection)value); result.addAll(flatCollection); } else { result.add(value); } } return result; } /** * This class is not meant to be instantiated. */ private MultivaluedPersonAttributeUtils() { // private constructor makes this static utility method class // uninstantiable. } }
source/org/jasig/portal/services/persondir/support/MultivaluedPersonAttributeUtils.java
/* Copyright 2004 The JA-SIG Collaborative. All rights reserved. * See license distributed with this file and * available online at http://www.uportal.org/license.html */ package org.jasig.portal.services.persondir.support; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * @author Eric Dalquist <a href="mailto:[email protected]">[email protected]</a> * @version $Revision$ $Date$ * @since uPortal 2.5 */ public final class MultivaluedPersonAttributeUtils { private MultivaluedPersonAttributeUtils() { } /** * Set the {@link Map} to use for mapping from a attribute name to another * attribute name or {@link Set} of attribute names. * <br> * The passed {@link Map} must have keys of type {@link String} and values * of type {@link String} or a {@link Set} of {@link String}. * * @param mapping {@link Map} from column names to attribute names. * @throws IllegalArgumentException If the {@link Map} doesn't follow the rules stated above. */ public static Map parseAttributeToAttributeMapping(final Map mapping) { //null is assumed to be an empty map if (mapping == null) { return Collections.EMPTY_MAP; } //do a defenisve copy of the map else { final Map mappedAttributesBuilder = new HashMap(); for (final Iterator sourceAttrNameItr = mapping.keySet().iterator(); sourceAttrNameItr.hasNext(); ) { final String sourceAttrName = (String)sourceAttrNameItr.next(); //The column name must exist if (sourceAttrName == null) throw new IllegalArgumentException("The map from attribute names to attributes must not have any null keys."); final Object mappedAttribute = mapping.get(sourceAttrName); //mapping cannot be null if (mappedAttribute == null) throw new IllegalArgumentException("Values in the map cannot be null. key='" + sourceAttrName + "'"); //Create a single item set for the string mapping if (mappedAttribute instanceof String) { final Set mappedSet = Collections.singleton(mappedAttribute); mappedAttributesBuilder.put(sourceAttrName, mappedSet); } //Create a defenisve copy of the mapped set & verify it's contents are strings else if (mappedAttribute instanceof Set) { final Set sourceSet = (Set)mappedAttribute; final Set mappedSet = new HashSet(); for (final Iterator sourceSetItr = sourceSet.iterator(); sourceSetItr.hasNext(); ) { final Object mappedAttributeName = sourceSetItr.next(); if (mappedAttributeName instanceof String) { mappedSet.add(mappedAttributeName); } else { throw new IllegalArgumentException("Invalid mapped type. key='" + sourceAttrName + "', value type='" + mappedAttribute.getClass().getName() + "', sub value type='" + mappedAttributeName.getClass().getName() + "'"); } } mappedAttributesBuilder.put(sourceAttrName, Collections.unmodifiableSet(mappedSet)); } //Not a valid type for the mapping else { throw new IllegalArgumentException("Invalid mapped type. key='" + sourceAttrName + "', value type='" + mappedAttribute.getClass().getName() + "'"); } } return Collections.unmodifiableMap(mappedAttributesBuilder); } } /** * Adds a key/value pair to the specified {@link Map}, creating multi-valued * values when appropriate. * <br> * Since multi-valued attributes end up with a value of type * {@link List}, passing in a {@link List} of any type will * cause it's contents to be added to the <code>results</code> * {@link Map} directly under the specified <code>key</code> * * @param results The {@link Map} to modify. * @param key The key to add the value for. * @param value The value to add for the key. */ public static void addResult(final Map results, final Object key, final Object value) { final Object currentValue = results.get(key); //Key doesn't have a value yet, add the value if (currentValue == null) { results.put(key, value); } //Set of values else if (value instanceof List) { final List newValues = (List)value; //Key exists with List, add to it if (currentValue instanceof List) { final List values = (List)currentValue; values.addAll(newValues); results.put(key, values); } //Key exists with a single value, create a List else { final List values = new ArrayList(newValues.size() + 1); values.add(currentValue); values.addAll(newValues); results.put(key, values); } } //Standard value else { //Key exists with List, add to it if (currentValue instanceof List) { final List values = (List)currentValue; values.add(value); results.put(key, values); } //Key exists with a single value, create a List else { final List values = new ArrayList(2); values.add(currentValue); values.add(value); results.put(key, values); } } } /** * Takes a {@link Collection} and creates a flattened {@link Collection} out * of it. * * @param source The {@link Collection} to flatten. * @return A flattened {@link Collection} that contains all entries from all levels of <code>source</code>. */ public static Collection flattenCollection(final Collection source) { final Collection result = new LinkedList(); for (final Iterator setItr = source.iterator(); setItr.hasNext();) { final Object value = setItr.next(); if (value instanceof Collection) { final Collection flatCollection = flattenCollection((Collection)value); result.addAll(flatCollection); } else { result.add(value); } } return result; } }
UP-777 JavaDoc improvements, argument checking. git-svn-id: 477788cc2a8229a747c5b8073e47c1d0f6ec0604@10055 f5dbab47-78f9-eb45-b975-e544023573eb
source/org/jasig/portal/services/persondir/support/MultivaluedPersonAttributeUtils.java
UP-777 JavaDoc improvements, argument checking.
<ide><path>ource/org/jasig/portal/services/persondir/support/MultivaluedPersonAttributeUtils.java <ide> * @since uPortal 2.5 <ide> */ <ide> public final class MultivaluedPersonAttributeUtils { <del> private MultivaluedPersonAttributeUtils() { } <del> <del> /** <del> * Set the {@link Map} to use for mapping from a attribute name to another <del> * attribute name or {@link Set} of attribute names. <del> * <br> <del> * The passed {@link Map} must have keys of type {@link String} and values <del> * of type {@link String} or a {@link Set} of {@link String}. <del> * <del> * @param mapping {@link Map} from column names to attribute names. <add> <add> <add> /** <add> * Translate from a more flexible Attribute to Attribute mapping format to a Map <add> * from String to Set of Strings. <add> * <add> * The point of the map is to map from attribute names in the underlying data store <add> * (e.g., JDBC column names, LDAP attribute names) to uPortal attribute names. <add> * Any given underlying data store attribute might map to zero uPortal <add> * attributes (not appear in the map at all), map to exactly one uPortal attribute <add> * (appear in the Map as a mapping from a String to a String or as a mapping <add> * from a String to a Set containing just one String), or map to several uPortal <add> * attribute names (appear in the Map as a mapping from a String to a Set <add> * of Strings). <add> * <add> * This method takes as its argument a {@link Map} that must have keys of <add> * type {@link String} and values of type {@link String} or {@link Set} of <add> * {@link String}s. The argument must not be null and must have no null <add> * keys or null values. It must contain no keys other than Strings and no <add> * values other than Strings or Sets of Strings. This method will throw <add> * IllegalArgumentException if the method argument doesn't meet these <add> * requirements. <add> * <add> * This method returns a Map equivalent to its argument except whereever there <add> * was a String value in the Map there will instead be an immutable Set containing <add> * the String value. That is, the return value is normalized to be a Map from <add> * String to Set (of String). <add> * <add> * @param mapping {@link Map} from String names of attributes in the underlying store <add> * to uP attribute names or Sets of such names. <add> * @return a Map from String to Set of Strings <ide> * @throws IllegalArgumentException If the {@link Map} doesn't follow the rules stated above. <ide> */ <del> public static Map parseAttributeToAttributeMapping(final Map mapping) { <add> static Map parseAttributeToAttributeMapping(final Map mapping) { <ide> //null is assumed to be an empty map <ide> if (mapping == null) { <ide> return Collections.EMPTY_MAP; <ide> } <ide> //do a defenisve copy of the map <del> else { <ide> final Map mappedAttributesBuilder = new HashMap(); <ide> <ide> for (final Iterator sourceAttrNameItr = mapping.keySet().iterator(); sourceAttrNameItr.hasNext(); ) { <del> final String sourceAttrName = (String)sourceAttrNameItr.next(); <del> <del> //The column name must exist <del> if (sourceAttrName == null) <add> final Object key = sourceAttrNameItr.next(); <add> <add> //The key must exist <add> if (key == null) { <ide> throw new IllegalArgumentException("The map from attribute names to attributes must not have any null keys."); <del> <add> } <add> <add> // the key must be of type String <add> if (! (key instanceof String)) { <add> throw new IllegalArgumentException("The map from attribute names to attributes must only have String keys. Encountered a key of class [" + key.getClass().getName() + "]"); <add> } <add> <add> final String sourceAttrName = (String) key; <add> <add> <ide> final Object mappedAttribute = mapping.get(sourceAttrName); <ide> <ide> //mapping cannot be null <ide> final Set mappedSet = Collections.singleton(mappedAttribute); <ide> mappedAttributesBuilder.put(sourceAttrName, mappedSet); <ide> } <del> //Create a defenisve copy of the mapped set & verify it's contents are strings <add> //Create a defenisve copy of the mapped set & verify its contents are strings <ide> else if (mappedAttribute instanceof Set) { <ide> final Set sourceSet = (Set)mappedAttribute; <ide> final Set mappedSet = new HashSet(); <ide> } <ide> <ide> return Collections.unmodifiableMap(mappedAttributesBuilder); <del> } <ide> } <ide> <ide> /** <ide> * <br> <ide> * Since multi-valued attributes end up with a value of type <ide> * {@link List}, passing in a {@link List} of any type will <del> * cause it's contents to be added to the <code>results</code> <add> * cause its contents to be added to the <code>results</code> <ide> * {@link Map} directly under the specified <code>key</code> <ide> * <ide> * @param results The {@link Map} to modify. <ide> * @param key The key to add the value for. <ide> * @param value The value to add for the key. <del> */ <del> public static void addResult(final Map results, final Object key, final Object value) { <add> * @throws IllegalArgumentException if any argument is null <add> */ <add> static void addResult(final Map results, final Object key, final Object value) { <add> <add> if (results == null) { <add> throw new IllegalArgumentException("Cannot add a result to a null map."); <add> } <add> <add> if (key == null) { <add> throw new IllegalArgumentException("Cannot add a result with a null key."); <add> } <add> <add> if (value == null) { <add> throw new IllegalArgumentException("Cannot add a result with a null value."); <add> } <add> <ide> final Object currentValue = results.get(key); <ide> <ide> //Key doesn't have a value yet, add the value <ide> * @param source The {@link Collection} to flatten. <ide> * @return A flattened {@link Collection} that contains all entries from all levels of <code>source</code>. <ide> */ <del> public static Collection flattenCollection(final Collection source) { <add> static Collection flattenCollection(final Collection source) { <add> <add> if (source == null) { <add> throw new IllegalArgumentException("Cannot flatten a null collection."); <add> } <add> <ide> final Collection result = new LinkedList(); <ide> <ide> for (final Iterator setItr = source.iterator(); setItr.hasNext();) { <ide> <ide> return result; <ide> } <add> <add> /** <add> * This class is not meant to be instantiated. <add> */ <add> private MultivaluedPersonAttributeUtils() { <add> // private constructor makes this static utility method class <add> // uninstantiable. <add> } <ide> }
Java
mit
e790c7082d58c5a23bea342df98bf78b41142ad6
0
ruediger-w/opacclient,opacapp/opacclient,johan12345/opacclient,raphaelm/opacclient,ruediger-w/opacclient,raphaelm/opacclient,johan12345/opacclient,johan12345/opacclient,opacapp/opacclient,johan12345/opacclient,ruediger-w/opacclient,opacapp/opacclient,opacapp/opacclient,opacapp/opacclient,ruediger-w/opacclient,johan12345/opacclient,ruediger-w/opacclient,raphaelm/opacclient
/* * Copyright (C) 2015 by Johan von Forstner under the MIT license: * * 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 de.geeksfactory.opacclient.apis; import org.apache.http.client.utils.URIBuilder; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.FormElement; import org.jsoup.select.Elements; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import de.geeksfactory.opacclient.i18n.StringProvider; import de.geeksfactory.opacclient.networking.HttpClientFactory; import de.geeksfactory.opacclient.networking.NotReachableException; import de.geeksfactory.opacclient.objects.Account; import de.geeksfactory.opacclient.objects.AccountData; import de.geeksfactory.opacclient.objects.Copy; import de.geeksfactory.opacclient.objects.CoverHolder; import de.geeksfactory.opacclient.objects.Detail; import de.geeksfactory.opacclient.objects.DetailedItem; import de.geeksfactory.opacclient.objects.Filter; import de.geeksfactory.opacclient.objects.Library; import de.geeksfactory.opacclient.objects.SearchRequestResult; import de.geeksfactory.opacclient.objects.SearchResult; import de.geeksfactory.opacclient.objects.Volume; import de.geeksfactory.opacclient.searchfields.BarcodeSearchField; import de.geeksfactory.opacclient.searchfields.CheckboxSearchField; import de.geeksfactory.opacclient.searchfields.DropdownSearchField; import de.geeksfactory.opacclient.searchfields.SearchField; import de.geeksfactory.opacclient.searchfields.SearchQuery; import de.geeksfactory.opacclient.searchfields.TextSearchField; import java8.util.concurrent.CompletableFuture; import okhttp3.Headers; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; import static okhttp3.MultipartBody.Part.create; /** * API for Bibliotheca+/OPEN OPAC software * * @author Johan von Forstner, 29.03.2015 */ public class OpenSearch extends OkHttpBaseApi implements OpacApi { protected JSONObject data; protected String opac_url; protected Document searchResultDoc; protected static HashMap<String, SearchResult.MediaType> defaulttypes = new HashMap<>(); static { // icons defaulttypes.put("archv", SearchResult.MediaType.BOOK); defaulttypes.put("archv-digital", SearchResult.MediaType.EDOC); defaulttypes.put("artchap", SearchResult.MediaType.ART); defaulttypes.put("artchap-artcl", SearchResult.MediaType.ART); defaulttypes.put("artchap-chptr", SearchResult.MediaType.ART); defaulttypes.put("artchap-digital", SearchResult.MediaType.ART); defaulttypes.put("audiobook", SearchResult.MediaType.AUDIOBOOK); defaulttypes.put("audiobook-cd", SearchResult.MediaType.AUDIOBOOK); defaulttypes.put("audiobook-lp", SearchResult.MediaType.AUDIOBOOK); defaulttypes.put("audiobook-digital", SearchResult.MediaType.MP3); defaulttypes.put("book", SearchResult.MediaType.BOOK); defaulttypes.put("book-braille", SearchResult.MediaType.BOOK); defaulttypes.put("book-continuing", SearchResult.MediaType.BOOK); defaulttypes.put("book-digital", SearchResult.MediaType.EBOOK); defaulttypes.put("book-largeprint", SearchResult.MediaType.BOOK); defaulttypes.put("book-mic", SearchResult.MediaType.BOOK); defaulttypes.put("book-thsis", SearchResult.MediaType.BOOK); defaulttypes.put("compfile", SearchResult.MediaType.PACKAGE); defaulttypes.put("compfile-digital", SearchResult.MediaType.PACKAGE); defaulttypes.put("corpprof", SearchResult.MediaType.UNKNOWN); defaulttypes.put("encyc", SearchResult.MediaType.UNKNOWN); defaulttypes.put("game", SearchResult.MediaType.BOARDGAME); defaulttypes.put("game-digital", SearchResult.MediaType.GAME_CONSOLE); defaulttypes.put("image", SearchResult.MediaType.ART); defaulttypes.put("image-2d", SearchResult.MediaType.ART); defaulttypes.put("intmm", SearchResult.MediaType.EVIDEO); defaulttypes.put("intmm-digital", SearchResult.MediaType.EVIDEO); defaulttypes.put("jrnl", SearchResult.MediaType.MAGAZINE); defaulttypes.put("jrnl-issue", SearchResult.MediaType.MAGAZINE); defaulttypes.put("jrnl-digital", SearchResult.MediaType.EBOOK); defaulttypes.put("kit", SearchResult.MediaType.PACKAGE); defaulttypes.put("map", SearchResult.MediaType.MAP); defaulttypes.put("map-digital", SearchResult.MediaType.EBOOK); defaulttypes.put("msscr", SearchResult.MediaType.MP3); defaulttypes.put("msscr-digital", SearchResult.MediaType.MP3); defaulttypes.put("music", SearchResult.MediaType.MP3); defaulttypes.put("music-cassette", SearchResult.MediaType.AUDIO_CASSETTE); defaulttypes.put("music-cd", SearchResult.MediaType.CD_MUSIC); defaulttypes.put("music-digital", SearchResult.MediaType.MP3); defaulttypes.put("music-lp", SearchResult.MediaType.LP_RECORD); defaulttypes.put("news", SearchResult.MediaType.NEWSPAPER); defaulttypes.put("news-digital", SearchResult.MediaType.EBOOK); defaulttypes.put("object", SearchResult.MediaType.UNKNOWN); defaulttypes.put("object-digital", SearchResult.MediaType.UNKNOWN); defaulttypes.put("paper", SearchResult.MediaType.UNKNOWN); defaulttypes.put("pub", SearchResult.MediaType.UNKNOWN); defaulttypes.put("rev", SearchResult.MediaType.UNKNOWN); defaulttypes.put("snd", SearchResult.MediaType.MP3); defaulttypes.put("snd-cassette", SearchResult.MediaType.AUDIO_CASSETTE); defaulttypes.put("snd-cd", SearchResult.MediaType.CD_MUSIC); defaulttypes.put("snd-lp", SearchResult.MediaType.LP_RECORD); defaulttypes.put("snd-digital", SearchResult.MediaType.EAUDIO); defaulttypes.put("toy", SearchResult.MediaType.BOARDGAME); defaulttypes.put("und", SearchResult.MediaType.UNKNOWN); defaulttypes.put("video-bluray", SearchResult.MediaType.BLURAY); defaulttypes.put("video-digital", SearchResult.MediaType.EVIDEO); defaulttypes.put("video-dvd", SearchResult.MediaType.DVD); defaulttypes.put("video-film", SearchResult.MediaType.MOVIE); defaulttypes.put("video-vhs", SearchResult.MediaType.MOVIE); defaulttypes.put("vis", SearchResult.MediaType.ART); defaulttypes.put("vis-digital", SearchResult.MediaType.ART); defaulttypes.put("web", SearchResult.MediaType.URL); defaulttypes.put("web-digital", SearchResult.MediaType.URL); defaulttypes.put("art", SearchResult.MediaType.ART); defaulttypes.put("arturl", SearchResult.MediaType.URL); defaulttypes.put("bks", SearchResult.MediaType.BOOK); defaulttypes.put("bksbrl", SearchResult.MediaType.BOOK); defaulttypes.put("bksdeg", SearchResult.MediaType.BOOK); defaulttypes.put("bkslpt", SearchResult.MediaType.BOOK); defaulttypes.put("bksurl", SearchResult.MediaType.EBOOK); defaulttypes.put("braille", SearchResult.MediaType.BOOK); defaulttypes.put("com", SearchResult.MediaType.CD_SOFTWARE); defaulttypes.put("comcgm", SearchResult.MediaType.GAME_CONSOLE); defaulttypes.put("comcgmurl", SearchResult.MediaType.GAME_CONSOLE); defaulttypes.put("comimm", SearchResult.MediaType.EVIDEO); defaulttypes.put("comimmurl", SearchResult.MediaType.EVIDEO); defaulttypes.put("comurl", SearchResult.MediaType.URL); defaulttypes.put("int", SearchResult.MediaType.UNKNOWN); defaulttypes.put("inturl", SearchResult.MediaType.UNKNOWN); defaulttypes.put("map", SearchResult.MediaType.MAP); defaulttypes.put("mapurl", SearchResult.MediaType.MAP); defaulttypes.put("mic", SearchResult.MediaType.UNKNOWN); defaulttypes.put("micro", SearchResult.MediaType.UNKNOWN); defaulttypes.put("mix", SearchResult.MediaType.PACKAGE); defaulttypes.put("mixurl", SearchResult.MediaType.PACKAGE); defaulttypes.put("rec", SearchResult.MediaType.MP3); defaulttypes.put("recmsr", SearchResult.MediaType.MP3); defaulttypes.put("recmsrcas", SearchResult.MediaType.AUDIO_CASSETTE); defaulttypes.put("recmsrcda", SearchResult.MediaType.CD_MUSIC); defaulttypes.put("recmsrlps", SearchResult.MediaType.LP_RECORD); defaulttypes.put("recmsrurl", SearchResult.MediaType.EAUDIO); defaulttypes.put("recnsr", SearchResult.MediaType.UNKNOWN); defaulttypes.put("recnsrcas", SearchResult.MediaType.UNKNOWN); defaulttypes.put("recnsrcda", SearchResult.MediaType.UNKNOWN); defaulttypes.put("recnsrlps", SearchResult.MediaType.UNKNOWN); defaulttypes.put("recnsrurl", SearchResult.MediaType.UNKNOWN); defaulttypes.put("recurl", SearchResult.MediaType.EAUDIO); defaulttypes.put("sco", SearchResult.MediaType.SCORE_MUSIC); defaulttypes.put("scourl", SearchResult.MediaType.SCORE_MUSIC); defaulttypes.put("ser", SearchResult.MediaType.PACKAGE_BOOKS); defaulttypes.put("sernew", SearchResult.MediaType.PACKAGE_BOOKS); defaulttypes.put("sernewurl", SearchResult.MediaType.PACKAGE_BOOKS); defaulttypes.put("serurl", SearchResult.MediaType.PACKAGE_BOOKS); defaulttypes.put("url", SearchResult.MediaType.URL); defaulttypes.put("vis", SearchResult.MediaType.ART); defaulttypes.put("visart", SearchResult.MediaType.ART); defaulttypes.put("visdvv", SearchResult.MediaType.DVD); defaulttypes.put("vismot", SearchResult.MediaType.MOVIE); defaulttypes.put("visngr", SearchResult.MediaType.ART); defaulttypes.put("visngrurl", SearchResult.MediaType.ART); defaulttypes.put("visphg", SearchResult.MediaType.BOARDGAME); defaulttypes.put("vistoy", SearchResult.MediaType.BOARDGAME); defaulttypes.put("visurl", SearchResult.MediaType.URL); defaulttypes.put("visvhs", SearchResult.MediaType.MOVIE); defaulttypes.put("visvid", SearchResult.MediaType.MOVIE); defaulttypes.put("visvidurl", SearchResult.MediaType.EVIDEO); defaulttypes.put("web", SearchResult.MediaType.URL); // fallback: Text defaulttypes.put("Buch", SearchResult.MediaType.BOOK); defaulttypes.put("Compact Disc", SearchResult.MediaType.CD); defaulttypes.put("DVD", SearchResult.MediaType.DVD); defaulttypes.put("Konsolenspiel", SearchResult.MediaType.GAME_CONSOLE); defaulttypes.put("Noten", SearchResult.MediaType.SCORE_MUSIC); defaulttypes.put("eBook", SearchResult.MediaType.EBOOK); defaulttypes.put("Zeitschrift", SearchResult.MediaType.MAGAZINE); defaulttypes.put("Blu-ray", SearchResult.MediaType.BLURAY); defaulttypes.put("eAudio", SearchResult.MediaType.EAUDIO); defaulttypes.put("DVD-ROM", SearchResult.MediaType.CD_SOFTWARE); defaulttypes.put("Kinderzeitschriften", SearchResult.MediaType.MAGAZINE); } /** * This parameter needs to be passed to a URL to make sure we are not redirected to the mobile * site */ protected static final String NO_MOBILE = "?nomo=1"; @Override public void init(Library lib, HttpClientFactory httpClientFactory) { super.init(lib, httpClientFactory); this.data = lib.getData(); try { this.opac_url = data.getString("baseurl"); } catch (JSONException e) { throw new RuntimeException(e); } } @Override public SearchRequestResult search(List<SearchQuery> queries) throws IOException, OpacErrorException, JSONException { String url = opac_url + "/" + data.getJSONObject("urls").getString("advanced_search") + NO_MOBILE; Document doc = Jsoup.parse(httpGet(url, getDefaultEncoding())); doc.setBaseUri(url); int selectableCount = 0; for (SearchQuery query : queries) { if (query.getValue().equals("") || query.getValue().equals("false")) continue; if (query.getSearchField() instanceof TextSearchField | query.getSearchField() instanceof BarcodeSearchField) { SearchField field = query.getSearchField(); if (field.getData().getBoolean("selectable")) { selectableCount++; if (selectableCount > 3) { throw new OpacErrorException(stringProvider.getQuantityString( StringProvider.LIMITED_NUM_OF_CRITERIA, 3, 3)); } String number = numberToText(selectableCount); Element searchField = doc.select("select[name$=" + number + "SearchField]").first(); Element searchValue = doc.select("input[name$=" + number + "SearchValue]").first(); setSelectValue(searchField, field.getId()); searchValue.val(query.getValue()); } else { Element input = doc.select("input[name=" + field.getId() + "]").first(); input.val(query.getValue()); } } else if (query.getSearchField() instanceof DropdownSearchField) { DropdownSearchField field = (DropdownSearchField) query.getSearchField(); Element select = doc.select("select[name=" + field.getId() + "]").first(); setSelectValue(select, query.getValue()); } else if (query.getSearchField() instanceof CheckboxSearchField) { CheckboxSearchField field = (CheckboxSearchField) query.getSearchField(); Element input = doc.select("input[name=" + field.getId() + "]").first(); input.attr("checked", query.getValue()); } } // Submit form FormElement form = (FormElement) doc.select("form").first(); MultipartBody data = formData(form, "BtnSearch").build(); String postUrl = form.attr("abs:action"); String html = httpPost(postUrl, data, "UTF-8"); Document doc2 = Jsoup.parse(html); doc2.setBaseUri(postUrl); return parse_search(doc2, 0); } protected void setSelectValue(Element select, String value) { for (Element opt : select.select("option")) { if (value.equals(opt.val())) { opt.attr("selected", "selected"); } else { opt.removeAttr("selected"); } } } protected CompletableFuture<Void> assignBestCover(final CoverHolder result, final List<String> queue) { if (queue.size() > 0) { final String url = queue.get(0); queue.remove(0); return asyncHead(url, false) .handle((response, throwable) -> { if (throwable == null) { result.setCover(url); } else { assignBestCover(result, queue).join(); } return null; }); } else { // we don't have any more URLs in the queue CompletableFuture<Void> future = new CompletableFuture<>(); future.complete(null); return future; } } protected SearchRequestResult parse_search(Document doc, int page) throws OpacErrorException { searchResultDoc = doc; if (doc.select("#Label1, span[id$=LblInfoMessage], .oclc-searchmodule-searchresult > " + ".boldText").size() > 0) { String message = doc.select("#Label1, span[id$=LblInfoMessage], .boldText").text(); if (message.contains("keine Treffer")) { return new SearchRequestResult(new ArrayList<>(), 0, 1, page); } else { throw new OpacErrorException(message); } } int totalCount; if (doc.select("span[id$=TotalItemsLabel]").size() > 0) { totalCount = Integer.parseInt( doc.select("span[id$=TotalItemsLabel]").first().text().split("[ \\t\\xA0\\u1680\\u180e\\u2000-\\u200a\\u202f\\u205f\\u3000]")[0]); } else { throw new OpacErrorException(stringProvider.getString(StringProvider.UNKNOWN_ERROR)); } Pattern idPattern = Pattern.compile("\\$(mdv|civ|dcv)(\\d+)\\$"); Pattern weakIdPattern = Pattern.compile("(mdv|civ|dcv)(\\d+)[^\\d]"); // Determine portalID value for availability AvailabilityRestInfo restInfo = getAvailabilityRestInfo(doc); Elements elements = doc.select("div[id$=divMedium], div[id$=divComprehensiveItem], div[id$=divDependentCatalogue]"); List<SearchResult> results = new ArrayList<>(); int i = 0; List<CompletableFuture<Void>> futures = new ArrayList<>(); for (Element element : elements) { final SearchResult result = new SearchResult(); // Cover if (element.select("input[id$=mediumImage]").size() > 0) { result.setCover(element.select("input[id$=mediumImage]").first().attr("src")); } else if (element.select("img[id$=CoverView_Image]").size() > 0) { assignBestCover(result, getCoverUrlList(element.select("img[id$=CoverView_Image]").first())); } Element catalogueContent = element.select(".catalogueContent, .oclc-searchmodule-mediumview-content, .oclc-searchmodule-comprehensiveitemview-content, .oclc-searchmodule-dependentitemview-content") .first(); // Media Type if (catalogueContent.select("#spanMediaGrpIcon, .spanMediaGrpIcon").size() > 0) { String mediatype = catalogueContent.select("#spanMediaGrpIcon, .spanMediaGrpIcon").attr("class"); if (mediatype.startsWith("itemtype ")) { mediatype = mediatype.substring("itemtype ".length()); } if ("".equals(mediatype)) { // fallback: use text media type if icon is not available (e.g. Wien) mediatype = catalogueContent.select("[id$=spanMediaGrpValue]").text(); } SearchResult.MediaType defaulttype = defaulttypes.get(mediatype); if (defaulttype == null) defaulttype = SearchResult.MediaType.UNKNOWN; if (data.has("mediatypes")) { try { result.setType(SearchResult.MediaType .valueOf(data.getJSONObject("mediatypes").getString(mediatype))); } catch (JSONException e) { result.setType(defaulttype); } } else { result.setType(defaulttype); } } else { result.setType(SearchResult.MediaType.UNKNOWN); } // Text String title = catalogueContent .select("a[id$=LbtnShortDescriptionValue], a[id$=LbtnTitleValue]").text(); String subtitle = catalogueContent.select("span[id$=LblSubTitleValue]").text(); String author = catalogueContent.select("span[id$=LblAuthorValue]").text(); String year = catalogueContent.select("span[id$=LblProductionYearValue]").text(); String mediumIdentifier = catalogueContent.select("span[id$=LblMediumIdentifierValue]").text(); String series = catalogueContent.select("span[id$=LblSeriesValue]").text(); // Some libraries, such as Bern, have labels but no <span id="..Value"> tags int j = 0; for (Element div : catalogueContent.children()) { if (subtitle.equals("") && div.select("span").size() == 0 && j > 0 && j < 3) { subtitle = div.text().trim(); } if (author.equals("") && div.select("span[id$=LblAuthor]").size() == 1) { author = div.text().trim(); if (author.contains(":")) { author = author.split(":")[1]; } } if (year.equals("") && div.select("span[id$=LblProductionYear]").size() == 1) { year = div.text().trim(); if (year.contains(":")) { year = year.split(":")[1]; } } j++; } StringBuilder text = new StringBuilder(); text.append("<b>").append(title).append("</b>"); if (!subtitle.equals("")) text.append("<br/>").append(subtitle); if (!author.equals("")) text.append("<br/>").append(author); if (!mediumIdentifier.equals("")) text.append("<br/>").append(mediumIdentifier); if (!year.equals("")) text.append("<br/>").append(year); if (!series.equals("")) text.append("<br/>").append(series); result.setInnerhtml(text.toString()); // ID Matcher matcher = idPattern.matcher(element.html()); if (matcher.find()) { result.setId(matcher.group(2)); } else { matcher = weakIdPattern.matcher(element.html()); if (matcher.find()) { result.setId(matcher.group(2)); } } // Availability if (result.getId() != null) { String culture = element.select("input[name$=culture]").val(); String ekzid = element.select("input[name$=ekzid]").val(); boolean ebook = !ekzid.equals(""); String url; if (ebook) { url = restInfo.ebookRestUrl != null ? restInfo.ebookRestUrl : opac_url + "/DesktopModules/OCLC.OPEN.PL.DNN.CopConnector/Services" + "/Onleihe.asmx/GetNcipLookupItem"; } else { url = restInfo.restUrl != null ? restInfo.restUrl : opac_url + "/DesktopModules/OCLC.OPEN.PL.DNN.SearchModule/" + "SearchService.asmx/GetAvailability"; } JSONObject data = new JSONObject(); try { if (ebook) { data.put("portalId", restInfo.portalId).put("itemid", ekzid) .put("language", culture); } else { data.put("portalId", restInfo.portalId).put("mednr", result.getId()) .put("culture", culture).put("requestCopyData", false) .put("branchFilter", ""); } RequestBody entity = RequestBody.create(MEDIA_TYPE_JSON, data.toString()); futures.add(asyncPost(url, entity, false).handle((response, throwable) -> { if (throwable != null) return null; ResponseBody body = response.body(); try { JSONObject availabilityData = new JSONObject(body.string()); String isAvail; if (ebook) { isAvail = availabilityData .getJSONObject("d").getJSONObject("LookupItem") .getString("Available"); } else { isAvail = availabilityData .getJSONObject("d").getString("IsAvail"); } switch (isAvail) { case "true": result.setStatus(SearchResult.Status.GREEN); break; case "false": result.setStatus(SearchResult.Status.RED); break; case "digital": result.setStatus(SearchResult.Status.UNKNOWN); break; } } catch (JSONException | IOException e) { e.printStackTrace(); } body.close(); return null; })); } catch (JSONException e) { e.printStackTrace(); } } result.setNr(i); results.add(result); } CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).join(); return new SearchRequestResult(results, totalCount, page); } private AvailabilityRestInfo getAvailabilityRestInfo(Document doc) { AvailabilityRestInfo info = new AvailabilityRestInfo(); info.portalId = 1; for (Element scripttag : doc.select("script")) { String scr = scripttag.html(); if (scr.contains("LoadSharedCatalogueViewAvailabilityAsync")) { Pattern pattern = Pattern.compile( ".*LoadSharedCatalogueViewAvailabilityAsync\\(\"([^,]*)\",\"([^,]*)\"," + "[^0-9,]*([0-9]+)[^0-9,]*,.*\\).*"); Matcher matcher = pattern.matcher(scr); if (matcher.find()) { info.restUrl = getAbsoluteUrl(opac_url, matcher.group(1)); info.ebookRestUrl = getAbsoluteUrl(opac_url, matcher.group(2)); info.portalId = Integer.parseInt(matcher.group(3)); } } } return info; } protected static String getAbsoluteUrl(String baseUrl, String url) { if (!url.contains("://")) { try { URIBuilder uriBuilder = new URIBuilder(baseUrl); url = uriBuilder.setPath(url) .build() .normalize().toString(); } catch (URISyntaxException e) { e.printStackTrace(); } } return url; } private class AvailabilityRestInfo { public int portalId; public String restUrl; public String ebookRestUrl; } private List<String> getCoverUrlList(Element img) { String[] parts = img.attr("sources").split("\\|"); // Example: SetSimpleCover|a|https://vlb.de/GetBlob.aspx?strIsbn=9783868511291&amp; // size=S|a|http://www.buchhandel.de/default.aspx?strframe=titelsuche&amp; // caller=vlbPublic&amp;func=DirectIsbnSearch&amp;isbn=9783868511291&amp; // nSiteId=11|c|SetNoCover|a|/DesktopModules/OCLC.OPEN.PL.DNN // .BaseLibrary/StyleSheets/Images/Fallbacks/emptyURL.gif?4.2.0.0|a| List<String> alternatives = new ArrayList<>(); for (int i = 0; i + 2 < parts.length; i++) { if (parts[i].equals("SetSimpleCover")) { String url = parts[i + 2].replace("&amp;", "&"); try { alternatives.add(new URL(new URL(opac_url), url).toString()); } catch (MalformedURLException ignored) { } } } if (img.hasAttr("devsources")) { parts = img.attr("devsources").split("\\|"); for (int i = 0; i + 2 < parts.length; i++) { if (parts[i].equals("SetSimpleCover")) { String url = parts[i + 2].replace("&amp;", "&"); try { alternatives.add(new URL(new URL(opac_url), url).toString()); } catch (MalformedURLException ignored) { } } } } return alternatives; } private String numberToText(int number) { switch (number) { case 1: return "First"; case 2: return "Second"; case 3: return "Third"; default: return null; } } @Override public SearchRequestResult filterResults(Filter filter, Filter.Option option) throws IOException, OpacErrorException { return null; } @Override public SearchRequestResult searchGetPage(int page) throws IOException, OpacErrorException, JSONException { if (searchResultDoc == null) throw new NotReachableException(); Document doc = searchResultDoc; if (doc.select("span[id$=DataPager1]").size() == 0) { /* New style: Page buttons using normal links We can go directly to the correct page */ if (doc.select("a[id*=LinkButtonPageN]").size() > 0) { String href = doc.select("a[id*=LinkButtonPageN][href*=page]").first().attr("href"); String url = href.replaceFirst("page=\\d+", "page=" + page); Document doc2 = Jsoup.parse(httpGet(url, getDefaultEncoding())); doc2.setBaseUri(url); return parse_search(doc2, page); } else { int totalCount; try { totalCount = Integer.parseInt( doc.select("span[id$=TotalItemsLabel]").first().text()); } catch (Exception e) { totalCount = 0; } // Next page does not exist return new SearchRequestResult( new ArrayList<SearchResult>(), 0, totalCount ); } } else { /* Old style: Page buttons using Javascript When there are many pages of results, there will only be links to the next 4 and previous 4 pages, so we will click links until it gets to the correct page. */ Elements pageLinks = doc.select("span[id$=DataPager1]").first() .select("a[id*=LinkButtonPageN], span[id*=LabelPageN]"); int from = Integer.valueOf(pageLinks.first().text()); int to = Integer.valueOf(pageLinks.last().text()); Element linkToClick; boolean willBeCorrectPage; if (page < from) { linkToClick = pageLinks.first(); willBeCorrectPage = false; } else if (page > to) { linkToClick = pageLinks.last(); willBeCorrectPage = false; } else { linkToClick = pageLinks.get(page - from); willBeCorrectPage = true; } if (linkToClick.tagName().equals("span")) { // we are trying to get the page we are already on return parse_search(searchResultDoc, page); } Pattern pattern = Pattern.compile("javascript:__doPostBack\\('([^,]*)','([^\\)]*)'\\)"); Matcher matcher = pattern.matcher(linkToClick.attr("href")); if (!matcher.find()) throw new OpacErrorException(StringProvider.INTERNAL_ERROR); FormElement form = (FormElement) doc.select("form").first(); MultipartBody data = formData(form, null).addFormDataPart("__EVENTTARGET", matcher.group(1)) .addFormDataPart("__EVENTARGUMENT", matcher.group(2)) .build(); String postUrl = form.attr("abs:action"); String html = httpPost(postUrl, data, "UTF-8"); if (willBeCorrectPage) { // We clicked on the correct link Document doc2 = Jsoup.parse(html); doc2.setBaseUri(postUrl); return parse_search(doc2, page); } else { // There was no correct link, so try to find one again searchResultDoc = Jsoup.parse(html); searchResultDoc.setBaseUri(postUrl); return searchGetPage(page); } } } @Override public DetailedItem getResultById(String id, String homebranch) throws IOException, OpacErrorException { try { String url; if (id.startsWith("https://") || id.startsWith("http://")) { url = id; } else { url = opac_url + "/" + data.getJSONObject("urls").getString("simple_search") + NO_MOBILE + "&id=" + id; } Document doc = Jsoup.parse(httpGet(url, getDefaultEncoding())); doc.setBaseUri(url); return parse_result(doc); } catch (JSONException e) { throw new IOException(e.getMessage()); } } protected DetailedItem parse_result(Document doc) { DetailedItem item = new DetailedItem(); // Title and Subtitle item.setTitle(doc.select("span[id$=LblShortDescriptionValue], span[id$=LblTitleValue]").text()); String subtitle = doc.select("span[id$=LblSubTitleValue]").text(); if (subtitle.equals("") && doc.select("span[id$=LblShortDescriptionValue]").size() > 0) { // Subtitle detection for Bern Element next = doc.select("span[id$=LblShortDescriptionValue]").first().parent() .nextElementSibling(); if (next.select("span").size() == 0) { subtitle = next.text().trim(); } } if (!subtitle.equals("")) { item.addDetail(new Detail(stringProvider.getString(StringProvider.SUBTITLE), subtitle)); } // Cover if (doc.select("input[id$=mediumImage]").size() > 0) { item.setCover(doc.select("input[id$=mediumImage]").attr("src")); } else if (doc.select("img[id$=CoverView_Image]").size() > 0) { assignBestCover(item, getCoverUrlList(doc.select("img[id$=CoverView_Image]").first())); } // ID item.setId(doc.select("input[id$=regionmednr]").val()); // Description if (doc.select("span[id$=ucCatalogueContent_LblAnnotation]").size() > 0) { String name = doc.select("span[id$=lblCatalogueContent]").text(); String value = doc.select("span[id$=ucCatalogueContent_LblAnnotation]").text(); item.addDetail(new Detail(name, value)); } // Parent if (doc.select("a[id$=HyperLinkParent]").size() > 0) { item.setCollectionId(doc.select("a[id$=HyperLinkParent]").first().attr("href")); } // Details String DETAIL_SELECTOR = "div[id$=CatalogueDetailView] .spacingBottomSmall:has(span+span)," + "div[id$=CatalogueDetailView] .spacingBottomSmall:has(span+a), " + "div[id$=CatalogueDetailView] .oclc-searchmodule-detail-data div:has" + "(span+span), " + "div[id$=CatalogueDetailView] .oclc-searchmodule-detail-data div:has" + "(span+a)"; for (Element detail : doc.select(DETAIL_SELECTOR)) { String name = detail.select("span").get(0).text().replace(": ", ""); String value = ""; if (detail.select("a").size() > 1) { int i = 0; for (Element a : detail.select("a")) { if (i != 0) { value += ", "; } value += a.text().trim(); i++; } } else { value = detail.select("span, a").get(1).text(); if ((value.contains("ffnen") || value.contains("hier klicken")) && detail.select("a").size() > 0) { value = value + " " + detail.select("a").first().attr("href"); } } item.addDetail(new Detail(name, value)); } // Description if (doc.select("div[id$=CatalogueContent]").size() > 0) { String name = doc.select("div[id$=CatalogueContent] .oclc-module-header").text(); String value = doc.select("div[id$=CatalogueContent] .oclc-searchmodule-detail-annotation") .text(); item.addDetail(new Detail(name, value)); } // Copies Element table = doc.select("table[id$=grdViewMediumCopies]").first(); if (table != null) { Elements trs = table.select("tr"); List<String> columnmap = new ArrayList<>(); for (Element th : trs.first().select("th")) { columnmap.add(getCopyColumnKey(th.text())); } DateTimeFormatter fmt = DateTimeFormat.forPattern("dd.MM.yyyy").withLocale(Locale.GERMAN); for (int i = 1; i < trs.size(); i++) { Elements tds = trs.get(i).select("td"); Copy copy = new Copy(); for (int j = 0; j < tds.size(); j++) { if (columnmap.get(j) == null) continue; String text = tds.get(j).text().replace("\u00a0", ""); if (tds.get(j).select(".oclc-module-label").size() > 0 && tds.get(j).select("span").size() == 2) { text = tds.get(j).select("span").get(1).text(); } if (text.equals("")) continue; String colname = columnmap.get(j); if (copy.get(colname) != null && !copy.get(colname).isEmpty()) { text = copy.get(colname) + " / " + text; } copy.set(colname, text, fmt); } item.addCopy(copy); } } // Dependent (e.g. Verden) if (doc.select("div[id$=DivDependentCatalogue]").size() > 0) { String url = opac_url + "/DesktopModules/OCLC.OPEN.PL.DNN.SearchModule/SearchService.asmx/GetDependantCatalogues"; JSONObject postData = new JSONObject(); // Determine portalID value int portalId = 1; for (Element scripttag : doc.select("script")) { String scr = scripttag.html(); if (scr.contains("LoadCatalogueViewDependantCataloguesAsync")) { Pattern portalIdPattern = Pattern.compile( ".*LoadCatalogueViewDependantCataloguesAsync\\([^,]*,[^,]*," + "[^,]*,[^,]*,[^,]*,[^0-9,]*([0-9]+)[^0-9,]*,.*\\).*"); Matcher portalIdMatcher = portalIdPattern.matcher(scr); if (portalIdMatcher.find()) { portalId = Integer.parseInt(portalIdMatcher.group(1)); } } } try { postData.put("portalId", portalId).put("mednr", item.getId()) .put("tabUrl", opac_url + "/" + data.getJSONObject("urls").getString("simple_search") + NO_MOBILE + "&id=") .put("branchFilter", ""); RequestBody entity = RequestBody.create(MEDIA_TYPE_JSON, postData.toString()); String json = httpPost(url, entity, getDefaultEncoding()); JSONObject volumeData = new JSONObject(json); JSONArray cat = volumeData.getJSONObject("d").getJSONArray("Catalogues"); for (int i = 0; i < cat.length(); i++) { JSONObject obj = cat.getJSONObject(i); Map<String, String> params = getQueryParamsFirst(obj.getString("DependantUrl")); item.addVolume(new Volume( params.get("id"), obj.getString("DependantTitle") )); } } catch (JSONException | IOException e) { e.printStackTrace(); } } return item; } protected String getCopyColumnKey(String text) { switch (text) { case "Zweigstelle": case "Bibliothek": return "branch"; case "Standorte": case "Standort": case "Standort 2": case "Standort 3": return "location"; case "Status": return "status"; case "Vorbestellungen": return "reservations"; case "Frist": case "Rückgabedatum": return "returndate"; case "Signatur": return "signature"; case "Barcode": return "barcode"; default: return null; } } @Override public DetailedItem getResult(int position) throws IOException, OpacErrorException { return null; } @Override public ReservationResult reservation(DetailedItem item, Account account, int useraction, String selection) throws IOException { return null; } @Override public ProlongResult prolong(String media, Account account, int useraction, String selection) throws IOException { return null; } @Override public ProlongAllResult prolongAll(Account account, int useraction, String selection) throws IOException { return null; } @Override public CancelResult cancel(String media, Account account, int useraction, String selection) throws IOException, OpacErrorException { return null; } @Override public AccountData account(Account account) throws IOException, JSONException, OpacErrorException { return null; } @Override public void checkAccountData(Account account) throws IOException, JSONException, OpacErrorException { } @Override public List<SearchField> parseSearchFields() throws IOException, OpacErrorException, JSONException { String url = opac_url + "/" + data.getJSONObject("urls").getString("advanced_search") + NO_MOBILE; Document doc = Jsoup.parse(httpGet(url, getDefaultEncoding())); if (doc.select("[id$=LblErrorMsg]").size() > 0 && doc.select("[id$=ContentPane] input").size() == 0) { throw new OpacErrorException(doc.select("[id$=LblErrorMsg]").text()); } Element module = doc.select(".ModOPENExtendedSearchModuleC").first(); List<SearchField> fields = new ArrayList<>(); JSONObject selectable = new JSONObject(); selectable.put("selectable", true); JSONObject notSelectable = new JSONObject(); notSelectable.put("selectable", false); // Selectable search criteria Elements options = module.select("select[id$=FirstSearchField] option"); for (Element option : options) { TextSearchField field = new TextSearchField(); field.setId(option.val()); field.setDisplayName(option.text()); field.setData(selectable); fields.add(field); } // More criteria Element moreHeader = null; if (module.select("table").size() == 1) { moreHeader = module.select("span[id$=LblMoreCriterias]").parents().select("tr").first(); } else { // Newer OPEN, e.g. Erlangen moreHeader = module.select("span[id$=LblMoreCriterias]").first(); } if (moreHeader != null) { Elements siblings = moreHeader.siblingElements(); int startIndex = moreHeader.elementSiblingIndex(); for (int i = startIndex; i < siblings.size(); i++) { Element tr = siblings.get(i); if (tr.select("input, select").size() == 0) continue; if (tr.select("input[type=text]").size() == 1) { Element input = tr.select("input[type=text]").first(); TextSearchField field = new TextSearchField(); field.setId(input.attr("name")); field.setDisplayName(tr.select("span[id*=Lbl]").first().text()); field.setData(notSelectable); if (tr.text().contains("nur Ziffern")) field.setNumber(true); fields.add(field); } else if (tr.select("input[type=text]").size() == 2) { Element input1 = tr.select("input[type=text]").get(0); Element input2 = tr.select("input[type=text]").get(1); TextSearchField field1 = new TextSearchField(); field1.setId(input1.attr("name")); field1.setDisplayName(tr.select("span[id*=Lbl]").first().text()); field1.setData(notSelectable); if (tr.text().contains("nur Ziffern")) field1.setNumber(true); fields.add(field1); TextSearchField field2 = new TextSearchField(); field2.setId(input2.attr("name")); field2.setDisplayName(tr.select("span[id*=Lbl]").first().text()); field2.setData(notSelectable); field2.setHalfWidth(true); if (tr.text().contains("nur Ziffern")) field2.setNumber(true); fields.add(field2); } else if (tr.select("select").size() == 1) { Element select = tr.select("select").first(); DropdownSearchField dropdown = new DropdownSearchField(); dropdown.setId(select.attr("name")); dropdown.setDisplayName(tr.select("span[id*=Lbl]").first().text()); List<DropdownSearchField.Option> values = new ArrayList<>(); for (Element option : select.select("option")) { DropdownSearchField.Option opt = new DropdownSearchField.Option(option.val(), option.text()); values.add(opt); } dropdown.setDropdownValues(values); fields.add(dropdown); } else if (tr.select("input[type=checkbox]").size() == 1) { Element checkbox = tr.select("input[type=checkbox]").first(); CheckboxSearchField field = new CheckboxSearchField(); field.setId(checkbox.attr("name")); field.setDisplayName(tr.select("span[id*=Lbl]").first().text()); fields.add(field); } } } return fields; } @Override public String getShareUrl(String id, String title) { return opac_url + "/Permalink.aspx" + "?id" + "=" + id; } @Override public int getSupportFlags() { return SUPPORT_FLAG_ENDLESS_SCROLLING; } @Override public Set<String> getSupportedLanguages() throws IOException { return null; } @Override public void setLanguage(String language) { } @Override protected String getDefaultEncoding() { try { if (data.has("charset")) { return data.getString("charset"); } } catch (JSONException e) { e.printStackTrace(); } return "UTF-8"; } static StringBuilder appendQuotedString(StringBuilder target, String key) { target.append('"'); for (int i = 0, len = key.length(); i < len; i++) { char ch = key.charAt(i); switch (ch) { case '\n': target.append("%0A"); break; case '\r': target.append("%0D"); break; case '"': target.append("%22"); break; default: target.append(ch); break; } } target.append('"'); return target; } public static MultipartBody.Part createFormData(String name, String value) { return createFormData(name, null, RequestBody.create(null, value.getBytes())); } public static MultipartBody.Part createFormData(String name, String filename, RequestBody body) { if (name == null) { throw new NullPointerException("name == null"); } StringBuilder disposition = new StringBuilder("form-data; name="); appendQuotedString(disposition, name); if (filename != null) { disposition.append("; filename="); appendQuotedString(disposition, filename); } return create(Headers.of("Content-Disposition", disposition.toString()), body); } /** * Better version of JSoup's implementation of this function ({@link * org.jsoup.nodes.FormElement#formData()}). * * @param form The form to submit * @param submitName The name attribute of the button which is clicked to submit the form, or * null * @return A MultipartEntityBuilder containing the data of the form */ protected static MultipartBody.Builder formData(FormElement form, String submitName) { MultipartBody.Builder data = new MultipartBody.Builder(); data.setType(MediaType.parse("multipart/form-data")); // data.setCharset somehow breaks everything in Bern. // data.addTextBody breaks utf-8 characters in select boxes in Bern // .getBytes is an implicit, undeclared UTF-8 conversion, this seems to work -- at least // in Bern // Remove nested forms form.select("form form").remove(); form = ((FormElement) Jsoup.parse(form.outerHtml()).select("form").get(0)); // iterate the form control elements and accumulate their values for (Element el : form.elements()) { if (!el.tag().isFormSubmittable()) { continue; // contents are form listable, superset of submitable } String name = el.attr("name"); if (name.length() == 0) continue; String type = el.attr("type"); if ("select".equals(el.tagName())) { Elements options = el.select("option[selected]"); boolean set = false; for (Element option : options) { data.addPart(createFormData(name, option.val())); set = true; } if (!set) { Element option = el.select("option").first(); if (option != null) { data.addPart(createFormData(name, option.val())); } } } else if ("checkbox".equalsIgnoreCase(type) || "radio".equalsIgnoreCase(type)) { // only add checkbox or radio if they have the checked attribute if (el.hasAttr("checked")) { data.addFormDataPart(name, el.val().length() > 0 ? el.val() : "on"); } } else if ("submit".equalsIgnoreCase(type) || "image".equalsIgnoreCase(type) || "button".equalsIgnoreCase(type)) { if (submitName != null && el.attr("name").contains(submitName)) { data.addPart(createFormData(name, el.val())); } } else { data.addPart(createFormData(name, el.val())); } } return data; } }
opacclient/libopac/src/main/java/de/geeksfactory/opacclient/apis/OpenSearch.java
/* * Copyright (C) 2015 by Johan von Forstner under the MIT license: * * 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 de.geeksfactory.opacclient.apis; import org.apache.http.client.utils.URIBuilder; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.FormElement; import org.jsoup.select.Elements; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import de.geeksfactory.opacclient.i18n.StringProvider; import de.geeksfactory.opacclient.networking.HttpClientFactory; import de.geeksfactory.opacclient.networking.NotReachableException; import de.geeksfactory.opacclient.objects.Account; import de.geeksfactory.opacclient.objects.AccountData; import de.geeksfactory.opacclient.objects.Copy; import de.geeksfactory.opacclient.objects.CoverHolder; import de.geeksfactory.opacclient.objects.Detail; import de.geeksfactory.opacclient.objects.DetailedItem; import de.geeksfactory.opacclient.objects.Filter; import de.geeksfactory.opacclient.objects.Library; import de.geeksfactory.opacclient.objects.SearchRequestResult; import de.geeksfactory.opacclient.objects.SearchResult; import de.geeksfactory.opacclient.objects.Volume; import de.geeksfactory.opacclient.searchfields.BarcodeSearchField; import de.geeksfactory.opacclient.searchfields.CheckboxSearchField; import de.geeksfactory.opacclient.searchfields.DropdownSearchField; import de.geeksfactory.opacclient.searchfields.SearchField; import de.geeksfactory.opacclient.searchfields.SearchQuery; import de.geeksfactory.opacclient.searchfields.TextSearchField; import java8.util.concurrent.CompletableFuture; import okhttp3.Headers; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; import static okhttp3.MultipartBody.Part.create; /** * API for Bibliotheca+/OPEN OPAC software * * @author Johan von Forstner, 29.03.2015 */ public class OpenSearch extends OkHttpBaseApi implements OpacApi { protected JSONObject data; protected String opac_url; protected Document searchResultDoc; protected static HashMap<String, SearchResult.MediaType> defaulttypes = new HashMap<>(); static { // icons defaulttypes.put("archv", SearchResult.MediaType.BOOK); defaulttypes.put("archv-digital", SearchResult.MediaType.EDOC); defaulttypes.put("artchap", SearchResult.MediaType.ART); defaulttypes.put("artchap-artcl", SearchResult.MediaType.ART); defaulttypes.put("artchap-chptr", SearchResult.MediaType.ART); defaulttypes.put("artchap-digital", SearchResult.MediaType.ART); defaulttypes.put("audiobook", SearchResult.MediaType.AUDIOBOOK); defaulttypes.put("audiobook-cd", SearchResult.MediaType.AUDIOBOOK); defaulttypes.put("audiobook-lp", SearchResult.MediaType.AUDIOBOOK); defaulttypes.put("audiobook-digital", SearchResult.MediaType.MP3); defaulttypes.put("book", SearchResult.MediaType.BOOK); defaulttypes.put("book-braille", SearchResult.MediaType.BOOK); defaulttypes.put("book-continuing", SearchResult.MediaType.BOOK); defaulttypes.put("book-digital", SearchResult.MediaType.EBOOK); defaulttypes.put("book-largeprint", SearchResult.MediaType.BOOK); defaulttypes.put("book-mic", SearchResult.MediaType.BOOK); defaulttypes.put("book-thsis", SearchResult.MediaType.BOOK); defaulttypes.put("compfile", SearchResult.MediaType.PACKAGE); defaulttypes.put("compfile-digital", SearchResult.MediaType.PACKAGE); defaulttypes.put("corpprof", SearchResult.MediaType.UNKNOWN); defaulttypes.put("encyc", SearchResult.MediaType.UNKNOWN); defaulttypes.put("game", SearchResult.MediaType.BOARDGAME); defaulttypes.put("game-digital", SearchResult.MediaType.GAME_CONSOLE); defaulttypes.put("image", SearchResult.MediaType.ART); defaulttypes.put("image-2d", SearchResult.MediaType.ART); defaulttypes.put("intmm", SearchResult.MediaType.EVIDEO); defaulttypes.put("intmm-digital", SearchResult.MediaType.EVIDEO); defaulttypes.put("jrnl", SearchResult.MediaType.MAGAZINE); defaulttypes.put("jrnl-issue", SearchResult.MediaType.MAGAZINE); defaulttypes.put("jrnl-digital", SearchResult.MediaType.EBOOK); defaulttypes.put("kit", SearchResult.MediaType.PACKAGE); defaulttypes.put("map", SearchResult.MediaType.MAP); defaulttypes.put("map-digital", SearchResult.MediaType.EBOOK); defaulttypes.put("msscr", SearchResult.MediaType.MP3); defaulttypes.put("msscr-digital", SearchResult.MediaType.MP3); defaulttypes.put("music", SearchResult.MediaType.MP3); defaulttypes.put("music-cassette", SearchResult.MediaType.AUDIO_CASSETTE); defaulttypes.put("music-cd", SearchResult.MediaType.CD_MUSIC); defaulttypes.put("music-digital", SearchResult.MediaType.MP3); defaulttypes.put("music-lp", SearchResult.MediaType.LP_RECORD); defaulttypes.put("news", SearchResult.MediaType.NEWSPAPER); defaulttypes.put("news-digital", SearchResult.MediaType.EBOOK); defaulttypes.put("object", SearchResult.MediaType.UNKNOWN); defaulttypes.put("object-digital", SearchResult.MediaType.UNKNOWN); defaulttypes.put("paper", SearchResult.MediaType.UNKNOWN); defaulttypes.put("pub", SearchResult.MediaType.UNKNOWN); defaulttypes.put("rev", SearchResult.MediaType.UNKNOWN); defaulttypes.put("snd", SearchResult.MediaType.MP3); defaulttypes.put("snd-cassette", SearchResult.MediaType.AUDIO_CASSETTE); defaulttypes.put("snd-cd", SearchResult.MediaType.CD_MUSIC); defaulttypes.put("snd-lp", SearchResult.MediaType.LP_RECORD); defaulttypes.put("snd-digital", SearchResult.MediaType.EAUDIO); defaulttypes.put("toy", SearchResult.MediaType.BOARDGAME); defaulttypes.put("und", SearchResult.MediaType.UNKNOWN); defaulttypes.put("video-bluray", SearchResult.MediaType.BLURAY); defaulttypes.put("video-digital", SearchResult.MediaType.EVIDEO); defaulttypes.put("video-dvd", SearchResult.MediaType.DVD); defaulttypes.put("video-film", SearchResult.MediaType.MOVIE); defaulttypes.put("video-vhs", SearchResult.MediaType.MOVIE); defaulttypes.put("vis", SearchResult.MediaType.ART); defaulttypes.put("vis-digital", SearchResult.MediaType.ART); defaulttypes.put("web", SearchResult.MediaType.URL); defaulttypes.put("web-digital", SearchResult.MediaType.URL); defaulttypes.put("art", SearchResult.MediaType.ART); defaulttypes.put("arturl", SearchResult.MediaType.URL); defaulttypes.put("bks", SearchResult.MediaType.BOOK); defaulttypes.put("bksbrl", SearchResult.MediaType.BOOK); defaulttypes.put("bksdeg", SearchResult.MediaType.BOOK); defaulttypes.put("bkslpt", SearchResult.MediaType.BOOK); defaulttypes.put("bksurl", SearchResult.MediaType.EBOOK); defaulttypes.put("braille", SearchResult.MediaType.BOOK); defaulttypes.put("com", SearchResult.MediaType.CD_SOFTWARE); defaulttypes.put("comcgm", SearchResult.MediaType.GAME_CONSOLE); defaulttypes.put("comcgmurl", SearchResult.MediaType.GAME_CONSOLE); defaulttypes.put("comimm", SearchResult.MediaType.EVIDEO); defaulttypes.put("comimmurl", SearchResult.MediaType.EVIDEO); defaulttypes.put("comurl", SearchResult.MediaType.URL); defaulttypes.put("int", SearchResult.MediaType.UNKNOWN); defaulttypes.put("inturl", SearchResult.MediaType.UNKNOWN); defaulttypes.put("map", SearchResult.MediaType.MAP); defaulttypes.put("mapurl", SearchResult.MediaType.MAP); defaulttypes.put("mic", SearchResult.MediaType.UNKNOWN); defaulttypes.put("micro", SearchResult.MediaType.UNKNOWN); defaulttypes.put("mix", SearchResult.MediaType.PACKAGE); defaulttypes.put("mixurl", SearchResult.MediaType.PACKAGE); defaulttypes.put("rec", SearchResult.MediaType.MP3); defaulttypes.put("recmsr", SearchResult.MediaType.MP3); defaulttypes.put("recmsrcas", SearchResult.MediaType.AUDIO_CASSETTE); defaulttypes.put("recmsrcda", SearchResult.MediaType.CD_MUSIC); defaulttypes.put("recmsrlps", SearchResult.MediaType.LP_RECORD); defaulttypes.put("recmsrurl", SearchResult.MediaType.EAUDIO); defaulttypes.put("recnsr", SearchResult.MediaType.UNKNOWN); defaulttypes.put("recnsrcas", SearchResult.MediaType.UNKNOWN); defaulttypes.put("recnsrcda", SearchResult.MediaType.UNKNOWN); defaulttypes.put("recnsrlps", SearchResult.MediaType.UNKNOWN); defaulttypes.put("recnsrurl", SearchResult.MediaType.UNKNOWN); defaulttypes.put("recurl", SearchResult.MediaType.EAUDIO); defaulttypes.put("sco", SearchResult.MediaType.SCORE_MUSIC); defaulttypes.put("scourl", SearchResult.MediaType.SCORE_MUSIC); defaulttypes.put("ser", SearchResult.MediaType.PACKAGE_BOOKS); defaulttypes.put("sernew", SearchResult.MediaType.PACKAGE_BOOKS); defaulttypes.put("sernewurl", SearchResult.MediaType.PACKAGE_BOOKS); defaulttypes.put("serurl", SearchResult.MediaType.PACKAGE_BOOKS); defaulttypes.put("url", SearchResult.MediaType.URL); defaulttypes.put("vis", SearchResult.MediaType.ART); defaulttypes.put("visart", SearchResult.MediaType.ART); defaulttypes.put("visdvv", SearchResult.MediaType.DVD); defaulttypes.put("vismot", SearchResult.MediaType.MOVIE); defaulttypes.put("visngr", SearchResult.MediaType.ART); defaulttypes.put("visngrurl", SearchResult.MediaType.ART); defaulttypes.put("visphg", SearchResult.MediaType.BOARDGAME); defaulttypes.put("vistoy", SearchResult.MediaType.BOARDGAME); defaulttypes.put("visurl", SearchResult.MediaType.URL); defaulttypes.put("visvhs", SearchResult.MediaType.MOVIE); defaulttypes.put("visvid", SearchResult.MediaType.MOVIE); defaulttypes.put("visvidurl", SearchResult.MediaType.EVIDEO); defaulttypes.put("web", SearchResult.MediaType.URL); // fallback: Text defaulttypes.put("Buch", SearchResult.MediaType.BOOK); defaulttypes.put("Compact Disc", SearchResult.MediaType.CD); defaulttypes.put("DVD", SearchResult.MediaType.DVD); defaulttypes.put("Konsolenspiel", SearchResult.MediaType.GAME_CONSOLE); defaulttypes.put("Noten", SearchResult.MediaType.SCORE_MUSIC); defaulttypes.put("eBook", SearchResult.MediaType.EBOOK); defaulttypes.put("Zeitschrift", SearchResult.MediaType.MAGAZINE); defaulttypes.put("Blu-ray", SearchResult.MediaType.BLURAY); defaulttypes.put("eAudio", SearchResult.MediaType.EAUDIO); defaulttypes.put("DVD-ROM", SearchResult.MediaType.CD_SOFTWARE); defaulttypes.put("Kinderzeitschriften", SearchResult.MediaType.MAGAZINE); } /** * This parameter needs to be passed to a URL to make sure we are not redirected to the mobile * site */ protected static final String NO_MOBILE = "?nomo=1"; @Override public void init(Library lib, HttpClientFactory httpClientFactory) { super.init(lib, httpClientFactory); this.data = lib.getData(); try { this.opac_url = data.getString("baseurl"); } catch (JSONException e) { throw new RuntimeException(e); } } @Override public SearchRequestResult search(List<SearchQuery> queries) throws IOException, OpacErrorException, JSONException { String url = opac_url + "/" + data.getJSONObject("urls").getString("advanced_search") + NO_MOBILE; Document doc = Jsoup.parse(httpGet(url, getDefaultEncoding())); doc.setBaseUri(url); int selectableCount = 0; for (SearchQuery query : queries) { if (query.getValue().equals("") || query.getValue().equals("false")) continue; if (query.getSearchField() instanceof TextSearchField | query.getSearchField() instanceof BarcodeSearchField) { SearchField field = query.getSearchField(); if (field.getData().getBoolean("selectable")) { selectableCount++; if (selectableCount > 3) { throw new OpacErrorException(stringProvider.getQuantityString( StringProvider.LIMITED_NUM_OF_CRITERIA, 3, 3)); } String number = numberToText(selectableCount); Element searchField = doc.select("select[name$=" + number + "SearchField]").first(); Element searchValue = doc.select("input[name$=" + number + "SearchValue]").first(); setSelectValue(searchField, field.getId()); searchValue.val(query.getValue()); } else { Element input = doc.select("input[name=" + field.getId() + "]").first(); input.val(query.getValue()); } } else if (query.getSearchField() instanceof DropdownSearchField) { DropdownSearchField field = (DropdownSearchField) query.getSearchField(); Element select = doc.select("select[name=" + field.getId() + "]").first(); setSelectValue(select, query.getValue()); } else if (query.getSearchField() instanceof CheckboxSearchField) { CheckboxSearchField field = (CheckboxSearchField) query.getSearchField(); Element input = doc.select("input[name=" + field.getId() + "]").first(); input.attr("checked", query.getValue()); } } // Submit form FormElement form = (FormElement) doc.select("form").first(); MultipartBody data = formData(form, "BtnSearch").build(); String postUrl = form.attr("abs:action"); String html = httpPost(postUrl, data, "UTF-8"); Document doc2 = Jsoup.parse(html); doc2.setBaseUri(postUrl); return parse_search(doc2, 0); } protected void setSelectValue(Element select, String value) { for (Element opt : select.select("option")) { if (value.equals(opt.val())) { opt.attr("selected", "selected"); } else { opt.removeAttr("selected"); } } } protected CompletableFuture<Void> assignBestCover(final CoverHolder result, final List<String> queue) { if (queue.size() > 0) { final String url = queue.get(0); queue.remove(0); return asyncHead(url, false) .handle((response, throwable) -> { if (throwable == null) { result.setCover(url); } else { assignBestCover(result, queue).join(); } return null; }); } else { // we don't have any more URLs in the queue CompletableFuture<Void> future = new CompletableFuture<>(); future.complete(null); return future; } } protected SearchRequestResult parse_search(Document doc, int page) throws OpacErrorException { searchResultDoc = doc; if (doc.select("#Label1, span[id$=LblInfoMessage], .oclc-searchmodule-searchresult > " + ".boldText").size() > 0) { String message = doc.select("#Label1, span[id$=LblInfoMessage], .boldText").text(); if (message.contains("keine Treffer")) { return new SearchRequestResult(new ArrayList<>(), 0, 1, page); } else { throw new OpacErrorException(message); } } int totalCount; if (doc.select("span[id$=TotalItemsLabel]").size() > 0) { totalCount = Integer.parseInt( doc.select("span[id$=TotalItemsLabel]").first().text().split("[ \\t\\xA0\\u1680\\u180e\\u2000-\\u200a\\u202f\\u205f\\u3000]")[0]); } else { throw new OpacErrorException(stringProvider.getString(StringProvider.UNKNOWN_ERROR)); } Pattern idPattern = Pattern.compile("\\$(mdv|civ|dcv)(\\d+)\\$"); Pattern weakIdPattern = Pattern.compile("(mdv|civ|dcv)(\\d+)[^\\d]"); // Determine portalID value for availability AvailabilityRestInfo restInfo = getAvailabilityRestInfo(doc); Elements elements = doc.select("div[id$=divMedium], div[id$=divComprehensiveItem], div[id$=divDependentCatalogue]"); List<SearchResult> results = new ArrayList<>(); int i = 0; List<CompletableFuture<Void>> futures = new ArrayList<>(); for (Element element : elements) { final SearchResult result = new SearchResult(); // Cover if (element.select("input[id$=mediumImage]").size() > 0) { result.setCover(element.select("input[id$=mediumImage]").first().attr("src")); } else if (element.select("img[id$=CoverView_Image]").size() > 0) { assignBestCover(result, getCoverUrlList(element.select("img[id$=CoverView_Image]").first())); } Element catalogueContent = element.select(".catalogueContent, .oclc-searchmodule-mediumview-content, .oclc-searchmodule-comprehensiveitemview-content, .oclc-searchmodule-dependentitemview-content") .first(); // Media Type if (catalogueContent.select("#spanMediaGrpIcon, .spanMediaGrpIcon").size() > 0) { String mediatype = catalogueContent.select("#spanMediaGrpIcon, .spanMediaGrpIcon").attr("class"); if (mediatype.startsWith("itemtype ")) { mediatype = mediatype.substring("itemtype ".length()); } if ("".equals(mediatype)) { // fallback: use text media type if icon is not available (e.g. Wien) mediatype = catalogueContent.select("[id$=spanMediaGrpValue]").text(); } SearchResult.MediaType defaulttype = defaulttypes.get(mediatype); if (defaulttype == null) defaulttype = SearchResult.MediaType.UNKNOWN; if (data.has("mediatypes")) { try { result.setType(SearchResult.MediaType .valueOf(data.getJSONObject("mediatypes").getString(mediatype))); } catch (JSONException e) { result.setType(defaulttype); } } else { result.setType(defaulttype); } } else { result.setType(SearchResult.MediaType.UNKNOWN); } // Text String title = catalogueContent .select("a[id$=LbtnShortDescriptionValue], a[id$=LbtnTitleValue]").text(); String subtitle = catalogueContent.select("span[id$=LblSubTitleValue]").text(); String author = catalogueContent.select("span[id$=LblAuthorValue]").text(); String year = catalogueContent.select("span[id$=LblProductionYearValue]").text(); String mediumIdentifier = catalogueContent.select("span[id$=LblMediumIdentifierValue]").text(); String series = catalogueContent.select("span[id$=LblSeriesValue]").text(); // Some libraries, such as Bern, have labels but no <span id="..Value"> tags int j = 0; for (Element div : catalogueContent.children()) { if (subtitle.equals("") && div.select("span").size() == 0 && j > 0 && j < 3) { subtitle = div.text().trim(); } if (author.equals("") && div.select("span[id$=LblAuthor]").size() == 1) { author = div.text().trim(); if (author.contains(":")) { author = author.split(":")[1]; } } if (year.equals("") && div.select("span[id$=LblProductionYear]").size() == 1) { year = div.text().trim(); if (year.contains(":")) { year = year.split(":")[1]; } } j++; } StringBuilder text = new StringBuilder(); text.append("<b>").append(title).append("</b>"); if (!subtitle.equals("")) text.append("<br/>").append(subtitle); if (!author.equals("")) text.append("<br/>").append(author); if (!mediumIdentifier.equals("")) text.append("<br/>").append(mediumIdentifier); if (!year.equals("")) text.append("<br/>").append(year); if (!series.equals("")) text.append("<br/>").append(series); result.setInnerhtml(text.toString()); // ID Matcher matcher = idPattern.matcher(element.html()); if (matcher.find()) { result.setId(matcher.group(2)); } else { matcher = weakIdPattern.matcher(element.html()); if (matcher.find()) { result.setId(matcher.group(2)); } } // Availability if (result.getId() != null) { String culture = element.select("input[name$=culture]").val(); String ekzid = element.select("input[name$=ekzid]").val(); boolean ebook = !ekzid.equals(""); String url; if (ebook) { url = restInfo.ebookRestUrl != null ? restInfo.ebookRestUrl : opac_url + "/DesktopModules/OCLC.OPEN.PL.DNN.CopConnector/Services" + "/Onleihe.asmx/GetNcipLookupItem"; } else { url = restInfo.restUrl != null ? restInfo.restUrl : opac_url + "/DesktopModules/OCLC.OPEN.PL.DNN.SearchModule/" + "SearchService.asmx/GetAvailability"; } JSONObject data = new JSONObject(); try { if (ebook) { data.put("portalId", restInfo.portalId).put("itemid", ekzid) .put("language", culture); } else { data.put("portalId", restInfo.portalId).put("mednr", result.getId()) .put("culture", culture).put("requestCopyData", false) .put("branchFilter", ""); } RequestBody entity = RequestBody.create(MEDIA_TYPE_JSON, data.toString()); futures.add(asyncPost(url, entity, false).handle((response, throwable) -> { if (throwable != null) return null; ResponseBody body = response.body(); try { JSONObject availabilityData = new JSONObject(body.string()); String isAvail; if (ebook) { isAvail = availabilityData .getJSONObject("d").getJSONObject("LookupItem") .getString("Available"); } else { isAvail = availabilityData .getJSONObject("d").getString("IsAvail"); } switch (isAvail) { case "true": result.setStatus(SearchResult.Status.GREEN); break; case "false": result.setStatus(SearchResult.Status.RED); break; case "digital": result.setStatus(SearchResult.Status.UNKNOWN); break; } } catch (JSONException | IOException e) { e.printStackTrace(); } body.close(); return null; })); } catch (JSONException e) { e.printStackTrace(); } } result.setNr(i); results.add(result); } CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).join(); return new SearchRequestResult(results, totalCount, page); } private AvailabilityRestInfo getAvailabilityRestInfo(Document doc) { AvailabilityRestInfo info = new AvailabilityRestInfo(); info.portalId = 1; for (Element scripttag : doc.select("script")) { String scr = scripttag.html(); if (scr.contains("LoadSharedCatalogueViewAvailabilityAsync")) { Pattern pattern = Pattern.compile( ".*LoadSharedCatalogueViewAvailabilityAsync\\(\"([^,]*)\",\"([^,]*)\"," + "[^0-9,]*([0-9]+)[^0-9,]*,.*\\).*"); Matcher matcher = pattern.matcher(scr); if (matcher.find()) { info.restUrl = getAbsoluteUrl(opac_url, matcher.group(1)); info.ebookRestUrl = getAbsoluteUrl(opac_url, matcher.group(2)); info.portalId = Integer.parseInt(matcher.group(3)); } } } return info; } protected static String getAbsoluteUrl(String baseUrl, String url) { if (!url.contains("://")) { try { URIBuilder uriBuilder = new URIBuilder(baseUrl); url = uriBuilder.setPath(url) .build() .normalize().toString(); } catch (URISyntaxException e) { e.printStackTrace(); } } return url; } private class AvailabilityRestInfo { public int portalId; public String restUrl; public String ebookRestUrl; } private List<String> getCoverUrlList(Element img) { String[] parts = img.attr("sources").split("\\|"); // Example: SetSimpleCover|a|https://vlb.de/GetBlob.aspx?strIsbn=9783868511291&amp; // size=S|a|http://www.buchhandel.de/default.aspx?strframe=titelsuche&amp; // caller=vlbPublic&amp;func=DirectIsbnSearch&amp;isbn=9783868511291&amp; // nSiteId=11|c|SetNoCover|a|/DesktopModules/OCLC.OPEN.PL.DNN // .BaseLibrary/StyleSheets/Images/Fallbacks/emptyURL.gif?4.2.0.0|a| List<String> alternatives = new ArrayList<>(); for (int i = 0; i + 2 < parts.length; i++) { if (parts[i].equals("SetSimpleCover")) { String url = parts[i + 2].replace("&amp;", "&"); try { alternatives.add(new URL(new URL(opac_url), url).toString()); } catch (MalformedURLException ignored) { } } } if (img.hasAttr("devsources")) { parts = img.attr("devsources").split("\\|"); for (int i = 0; i + 2 < parts.length; i++) { if (parts[i].equals("SetSimpleCover")) { String url = parts[i + 2].replace("&amp;", "&"); try { alternatives.add(new URL(new URL(opac_url), url).toString()); } catch (MalformedURLException ignored) { } } } } return alternatives; } private String numberToText(int number) { switch (number) { case 1: return "First"; case 2: return "Second"; case 3: return "Third"; default: return null; } } @Override public SearchRequestResult filterResults(Filter filter, Filter.Option option) throws IOException, OpacErrorException { return null; } @Override public SearchRequestResult searchGetPage(int page) throws IOException, OpacErrorException, JSONException { if (searchResultDoc == null) throw new NotReachableException(); Document doc = searchResultDoc; if (doc.select("span[id$=DataPager1]").size() == 0) { /* New style: Page buttons using normal links We can go directly to the correct page */ if (doc.select("a[id*=LinkButtonPageN]").size() > 0) { String href = doc.select("a[id*=LinkButtonPageN][href*=page]").first().attr("href"); String url = href.replaceFirst("page=\\d+", "page=" + page); Document doc2 = Jsoup.parse(httpGet(url, getDefaultEncoding())); doc2.setBaseUri(url); return parse_search(doc2, page); } else { int totalCount; try { totalCount = Integer.parseInt( doc.select("span[id$=TotalItemsLabel]").first().text()); } catch (Exception e) { totalCount = 0; } // Next page does not exist return new SearchRequestResult( new ArrayList<SearchResult>(), 0, totalCount ); } } else { /* Old style: Page buttons using Javascript When there are many pages of results, there will only be links to the next 4 and previous 4 pages, so we will click links until it gets to the correct page. */ Elements pageLinks = doc.select("span[id$=DataPager1]").first() .select("a[id*=LinkButtonPageN], span[id*=LabelPageN]"); int from = Integer.valueOf(pageLinks.first().text()); int to = Integer.valueOf(pageLinks.last().text()); Element linkToClick; boolean willBeCorrectPage; if (page < from) { linkToClick = pageLinks.first(); willBeCorrectPage = false; } else if (page > to) { linkToClick = pageLinks.last(); willBeCorrectPage = false; } else { linkToClick = pageLinks.get(page - from); willBeCorrectPage = true; } if (linkToClick.tagName().equals("span")) { // we are trying to get the page we are already on return parse_search(searchResultDoc, page); } Pattern pattern = Pattern.compile("javascript:__doPostBack\\('([^,]*)','([^\\)]*)'\\)"); Matcher matcher = pattern.matcher(linkToClick.attr("href")); if (!matcher.find()) throw new OpacErrorException(StringProvider.INTERNAL_ERROR); FormElement form = (FormElement) doc.select("form").first(); MultipartBody data = formData(form, null).addFormDataPart("__EVENTTARGET", matcher.group(1)) .addFormDataPart("__EVENTARGUMENT", matcher.group(2)) .build(); String postUrl = form.attr("abs:action"); String html = httpPost(postUrl, data, "UTF-8"); if (willBeCorrectPage) { // We clicked on the correct link Document doc2 = Jsoup.parse(html); doc2.setBaseUri(postUrl); return parse_search(doc2, page); } else { // There was no correct link, so try to find one again searchResultDoc = Jsoup.parse(html); searchResultDoc.setBaseUri(postUrl); return searchGetPage(page); } } } @Override public DetailedItem getResultById(String id, String homebranch) throws IOException, OpacErrorException { try { String url; if (id.startsWith("https://") || id.startsWith("http://")) { url = id; } else { url = opac_url + "/" + data.getJSONObject("urls").getString("simple_search") + NO_MOBILE + "&id=" + id; } Document doc = Jsoup.parse(httpGet(url, getDefaultEncoding())); doc.setBaseUri(url); return parse_result(doc); } catch (JSONException e) { throw new IOException(e.getMessage()); } } protected DetailedItem parse_result(Document doc) { DetailedItem item = new DetailedItem(); // Title and Subtitle item.setTitle(doc.select("span[id$=LblShortDescriptionValue], span[id$=LblTitleValue]").text()); String subtitle = doc.select("span[id$=LblSubTitleValue]").text(); if (subtitle.equals("") && doc.select("span[id$=LblShortDescriptionValue]").size() > 0) { // Subtitle detection for Bern Element next = doc.select("span[id$=LblShortDescriptionValue]").first().parent() .nextElementSibling(); if (next.select("span").size() == 0) { subtitle = next.text().trim(); } } if (!subtitle.equals("")) { item.addDetail(new Detail(stringProvider.getString(StringProvider.SUBTITLE), subtitle)); } // Cover if (doc.select("input[id$=mediumImage]").size() > 0) { item.setCover(doc.select("input[id$=mediumImage]").attr("src")); } else if (doc.select("img[id$=CoverView_Image]").size() > 0) { assignBestCover(item, getCoverUrlList(doc.select("img[id$=CoverView_Image]").first())); } // ID item.setId(doc.select("input[id$=regionmednr]").val()); // Description if (doc.select("span[id$=ucCatalogueContent_LblAnnotation]").size() > 0) { String name = doc.select("span[id$=lblCatalogueContent]").text(); String value = doc.select("span[id$=ucCatalogueContent_LblAnnotation]").text(); item.addDetail(new Detail(name, value)); } // Parent if (doc.select("a[id$=HyperLinkParent]").size() > 0) { item.setCollectionId(doc.select("a[id$=HyperLinkParent]").first().attr("href")); } // Details String DETAIL_SELECTOR = "div[id$=CatalogueDetailView] .spacingBottomSmall:has(span+span)," + "div[id$=CatalogueDetailView] .spacingBottomSmall:has(span+a), " + "div[id$=CatalogueDetailView] .oclc-searchmodule-detail-data div:has" + "(span+span), " + "div[id$=CatalogueDetailView] .oclc-searchmodule-detail-data div:has" + "(span+a)"; for (Element detail : doc.select(DETAIL_SELECTOR)) { String name = detail.select("span").get(0).text().replace(": ", ""); String value = ""; if (detail.select("a").size() > 1) { int i = 0; for (Element a : detail.select("a")) { if (i != 0) { value += ", "; } value += a.text().trim(); i++; } } else { value = detail.select("span, a").get(1).text(); if (value.contains("hier klicken") && detail.select("a").size() > 0) { value = value + " " + detail.select("a").first().attr("href"); } } item.addDetail(new Detail(name, value)); } // Description if (doc.select("div[id$=CatalogueContent]").size() > 0) { String name = doc.select("div[id$=CatalogueContent] .oclc-module-header").text(); String value = doc.select("div[id$=CatalogueContent] .oclc-searchmodule-detail-annotation") .text(); item.addDetail(new Detail(name, value)); } // Copies Element table = doc.select("table[id$=grdViewMediumCopies]").first(); if (table != null) { Elements trs = table.select("tr"); List<String> columnmap = new ArrayList<>(); for (Element th : trs.first().select("th")) { columnmap.add(getCopyColumnKey(th.text())); } DateTimeFormatter fmt = DateTimeFormat.forPattern("dd.MM.yyyy").withLocale(Locale.GERMAN); for (int i = 1; i < trs.size(); i++) { Elements tds = trs.get(i).select("td"); Copy copy = new Copy(); for (int j = 0; j < tds.size(); j++) { if (columnmap.get(j) == null) continue; String text = tds.get(j).text().replace("\u00a0", ""); if (tds.get(j).select(".oclc-module-label").size() > 0 && tds.get(j).select("span").size() == 2) { text = tds.get(j).select("span").get(1).text(); } if (text.equals("")) continue; String colname = columnmap.get(j); if (copy.get(colname) != null && !copy.get(colname).isEmpty()) { text = copy.get(colname) + " / " + text; } copy.set(colname, text, fmt); } item.addCopy(copy); } } // Dependent (e.g. Verden) if (doc.select("div[id$=DivDependentCatalogue]").size() > 0) { String url = opac_url + "/DesktopModules/OCLC.OPEN.PL.DNN.SearchModule/SearchService.asmx/GetDependantCatalogues"; JSONObject postData = new JSONObject(); // Determine portalID value int portalId = 1; for (Element scripttag : doc.select("script")) { String scr = scripttag.html(); if (scr.contains("LoadCatalogueViewDependantCataloguesAsync")) { Pattern portalIdPattern = Pattern.compile( ".*LoadCatalogueViewDependantCataloguesAsync\\([^,]*,[^,]*," + "[^,]*,[^,]*,[^,]*,[^0-9,]*([0-9]+)[^0-9,]*,.*\\).*"); Matcher portalIdMatcher = portalIdPattern.matcher(scr); if (portalIdMatcher.find()) { portalId = Integer.parseInt(portalIdMatcher.group(1)); } } } try { postData.put("portalId", portalId).put("mednr", item.getId()) .put("tabUrl", opac_url + "/" + data.getJSONObject("urls").getString("simple_search") + NO_MOBILE + "&id=") .put("branchFilter", ""); RequestBody entity = RequestBody.create(MEDIA_TYPE_JSON, postData.toString()); String json = httpPost(url, entity, getDefaultEncoding()); JSONObject volumeData = new JSONObject(json); JSONArray cat = volumeData.getJSONObject("d").getJSONArray("Catalogues"); for (int i = 0; i < cat.length(); i++) { JSONObject obj = cat.getJSONObject(i); Map<String, String> params = getQueryParamsFirst(obj.getString("DependantUrl")); item.addVolume(new Volume( params.get("id"), obj.getString("DependantTitle") )); } } catch (JSONException | IOException e) { e.printStackTrace(); } } return item; } protected String getCopyColumnKey(String text) { switch (text) { case "Zweigstelle": case "Bibliothek": return "branch"; case "Standorte": case "Standort": case "Standort 2": case "Standort 3": return "location"; case "Status": return "status"; case "Vorbestellungen": return "reservations"; case "Frist": case "Rückgabedatum": return "returndate"; case "Signatur": return "signature"; case "Barcode": return "barcode"; default: return null; } } @Override public DetailedItem getResult(int position) throws IOException, OpacErrorException { return null; } @Override public ReservationResult reservation(DetailedItem item, Account account, int useraction, String selection) throws IOException { return null; } @Override public ProlongResult prolong(String media, Account account, int useraction, String selection) throws IOException { return null; } @Override public ProlongAllResult prolongAll(Account account, int useraction, String selection) throws IOException { return null; } @Override public CancelResult cancel(String media, Account account, int useraction, String selection) throws IOException, OpacErrorException { return null; } @Override public AccountData account(Account account) throws IOException, JSONException, OpacErrorException { return null; } @Override public void checkAccountData(Account account) throws IOException, JSONException, OpacErrorException { } @Override public List<SearchField> parseSearchFields() throws IOException, OpacErrorException, JSONException { String url = opac_url + "/" + data.getJSONObject("urls").getString("advanced_search") + NO_MOBILE; Document doc = Jsoup.parse(httpGet(url, getDefaultEncoding())); if (doc.select("[id$=LblErrorMsg]").size() > 0 && doc.select("[id$=ContentPane] input").size() == 0) { throw new OpacErrorException(doc.select("[id$=LblErrorMsg]").text()); } Element module = doc.select(".ModOPENExtendedSearchModuleC").first(); List<SearchField> fields = new ArrayList<>(); JSONObject selectable = new JSONObject(); selectable.put("selectable", true); JSONObject notSelectable = new JSONObject(); notSelectable.put("selectable", false); // Selectable search criteria Elements options = module.select("select[id$=FirstSearchField] option"); for (Element option : options) { TextSearchField field = new TextSearchField(); field.setId(option.val()); field.setDisplayName(option.text()); field.setData(selectable); fields.add(field); } // More criteria Element moreHeader = null; if (module.select("table").size() == 1) { moreHeader = module.select("span[id$=LblMoreCriterias]").parents().select("tr").first(); } else { // Newer OPEN, e.g. Erlangen moreHeader = module.select("span[id$=LblMoreCriterias]").first(); } if (moreHeader != null) { Elements siblings = moreHeader.siblingElements(); int startIndex = moreHeader.elementSiblingIndex(); for (int i = startIndex; i < siblings.size(); i++) { Element tr = siblings.get(i); if (tr.select("input, select").size() == 0) continue; if (tr.select("input[type=text]").size() == 1) { Element input = tr.select("input[type=text]").first(); TextSearchField field = new TextSearchField(); field.setId(input.attr("name")); field.setDisplayName(tr.select("span[id*=Lbl]").first().text()); field.setData(notSelectable); if (tr.text().contains("nur Ziffern")) field.setNumber(true); fields.add(field); } else if (tr.select("input[type=text]").size() == 2) { Element input1 = tr.select("input[type=text]").get(0); Element input2 = tr.select("input[type=text]").get(1); TextSearchField field1 = new TextSearchField(); field1.setId(input1.attr("name")); field1.setDisplayName(tr.select("span[id*=Lbl]").first().text()); field1.setData(notSelectable); if (tr.text().contains("nur Ziffern")) field1.setNumber(true); fields.add(field1); TextSearchField field2 = new TextSearchField(); field2.setId(input2.attr("name")); field2.setDisplayName(tr.select("span[id*=Lbl]").first().text()); field2.setData(notSelectable); field2.setHalfWidth(true); if (tr.text().contains("nur Ziffern")) field2.setNumber(true); fields.add(field2); } else if (tr.select("select").size() == 1) { Element select = tr.select("select").first(); DropdownSearchField dropdown = new DropdownSearchField(); dropdown.setId(select.attr("name")); dropdown.setDisplayName(tr.select("span[id*=Lbl]").first().text()); List<DropdownSearchField.Option> values = new ArrayList<>(); for (Element option : select.select("option")) { DropdownSearchField.Option opt = new DropdownSearchField.Option(option.val(), option.text()); values.add(opt); } dropdown.setDropdownValues(values); fields.add(dropdown); } else if (tr.select("input[type=checkbox]").size() == 1) { Element checkbox = tr.select("input[type=checkbox]").first(); CheckboxSearchField field = new CheckboxSearchField(); field.setId(checkbox.attr("name")); field.setDisplayName(tr.select("span[id*=Lbl]").first().text()); fields.add(field); } } } return fields; } @Override public String getShareUrl(String id, String title) { return opac_url + "/Permalink.aspx" + "?id" + "=" + id; } @Override public int getSupportFlags() { return SUPPORT_FLAG_ENDLESS_SCROLLING; } @Override public Set<String> getSupportedLanguages() throws IOException { return null; } @Override public void setLanguage(String language) { } @Override protected String getDefaultEncoding() { try { if (data.has("charset")) { return data.getString("charset"); } } catch (JSONException e) { e.printStackTrace(); } return "UTF-8"; } static StringBuilder appendQuotedString(StringBuilder target, String key) { target.append('"'); for (int i = 0, len = key.length(); i < len; i++) { char ch = key.charAt(i); switch (ch) { case '\n': target.append("%0A"); break; case '\r': target.append("%0D"); break; case '"': target.append("%22"); break; default: target.append(ch); break; } } target.append('"'); return target; } public static MultipartBody.Part createFormData(String name, String value) { return createFormData(name, null, RequestBody.create(null, value.getBytes())); } public static MultipartBody.Part createFormData(String name, String filename, RequestBody body) { if (name == null) { throw new NullPointerException("name == null"); } StringBuilder disposition = new StringBuilder("form-data; name="); appendQuotedString(disposition, name); if (filename != null) { disposition.append("; filename="); appendQuotedString(disposition, filename); } return create(Headers.of("Content-Disposition", disposition.toString()), body); } /** * Better version of JSoup's implementation of this function ({@link * org.jsoup.nodes.FormElement#formData()}). * * @param form The form to submit * @param submitName The name attribute of the button which is clicked to submit the form, or * null * @return A MultipartEntityBuilder containing the data of the form */ protected static MultipartBody.Builder formData(FormElement form, String submitName) { MultipartBody.Builder data = new MultipartBody.Builder(); data.setType(MediaType.parse("multipart/form-data")); // data.setCharset somehow breaks everything in Bern. // data.addTextBody breaks utf-8 characters in select boxes in Bern // .getBytes is an implicit, undeclared UTF-8 conversion, this seems to work -- at least // in Bern // Remove nested forms form.select("form form").remove(); form = ((FormElement) Jsoup.parse(form.outerHtml()).select("form").get(0)); // iterate the form control elements and accumulate their values for (Element el : form.elements()) { if (!el.tag().isFormSubmittable()) { continue; // contents are form listable, superset of submitable } String name = el.attr("name"); if (name.length() == 0) continue; String type = el.attr("type"); if ("select".equals(el.tagName())) { Elements options = el.select("option[selected]"); boolean set = false; for (Element option : options) { data.addPart(createFormData(name, option.val())); set = true; } if (!set) { Element option = el.select("option").first(); if (option != null) { data.addPart(createFormData(name, option.val())); } } } else if ("checkbox".equalsIgnoreCase(type) || "radio".equalsIgnoreCase(type)) { // only add checkbox or radio if they have the checked attribute if (el.hasAttr("checked")) { data.addFormDataPart(name, el.val().length() > 0 ? el.val() : "on"); } } else if ("submit".equalsIgnoreCase(type) || "image".equalsIgnoreCase(type) || "button".equalsIgnoreCase(type)) { if (submitName != null && el.attr("name").contains(submitName)) { data.addPart(createFormData(name, el.val())); } } else { data.addPart(createFormData(name, el.val())); } } return data; } }
OPEN: Recognize links to ebibliomedia
opacclient/libopac/src/main/java/de/geeksfactory/opacclient/apis/OpenSearch.java
OPEN: Recognize links to ebibliomedia
<ide><path>pacclient/libopac/src/main/java/de/geeksfactory/opacclient/apis/OpenSearch.java <ide> } <ide> } else { <ide> value = detail.select("span, a").get(1).text(); <del> if (value.contains("hier klicken") && detail.select("a").size() > 0) { <add> if ((value.contains("ffnen") || value.contains("hier klicken")) && detail.select("a").size() > 0) { <ide> value = value + " " + detail.select("a").first().attr("href"); <ide> } <ide> }
JavaScript
mit
22be57ccb3b99e27dfc771ec1d4571b6d6087454
0
GoodBoyDigital/p2.js,beni55/p2.js,mcanthony/p2.js,modulexcite/p2.js,psalaets/p2.js,beni55/p2.js,psalaets/p2.js,koopero/p2.js,markware/p2.js,GoodBoyDigital/p2.js,koopero/p2.js,markware/p2.js,mcanthony/p2.js,modulexcite/p2.js
var vec2 = require('../math/vec2') , decomp = require('poly-decomp') , Convex = require('../shapes/Convex') , AABB = require('../collision/AABB') , EventEmitter = require('../events/EventEmitter'); module.exports = Body; /** * A rigid body. Has got a center of mass, position, velocity and a number of * shapes that are used for collisions. * * @class Body * @constructor * @extends EventEmitter * @param {Object} [options] * @param {Number} [options.mass=0] A number >= 0. If zero, the .type will be set to Body.STATIC. * @param {Array} [options.position] * @param {Array} [options.velocity] * @param {Number} [options.angle=0] * @param {Number} [options.angularVelocity=0] * @param {Array} [options.force] * @param {Number} [options.angularForce=0] * @param {Number} [options.fixedRotation=false] * @param {Number} [options.ccdSpeedThreshold=-1] * @param {Number} [options.ccdIterations=10] * * @example * * // Create a typical dynamic body * var body = new Body({ * mass: 1, * position: [0, 0], * angle: 0, * velocity: [0, 0], * angularVelocity: 0 * }); * * // Add a circular shape to the body * body.addShape(new Circle(1)); * * // Add the body to the world * world.addBody(body); */ function Body(options){ options = options || {}; EventEmitter.call(this); /** * The body identifyer * @property id * @type {Number} */ this.id = ++Body._idCounter; /** * The world that this body is added to. This property is set to NULL if the body is not added to any world. * @property world * @type {World} */ this.world = null; /** * The shapes of the body. The local transform of the shape in .shapes[i] is * defined by .shapeOffsets[i] and .shapeAngles[i]. * * @property shapes * @type {Array} */ this.shapes = []; /** * The local shape offsets, relative to the body center of mass. This is an * array of Array. * @property shapeOffsets * @type {Array} */ this.shapeOffsets = []; /** * The body-local shape angle transforms. This is an array of numbers (angles). * @property shapeAngles * @type {Array} */ this.shapeAngles = []; /** * The mass of the body. * @property mass * @type {number} */ this.mass = options.mass || 0; /** * The inverse mass of the body. * @property invMass * @type {number} */ this.invMass = 0; /** * The inertia of the body around the Z axis. * @property inertia * @type {number} */ this.inertia = 0; /** * The inverse inertia of the body. * @property invInertia * @type {number} */ this.invInertia = 0; this.invMassSolve = 0; this.invInertiaSolve = 0; /** * Set to true if you want to fix the rotation of the body. * @property fixedRotation * @type {Boolean} */ this.fixedRotation = !!options.fixedRotation; /** * The position of the body * @property position * @type {Array} */ this.position = vec2.fromValues(0,0); if(options.position){ vec2.copy(this.position, options.position); } /** * The interpolated position of the body. * @property interpolatedPosition * @type {Array} */ this.interpolatedPosition = vec2.fromValues(0,0); /** * The interpolated angle of the body. * @property interpolatedAngle * @type {Number} */ this.interpolatedAngle = 0; /** * The previous position of the body. * @property previousPosition * @type {Array} */ this.previousPosition = vec2.fromValues(0,0); /** * The previous angle of the body. * @property previousAngle * @type {Number} */ this.previousAngle = 0; /** * The velocity of the body * @property velocity * @type {Array} */ this.velocity = vec2.fromValues(0,0); if(options.velocity){ vec2.copy(this.velocity, options.velocity); } /** * Constraint velocity that was added to the body during the last step. * @property vlambda * @type {Array} */ this.vlambda = vec2.fromValues(0,0); /** * Angular constraint velocity that was added to the body during last step. * @property wlambda * @type {Array} */ this.wlambda = 0; /** * The angle of the body, in radians. * @property angle * @type {number} * @example * // The angle property is not normalized to the interval 0 to 2*pi, it can be any value. * // If you need a value between 0 and 2*pi, use the following function to normalize it. * function normalizeAngle(angle){ * angle = angle % (2*Math.PI); * if(angle < 0){ * angle += (2*Math.PI); * } * return angle; * } */ this.angle = options.angle || 0; /** * The angular velocity of the body, in radians per second. * @property angularVelocity * @type {number} */ this.angularVelocity = options.angularVelocity || 0; /** * The force acting on the body. Since the body force (and {{#crossLink "Body/angularForce:property"}}{{/crossLink}}) will be zeroed after each step, so you need to set the force before each step. * @property force * @type {Array} * * @example * // This produces a forcefield of 1 Newton in the positive x direction. * for(var i=0; i<numSteps; i++){ * body.force[0] = 1; * world.step(1/60); * } * * @example * // This will apply a rotational force on the body * for(var i=0; i<numSteps; i++){ * body.angularForce = -3; * world.step(1/60); * } */ this.force = vec2.create(); if(options.force){ vec2.copy(this.force, options.force); } /** * The angular force acting on the body. See {{#crossLink "Body/force:property"}}{{/crossLink}}. * @property angularForce * @type {number} */ this.angularForce = options.angularForce || 0; /** * The linear damping acting on the body in the velocity direction. Should be a value between 0 and 1. * @property damping * @type {Number} * @default 0.1 */ this.damping = typeof(options.damping) === "number" ? options.damping : 0.1; /** * The angular force acting on the body. Should be a value between 0 and 1. * @property angularDamping * @type {Number} * @default 0.1 */ this.angularDamping = typeof(options.angularDamping) === "number" ? options.angularDamping : 0.1; /** * The type of motion this body has. Should be one of: {{#crossLink "Body/STATIC:property"}}Body.STATIC{{/crossLink}}, {{#crossLink "Body/DYNAMIC:property"}}Body.DYNAMIC{{/crossLink}} and {{#crossLink "Body/KINEMATIC:property"}}Body.KINEMATIC{{/crossLink}}. * * * Static bodies do not move, and they do not respond to forces or collision. * * Dynamic bodies body can move and respond to collisions and forces. * * Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force. * * @property type * @type {number} * * @example * // Bodies are static by default. Static bodies will never move. * var body = new Body(); * console.log(body.type == Body.STATIC); // true * * @example * // By setting the mass of a body to a nonzero number, the body * // will become dynamic and will move and interact with other bodies. * var dynamicBody = new Body({ * mass : 1 * }); * console.log(dynamicBody.type == Body.DYNAMIC); // true * * @example * // Kinematic bodies will only move if you change their velocity. * var kinematicBody = new Body({ * type: Body.KINEMATIC // Type can be set via the options object. * }); */ this.type = Body.STATIC; if(typeof(options.type) !== 'undefined'){ this.type = options.type; } else if(!options.mass){ this.type = Body.STATIC; } else { this.type = Body.DYNAMIC; } /** * Bounding circle radius. * @property boundingRadius * @type {Number} */ this.boundingRadius = 0; /** * Bounding box of this body. * @property aabb * @type {AABB} */ this.aabb = new AABB(); /** * Indicates if the AABB needs update. Update it with {{#crossLink "Body/updateAABB:method"}}.updateAABB(){{/crossLink}}. * @property aabbNeedsUpdate * @type {Boolean} * @see updateAABB * * @example * // Force update the AABB * body.aabbNeedsUpdate = true; * body.updateAABB(); * console.log(body.aabbNeedsUpdate); // false */ this.aabbNeedsUpdate = true; /** * If true, the body will automatically fall to sleep. Note that you need to enable sleeping in the {{#crossLink "World"}}{{/crossLink}} before anything will happen. * @property allowSleep * @type {Boolean} * @default true */ this.allowSleep = true; this.wantsToSleep = false; /** * One of {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}}, {{#crossLink "Body/SLEEPY:property"}}Body.SLEEPY{{/crossLink}} and {{#crossLink "Body/SLEEPING:property"}}Body.SLEEPING{{/crossLink}}. * * The body is initially Body.AWAKE. If its velocity norm is below .sleepSpeedLimit, the sleepState will become Body.SLEEPY. If the body continues to be Body.SLEEPY for .sleepTimeLimit seconds, it will fall asleep (Body.SLEEPY). * * @property sleepState * @type {Number} * @default Body.AWAKE */ this.sleepState = Body.AWAKE; /** * If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy. * @property sleepSpeedLimit * @type {Number} * @default 0.2 */ this.sleepSpeedLimit = 0.2; /** * If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping. * @property sleepTimeLimit * @type {Number} * @default 1 */ this.sleepTimeLimit = 1; /** * Gravity scaling factor. If you want the body to ignore gravity, set this to zero. If you want to reverse gravity, set it to -1. * @property {Number} gravityScale * @default 1 */ this.gravityScale = 1; /** * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this body will move through other bodies, but it will still trigger contact events, etc. * @property {Boolean} collisionResponse */ this.collisionResponse = true; /** * How long the body has been sleeping. * @property {Number} idleTime */ this.idleTime = 0; /** * The last time when the body went to SLEEPY state. * @property {Number} timeLastSleepy * @private */ this.timeLastSleepy = 0; /** * If the body speed exceeds this threshold, CCD (continuous collision detection) will be enabled. Set it to a negative number to disable CCD completely for this body. * @property {number} ccdSpeedThreshold * @default -1 */ this.ccdSpeedThreshold = options.ccdSpeedThreshold !== undefined ? options.ccdSpeedThreshold : -1; /** * The number of iterations that should be used when searching for the time of impact during CCD. A larger number will assure that there's a small penetration on CCD collision, but a small number will give more performance. * @property {number} ccdIterations * @default 10 */ this.ccdIterations = options.ccdIterations !== undefined ? options.ccdIterations : 10; this.concavePath = null; this._wakeUpAfterNarrowphase = false; this.updateMassProperties(); } Body.prototype = new EventEmitter(); Body.prototype.constructor = Body; Body._idCounter = 0; Body.prototype.updateSolveMassProperties = function(){ if(this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC){ this.invMassSolve = 0; this.invInertiaSolve = 0; } else { this.invMassSolve = this.invMass; this.invInertiaSolve = this.invInertia; } }; /** * Set the total density of the body * @method setDensity */ Body.prototype.setDensity = function(density) { var totalArea = this.getArea(); this.mass = totalArea * density; this.updateMassProperties(); }; /** * Get the total area of all shapes in the body * @method getArea * @return {Number} */ Body.prototype.getArea = function() { var totalArea = 0; for(var i=0; i<this.shapes.length; i++){ totalArea += this.shapes[i].area; } return totalArea; }; /** * Get the AABB from the body. The AABB is updated if necessary. * @method getAABB */ Body.prototype.getAABB = function(){ if(this.aabbNeedsUpdate){ this.updateAABB(); } return this.aabb; }; var shapeAABB = new AABB(), tmp = vec2.create(); /** * Updates the AABB of the Body * @method updateAABB */ Body.prototype.updateAABB = function() { var shapes = this.shapes, shapeOffsets = this.shapeOffsets, shapeAngles = this.shapeAngles, N = shapes.length, offset = tmp, bodyAngle = this.angle; for(var i=0; i!==N; i++){ var shape = shapes[i], angle = shapeAngles[i] + bodyAngle; // Get shape world offset vec2.rotate(offset, shapeOffsets[i], bodyAngle); vec2.add(offset, offset, this.position); // Get shape AABB shape.computeAABB(shapeAABB, offset, angle); if(i===0){ this.aabb.copy(shapeAABB); } else { this.aabb.extend(shapeAABB); } } this.aabbNeedsUpdate = false; }; /** * Update the bounding radius of the body. Should be done if any of the shapes * are changed. * @method updateBoundingRadius */ Body.prototype.updateBoundingRadius = function(){ var shapes = this.shapes, shapeOffsets = this.shapeOffsets, N = shapes.length, radius = 0; for(var i=0; i!==N; i++){ var shape = shapes[i], offset = vec2.length(shapeOffsets[i]), r = shape.boundingRadius; if(offset + r > radius){ radius = offset + r; } } this.boundingRadius = radius; }; /** * Add a shape to the body. You can pass a local transform when adding a shape, * so that the shape gets an offset and angle relative to the body center of mass. * Will automatically update the mass properties and bounding radius. * * @method addShape * @param {Shape} shape * @param {Array} [offset] Local body offset of the shape. * @param {Number} [angle] Local body angle. * * @example * var body = new Body(), * shape = new Circle(); * * // Add the shape to the body, positioned in the center * body.addShape(shape); * * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis. * body.addShape(shape,[1,0]); * * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW. * body.addShape(shape,[0,1],Math.PI/2); */ Body.prototype.addShape = function(shape,offset,angle){ angle = angle || 0.0; // Copy the offset vector if(offset){ offset = vec2.fromValues(offset[0],offset[1]); } else { offset = vec2.fromValues(0,0); } this.shapes .push(shape); this.shapeOffsets.push(offset); this.shapeAngles .push(angle); this.updateMassProperties(); this.updateBoundingRadius(); this.aabbNeedsUpdate = true; }; /** * Remove a shape * @method removeShape * @param {Shape} shape * @return {Boolean} True if the shape was found and removed, else false. */ Body.prototype.removeShape = function(shape){ var idx = this.shapes.indexOf(shape); if(idx !== -1){ this.shapes.splice(idx,1); this.shapeOffsets.splice(idx,1); this.shapeAngles.splice(idx,1); this.aabbNeedsUpdate = true; return true; } else { return false; } }; /** * Updates .inertia, .invMass, .invInertia for this Body. Should be called when * changing the structure or mass of the Body. * * @method updateMassProperties * * @example * body.mass += 1; * body.updateMassProperties(); */ Body.prototype.updateMassProperties = function(){ if(this.type === Body.STATIC || this.type === Body.KINEMATIC){ this.mass = Number.MAX_VALUE; this.invMass = 0; this.inertia = Number.MAX_VALUE; this.invInertia = 0; } else { var shapes = this.shapes, N = shapes.length, m = this.mass / N, I = 0; if(!this.fixedRotation){ for(var i=0; i<N; i++){ var shape = shapes[i], r2 = vec2.squaredLength(this.shapeOffsets[i]), Icm = shape.computeMomentOfInertia(m); I += Icm + m*r2; } this.inertia = I; this.invInertia = I>0 ? 1/I : 0; } else { this.inertia = Number.MAX_VALUE; this.invInertia = 0; } // Inverse mass properties are easy this.invMass = 1/this.mass;// > 0 ? 1/this.mass : 0; } }; var Body_applyForce_r = vec2.create(); /** * Apply force to a world point. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. * @method applyForce * @param {Array} force The force to add. * @param {Array} worldPoint A world point to apply the force on. */ Body.prototype.applyForce = function(force,worldPoint){ // Compute point position relative to the body center var r = Body_applyForce_r; vec2.sub(r,worldPoint,this.position); // Add linear force vec2.add(this.force,this.force,force); // Compute produced rotational force var rotForce = vec2.crossLength(r,force); // Add rotational force this.angularForce += rotForce; }; /** * Transform a world point to local body frame. * @method toLocalFrame * @param {Array} out The vector to store the result in * @param {Array} worldPoint The input world vector */ Body.prototype.toLocalFrame = function(out, worldPoint){ vec2.toLocalFrame(out, worldPoint, this.position, this.angle); }; /** * Transform a local point to world frame. * @method toWorldFrame * @param {Array} out The vector to store the result in * @param {Array} localPoint The input local vector */ Body.prototype.toWorldFrame = function(out, localPoint){ vec2.toGlobalFrame(out, localPoint, this.position, this.angle); }; /** * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. * @method fromPolygon * @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes. * @param {Object} [options] * @param {Boolean} [options.optimalDecomp=false] Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. * @param {Boolean} [options.skipSimpleCheck=false] Set to true if you already know that the path is not intersecting itself. * @param {Boolean|Number} [options.removeCollinearPoints=false] Set to a number (angle threshold value) to remove collinear points, or false to keep all points. * @return {Boolean} True on success, else false. */ Body.prototype.fromPolygon = function(path,options){ options = options || {}; // Remove all shapes for(var i=this.shapes.length; i>=0; --i){ this.removeShape(this.shapes[i]); } var p = new decomp.Polygon(); p.vertices = path; // Make it counter-clockwise p.makeCCW(); if(typeof(options.removeCollinearPoints) === "number"){ p.removeCollinearPoints(options.removeCollinearPoints); } // Check if any line segment intersects the path itself if(typeof(options.skipSimpleCheck) === "undefined"){ if(!p.isSimple()){ return false; } } // Save this path for later this.concavePath = p.vertices.slice(0); for(var i=0; i<this.concavePath.length; i++){ var v = [0,0]; vec2.copy(v,this.concavePath[i]); this.concavePath[i] = v; } // Slow or fast decomp? var convexes; if(options.optimalDecomp){ convexes = p.decomp(); } else { convexes = p.quickDecomp(); } var cm = vec2.create(); // Add convexes for(var i=0; i!==convexes.length; i++){ // Create convex var c = new Convex(convexes[i].vertices); // Move all vertices so its center of mass is in the local center of the convex for(var j=0; j!==c.vertices.length; j++){ var v = c.vertices[j]; vec2.sub(v,v,c.centerOfMass); } vec2.scale(cm,c.centerOfMass,1); c.updateTriangles(); c.updateCenterOfMass(); c.updateBoundingRadius(); // Add the shape this.addShape(c,cm); } this.adjustCenterOfMass(); this.aabbNeedsUpdate = true; return true; }; var adjustCenterOfMass_tmp1 = vec2.fromValues(0,0), adjustCenterOfMass_tmp2 = vec2.fromValues(0,0), adjustCenterOfMass_tmp3 = vec2.fromValues(0,0), adjustCenterOfMass_tmp4 = vec2.fromValues(0,0); /** * Moves the shape offsets so their center of mass becomes the body center of mass. * @method adjustCenterOfMass */ Body.prototype.adjustCenterOfMass = function(){ var offset_times_area = adjustCenterOfMass_tmp2, sum = adjustCenterOfMass_tmp3, cm = adjustCenterOfMass_tmp4, totalArea = 0; vec2.set(sum,0,0); for(var i=0; i!==this.shapes.length; i++){ var s = this.shapes[i], offset = this.shapeOffsets[i]; vec2.scale(offset_times_area,offset,s.area); vec2.add(sum,sum,offset_times_area); totalArea += s.area; } vec2.scale(cm,sum,1/totalArea); // Now move all shapes for(var i=0; i!==this.shapes.length; i++){ var s = this.shapes[i], offset = this.shapeOffsets[i]; // Offset may be undefined. Fix that. if(!offset){ offset = this.shapeOffsets[i] = vec2.create(); } vec2.sub(offset,offset,cm); } // Move the body position too vec2.add(this.position,this.position,cm); // And concave path for(var i=0; this.concavePath && i<this.concavePath.length; i++){ vec2.sub(this.concavePath[i], this.concavePath[i], cm); } this.updateMassProperties(); this.updateBoundingRadius(); }; /** * Sets the force on the body to zero. * @method setZeroForce */ Body.prototype.setZeroForce = function(){ vec2.set(this.force,0.0,0.0); this.angularForce = 0.0; }; Body.prototype.resetConstraintVelocity = function(){ var b = this, vlambda = b.vlambda; vec2.set(vlambda,0,0); b.wlambda = 0; }; Body.prototype.addConstraintVelocity = function(){ var b = this, v = b.velocity; vec2.add( v, v, b.vlambda); b.angularVelocity += b.wlambda; }; /** * Apply damping, see <a href="http://code.google.com/p/bullet/issues/detail?id=74">this</a> for details. * @method applyDamping * @param {number} dt Current time step */ Body.prototype.applyDamping = function(dt){ if(this.type === Body.DYNAMIC){ // Only for dynamic bodies var v = this.velocity; vec2.scale(v, v, Math.pow(1.0 - this.damping,dt)); this.angularVelocity *= Math.pow(1.0 - this.angularDamping,dt); } }; /** * Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions. * Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before. * @method wakeUp */ Body.prototype.wakeUp = function(){ var s = this.sleepState; this.sleepState = Body.AWAKE; this.idleTime = 0; if(s !== Body.AWAKE){ this.emit(Body.wakeUpEvent); } }; /** * Force body sleep * @method sleep */ Body.prototype.sleep = function(){ this.sleepState = Body.SLEEPING; this.angularVelocity = 0; this.angularForce = 0; vec2.set(this.velocity,0,0); vec2.set(this.force,0,0); this.emit(Body.sleepEvent); }; /** * Called every timestep to update internal sleep timer and change sleep state if needed. * @method sleepTick * @param {number} time The world time in seconds * @param {boolean} dontSleep * @param {number} dt */ Body.prototype.sleepTick = function(time, dontSleep, dt){ if(!this.allowSleep || this.type === Body.SLEEPING){ return; } this.wantsToSleep = false; var sleepState = this.sleepState, speedSquared = vec2.squaredLength(this.velocity) + Math.pow(this.angularVelocity,2), speedLimitSquared = Math.pow(this.sleepSpeedLimit,2); // Add to idle time if(speedSquared >= speedLimitSquared){ this.idleTime = 0; this.sleepState = Body.AWAKE; } else { this.idleTime += dt; this.sleepState = Body.SLEEPY; } if(this.idleTime > this.sleepTimeLimit){ if(!dontSleep){ this.sleep(); } else { this.wantsToSleep = true; } } /* if(sleepState===Body.AWAKE && speedSquared < speedLimitSquared){ this.sleepState = Body.SLEEPY; // Sleepy this.timeLastSleepy = time; this.emit(Body.sleepyEvent); } else if(sleepState===Body.SLEEPY && speedSquared >= speedLimitSquared){ this.wakeUp(); // Wake up } else if(sleepState===Body.SLEEPY && (time - this.timeLastSleepy ) > this.sleepTimeLimit){ this.wantsToSleep = true; if(!dontSleep){ this.sleep(); } } */ }; Body.prototype.getVelocityFromPosition = function(store, timeStep){ store = store || vec2.create(); vec2.sub(store, this.position, this.previousPosition); vec2.scale(store, store, 1/timeStep); return store; }; Body.prototype.getAngularVelocityFromPosition = function(timeStep){ return (this.angle - this.previousAngle) / timeStep; }; /** * Check if the body is overlapping another body. Note that this method only works if the body was added to a World and if at least one step was taken. * @method overlaps * @param {Body} body * @return {boolean} */ Body.prototype.overlaps = function(body){ return this.world.overlapKeeper.bodiesAreOverlapping(this, body); }; var integrate_fhMinv = vec2.create(); var integrate_velodt = vec2.create(); /** * Move the body forward in time given its current velocity. * @method integrate * @param {Number} dt */ Body.prototype.integrate = function(dt){ var minv = this.invMass, f = this.force, pos = this.position, velo = this.velocity; // Save old position vec2.copy(this.previousPosition, this.position); this.previousAngle = this.angle; // Velocity update if(!this.fixedRotation){ this.angularVelocity += this.angularForce * this.invInertia * dt; } vec2.scale(integrate_fhMinv, f, dt * minv); vec2.add(velo, integrate_fhMinv, velo); // CCD if(!this.integrateToTimeOfImpact(dt)){ // Regular position update vec2.scale(integrate_velodt, velo, dt); vec2.add(pos, pos, integrate_velodt); if(!this.fixedRotation){ this.angle += this.angularVelocity * dt; } } this.aabbNeedsUpdate = true; }; var direction = vec2.create(); var end = vec2.create(); var startToEnd = vec2.create(); var rememberPosition = vec2.create(); Body.prototype.integrateToTimeOfImpact = function(dt){ if(this.ccdSpeedThreshold < 0 || vec2.squaredLength(this.velocity) < Math.pow(this.ccdSpeedThreshold, 2)){ return false; } vec2.normalize(direction, this.velocity); vec2.scale(end, this.velocity, dt); vec2.add(end, end, this.position); vec2.sub(startToEnd, end, this.position); var startToEndAngle = this.angularVelocity * dt; var len = vec2.length(startToEnd); var timeOfImpact = 1; var hit; var that = this; this.world.raycastAll(this.position, end, {}, function (result) { if(result.body === that){ return; } hit = result.body; vec2.copy(end, result.hitPointWorld); vec2.sub(startToEnd, result.hitPointWorld, that.position); timeOfImpact = vec2.length(startToEnd) / len; result.abort(); }); if(!hit){ return false; } var rememberAngle = this.angle; vec2.copy(rememberPosition, this.position); // Got a start and end point. Approximate time of impact using binary search var iter = 0; var tmin = 0; var tmid = 0; var tmax = timeOfImpact; while (tmax >= tmin && iter < this.ccdIterations) { iter++; // calculate the midpoint tmid = (tmax - tmin) / 2; // Move the body to that point vec2.scale(integrate_velodt, startToEnd, timeOfImpact); vec2.add(this.position, rememberPosition, integrate_velodt); this.angle = rememberAngle + startToEndAngle * timeOfImpact; this.updateAABB(); // check overlap var overlaps = this.aabb.overlaps(hit.aabb) && this.world.narrowphase.bodiesOverlap(this, hit); if (overlaps) { // change min to search upper interval tmin = tmid; } else { // change max to search lower interval tmax = tmid; } } timeOfImpact = tmid; vec2.copy(this.position, rememberPosition); this.angle = rememberAngle; // move to TOI vec2.scale(integrate_velodt, startToEnd, timeOfImpact); vec2.add(this.position, this.position, integrate_velodt); if(!this.fixedRotation){ this.angle += startToEndAngle * timeOfImpact; } return true; }; /** * @event sleepy */ Body.sleepyEvent = { type: "sleepy" }; /** * @event sleep */ Body.sleepEvent = { type: "sleep" }; /** * @event wakeup */ Body.wakeUpEvent = { type: "wakeup" }; /** * Dynamic body. * @property DYNAMIC * @type {Number} * @static */ Body.DYNAMIC = 1; /** * Static body. * @property STATIC * @type {Number} * @static */ Body.STATIC = 2; /** * Kinematic body. * @property KINEMATIC * @type {Number} * @static */ Body.KINEMATIC = 4; /** * @property AWAKE * @type {Number} * @static */ Body.AWAKE = 0; /** * @property SLEEPY * @type {Number} * @static */ Body.SLEEPY = 1; /** * @property SLEEPING * @type {Number} * @static */ Body.SLEEPING = 2;
src/objects/Body.js
var vec2 = require('../math/vec2') , decomp = require('poly-decomp') , Convex = require('../shapes/Convex') , AABB = require('../collision/AABB') , EventEmitter = require('../events/EventEmitter'); module.exports = Body; /** * A rigid body. Has got a center of mass, position, velocity and a number of * shapes that are used for collisions. * * @class Body * @constructor * @extends EventEmitter * @param {Object} [options] * @param {Number} [options.mass=0] A number >= 0. If zero, the .type will be set to Body.STATIC. * @param {Array} [options.position] * @param {Array} [options.velocity] * @param {Number} [options.angle=0] * @param {Number} [options.angularVelocity=0] * @param {Array} [options.force] * @param {Number} [options.angularForce=0] * @param {Number} [options.fixedRotation=false] * @param {Number} [options.ccdSpeedThreshold=-1] * @param {Number} [options.ccdIterations=10] * * @example * * // Create a typical dynamic body * var body = new Body({ * mass: 1, * position: [0, 0], * angle: 0, * velocity: [0, 0], * angularVelocity: 0 * }); * * // Add a circular shape to the body * body.addShape(new Circle(1)); * * // Add the body to the world * world.addBody(body); */ function Body(options){ options = options || {}; EventEmitter.call(this); /** * The body identifyer * @property id * @type {Number} */ this.id = ++Body._idCounter; /** * The world that this body is added to. This property is set to NULL if the body is not added to any world. * @property world * @type {World} */ this.world = null; /** * The shapes of the body. The local transform of the shape in .shapes[i] is * defined by .shapeOffsets[i] and .shapeAngles[i]. * * @property shapes * @type {Array} */ this.shapes = []; /** * The local shape offsets, relative to the body center of mass. This is an * array of Array. * @property shapeOffsets * @type {Array} */ this.shapeOffsets = []; /** * The body-local shape angle transforms. This is an array of numbers (angles). * @property shapeAngles * @type {Array} */ this.shapeAngles = []; /** * The mass of the body. * @property mass * @type {number} */ this.mass = options.mass || 0; /** * The inverse mass of the body. * @property invMass * @type {number} */ this.invMass = 0; /** * The inertia of the body around the Z axis. * @property inertia * @type {number} */ this.inertia = 0; /** * The inverse inertia of the body. * @property invInertia * @type {number} */ this.invInertia = 0; this.invMassSolve = 0; this.invInertiaSolve = 0; /** * Set to true if you want to fix the rotation of the body. * @property fixedRotation * @type {Boolean} */ this.fixedRotation = !!options.fixedRotation; /** * The position of the body * @property position * @type {Array} */ this.position = vec2.fromValues(0,0); if(options.position){ vec2.copy(this.position, options.position); } /** * The interpolated position of the body. * @property interpolatedPosition * @type {Array} */ this.interpolatedPosition = vec2.fromValues(0,0); /** * The interpolated angle of the body. * @property interpolatedAngle * @type {Number} */ this.interpolatedAngle = 0; /** * The previous position of the body. * @property previousPosition * @type {Array} */ this.previousPosition = vec2.fromValues(0,0); /** * The previous angle of the body. * @property previousAngle * @type {Number} */ this.previousAngle = 0; /** * The velocity of the body * @property velocity * @type {Array} */ this.velocity = vec2.fromValues(0,0); if(options.velocity){ vec2.copy(this.velocity, options.velocity); } /** * Constraint velocity that was added to the body during the last step. * @property vlambda * @type {Array} */ this.vlambda = vec2.fromValues(0,0); /** * Angular constraint velocity that was added to the body during last step. * @property wlambda * @type {Array} */ this.wlambda = 0; /** * The angle of the body, in radians. * @property angle * @type {number} * @example * // The angle property is not normalized to the interval 0 to 2*pi, it can be any value. * // If you need a value between 0 and 2*pi, use the following function to normalize it. * function normalizeAngle(angle){ * angle = angle % (2*Math.PI); * if(angle < 0){ * angle += (2*Math.PI); * } * return angle; * } */ this.angle = options.angle || 0; /** * The angular velocity of the body, in radians per second. * @property angularVelocity * @type {number} */ this.angularVelocity = options.angularVelocity || 0; /** * The force acting on the body. Since the body force (and {{#crossLink "Body/angularForce:property"}}{{/crossLink}}) will be zeroed after each step, so you need to set the force before each step. * @property force * @type {Array} * * @example * // This produces a forcefield of 1 Newton in the positive x direction. * for(var i=0; i<numSteps; i++){ * body.force[0] = 1; * world.step(1/60); * } * * @example * // This will apply a rotational force on the body * for(var i=0; i<numSteps; i++){ * body.angularForce = -3; * world.step(1/60); * } */ this.force = vec2.create(); if(options.force){ vec2.copy(this.force, options.force); } /** * The angular force acting on the body. See {{#crossLink "Body/force:property"}}{{/crossLink}}. * @property angularForce * @type {number} */ this.angularForce = options.angularForce || 0; /** * The linear damping acting on the body in the velocity direction. Should be a value between 0 and 1. * @property damping * @type {Number} * @default 0.1 */ this.damping = typeof(options.damping) === "number" ? options.damping : 0.1; /** * The angular force acting on the body. Should be a value between 0 and 1. * @property angularDamping * @type {Number} * @default 0.1 */ this.angularDamping = typeof(options.angularDamping) === "number" ? options.angularDamping : 0.1; /** * The type of motion this body has. Should be one of: {{#crossLink "Body/STATIC:property"}}Body.STATIC{{/crossLink}}, {{#crossLink "Body/DYNAMIC:property"}}Body.DYNAMIC{{/crossLink}} and {{#crossLink "Body/KINEMATIC:property"}}Body.KINEMATIC{{/crossLink}}. * * * Static bodies do not move, and they do not respond to forces or collision. * * Dynamic bodies body can move and respond to collisions and forces. * * Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force. * * @property type * @type {number} * * @example * // Bodies are static by default. Static bodies will never move. * var body = new Body(); * console.log(body.type == Body.STATIC); // true * * @example * // By setting the mass of a body to a nonzero number, the body * // will become dynamic and will move and interact with other bodies. * var dynamicBody = new Body({ * mass : 1 * }); * console.log(dynamicBody.type == Body.DYNAMIC); // true * * @example * // Kinematic bodies will only move if you change their velocity. * var kinematicBody = new Body({ * type: Body.KINEMATIC // Type can be set via the options object. * }); */ this.type = Body.STATIC; if(typeof(options.type) !== 'undefined'){ this.type = options.type; } else if(!options.mass){ this.type = Body.STATIC; } else { this.type = Body.DYNAMIC; } /** * Bounding circle radius. * @property boundingRadius * @type {Number} */ this.boundingRadius = 0; /** * Bounding box of this body. * @property aabb * @type {AABB} */ this.aabb = new AABB(); /** * Indicates if the AABB needs update. Update it with {{#crossLink "Body/updateAABB:method"}}.updateAABB(){{/crossLink}}. * @property aabbNeedsUpdate * @type {Boolean} * @see updateAABB * * @example * // Force update the AABB * body.aabbNeedsUpdate = true; * body.updateAABB(); * console.log(body.aabbNeedsUpdate); // false */ this.aabbNeedsUpdate = true; /** * If true, the body will automatically fall to sleep. Note that you need to enable sleeping in the {{#crossLink "World"}}{{/crossLink}} before anything will happen. * @property allowSleep * @type {Boolean} * @default true */ this.allowSleep = true; this.wantsToSleep = false; /** * One of {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}}, {{#crossLink "Body/SLEEPY:property"}}Body.SLEEPY{{/crossLink}} and {{#crossLink "Body/SLEEPING:property"}}Body.SLEEPING{{/crossLink}}. * * The body is initially Body.AWAKE. If its velocity norm is below .sleepSpeedLimit, the sleepState will become Body.SLEEPY. If the body continues to be Body.SLEEPY for .sleepTimeLimit seconds, it will fall asleep (Body.SLEEPY). * * @property sleepState * @type {Number} * @default Body.AWAKE */ this.sleepState = Body.AWAKE; /** * If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy. * @property sleepSpeedLimit * @type {Number} * @default 0.2 */ this.sleepSpeedLimit = 0.2; /** * If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping. * @property sleepTimeLimit * @type {Number} * @default 1 */ this.sleepTimeLimit = 1; /** * Gravity scaling factor. If you want the body to ignore gravity, set this to zero. If you want to reverse gravity, set it to -1. * @property {Number} gravityScale * @default 1 */ this.gravityScale = 1; /** * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this body will move through other bodies, but it will still trigger contact events, etc. * @property {Boolean} collisionResponse */ this.collisionResponse = true; /** * How long the body has been sleeping. * @property {Number} idleTime */ this.idleTime = 0; /** * The last time when the body went to SLEEPY state. * @property {Number} timeLastSleepy * @private */ this.timeLastSleepy = 0; /** * If the body speed exceeds this threshold, CCD (continuous collision detection) will be enabled. Set it to a negative number to disable CCD completely for this body. * @property {number} ccdSpeedThreshold * @default -1 */ this.ccdSpeedThreshold = options.ccdSpeedThreshold !== undefined ? options.ccdSpeedThreshold : -1; /** * The number of iterations that should be used when searching for the time of impact during CCD. A larger number will assure that there's a small penetration on CCD collision, but a small number will give more performance. * @property {number} ccdIterations * @default 10 */ this.ccdIterations = options.ccdIterations !== undefined ? options.ccdIterations : 10; this.concavePath = null; this._wakeUpAfterNarrowphase = false; this.updateMassProperties(); } Body.prototype = new EventEmitter(); Body.prototype.constructor = Body; Body._idCounter = 0; Body.prototype.updateSolveMassProperties = function(){ if(this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC){ this.invMassSolve = 0; this.invInertiaSolve = 0; } else { this.invMassSolve = this.invMass; this.invInertiaSolve = this.invInertia; } }; /** * Set the total density of the body * @method setDensity */ Body.prototype.setDensity = function(density) { var totalArea = this.getArea(); this.mass = totalArea * density; this.updateMassProperties(); }; /** * Get the total area of all shapes in the body * @method getArea * @return {Number} */ Body.prototype.getArea = function() { var totalArea = 0; for(var i=0; i<this.shapes.length; i++){ totalArea += this.shapes[i].area; } return totalArea; }; /** * Get the AABB from the body. The AABB is updated if necessary. * @method getAABB */ Body.prototype.getAABB = function(){ if(this.aabbNeedsUpdate){ this.updateAABB(); } return this.aabb; }; var shapeAABB = new AABB(), tmp = vec2.create(); /** * Updates the AABB of the Body * @method updateAABB */ Body.prototype.updateAABB = function() { var shapes = this.shapes, shapeOffsets = this.shapeOffsets, shapeAngles = this.shapeAngles, N = shapes.length, offset = tmp, bodyAngle = this.angle; for(var i=0; i!==N; i++){ var shape = shapes[i], angle = shapeAngles[i] + bodyAngle; // Get shape world offset vec2.rotate(offset, shapeOffsets[i], bodyAngle); vec2.add(offset, offset, this.position); // Get shape AABB shape.computeAABB(shapeAABB, offset, angle); if(i===0){ this.aabb.copy(shapeAABB); } else { this.aabb.extend(shapeAABB); } } this.aabbNeedsUpdate = false; }; /** * Update the bounding radius of the body. Should be done if any of the shapes * are changed. * @method updateBoundingRadius */ Body.prototype.updateBoundingRadius = function(){ var shapes = this.shapes, shapeOffsets = this.shapeOffsets, N = shapes.length, radius = 0; for(var i=0; i!==N; i++){ var shape = shapes[i], offset = vec2.length(shapeOffsets[i]), r = shape.boundingRadius; if(offset + r > radius){ radius = offset + r; } } this.boundingRadius = radius; }; /** * Add a shape to the body. You can pass a local transform when adding a shape, * so that the shape gets an offset and angle relative to the body center of mass. * Will automatically update the mass properties and bounding radius. * * @method addShape * @param {Shape} shape * @param {Array} [offset] Local body offset of the shape. * @param {Number} [angle] Local body angle. * * @example * var body = new Body(), * shape = new Circle(); * * // Add the shape to the body, positioned in the center * body.addShape(shape); * * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis. * body.addShape(shape,[1,0]); * * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW. * body.addShape(shape,[0,1],Math.PI/2); */ Body.prototype.addShape = function(shape,offset,angle){ angle = angle || 0.0; // Copy the offset vector if(offset){ offset = vec2.fromValues(offset[0],offset[1]); } else { offset = vec2.fromValues(0,0); } this.shapes .push(shape); this.shapeOffsets.push(offset); this.shapeAngles .push(angle); this.updateMassProperties(); this.updateBoundingRadius(); this.aabbNeedsUpdate = true; }; /** * Remove a shape * @method removeShape * @param {Shape} shape * @return {Boolean} True if the shape was found and removed, else false. */ Body.prototype.removeShape = function(shape){ var idx = this.shapes.indexOf(shape); if(idx !== -1){ this.shapes.splice(idx,1); this.shapeOffsets.splice(idx,1); this.shapeAngles.splice(idx,1); this.aabbNeedsUpdate = true; return true; } else { return false; } }; /** * Updates .inertia, .invMass, .invInertia for this Body. Should be called when * changing the structure or mass of the Body. * * @method updateMassProperties * * @example * body.mass += 1; * body.updateMassProperties(); */ Body.prototype.updateMassProperties = function(){ if(this.type === Body.STATIC || this.type === Body.KINEMATIC){ this.mass = Number.MAX_VALUE; this.invMass = 0; this.inertia = Number.MAX_VALUE; this.invInertia = 0; } else { var shapes = this.shapes, N = shapes.length, m = this.mass / N, I = 0; if(!this.fixedRotation){ for(var i=0; i<N; i++){ var shape = shapes[i], r2 = vec2.squaredLength(this.shapeOffsets[i]), Icm = shape.computeMomentOfInertia(m); I += Icm + m*r2; } this.inertia = I; this.invInertia = I>0 ? 1/I : 0; } else { this.inertia = Number.MAX_VALUE; this.invInertia = 0; } // Inverse mass properties are easy this.invMass = 1/this.mass;// > 0 ? 1/this.mass : 0; } }; var Body_applyForce_r = vec2.create(); /** * Apply force to a world point. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. * @method applyForce * @param {Array} force The force to add. * @param {Array} worldPoint A world point to apply the force on. */ Body.prototype.applyForce = function(force,worldPoint){ // Compute point position relative to the body center var r = Body_applyForce_r; vec2.sub(r,worldPoint,this.position); // Add linear force vec2.add(this.force,this.force,force); // Compute produced rotational force var rotForce = vec2.crossLength(r,force); // Add rotational force this.angularForce += rotForce; }; /** * Transform a world point to local body frame. * @method toLocalFrame * @param {Array} out The vector to store the result in * @param {Array} worldPoint The input world vector */ Body.prototype.toLocalFrame = function(out, worldPoint){ vec2.toLocalFrame(out, worldPoint, this.position, this.angle); }; /** * Transform a local point to world frame. * @method toWorldFrame * @param {Array} out The vector to store the result in * @param {Array} localPoint The input local vector */ Body.prototype.toWorldFrame = function(out, localPoint){ vec2.toGlobalFrame(out, localPoint, this.position, this.angle); }; /** * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. * @method fromPolygon * @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes. * @param {Object} [options] * @param {Boolean} [options.optimalDecomp=false] Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. * @param {Boolean} [options.skipSimpleCheck=false] Set to true if you already know that the path is not intersecting itself. * @param {Boolean|Number} [options.removeCollinearPoints=false] Set to a number (angle threshold value) to remove collinear points, or false to keep all points. * @return {Boolean} True on success, else false. */ Body.prototype.fromPolygon = function(path,options){ options = options || {}; // Remove all shapes for(var i=this.shapes.length; i>=0; --i){ this.removeShape(this.shapes[i]); } var p = new decomp.Polygon(); p.vertices = path; // Make it counter-clockwise p.makeCCW(); if(typeof(options.removeCollinearPoints) === "number"){ p.removeCollinearPoints(options.removeCollinearPoints); } // Check if any line segment intersects the path itself if(typeof(options.skipSimpleCheck) === "undefined"){ if(!p.isSimple()){ return false; } } // Save this path for later this.concavePath = p.vertices.slice(0); for(var i=0; i<this.concavePath.length; i++){ var v = [0,0]; vec2.copy(v,this.concavePath[i]); this.concavePath[i] = v; } // Slow or fast decomp? var convexes; if(options.optimalDecomp){ convexes = p.decomp(); } else { convexes = p.quickDecomp(); } var cm = vec2.create(); // Add convexes for(var i=0; i!==convexes.length; i++){ // Create convex var c = new Convex(convexes[i].vertices); // Move all vertices so its center of mass is in the local center of the convex for(var j=0; j!==c.vertices.length; j++){ var v = c.vertices[j]; vec2.sub(v,v,c.centerOfMass); } vec2.scale(cm,c.centerOfMass,1); c.updateTriangles(); c.updateCenterOfMass(); c.updateBoundingRadius(); // Add the shape this.addShape(c,cm); } this.adjustCenterOfMass(); this.aabbNeedsUpdate = true; return true; }; var adjustCenterOfMass_tmp1 = vec2.fromValues(0,0), adjustCenterOfMass_tmp2 = vec2.fromValues(0,0), adjustCenterOfMass_tmp3 = vec2.fromValues(0,0), adjustCenterOfMass_tmp4 = vec2.fromValues(0,0); /** * Moves the shape offsets so their center of mass becomes the body center of mass. * @method adjustCenterOfMass */ Body.prototype.adjustCenterOfMass = function(){ var offset_times_area = adjustCenterOfMass_tmp2, sum = adjustCenterOfMass_tmp3, cm = adjustCenterOfMass_tmp4, totalArea = 0; vec2.set(sum,0,0); for(var i=0; i!==this.shapes.length; i++){ var s = this.shapes[i], offset = this.shapeOffsets[i]; vec2.scale(offset_times_area,offset,s.area); vec2.add(sum,sum,offset_times_area); totalArea += s.area; } vec2.scale(cm,sum,1/totalArea); // Now move all shapes for(var i=0; i!==this.shapes.length; i++){ var s = this.shapes[i], offset = this.shapeOffsets[i]; // Offset may be undefined. Fix that. if(!offset){ offset = this.shapeOffsets[i] = vec2.create(); } vec2.sub(offset,offset,cm); } // Move the body position too vec2.add(this.position,this.position,cm); // And concave path for(var i=0; this.concavePath && i<this.concavePath.length; i++){ vec2.sub(this.concavePath[i], this.concavePath[i], cm); } this.updateMassProperties(); this.updateBoundingRadius(); }; /** * Sets the force on the body to zero. * @method setZeroForce */ Body.prototype.setZeroForce = function(){ vec2.set(this.force,0.0,0.0); this.angularForce = 0.0; }; Body.prototype.resetConstraintVelocity = function(){ var b = this, vlambda = b.vlambda; vec2.set(vlambda,0,0); b.wlambda = 0; }; Body.prototype.addConstraintVelocity = function(){ var b = this, v = b.velocity; vec2.add( v, v, b.vlambda); b.angularVelocity += b.wlambda; }; /** * Apply damping, see <a href="http://code.google.com/p/bullet/issues/detail?id=74">this</a> for details. * @method applyDamping * @param {number} dt Current time step */ Body.prototype.applyDamping = function(dt){ if(this.type === Body.DYNAMIC){ // Only for dynamic bodies var v = this.velocity; vec2.scale(v, v, Math.pow(1.0 - this.damping,dt)); this.angularVelocity *= Math.pow(1.0 - this.angularDamping,dt); } }; /** * Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions. * Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before. * @method wakeUp */ Body.prototype.wakeUp = function(){ var s = this.sleepState; this.sleepState = Body.AWAKE; this.idleTime = 0; if(s !== Body.AWAKE){ this.emit(Body.wakeUpEvent); } }; /** * Force body sleep * @method sleep */ Body.prototype.sleep = function(){ this.sleepState = Body.SLEEPING; this.angularVelocity = 0; this.angularForce = 0; vec2.set(this.velocity,0,0); vec2.set(this.force,0,0); this.emit(Body.sleepEvent); }; /** * Called every timestep to update internal sleep timer and change sleep state if needed. * @method sleepTick * @param {number} time The world time in seconds * @param {boolean} dontSleep * @param {number} dt */ Body.prototype.sleepTick = function(time, dontSleep, dt){ if(!this.allowSleep || this.type === Body.SLEEPING){ return; } this.wantsToSleep = false; var sleepState = this.sleepState, speedSquared = vec2.squaredLength(this.velocity) + Math.pow(this.angularVelocity,2), speedLimitSquared = Math.pow(this.sleepSpeedLimit,2); // Add to idle time if(speedSquared >= speedLimitSquared){ this.idleTime = 0; this.sleepState = Body.AWAKE; } else { this.idleTime += dt; this.sleepState = Body.SLEEPY; } if(this.idleTime > this.sleepTimeLimit){ if(!dontSleep){ this.sleep(); } else { this.wantsToSleep = true; } } /* if(sleepState===Body.AWAKE && speedSquared < speedLimitSquared){ this.sleepState = Body.SLEEPY; // Sleepy this.timeLastSleepy = time; this.emit(Body.sleepyEvent); } else if(sleepState===Body.SLEEPY && speedSquared >= speedLimitSquared){ this.wakeUp(); // Wake up } else if(sleepState===Body.SLEEPY && (time - this.timeLastSleepy ) > this.sleepTimeLimit){ this.wantsToSleep = true; if(!dontSleep){ this.sleep(); } } */ }; Body.prototype.getVelocityFromPosition = function(store, timeStep){ store = store || vec2.create(); vec2.sub(store, this.position, this.previousPosition); vec2.scale(store, store, 1/timeStep); return store; }; Body.prototype.getAngularVelocityFromPosition = function(timeStep){ return (this.angle - this.previousAngle) / timeStep; }; /** * Check if the body is overlapping another body. Note that this method only works if the body was added to a World and if at least one step was taken. * @method overlaps * @param {Body} body * @return {boolean} */ Body.prototype.overlaps = function(body){ return this.world.overlapKeeper.bodiesAreOverlapping(this, body); }; var integrate_fhMinv = vec2.create(); var integrate_velodt = vec2.create(); /** * Move the body forward in time given its current velocity. * @method integrate * @param {Number} dt */ Body.prototype.integrate = function(dt){ var minv = this.invMass, f = this.force, pos = this.position, velo = this.velocity; // Save old position vec2.copy(this.previousPosition, this.position); this.previousAngle = this.angle; // Velocity update if(!this.fixedRotation){ this.angularVelocity += this.angularForce * this.invInertia * dt; } vec2.scale(integrate_fhMinv, f, dt * minv); vec2.add(velo, integrate_fhMinv, velo); // CCD if(!this.integrateToTimeOfImpact(dt)){ // Regular position update vec2.scale(integrate_velodt, velo, dt); vec2.add(pos, pos, integrate_velodt); if(!this.fixedRotation){ this.angle += this.angularVelocity * dt; } } this.aabbNeedsUpdate = true; }; var directionRadius = vec2.create(); var direction = vec2.create(); var end = vec2.create(); var startToEnd = vec2.create(); var rememberPosition = vec2.create(); Body.prototype.integrateToTimeOfImpact = function(dt){ if(this.ccdSpeedThreshold < 0 || vec2.squaredLength(this.velocity) < Math.pow(this.ccdSpeedThreshold, 2)){ return false; } vec2.normalize(direction, this.velocity); vec2.copy(directionRadius, direction); vec2.scale(directionRadius, directionRadius, this.boundingRadius); vec2.scale(end, this.velocity, dt); vec2.add(end, end, this.position); vec2.add(end, end, directionRadius); vec2.sub(startToEnd, end, this.position); var startToEndAngle = this.angularVelocity * dt; var len = vec2.length(startToEnd); var timeOfImpact = 1; var hit; var that = this; this.world.raycastAll(this.position, end, {}, function (result) { if(result.body === that){ return; } hit = result.body; vec2.copy(end, result.hitPointWorld); vec2.sub(startToEnd, result.hitPointWorld, that.position); timeOfImpact = vec2.length(startToEnd) / len; result.abort(); }); if(!hit){ return false; } var rememberAngle = this.angle; vec2.copy(rememberPosition, this.position); // Got a start and end point. Approximate time of impact using binary search var iter = 0; var tmin = 0; var tmid = 0; var tmax = timeOfImpact; while (tmax >= tmin && iter < this.ccdIterations) { iter++; // calculate the midpoint tmid = (tmax - tmin) / 2; // Move the body to that point vec2.scale(integrate_velodt, startToEnd, timeOfImpact); vec2.add(this.position, rememberPosition, integrate_velodt); this.angle = rememberAngle + startToEndAngle * timeOfImpact; this.updateAABB(); // check overlap var overlaps = this.aabb.overlaps(hit.aabb) && this.world.narrowphase.bodiesOverlap(this, hit); if (overlaps) { // change min to search upper interval tmin = tmid; } else { // change max to search lower interval tmax = tmid; } } timeOfImpact = tmid; vec2.copy(this.position, rememberPosition); this.angle = rememberAngle; // move to TOI vec2.scale(integrate_velodt, startToEnd, timeOfImpact); vec2.add(this.position, this.position, integrate_velodt); if(!this.fixedRotation){ this.angle += startToEndAngle * timeOfImpact; } return true; }; /** * @event sleepy */ Body.sleepyEvent = { type: "sleepy" }; /** * @event sleep */ Body.sleepEvent = { type: "sleep" }; /** * @event wakeup */ Body.wakeUpEvent = { type: "wakeup" }; /** * Dynamic body. * @property DYNAMIC * @type {Number} * @static */ Body.DYNAMIC = 1; /** * Static body. * @property STATIC * @type {Number} * @static */ Body.STATIC = 2; /** * Kinematic body. * @property KINEMATIC * @type {Number} * @static */ Body.KINEMATIC = 4; /** * @property AWAKE * @type {Number} * @static */ Body.AWAKE = 0; /** * @property SLEEPY * @type {Number} * @static */ Body.SLEEPY = 1; /** * @property SLEEPING * @type {Number} * @static */ Body.SLEEPING = 2;
removed the extra bounding radius distance for CCD rays, dont think its needed
src/objects/Body.js
removed the extra bounding radius distance for CCD rays, dont think its needed
<ide><path>rc/objects/Body.js <ide> this.aabbNeedsUpdate = true; <ide> }; <ide> <del>var directionRadius = vec2.create(); <ide> var direction = vec2.create(); <ide> var end = vec2.create(); <ide> var startToEnd = vec2.create(); <ide> <ide> vec2.normalize(direction, this.velocity); <ide> <del> vec2.copy(directionRadius, direction); <del> vec2.scale(directionRadius, directionRadius, this.boundingRadius); <del> <ide> vec2.scale(end, this.velocity, dt); <ide> vec2.add(end, end, this.position); <del> vec2.add(end, end, directionRadius); <ide> <ide> vec2.sub(startToEnd, end, this.position); <ide> var startToEndAngle = this.angularVelocity * dt;
Java
agpl-3.0
5c949fc84cfc87cea07844e896e93e4a7e4bd603
0
jspacco/NetCoder,jspacco/NetCoder,jspacco/NetCoder,jspacco/NetCoder
// NetCoder - a web-based pedagogical programming environment // Copyright (C) 2011, Jaime Spacco <[email protected]> // Copyright (C) 2011, David H. Hovemeyer <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package edu.ycp.cs.netcoder.client; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.logical.shared.ResizeEvent; import com.google.gwt.event.logical.shared.ResizeHandler; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.LayoutPanel; import edu.ycp.cs.dh.acegwt.client.ace.AceEditor; import edu.ycp.cs.dh.acegwt.client.ace.AceEditorCallback; import edu.ycp.cs.dh.acegwt.client.ace.AceEditorMode; import edu.ycp.cs.dh.acegwt.client.ace.AceEditorTheme; import edu.ycp.cs.netcoder.client.logchange.ChangeFromAceOnChangeEvent; import edu.ycp.cs.netcoder.client.logchange.ChangeList; import edu.ycp.cs.netcoder.client.status.ProblemDescriptionWidget; import edu.ycp.cs.netcoder.client.status.ResultWidget; import edu.ycp.cs.netcoder.client.status.StatusAndButtonBarWidget; import edu.ycp.cs.netcoder.shared.affect.AffectEvent; import edu.ycp.cs.netcoder.shared.logchange.Change; import edu.ycp.cs.netcoder.shared.logchange.ChangeType; import edu.ycp.cs.netcoder.shared.problems.Problem; import edu.ycp.cs.netcoder.shared.problems.User; import edu.ycp.cs.netcoder.shared.testing.TestResult; import edu.ycp.cs.netcoder.shared.util.Publisher; import edu.ycp.cs.netcoder.shared.util.Subscriber; /** * View for working on a problem: code editor, submit button, feedback, etc. */ public class DevelopmentView extends NetCoderView implements Subscriber, ResizeHandler { private static final int PROBLEM_ID = 0; // FIXME private enum Mode { /** Loading problem and current text - editing not allowed. */ LOADING, /** Normal state - user is allowed to edit the program text. */ EDITING, /** * Submit in progress. * Editing disallowed until server response is received. */ SUBMIT_IN_PROGRESS, /** * Logging out. */ LOGOUT, } // UI mode private Mode mode; private boolean textLoaded; /* // Model objects added to the session. private Object[] sessionObjects; */ // Widgets private ProblemDescriptionWidget problemDescription; private AceEditor editor; private ResultWidget resultWidget; private Timer flushPendingChangeEventsTimer; // RPC services. private LoginServiceAsync loginService = GWT.create(LoginService.class); private LogCodeChangeServiceAsync logCodeChangeService = GWT.create(LogCodeChangeService.class); private SubmitServiceAsync submitService = GWT.create(SubmitService.class); private LoadExerciseServiceAsync loadService = GWT.create(LoadExerciseService.class); private AffectEventServiceAsync affectEventService = GWT.create(AffectEventService.class); public DevelopmentView(Session session) { super(session); /* // Add ChangeList and AffectEvent to session sessionObjects = new Object[]{ new ChangeList(), new AffectEvent() }; for (Object obj : sessionObjects) { getSession().add(obj); } */ addSessionObject(new ChangeList()); addSessionObject(new AffectEvent()); // Add logout handler. // The goal is to completely purge session data on both server // and client when the user logs out. getTopBar().setLogoutHandler(new Runnable() { @Override public void run() { AsyncCallback<Void> callback = new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { GWT.log("Could not log out?", caught); // well, at least we tried clearSessionData(); } @Override public void onSuccess(Void result) { // server has purged the session clearSessionData(); } protected void clearSessionData() { // Clear the User object from the session. getSession().remove(User.class); // Publish the LOGOUT event. getSession().notifySubscribers(Session.Event.LOGOUT, null); } }; loginService.logout(callback); } }); // Observe ChangeList state. // We do this so that we know when the local editor contents are // up to date with the text on the server. session.get(ChangeList.class).subscribe(ChangeList.State.CLEAN, this, getSubscriptionRegistrar()); // User won't be allowed to edit until the problem (and previous editor contents, if any) // are loaded. mode = Mode.LOADING; textLoaded = false; // The overall UI is build in a LayoutPanel (which the parent class creates) LayoutPanel layoutPanel = getLayoutPanel(); // Add problem description widget problemDescription = new ProblemDescriptionWidget(session, getSubscriptionRegistrar()); layoutPanel.add(problemDescription); layoutPanel.setWidgetTopHeight( problemDescription, LayoutConstants.TOP_BAR_HEIGHT_PX, Unit.PX, LayoutConstants.PROBLEM_DESC_HEIGHT_PX, Unit.PX); // Add AceEditor widget editor = new AceEditor(); editor.setStyleName("NetCoderEditor"); layoutPanel.add(editor); layoutPanel.setWidgetTopHeight(editor, LayoutConstants.TOP_BAR_HEIGHT_PX + LayoutConstants.PROBLEM_DESC_HEIGHT_PX, Unit.PX, 200, Unit.PX); // Add the status and button bar widget StatusAndButtonBarWidget statusAndButtonBarWidget = new StatusAndButtonBarWidget(session); layoutPanel.add(statusAndButtonBarWidget); layoutPanel.setWidgetBottomHeight( statusAndButtonBarWidget, LayoutConstants.RESULTS_PANEL_HEIGHT_PX, Unit.PX, LayoutConstants.STATUS_AND_BUTTON_BAR_HEIGHT_PX, Unit.PX); statusAndButtonBarWidget.setOnSubmit(new Runnable() { @Override public void run() { submitCode(); } }); // Add the ResultWidget resultWidget = new ResultWidget(); layoutPanel.add(resultWidget); layoutPanel.setWidgetBottomHeight( resultWidget, 0, Unit.PX, LayoutConstants.RESULTS_PANEL_HEIGHT_PX, Unit.PX); // UI is now complete initWidget(layoutPanel); // Initiate loading of the problem and current editor text. loadProblemAndCurrentText(); // Create timer to flush unsent change events periodically. this.flushPendingChangeEventsTimer = new Timer() { @Override public void run() { final ChangeList changeList = getSession().get(ChangeList.class); if (changeList == null) { // paranoia return; } if (changeList.getState() == ChangeList.State.UNSENT) { Change[] changeBatch = changeList.beginTransmit(); AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() { @Override public void onFailure(Throwable caught) { changeList.endTransmit(false); GWT.log("Failed to send change batch to server"); } @Override public void onSuccess(Boolean result) { changeList.endTransmit(true); } }; logCodeChangeService.logChange(changeBatch, callback); } } }; flushPendingChangeEventsTimer.scheduleRepeating(1000); } /** * Load the problem and current editor text. * The current editor text is (hopefully) whatever the user * had in his/her editor the last time they were logged in. */ protected void loadProblemAndCurrentText() { // Load the problem. loadService.load(PROBLEM_ID, new AsyncCallback<Problem>() { @Override public void onSuccess(Problem result) { if (result != null) { getSession().add(result); onProblemLoaded(); } else { loadProblemFailed(); } } @Override public void onFailure(Throwable caught) { GWT.log("Could not load problem", caught); loadProblemFailed(); } }); // Load current text. loadService.loadCurrentText(PROBLEM_ID, new AsyncCallback<String>() { @Override public void onFailure(Throwable caught) { GWT.log("Could not load current text", caught); loadCurrentTextFailed(); } public void onSuccess(String result) { onCurrentTextLoaded(result); } }); } /** * Called when the problem has been loaded. */ protected void onProblemLoaded() { // If the current editor text has been loaded, // then it is ok to start editing. if (textLoaded == true) { startEditing(); } } /** * Called when the current text has been retrieved from the server. * * @param text the current text to load into the editor */ protected void onCurrentTextLoaded(String text) { editor.setText(text); textLoaded = true; // If the problem has been loaded, then it is ok to start editing. if (getSession().get(Problem.class) != null) { startEditing(); } } protected void startEditing() { editor.setReadOnly(false); mode = Mode.EDITING; } protected void loadProblemFailed() { // TODO - improve problemDescription.setErrorText("Could not load problem description"); } protected void loadCurrentTextFailed() { // TODO - improve problemDescription.setErrorText("Could not load text for problem"); } @Override public void activate() { editor.startEditor(); editor.setReadOnly(true); // until a Problem is loaded editor.setTheme(AceEditorTheme.ECLIPSE); editor.setFontSize("14px"); editor.setMode(AceEditorMode.JAVA); editor.addOnChangeHandler(new AceEditorCallback() { @Override public void invokeAceCallback(JavaScriptObject obj) { // Important: don't send the change to the server unless the // initial editor contents has been loaded. Otherwise, // the setting of the initial editor contents will get sent // to the server as a change, which is obviously not what // we want. if (!textLoaded) { return; } // Convert ACE onChange event object to a Change object, // and add it to the session's ChangeList User user = getSession().get(User.class); Problem problem = getSession().get(Problem.class); Change change = ChangeFromAceOnChangeEvent.convert(obj, user.getId(), problem.getProblemId()); getSession().get(ChangeList.class).addChange(change); } }); // make the editor the correct height doResize(); } @Override public void deactivate() { // Turn off the flush pending events timer flushPendingChangeEventsTimer.cancel(); // Unsubscribe all event subscribers getSubscriptionRegistrar().unsubscribeAllEventSubscribers(); // Clear all local session data removeAllSessionObjects(); } protected void submitCode() { // If the problem has not been loaded yet, // then there is nothing to do. if (getSession().get(Problem.class) == null) { return; } // Set the editor to read-only! // We don't want any edits until the results have // come back from the server. editor.setReadOnly(true); // Create a Change representing the full text of the document, // and schedule it for transmission to the server. Change fullText = new Change( ChangeType.FULL_TEXT, 0, 0, 0, 0, // ignored System.currentTimeMillis(), getSession().get(User.class).getId(), getSession().get(Problem.class).getProblemId(), editor.getText()); getSession().get(ChangeList.class).addChange(fullText); // Set the mode to SUBMIT_IN_PROGRESS, indicating that we are // waiting for the full text to be uploaded to the server. mode = Mode.SUBMIT_IN_PROGRESS; } @Override public void eventOccurred(Object key, Publisher publisher, Object hint) { if (key == ChangeList.State.CLEAN && mode == Mode.SUBMIT_IN_PROGRESS) { // Full text of submission has arrived at server, // and because the editor is read-only, we know that the // local text is in-sync. So, submit the code! AsyncCallback<TestResult[]> callback = new AsyncCallback<TestResult[]>() { @Override public void onFailure(Throwable caught) { final String msg = "Error sending submission to server for compilation"; resultWidget.setMessage(msg); GWT.log(msg, caught); // TODO: should set editor back to read/write? } @Override public void onSuccess(TestResult[] results) { // Great, got results back from server! resultWidget.setResults(results); // Can resume editing now startEditing(); } }; // Send editor text to server. int problemId = getSession().get(Problem.class).getProblemId(); submitService.submit(problemId, editor.getText(), callback); } } @Override public void unsubscribeFromAll() { getSession().get(ChangeList.class).unsubscribeFromAll(this); } @Override public void onResize(ResizeEvent event) { doResize(); } protected void doResize() { int height = Window.getClientHeight(); int availableForEditor = height - (LayoutConstants.TOP_BAR_HEIGHT_PX + LayoutConstants.PROBLEM_DESC_HEIGHT_PX + LayoutConstants.STATUS_AND_BUTTON_BAR_HEIGHT_PX + LayoutConstants.RESULTS_PANEL_HEIGHT_PX); if (availableForEditor < 0) { availableForEditor = 0; } getLayoutPanel().setWidgetTopHeight( editor, LayoutConstants.TOP_BAR_HEIGHT_PX + LayoutConstants.PROBLEM_DESC_HEIGHT_PX, Unit.PX, availableForEditor, Unit.PX); } }
src/edu/ycp/cs/netcoder/client/DevelopmentView.java
// NetCoder - a web-based pedagogical programming environment // Copyright (C) 2011, Jaime Spacco <[email protected]> // Copyright (C) 2011, David H. Hovemeyer <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package edu.ycp.cs.netcoder.client; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.logical.shared.ResizeEvent; import com.google.gwt.event.logical.shared.ResizeHandler; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.LayoutPanel; import edu.ycp.cs.dh.acegwt.client.ace.AceEditor; import edu.ycp.cs.dh.acegwt.client.ace.AceEditorCallback; import edu.ycp.cs.dh.acegwt.client.ace.AceEditorMode; import edu.ycp.cs.dh.acegwt.client.ace.AceEditorTheme; import edu.ycp.cs.netcoder.client.logchange.ChangeFromAceOnChangeEvent; import edu.ycp.cs.netcoder.client.logchange.ChangeList; import edu.ycp.cs.netcoder.client.status.ProblemDescriptionWidget; import edu.ycp.cs.netcoder.client.status.ResultWidget; import edu.ycp.cs.netcoder.client.status.StatusAndButtonBarWidget; import edu.ycp.cs.netcoder.shared.affect.AffectEvent; import edu.ycp.cs.netcoder.shared.logchange.Change; import edu.ycp.cs.netcoder.shared.logchange.ChangeType; import edu.ycp.cs.netcoder.shared.problems.Problem; import edu.ycp.cs.netcoder.shared.problems.User; import edu.ycp.cs.netcoder.shared.testing.TestResult; import edu.ycp.cs.netcoder.shared.util.Publisher; import edu.ycp.cs.netcoder.shared.util.Subscriber; /** * View for working on a problem: code editor, submit button, feedback, etc. */ public class DevelopmentView extends NetCoderView implements Subscriber, ResizeHandler { private static final int PROBLEM_ID = 0; // FIXME private enum Mode { /** Loading problem and current text - editing not allowed. */ LOADING, /** Normal state - user is allowed to edit the program text. */ EDITING, /** * Submit in progress. * Editing disallowed until server response is received. */ SUBMIT_IN_PROGRESS, /** * Logging out. */ LOGOUT, } // UI mode private Mode mode; private boolean textLoaded; /* // Model objects added to the session. private Object[] sessionObjects; */ // Widgets private ProblemDescriptionWidget problemDescription; private AceEditor editor; private ResultWidget resultWidget; private Timer flushPendingChangeEventsTimer; // RPC services. private LoginServiceAsync loginService = GWT.create(LoginService.class); private LogCodeChangeServiceAsync logCodeChangeService = GWT.create(LogCodeChangeService.class); private SubmitServiceAsync submitService = GWT.create(SubmitService.class); private LoadExerciseServiceAsync loadService = GWT.create(LoadExerciseService.class); private AffectEventServiceAsync affectEventService = GWT.create(AffectEventService.class); public DevelopmentView(Session session) { super(session); /* // Add ChangeList and AffectEvent to session sessionObjects = new Object[]{ new ChangeList(), new AffectEvent() }; for (Object obj : sessionObjects) { getSession().add(obj); } */ addSessionObject(new ChangeList()); addSessionObject(new AffectEvent()); // Add logout handler. // The goal is to completely purge session data on both server // and client when the user logs out. getTopBar().setLogoutHandler(new Runnable() { @Override public void run() { AsyncCallback<Void> callback = new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { GWT.log("Could not log out?", caught); // well, at least we tried clearSessionData(); } @Override public void onSuccess(Void result) { // server has purged the session clearSessionData(); } protected void clearSessionData() { // Clear the User object from the session. getSession().remove(User.class); // Publish the LOGOUT event. getSession().notifySubscribers(Session.Event.LOGOUT, null); } }; loginService.logout(callback); } }); // Observe ChangeList state. // We do this so that we know when the local editor contents are // up to date with the text on the server. session.get(ChangeList.class).subscribe(ChangeList.State.CLEAN, this, getSubscriptionRegistrar()); // User won't be allowed to edit until the problem (and previous editor contents, if any) // are loaded. mode = Mode.LOADING; textLoaded = false; // The overall UI is build in a LayoutPanel (which the parent class creates) LayoutPanel layoutPanel = getLayoutPanel(); // Add problem description widget problemDescription = new ProblemDescriptionWidget(session, getSubscriptionRegistrar()); layoutPanel.add(problemDescription); layoutPanel.setWidgetTopHeight( problemDescription, LayoutConstants.TOP_BAR_HEIGHT_PX, Unit.PX, LayoutConstants.PROBLEM_DESC_HEIGHT_PX, Unit.PX); // Add AceEditor widget editor = new AceEditor(); editor.setStyleName("NetCoderEditor"); layoutPanel.add(editor); layoutPanel.setWidgetTopHeight(editor, LayoutConstants.TOP_BAR_HEIGHT_PX + LayoutConstants.PROBLEM_DESC_HEIGHT_PX, Unit.PX, 200, Unit.PX); // Add the status and button bar widget StatusAndButtonBarWidget statusAndButtonBarWidget = new StatusAndButtonBarWidget(session); layoutPanel.add(statusAndButtonBarWidget); layoutPanel.setWidgetBottomHeight( statusAndButtonBarWidget, LayoutConstants.RESULTS_PANEL_HEIGHT_PX, Unit.PX, LayoutConstants.STATUS_AND_BUTTON_BAR_HEIGHT_PX, Unit.PX); statusAndButtonBarWidget.setOnSubmit(new Runnable() { @Override public void run() { submitCode(); } }); // Add the ResultWidget resultWidget = new ResultWidget(); layoutPanel.add(resultWidget); layoutPanel.setWidgetBottomHeight( resultWidget, 0, Unit.PX, LayoutConstants.RESULTS_PANEL_HEIGHT_PX, Unit.PX); // UI is now complete initWidget(layoutPanel); // Initiate loading of the problem and current editor text. loadProblemAndCurrentText(); // Create timer to flush unsent change events periodically. this.flushPendingChangeEventsTimer = new Timer() { @Override public void run() { final ChangeList changeList = getSession().get(ChangeList.class); if (changeList == null) { // paranoia return; } if (changeList.getState() == ChangeList.State.UNSENT) { Change[] changeBatch = changeList.beginTransmit(); AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() { @Override public void onFailure(Throwable caught) { changeList.endTransmit(false); GWT.log("Failed to send change batch to server"); } @Override public void onSuccess(Boolean result) { changeList.endTransmit(true); } }; logCodeChangeService.logChange(changeBatch, callback); } } }; flushPendingChangeEventsTimer.scheduleRepeating(1000); } /** * Load the problem and current editor text. * The current editor text is (hopefully) whatever the user * had in his/her editor the last time they were logged in. */ protected void loadProblemAndCurrentText() { // Load the problem. loadService.load(PROBLEM_ID, new AsyncCallback<Problem>() { @Override public void onSuccess(Problem result) { if (result != null) { getSession().add(result); onProblemLoaded(); } else { loadProblemFailed(); } } @Override public void onFailure(Throwable caught) { GWT.log("Could not load problem", caught); loadProblemFailed(); } }); // Load current text. loadService.loadCurrentText(PROBLEM_ID, new AsyncCallback<String>() { @Override public void onFailure(Throwable caught) { GWT.log("Could not load current text", caught); loadCurrentTextFailed(); } public void onSuccess(String result) { onCurrentTextLoaded(result); } }); } /** * Called when the problem has been loaded. */ protected void onProblemLoaded() { // If the current editor text has been loaded, // then it is ok to start editing. if (textLoaded == true) { startEditing(); } } /** * Called when the current text has been retrieved from the server. * * @param text the current text to load into the editor */ protected void onCurrentTextLoaded(String text) { editor.setText(text); textLoaded = true; // If the problem has been loaded, then it is ok to start editing. if (getSession().get(Problem.class) != null) { startEditing(); } } protected void startEditing() { editor.setReadOnly(false); mode = Mode.EDITING; } protected void loadProblemFailed() { // TODO - improve problemDescription.setErrorText("Could not load problem description"); } protected void loadCurrentTextFailed() { // TODO - improve problemDescription.setErrorText("Could not load text for problem"); } @Override public void activate() { editor.startEditor(); editor.setReadOnly(true); // until a Problem is loaded editor.setTheme(AceEditorTheme.ECLIPSE); editor.setFontSize("14px"); editor.setMode(AceEditorMode.JAVA); editor.addOnChangeHandler(new AceEditorCallback() { @Override public void invokeAceCallback(JavaScriptObject obj) { // Important: don't send the change to the server unless the // initial editor contents has been loaded. Otherwise, // the setting of the initial editor contents will get sent // to the server as a change, which is obviously not what // we want. if (!textLoaded) { return; } // Convert ACE onChange event object to a Change object, // and add it to the session's ChangeList User user = getSession().get(User.class); Problem problem = getSession().get(Problem.class); Change change = ChangeFromAceOnChangeEvent.convert(obj, user.getId(), problem.getProblemId()); getSession().get(ChangeList.class).addChange(change); } }); // make the editor the correct height doResize(); } @Override public void deactivate() { // Turn off the flush pending events timer flushPendingChangeEventsTimer.cancel(); // Unsubscribe all event subscribers getSubscriptionRegistrar().unsubscribeAllEventSubscribers(); // Clear all local session data removeAllSessionObjects(); } protected void submitCode() { // If the problem has not been loaded yet, // then there is nothing to do. if (getSession().get(Problem.class) == null) { return; } // Set the editor to read-only! // We don't want any edits until the results have // come back from the server. editor.setReadOnly(true); // Create a Change representing the full text of the document, // and schedule it for transmission to the server. Change fullText = new Change( ChangeType.FULL_TEXT, 0, 0, 0, 0, // ignored System.currentTimeMillis(), getSession().get(User.class).getId(), getSession().get(Problem.class).getProblemId(), editor.getText()); getSession().get(ChangeList.class).addChange(fullText); // Set the mode to SUBMIT_IN_PROGRESS, indicating that we are // waiting for the full text to be uploaded to the server. mode = Mode.SUBMIT_IN_PROGRESS; } /* @Override public void update(Observable obj, Object hint) { ChangeList changeList = getSession().get(ChangeList.class); if (obj == changeList) { if (mode == Mode.SUBMIT_IN_PROGRESS && changeList.getState() == ChangeList.State.CLEAN) { // Full text of submission has arrived at server, // and because the editor is read-only, we know that the // local text is in-sync. So, submit the code! AsyncCallback<TestResult[]> callback = new AsyncCallback<TestResult[]>() { @Override public void onFailure(Throwable caught) { final String msg = "Error sending submission to server for compilation"; resultWidget.setMessage(msg); GWT.log(msg, caught); // TODO: should set editor back to read/write? } @Override public void onSuccess(TestResult[] results) { // Great, got results back from server! resultWidget.setResults(results); // Can resume editing now startEditing(); } }; // Send editor text to server. int problemId = getSession().get(Problem.class).getProblemId(); submitService.submit(problemId, editor.getText(), callback); } } } */ @Override public void eventOccurred(Object key, Publisher publisher, Object hint) { if (key == ChangeList.State.CLEAN && mode == Mode.SUBMIT_IN_PROGRESS) { // Full text of submission has arrived at server, // and because the editor is read-only, we know that the // local text is in-sync. So, submit the code! AsyncCallback<TestResult[]> callback = new AsyncCallback<TestResult[]>() { @Override public void onFailure(Throwable caught) { final String msg = "Error sending submission to server for compilation"; resultWidget.setMessage(msg); GWT.log(msg, caught); // TODO: should set editor back to read/write? } @Override public void onSuccess(TestResult[] results) { // Great, got results back from server! resultWidget.setResults(results); // Can resume editing now startEditing(); } }; // Send editor text to server. int problemId = getSession().get(Problem.class).getProblemId(); submitService.submit(problemId, editor.getText(), callback); } } @Override public void unsubscribeFromAll() { getSession().get(ChangeList.class).unsubscribeFromAll(this); } @Override public void onResize(ResizeEvent event) { doResize(); } protected void doResize() { int height = Window.getClientHeight(); int availableForEditor = height - (LayoutConstants.TOP_BAR_HEIGHT_PX + LayoutConstants.PROBLEM_DESC_HEIGHT_PX + LayoutConstants.STATUS_AND_BUTTON_BAR_HEIGHT_PX + LayoutConstants.RESULTS_PANEL_HEIGHT_PX); if (availableForEditor < 0) { availableForEditor = 0; } getLayoutPanel().setWidgetTopHeight( editor, LayoutConstants.TOP_BAR_HEIGHT_PX + LayoutConstants.PROBLEM_DESC_HEIGHT_PX, Unit.PX, availableForEditor, Unit.PX); } // protected void flushAllChanges() { // } // private static final int APP_PANEL_HEIGHT_PX = 30; // private static final int DESC_PANEL_HEIGHT_PX = 70; // private static final int STATUS_PANEL_HEIGHT_PX = 30; // private static final int BUTTON_PANEL_HEIGHT_PX = 40; // // private static final String PROBLEM_ID="problemId"; // // private static final int NORTH_SOUTH_PANELS_HEIGHT_PX = // APP_PANEL_HEIGHT_PX + DESC_PANEL_HEIGHT_PX + STATUS_PANEL_HEIGHT_PX + BUTTON_PANEL_HEIGHT_PX; // // private static final int FAKE_USER_ID = 1; // FIXME // // // Data (model) objects. // private Session session; // // // UI widgets. // private HorizontalPanel appPanel; // private HorizontalPanel descPanel; // private HorizontalPanel editorAndWidgetPanel; // private HintsWidget hintsWidget; // private AffectWidget affectWidget; // private VerticalPanel widgetPanel; // private HorizontalPanel buttonPanel; // private EditorStatusWidget statusWidget; // //private InlineLabel statusLabel; // private ResultWidget resultWidget; // private InlineLabel descLabel; // private AceEditor editor; // private Timer flushPendingChangeEventsTimer; // // // RPC services. // private LogCodeChangeServiceAsync logCodeChangeService; // private SubmitServiceAsync submitService; // private LoadExerciseServiceAsync loadService; // private AffectEventServiceAsync affectEventService; // // /** // * This is the entry point method. // * @param session // */ // public DevelopmentView(Session session) { // this.session = session; // session.get(AffectEvent.class).addObserver(this); // when complete, send to server // // // Id of the problem we're solving // // currently this is a request parameter // Integer problemId = getProblemId(); // // createServices(); // // DockLayoutPanel mainPanel = new DockLayoutPanel(Unit.PX); // // // The app panel can be for logout button, menus, etc. // appPanel = new HorizontalPanel(); // appPanel.add(new Label("Menus and logout button should go here")); // mainPanel.addNorth(appPanel, APP_PANEL_HEIGHT_PX); // // // The description panel is for the problem description // descPanel=new HorizontalPanel(); // descLabel = new InlineLabel(); // descPanel.add(descLabel); // mainPanel.addNorth(descPanel, DESC_PANEL_HEIGHT_PX); // // Load the problem (will update the description panel created above) // loadExerciseDescription(problemId); // // // The editor (left) and widget panel (right) occupy the center location // // in the DockLayoutPanel, and expand to fill space not occupied by // // docked panels. // editorAndWidgetPanel = new HorizontalPanel(); // editorAndWidgetPanel.setWidth("100%"); // // // Button panel is for buttons // buttonPanel = new HorizontalPanel(); // Button submitButton=new Button("Submit"); // submitButton.addClickHandler(new ClickHandler() { // @Override // public void onClick(ClickEvent event){ // submitCode(); // } // }); // buttonPanel.add(submitButton); // mainPanel.addSouth(buttonPanel, BUTTON_PANEL_HEIGHT_PX); // // // Status panel - need to think more about what feedback to provide and how // HorizontalPanel statusPanel = new HorizontalPanel(); // statusWidget = new EditorStatusWidget(); // session.get(ChangeList.class).addObserver(statusWidget); // statusPanel.add(statusWidget); // // resultWidget=new ResultWidget(); // statusPanel.add(resultWidget); // statusPanel.setWidth("100%"); // // VerticalPanel shimAndStatusPanel = new VerticalPanel(); // shimAndStatusPanel.add(new HTML("<div style='height: 6px;'></div>")); // shimAndStatusPanel.add(statusPanel); // mainPanel.addSouth(shimAndStatusPanel, STATUS_PANEL_HEIGHT_PX); // // // Code editor // editor = new AceEditor(); // editor.setStylePrimaryName("NetCoderEditor"); // editor.setHeight("500px"); // // // Widget panel: for things like hints, affect data collection, etc. // widgetPanel = new VerticalPanel(); // widgetPanel.setWidth("100%"); // hintsWidget = new HintsWidget(); // hintsWidget.setWidth("100%"); // widgetPanel.add(hintsWidget); // //widgetPanel.add(new HTML("<div style='height: 6px; width: 0px;'></div>")); // hack // affectWidget = new AffectWidget(session.get(AffectEvent.class)); // affectWidget.setWidth("100%"); // affectWidget.setHeight("300px"); // widgetPanel.add(affectWidget); // // another try to get results into here... // resultWidget = new ResultWidget(); // widgetPanel.add(resultWidget); // // // Add the editor and widget panel so that it is a 80/20 split // editorAndWidgetPanel.add(editor); // editorAndWidgetPanel.setCellWidth(editor, "80%"); // editorAndWidgetPanel.add(widgetPanel); // editorAndWidgetPanel.setCellWidth(widgetPanel, "20%"); // mainPanel.add(editorAndWidgetPanel); // // // Add the main panel to the window // //RootLayoutPanel.get().add(mainPanel); // initWidget(mainPanel); // // // // Size the editor and widget panel to fill available space // // resize(Window.getClientWidth(), Window.getClientHeight()); // // // Add window resize handler so that we can make editor and widget // // panel expand vertically as necessary // Window.addResizeHandler(this); // // //startEditor(); // // // create timer to flush unsent change events periodically // flushPendingChangeEventsTimer = new Timer() { // @Override // public void run() { // final ChangeList changeList = DevelopmentView.this.session.get(ChangeList.class); // if (changeList.getState() == ChangeList.State.UNSENT) { // Change[] changeBatch = changeList.beginTransmit(); // // AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() { // @Override // public void onFailure(Throwable caught) { // changeList.endTransmit(false); // GWT.log("Failed to send change batch to server"); // } // // @Override // public void onSuccess(Boolean result) { // changeList.endTransmit(true); // } // }; // // logCodeChangeService.logChange(changeBatch, callback); // } // } // }; // flushPendingChangeEventsTimer.scheduleRepeating(1000); // } // // public void startEditor() { // // fire up the ACE editor // editor.startEditor(); // editor.setReadOnly(true); // until a Problem is loaded // editor.setTheme(AceEditorTheme.ECLIPSE); // editor.setFontSize("14px"); // editor.setMode(AceEditorMode.JAVA); // editor.addOnChangeHandler(this); // } // // private void createServices() { // // Create async service objects for communication with server // logCodeChangeService = (LogCodeChangeServiceAsync) GWT.create(LogCodeChangeService.class); // //compileService = (CompileServiceAsync) GWT.create(CompileService.class); // submitService =(SubmitServiceAsync) GWT.create(SubmitService.class); // loadService =(LoadExerciseServiceAsync) GWT.create(LoadExerciseService.class); // affectEventService = (AffectEventServiceAsync) GWT.create(AffectEventService.class); // } // // /** // * Handles onChange events from the editor. // */ // @Override // public void invokeAceCallback(JavaScriptObject obj) { // ChangeList changeList = session.get(ChangeList.class); // Problem problem = session.get(Problem.class); // changeList.addChange(ChangeFromAceOnChangeEvent.convert(obj, FAKE_USER_ID, problem.getProblemId())); // } // // /** // * Send the current text in the editor to the server to be compiled. // */ // // protected void compileCode() { // // AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() { // // @Override // // public void onFailure(Throwable caught) { // // statusLabel.setText("Error sending submission to server for compilation"); // // GWT.log("compile failed", caught); // // } // // // // @Override // // public void onSuccess(Boolean result) { // // statusLabel.setText(result ? "Compile succeeded" : "Compile failed"); // // } // // }; // // // // compileService.compile(editor.getText(), callback); // // } // // protected void loadExerciseDescription(int problemId) { // AsyncCallback<Problem> callback = new AsyncCallback<Problem>() { // @Override // public void onFailure(Throwable caught) { // descLabel.setText("Error loading exercise"); // GWT.log("loading exercise description failed", caught); // } // // @Override // public void onSuccess(Problem result) { // setProblem(result); // } // }; // loadService.load(problemId, callback); // } // // protected void submitCode() { // AsyncCallback<TestResult[]> callback = new AsyncCallback<TestResult[]>() { // @Override // public void onFailure(Throwable caught) { // resultWidget.setMessage("Error sending submission to server for compilation"); // GWT.log("compile failed", caught); // } // // @Override // public void onSuccess(TestResult[] results) { // resultWidget.setResults(results); // } // }; // int problemId=getProblemId(); // submitService.submit(problemId, editor.getText(), callback); // } // // @Override // public void onResize(ResizeEvent event) { // resize(Window.getClientWidth(), Window.getClientHeight()); // } // // private int getProblemId() { // String problemIdStr=Window.Location.getParameter(PROBLEM_ID); // if (problemIdStr==null) { // return 0; // } // return Integer.parseInt(problemIdStr); // } // // private void resize(int width, int height) { // // Let the editor and widget panel take up all of the vertical // // height not consumed by the north/south panels. // int availHeight = (height - NORTH_SOUTH_PANELS_HEIGHT_PX) - 10; // if (availHeight < 0) { // availHeight = 0; // } // editor.setHeight(availHeight + "px"); // } // // protected void setProblem(Problem result) { // //this.problem = result; // this.session.add(result); // this.descLabel.setText(result.getDescription()); // this.editor.setReadOnly(false); // } // // // FIXME: is there a better way to do this? // // (maybe send completed AffectEvent using time, same as Change events) // private boolean sendingAffectData = false; // // @Override // public void update(Observable obj, Object hint) { // final AffectEvent affectEvent = session.get(AffectEvent.class); // if (obj == affectEvent && !sendingAffectData && affectEvent.isComplete()) { // GWT.log("Sending affect data"); // // sendingAffectData = true; // // AsyncCallback<Void> callback = new AsyncCallback<Void>() { // @Override // public void onFailure(Throwable caught) { // GWT.log("Could not store affect event: " + caught.getMessage()); // sendingAffectData = false; // } // // @Override // public void onSuccess(Void result) { // GWT.log("Affect data recorded successfully"); // // Yay! // affectEvent.clear(); // sendingAffectData = false; // } // }; // // // Fill in event details. // Problem problem = session.get(Problem.class); // affectEvent.createEvent(FAKE_USER_ID, problem.getProblemId(), System.currentTimeMillis()); // // // Send to server. // affectEventService.recordAffectEvent(affectEvent, callback); // } // } }
got rid of commented out code
src/edu/ycp/cs/netcoder/client/DevelopmentView.java
got rid of commented out code
<ide><path>rc/edu/ycp/cs/netcoder/client/DevelopmentView.java <ide> mode = Mode.SUBMIT_IN_PROGRESS; <ide> } <ide> <del> /* <del> @Override <del> public void update(Observable obj, Object hint) { <del> ChangeList changeList = getSession().get(ChangeList.class); <del> if (obj == changeList) { <del> if (mode == Mode.SUBMIT_IN_PROGRESS && changeList.getState() == ChangeList.State.CLEAN) { <del> // Full text of submission has arrived at server, <del> // and because the editor is read-only, we know that the <del> // local text is in-sync. So, submit the code! <del> <del> AsyncCallback<TestResult[]> callback = new AsyncCallback<TestResult[]>() { <del> @Override <del> public void onFailure(Throwable caught) { <del> final String msg = "Error sending submission to server for compilation"; <del> resultWidget.setMessage(msg); <del> GWT.log(msg, caught); <del> // TODO: should set editor back to read/write? <del> } <del> <del> @Override <del> public void onSuccess(TestResult[] results) { <del> // Great, got results back from server! <del> resultWidget.setResults(results); <del> <del> // Can resume editing now <del> startEditing(); <del> } <del> }; <del> <del> // Send editor text to server. <del> int problemId = getSession().get(Problem.class).getProblemId(); <del> submitService.submit(problemId, editor.getText(), callback); <del> } <del> } <del> } <del> */ <del> <ide> @Override <ide> public void eventOccurred(Object key, Publisher publisher, Object hint) { <ide> if (key == ChangeList.State.CLEAN && mode == Mode.SUBMIT_IN_PROGRESS) { <ide> LayoutConstants.TOP_BAR_HEIGHT_PX + LayoutConstants.PROBLEM_DESC_HEIGHT_PX, Unit.PX, <ide> availableForEditor, Unit.PX); <ide> } <del> <del>// protected void flushAllChanges() { <del>// } <del> <del>// private static final int APP_PANEL_HEIGHT_PX = 30; <del>// private static final int DESC_PANEL_HEIGHT_PX = 70; <del>// private static final int STATUS_PANEL_HEIGHT_PX = 30; <del>// private static final int BUTTON_PANEL_HEIGHT_PX = 40; <del>// <del>// private static final String PROBLEM_ID="problemId"; <del>// <del>// private static final int NORTH_SOUTH_PANELS_HEIGHT_PX = <del>// APP_PANEL_HEIGHT_PX + DESC_PANEL_HEIGHT_PX + STATUS_PANEL_HEIGHT_PX + BUTTON_PANEL_HEIGHT_PX; <del>// <del>// private static final int FAKE_USER_ID = 1; // FIXME <del>// <del>// // Data (model) objects. <del>// private Session session; <del>// <del>// // UI widgets. <del>// private HorizontalPanel appPanel; <del>// private HorizontalPanel descPanel; <del>// private HorizontalPanel editorAndWidgetPanel; <del>// private HintsWidget hintsWidget; <del>// private AffectWidget affectWidget; <del>// private VerticalPanel widgetPanel; <del>// private HorizontalPanel buttonPanel; <del>// private EditorStatusWidget statusWidget; <del>// //private InlineLabel statusLabel; <del>// private ResultWidget resultWidget; <del>// private InlineLabel descLabel; <del>// private AceEditor editor; <del>// private Timer flushPendingChangeEventsTimer; <del>// <del>// // RPC services. <del>// private LogCodeChangeServiceAsync logCodeChangeService; <del>// private SubmitServiceAsync submitService; <del>// private LoadExerciseServiceAsync loadService; <del>// private AffectEventServiceAsync affectEventService; <del>// <del>// /** <del>// * This is the entry point method. <del>// * @param session <del>// */ <del>// public DevelopmentView(Session session) { <del>// this.session = session; <del>// session.get(AffectEvent.class).addObserver(this); // when complete, send to server <del>// <del>// // Id of the problem we're solving <del>// // currently this is a request parameter <del>// Integer problemId = getProblemId(); <del>// <del>// createServices(); <del>// <del>// DockLayoutPanel mainPanel = new DockLayoutPanel(Unit.PX); <del>// <del>// // The app panel can be for logout button, menus, etc. <del>// appPanel = new HorizontalPanel(); <del>// appPanel.add(new Label("Menus and logout button should go here")); <del>// mainPanel.addNorth(appPanel, APP_PANEL_HEIGHT_PX); <del>// <del>// // The description panel is for the problem description <del>// descPanel=new HorizontalPanel(); <del>// descLabel = new InlineLabel(); <del>// descPanel.add(descLabel); <del>// mainPanel.addNorth(descPanel, DESC_PANEL_HEIGHT_PX); <del>// // Load the problem (will update the description panel created above) <del>// loadExerciseDescription(problemId); <del>// <del>// // The editor (left) and widget panel (right) occupy the center location <del>// // in the DockLayoutPanel, and expand to fill space not occupied by <del>// // docked panels. <del>// editorAndWidgetPanel = new HorizontalPanel(); <del>// editorAndWidgetPanel.setWidth("100%"); <del>// <del>// // Button panel is for buttons <del>// buttonPanel = new HorizontalPanel(); <del>// Button submitButton=new Button("Submit"); <del>// submitButton.addClickHandler(new ClickHandler() { <del>// @Override <del>// public void onClick(ClickEvent event){ <del>// submitCode(); <del>// } <del>// }); <del>// buttonPanel.add(submitButton); <del>// mainPanel.addSouth(buttonPanel, BUTTON_PANEL_HEIGHT_PX); <del>// <del>// // Status panel - need to think more about what feedback to provide and how <del>// HorizontalPanel statusPanel = new HorizontalPanel(); <del>// statusWidget = new EditorStatusWidget(); <del>// session.get(ChangeList.class).addObserver(statusWidget); <del>// statusPanel.add(statusWidget); <del>// <del>// resultWidget=new ResultWidget(); <del>// statusPanel.add(resultWidget); <del>// statusPanel.setWidth("100%"); <del>// <del>// VerticalPanel shimAndStatusPanel = new VerticalPanel(); <del>// shimAndStatusPanel.add(new HTML("<div style='height: 6px;'></div>")); <del>// shimAndStatusPanel.add(statusPanel); <del>// mainPanel.addSouth(shimAndStatusPanel, STATUS_PANEL_HEIGHT_PX); <del>// <del>// // Code editor <del>// editor = new AceEditor(); <del>// editor.setStylePrimaryName("NetCoderEditor"); <del>// editor.setHeight("500px"); <del>// <del>// // Widget panel: for things like hints, affect data collection, etc. <del>// widgetPanel = new VerticalPanel(); <del>// widgetPanel.setWidth("100%"); <del>// hintsWidget = new HintsWidget(); <del>// hintsWidget.setWidth("100%"); <del>// widgetPanel.add(hintsWidget); <del>// //widgetPanel.add(new HTML("<div style='height: 6px; width: 0px;'></div>")); // hack <del>// affectWidget = new AffectWidget(session.get(AffectEvent.class)); <del>// affectWidget.setWidth("100%"); <del>// affectWidget.setHeight("300px"); <del>// widgetPanel.add(affectWidget); <del>// // another try to get results into here... <del>// resultWidget = new ResultWidget(); <del>// widgetPanel.add(resultWidget); <del>// <del>// // Add the editor and widget panel so that it is a 80/20 split <del>// editorAndWidgetPanel.add(editor); <del>// editorAndWidgetPanel.setCellWidth(editor, "80%"); <del>// editorAndWidgetPanel.add(widgetPanel); <del>// editorAndWidgetPanel.setCellWidth(widgetPanel, "20%"); <del>// mainPanel.add(editorAndWidgetPanel); <del>// <del>// // Add the main panel to the window <del>// //RootLayoutPanel.get().add(mainPanel); <del>// initWidget(mainPanel); <del>// <del>// // // Size the editor and widget panel to fill available space <del>// // resize(Window.getClientWidth(), Window.getClientHeight()); <del>// <del>// // Add window resize handler so that we can make editor and widget <del>// // panel expand vertically as necessary <del>// Window.addResizeHandler(this); <del>// <del>// //startEditor(); <del>// <del>// // create timer to flush unsent change events periodically <del>// flushPendingChangeEventsTimer = new Timer() { <del>// @Override <del>// public void run() { <del>// final ChangeList changeList = DevelopmentView.this.session.get(ChangeList.class); <del>// if (changeList.getState() == ChangeList.State.UNSENT) { <del>// Change[] changeBatch = changeList.beginTransmit(); <del>// <del>// AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() { <del>// @Override <del>// public void onFailure(Throwable caught) { <del>// changeList.endTransmit(false); <del>// GWT.log("Failed to send change batch to server"); <del>// } <del>// <del>// @Override <del>// public void onSuccess(Boolean result) { <del>// changeList.endTransmit(true); <del>// } <del>// }; <del>// <del>// logCodeChangeService.logChange(changeBatch, callback); <del>// } <del>// } <del>// }; <del>// flushPendingChangeEventsTimer.scheduleRepeating(1000); <del>// } <del>// <del>// public void startEditor() { <del>// // fire up the ACE editor <del>// editor.startEditor(); <del>// editor.setReadOnly(true); // until a Problem is loaded <del>// editor.setTheme(AceEditorTheme.ECLIPSE); <del>// editor.setFontSize("14px"); <del>// editor.setMode(AceEditorMode.JAVA); <del>// editor.addOnChangeHandler(this); <del>// } <del>// <del>// private void createServices() { <del>// // Create async service objects for communication with server <del>// logCodeChangeService = (LogCodeChangeServiceAsync) GWT.create(LogCodeChangeService.class); <del>// //compileService = (CompileServiceAsync) GWT.create(CompileService.class); <del>// submitService =(SubmitServiceAsync) GWT.create(SubmitService.class); <del>// loadService =(LoadExerciseServiceAsync) GWT.create(LoadExerciseService.class); <del>// affectEventService = (AffectEventServiceAsync) GWT.create(AffectEventService.class); <del>// } <del>// <del>// /** <del>// * Handles onChange events from the editor. <del>// */ <del>// @Override <del>// public void invokeAceCallback(JavaScriptObject obj) { <del>// ChangeList changeList = session.get(ChangeList.class); <del>// Problem problem = session.get(Problem.class); <del>// changeList.addChange(ChangeFromAceOnChangeEvent.convert(obj, FAKE_USER_ID, problem.getProblemId())); <del>// } <del>// <del>// /** <del>// * Send the current text in the editor to the server to be compiled. <del>// */ <del>// // protected void compileCode() { <del>// // AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() { <del>// // @Override <del>// // public void onFailure(Throwable caught) { <del>// // statusLabel.setText("Error sending submission to server for compilation"); <del>// // GWT.log("compile failed", caught); <del>// // } <del>// // <del>// // @Override <del>// // public void onSuccess(Boolean result) { <del>// // statusLabel.setText(result ? "Compile succeeded" : "Compile failed"); <del>// // } <del>// // }; <del>// // <del>// // compileService.compile(editor.getText(), callback); <del>// // } <del>// <del>// protected void loadExerciseDescription(int problemId) { <del>// AsyncCallback<Problem> callback = new AsyncCallback<Problem>() { <del>// @Override <del>// public void onFailure(Throwable caught) { <del>// descLabel.setText("Error loading exercise"); <del>// GWT.log("loading exercise description failed", caught); <del>// } <del>// <del>// @Override <del>// public void onSuccess(Problem result) { <del>// setProblem(result); <del>// } <del>// }; <del>// loadService.load(problemId, callback); <del>// } <del>// <del>// protected void submitCode() { <del>// AsyncCallback<TestResult[]> callback = new AsyncCallback<TestResult[]>() { <del>// @Override <del>// public void onFailure(Throwable caught) { <del>// resultWidget.setMessage("Error sending submission to server for compilation"); <del>// GWT.log("compile failed", caught); <del>// } <del>// <del>// @Override <del>// public void onSuccess(TestResult[] results) { <del>// resultWidget.setResults(results); <del>// } <del>// }; <del>// int problemId=getProblemId(); <del>// submitService.submit(problemId, editor.getText(), callback); <del>// } <del>// <del>// @Override <del>// public void onResize(ResizeEvent event) { <del>// resize(Window.getClientWidth(), Window.getClientHeight()); <del>// } <del>// <del>// private int getProblemId() { <del>// String problemIdStr=Window.Location.getParameter(PROBLEM_ID); <del>// if (problemIdStr==null) { <del>// return 0; <del>// } <del>// return Integer.parseInt(problemIdStr); <del>// } <del>// <del>// private void resize(int width, int height) { <del>// // Let the editor and widget panel take up all of the vertical <del>// // height not consumed by the north/south panels. <del>// int availHeight = (height - NORTH_SOUTH_PANELS_HEIGHT_PX) - 10; <del>// if (availHeight < 0) { <del>// availHeight = 0; <del>// } <del>// editor.setHeight(availHeight + "px"); <del>// } <del>// <del>// protected void setProblem(Problem result) { <del>// //this.problem = result; <del>// this.session.add(result); <del>// this.descLabel.setText(result.getDescription()); <del>// this.editor.setReadOnly(false); <del>// } <del>// <del>// // FIXME: is there a better way to do this? <del>// // (maybe send completed AffectEvent using time, same as Change events) <del>// private boolean sendingAffectData = false; <del>// <del>// @Override <del>// public void update(Observable obj, Object hint) { <del>// final AffectEvent affectEvent = session.get(AffectEvent.class); <del>// if (obj == affectEvent && !sendingAffectData && affectEvent.isComplete()) { <del>// GWT.log("Sending affect data"); <del>// <del>// sendingAffectData = true; <del>// <del>// AsyncCallback<Void> callback = new AsyncCallback<Void>() { <del>// @Override <del>// public void onFailure(Throwable caught) { <del>// GWT.log("Could not store affect event: " + caught.getMessage()); <del>// sendingAffectData = false; <del>// } <del>// <del>// @Override <del>// public void onSuccess(Void result) { <del>// GWT.log("Affect data recorded successfully"); <del>// // Yay! <del>// affectEvent.clear(); <del>// sendingAffectData = false; <del>// } <del>// }; <del>// <del>// // Fill in event details. <del>// Problem problem = session.get(Problem.class); <del>// affectEvent.createEvent(FAKE_USER_ID, problem.getProblemId(), System.currentTimeMillis()); <del>// <del>// // Send to server. <del>// affectEventService.recordAffectEvent(affectEvent, callback); <del>// } <del>// } <del> <ide> }
Java
apache-2.0
1e227e5fa55a575f7e827f46b2fa8d585c229250
0
WouterBanckenACA/aries,maxbruecken/aries,MeiSheng/aries,MeiSheng/aries,alexandreroman/aries,acartapanis/aries,alexandreroman/aries,tomdw/aries,tomdw/aries,kameshsampath/aries,jwross/aries,gnodet/aries,jwross/aries,metatechbe/aries,fwassmer/aries,kameshsampath/aries,acartapanis/aries,metatechbe/aries,maxbruecken/aries,metatechbe/aries,ggerla/aries,fwassmer/aries,WouterBanckenACA/aries,MeiSheng/aries,ggerla/aries,fwassmer/aries,alexandreroman/aries,WouterBanckenACA/aries,gnodet/aries,tomdw/aries,maxbruecken/aries,jwross/aries,gnodet/aries,acartapanis/aries,gnodet/aries,kameshsampath/aries,fwassmer/aries,jwross/aries,alexandreroman/aries,ggerla/aries,acartapanis/aries,ggerla/aries,kameshsampath/aries,WouterBanckenACA/aries,tomdw/aries,maxbruecken/aries,MeiSheng/aries,metatechbe/aries
/** * 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.aries.spifly.dynamic; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Dictionary; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.aries.spifly.BaseActivator; import org.apache.aries.spifly.Streams; import org.apache.aries.spifly.api.SpiFlyConstants; import org.easymock.EasyMock; import org.easymock.IAnswer; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleReference; import org.osgi.framework.Version; import org.osgi.framework.hooks.weaving.WeavingHook; import org.osgi.framework.hooks.weaving.WovenClass; import org.osgi.framework.wiring.BundleWiring; public class ClientWeavingHookTest { DynamicWeavingActivator activator; @Before public void setUp() { activator = new DynamicWeavingActivator(); BaseActivator.activator = activator; } @After public void tearDown() { BaseActivator.activator = null; activator = null; } @Test public void testClientWeavingHookBasicServiveLoaderUsage() throws Exception { Dictionary<String, String> consumerHeaders = new Hashtable<String, String>(); consumerHeaders.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "*"); // Register the bundle that provides the SPI implementation. Bundle providerBundle = mockProviderBundle("impl1", 1); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle); Bundle consumerBundle = mockConsumerBundle(consumerHeaders, providerBundle); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle spiFlyBundle = mockSpiFlyBundle("spifly", Version.parseVersion("1.9.4"), consumerBundle, providerBundle); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); // Weave the TestClient class. URL clsUrl = getClass().getResource("TestClient.class"); Assert.assertNotNull("Precondition", clsUrl); String clientClassName = "org.apache.aries.spifly.dynamic.TestClient"; WovenClass wc = new MyWovenClass(clsUrl, clientClassName, consumerBundle); Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size()); wh.weave(wc); Assert.assertEquals(1, wc.getDynamicImports().size()); String di1 = "org.apache.aries.spifly;bundle-symbolic-name=spifly;bundle-version=1.9.4"; String di2 = "org.apache.aries.spifly;bundle-version=1.9.4;bundle-symbolic-name=spifly"; String di = wc.getDynamicImports().get(0); Assert.assertTrue("Weaving should have added a dynamic import", di1.equals(di) || di2.equals(di)); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals("olleh", result); } @Test public void testClientWeavingHookAltServiceLoaderLoadUnprocessed() throws Exception { Bundle spiFlyBundle = mockSpiFlyBundle(); Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "*"); Bundle consumerBundle = mockConsumerBundle(headers, spiFlyBundle); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); // Weave the TestClient class. URL clsUrl = getClass().getResource("UnaffectedTestClient.class"); Assert.assertNotNull("Precondition", clsUrl); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.UnaffectedTestClient", consumerBundle); Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size()); wh.weave(wc); Assert.assertEquals("The client is not affected so no additional imports should have been added", 0, wc.getDynamicImports().size()); // ok the weaving is done, now prepare the registry for the call Bundle providerBundle = mockProviderBundle("impl1", 1); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals("impl4", result); } @Test public void testClientWeavingHookMultipleProviders() throws Exception { Bundle spiFlyBundle = mockSpiFlyBundle(); Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "*"); Bundle consumerBundle = mockConsumerBundle(headers, spiFlyBundle); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); // Weave the TestClient class. URL clsUrl = getClass().getResource("TestClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle); wh.weave(wc); Bundle providerBundle1 = mockProviderBundle("impl1", 1); Bundle providerBundle2 = mockProviderBundle("impl2", 2); // Register in reverse order to make sure the order in which bundles are sorted is correct activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI files from impl1 and impl2 are visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals("All three services should be invoked in the correct order", "ollehHELLO5", result); } @Test public void testClientSpecifyingProvider() throws Exception { Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "java.util.ServiceLoader#load(java.lang.Class);bundle=impl2"); Bundle providerBundle1 = mockProviderBundle("impl1", 1); Bundle providerBundle2 = mockProviderBundle("impl2", 2); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2); Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); // Weave the TestClient class. URL clsUrl = getClass().getResource("TestClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle); wh.weave(wc); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals("Only the services from bundle impl2 should be selected", "HELLO5", result); } @Test public void testClientSpecifyingProviderVersion() throws Exception { Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "java.util.ServiceLoader#load(java.lang.Class);bundle=impl2:version=1.2.3"); Bundle providerBundle1 = mockProviderBundle("impl1", 1); Bundle providerBundle2 = mockProviderBundle("impl2", 2); Bundle providerBundle3 = mockProviderBundle("impl2_123", 3, new Version(1, 2, 3)); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle3); Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2, providerBundle3); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2, providerBundle3); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); // Weave the TestClient class. URL clsUrl = getClass().getResource("TestClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle); wh.weave(wc); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals("Only the services from bundle impl2 should be selected", "Updated!hello!Updated", result); } @Test public void testClientMultipleTargetBundles() throws Exception { Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "java.util.ServiceLoader#load(java.lang.Class);bundle=impl1|impl4"); Bundle providerBundle1 = mockProviderBundle("impl1", 1); Bundle providerBundle2 = mockProviderBundle("impl2", 2); Bundle providerBundle4 = mockProviderBundle("impl4", 4); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle4); activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle4); Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2, providerBundle4); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2, providerBundle4); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); // Weave the TestClient class. URL clsUrl = getClass().getResource("TestClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle); wh.weave(wc); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals("All providers should be selected for this one", "ollehimpl4", result); } @Test public void testClientMultipleTargetBundles2() throws Exception { Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "java.util.ServiceLoader#load(java.lang.Class);bundleId=1|4"); Bundle providerBundle1 = mockProviderBundle("impl1", 1); Bundle providerBundle2 = mockProviderBundle("impl2", 2); Bundle providerBundle4 = mockProviderBundle("impl4", 4); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle4); activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle4); Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2, providerBundle4); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2, providerBundle4); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); // Weave the TestClient class. URL clsUrl = getClass().getResource("TestClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle); wh.weave(wc); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals("All providers should be selected for this one", "ollehimpl4", result); } @Test public void testClientSpecificProviderLoadArgument() throws Exception { Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "java.util.ServiceLoader#load(java.lang.Class[org.apache.aries.mytest.MySPI])," + "java.util.ServiceLoader#load(java.lang.Class[org.apache.aries.mytest.AltSPI]);bundle=impl4"); Bundle providerBundle1 = mockProviderBundle("impl1", 1); Bundle providerBundle2 = mockProviderBundle("impl2", 2); Bundle providerBundle4 = mockProviderBundle("impl4", 4); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle4); activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle4); Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2, providerBundle4); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2, providerBundle4); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); // Weave the TestClient class. URL clsUrl = getClass().getResource("TestClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle); wh.weave(wc); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals("All providers should be selected for this one", "ollehHELLO5impl4", result); // Weave the AltTestClient class. URL cls2Url = getClass().getResource("AltTestClient.class"); WovenClass wc2 = new MyWovenClass(cls2Url, "org.apache.aries.spifly.dynamic.AltTestClient", consumerBundle); wh.weave(wc2); // Invoke the AltTestClient Class<?> cls2 = wc2.getDefinedClass(); Method method2 = cls2.getMethod("test", new Class [] {long.class}); Object result2 = method2.invoke(cls2.newInstance(), 4096); Assert.assertEquals("Only the services from bundle impl4 should be selected", -4096L*4096L, result2); } @Test public void testClientSpecifyingDifferentMethodsLimitedToDifferentProviders() throws Exception { Dictionary<String, String> headers1 = new Hashtable<String, String>(); headers1.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance();bundle=impl3," + "java.util.ServiceLoader#load(java.lang.Class[org.apache.aries.mytest.MySPI]);bundle=impl4"); Dictionary<String, String> headers2 = new Hashtable<String, String>(); headers2.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance();bundle=system.bundle," + "java.util.ServiceLoader#load;bundle=impl1"); Dictionary<String, String> headers3 = new Hashtable<String, String>(); headers3.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "org.acme.blah#someMethod();bundle=mybundle"); Bundle providerBundle1 = mockProviderBundle("impl1", 1); Bundle providerBundle2 = mockProviderBundle("impl2", 2); Bundle providerBundle3 = mockProviderBundle("impl3", 3); Bundle providerBundle4 = mockProviderBundle("impl4", 4); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle2); activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle3); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle4); activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle4); Bundle consumerBundle1 = mockConsumerBundle(headers1, providerBundle1, providerBundle2, providerBundle3, providerBundle4); activator.addConsumerWeavingData(consumerBundle1, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle consumerBundle2 = mockConsumerBundle(headers2, providerBundle1, providerBundle2, providerBundle3, providerBundle4); activator.addConsumerWeavingData(consumerBundle2, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle consumerBundle3 = mockConsumerBundle(headers3, providerBundle1, providerBundle2, providerBundle3, providerBundle4); activator.addConsumerWeavingData(consumerBundle3, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle1, consumerBundle2, consumerBundle3, providerBundle1, providerBundle2, providerBundle3, providerBundle4); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); testConsumerBundleWeaving(consumerBundle1, wh, "impl4", "org.apache.aries.spifly.dynamic.impl3.MyAltDocumentBuilderFactory"); testConsumerBundleWeaving(consumerBundle2, wh, "olleh", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); testConsumerBundleWeaving(consumerBundle3, wh, "", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); } private void testConsumerBundleWeaving(Bundle consumerBundle, WeavingHook wh, String testClientResult, String jaxpClientResult) throws Exception { // Weave the TestClient class. URL clsUrl = getClass().getResource("TestClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle); wh.weave(wc); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals(testClientResult, result); URL clsUrl2 = getClass().getResource("JaxpClient.class"); WovenClass wc2 = new MyWovenClass(clsUrl2, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle); wh.weave(wc2); Class<?> cls2 = wc2.getDefinedClass(); Method method2 = cls2.getMethod("test", new Class [] {}); Class<?> result2 = (Class<?>) method2.invoke(cls2.newInstance()); Assert.assertEquals(jaxpClientResult, result2.getName()); } @Test public void testJAXPClientWantsJREImplementation1() throws Exception { Bundle systembundle = mockSystemBundle(); Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance()"); Bundle consumerBundle = mockConsumerBundle(headers, systembundle); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, systembundle).getBundleContext(), activator); URL clsUrl = getClass().getResource("JaxpClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle); wh.weave(wc); Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {}); Class<?> result = (Class<?>) method.invoke(cls.newInstance()); Assert.assertEquals("JAXP implementation from JRE", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl", result.getName()); } // If there is an alternate implementation it should always be favoured over the JRE one @Test public void testJAXPClientWantsAltImplementation1() throws Exception { Bundle systembundle = mockSystemBundle(); Bundle providerBundle = mockProviderBundle("impl3", 1); activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle); Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance()"); Bundle consumerBundle = mockConsumerBundle(headers, providerBundle, systembundle); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator); URL clsUrl = getClass().getResource("JaxpClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle); wh.weave(wc); Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {}); Class<?> result = (Class<?>) method.invoke(cls.newInstance()); Assert.assertEquals("JAXP implementation from JRE", "org.apache.aries.spifly.impl3.MyAltDocumentBuilderFactory", result.getName()); } @Test public void testJAXPClientWantsJREImplementation2() throws Exception { Bundle systembundle = mockSystemBundle(); Bundle providerBundle = mockProviderBundle("impl3", 1); activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle); Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance();bundleId=0"); Bundle consumerBundle = mockConsumerBundle(headers, providerBundle, systembundle); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator); URL clsUrl = getClass().getResource("JaxpClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle); wh.weave(wc); Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {}); Class<?> result = (Class<?>) method.invoke(cls.newInstance()); Assert.assertEquals("JAXP implementation from JRE", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl", result.getName()); } @Test public void testJAXPClientWantsAltImplementation2() throws Exception { Bundle systembundle = mockSystemBundle(); Bundle providerBundle = mockProviderBundle("impl3", 1); activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle); Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance();bundle=impl3"); Bundle consumerBundle = mockConsumerBundle(headers, providerBundle, systembundle); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator); URL clsUrl = getClass().getResource("JaxpClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle); wh.weave(wc); Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {}); Class<?> result = (Class<?>) method.invoke(cls.newInstance()); Assert.assertEquals("JAXP implementation from alternative bundle", "org.apache.aries.spifly.impl3.MyAltDocumentBuilderFactory", result.getName()); } private Bundle mockSpiFlyBundle(Bundle ... bundles) throws Exception { return mockSpiFlyBundle("spifly", new Version(1, 0, 0), bundles); } private Bundle mockSpiFlyBundle(String bsn, Version version, Bundle ... bundles) throws Exception { Bundle spiFlyBundle = EasyMock.createMock(Bundle.class); BundleContext spiFlyBundleContext = EasyMock.createMock(BundleContext.class); EasyMock.expect(spiFlyBundleContext.getBundle()).andReturn(spiFlyBundle).anyTimes(); List<Bundle> allBundles = new ArrayList<Bundle>(Arrays.asList(bundles)); allBundles.add(spiFlyBundle); EasyMock.expect(spiFlyBundleContext.getBundles()).andReturn(allBundles.toArray(new Bundle [] {})).anyTimes(); EasyMock.replay(spiFlyBundleContext); EasyMock.expect(spiFlyBundle.getSymbolicName()).andReturn(bsn).anyTimes(); EasyMock.expect(spiFlyBundle.getVersion()).andReturn(version).anyTimes(); EasyMock.expect(spiFlyBundle.getBundleId()).andReturn(Long.MAX_VALUE).anyTimes(); EasyMock.expect(spiFlyBundle.getBundleContext()).andReturn(spiFlyBundleContext).anyTimes(); EasyMock.replay(spiFlyBundle); // Set the bundle context for testing purposes Field bcField = BaseActivator.class.getDeclaredField("bundleContext"); bcField.setAccessible(true); bcField.set(activator, spiFlyBundle.getBundleContext()); return spiFlyBundle; } private Bundle mockProviderBundle(String subdir, long id) throws Exception { return mockProviderBundle(subdir, id, Version.emptyVersion); } private Bundle mockProviderBundle(String subdir, long id, Version version) throws Exception { URL url = getClass().getResource("/" + getClass().getName().replace('.', '/') + ".class"); File classFile = new File(url.getFile()); File baseDir = new File(classFile.getParentFile(), subdir); File directory = new File(baseDir, "/META-INF/services"); final List<String> classNames = new ArrayList<String>(); // Do a directory listing of the applicable META-INF/services directory List<String> resources = new ArrayList<String>(); for (File f : directory.listFiles()) { String fileName = f.getName(); if (fileName.startsWith(".") || fileName.endsWith(".")) continue; classNames.addAll(getClassNames(f)); // Needs to be something like: META-INF/services/org.apache.aries.mytest.MySPI String path = f.getAbsolutePath().substring(baseDir.getAbsolutePath().length()); path = path.replace('\\', '/'); if (path.startsWith("/")) { path = path.substring(1); } resources.add(path); } // Set up the classloader that will be used by the ASM-generated code as the TCCL. // It can load a META-INF/services file final ClassLoader cl = new TestProviderBundleClassLoader(subdir, resources.toArray(new String [] {})); List<String> classResources = new ArrayList<String>(); for(String className : classNames) { classResources.add("/" + className.replace('.', '/') + ".class"); } Bundle providerBundle = EasyMock.createMock(Bundle.class); String bsn = subdir; int idx = bsn.indexOf('_'); if (idx > 0) { bsn = bsn.substring(0, idx); } EasyMock.expect(providerBundle.getSymbolicName()).andReturn(bsn).anyTimes(); EasyMock.expect(providerBundle.getBundleId()).andReturn(id).anyTimes(); EasyMock.expect(providerBundle.getVersion()).andReturn(version).anyTimes(); EasyMock.expect(providerBundle.getEntryPaths("/")).andReturn(Collections.enumeration(classResources)).anyTimes(); EasyMock.<Class<?>>expect(providerBundle.loadClass(EasyMock.anyObject(String.class))).andAnswer(new IAnswer<Class<?>>() { @Override public Class<?> answer() throws Throwable { String name = (String) EasyMock.getCurrentArguments()[0]; if (!classNames.contains(name)) { throw new ClassCastException(name); } return cl.loadClass(name); } }).anyTimes(); EasyMock.replay(providerBundle); return providerBundle; } private Collection<String> getClassNames(File f) throws IOException { List<String> names = new ArrayList<String>(); BufferedReader br = new BufferedReader(new FileReader(f)); try { String line = null; while((line = br.readLine()) != null) { names.add(line.trim()); } } finally { br.close(); } return names; } private Bundle mockConsumerBundle(Dictionary<String, String> headers, Bundle ... otherBundles) { // Create a mock object for the client bundle which holds the code that uses ServiceLoader.load() // or another SPI invocation. BundleContext bc = EasyMock.createMock(BundleContext.class); Bundle consumerBundle = EasyMock.createMock(Bundle.class); EasyMock.expect(consumerBundle.getSymbolicName()).andReturn("testConsumer").anyTimes(); EasyMock.expect(consumerBundle.getHeaders()).andReturn(headers).anyTimes(); EasyMock.expect(consumerBundle.getBundleContext()).andReturn(bc).anyTimes(); EasyMock.expect(consumerBundle.getBundleId()).andReturn(Long.MAX_VALUE).anyTimes(); EasyMock.replay(consumerBundle); List<Bundle> allBundles = new ArrayList<Bundle>(Arrays.asList(otherBundles)); allBundles.add(consumerBundle); EasyMock.expect(bc.getBundles()).andReturn(allBundles.toArray(new Bundle [] {})).anyTimes(); EasyMock.replay(bc); return consumerBundle; } private Bundle mockSystemBundle() { Bundle systemBundle = EasyMock.createMock(Bundle.class); EasyMock.expect(systemBundle.getBundleId()).andReturn(0L).anyTimes(); EasyMock.expect(systemBundle.getSymbolicName()).andReturn("system.bundle").anyTimes(); EasyMock.replay(systemBundle); return systemBundle; } // A classloader that loads anything starting with org.apache.aries.spifly.dynamic.impl1 from it // and the rest from the parent. This is to mimic a bundle that holds a specific SPI implementation. public static class TestProviderBundleClassLoader extends URLClassLoader { private final List<String> resources; private final String prefix; private final String classPrefix; private final Map<String, Class<?>> loadedClasses = new ConcurrentHashMap<String, Class<?>>(); public TestProviderBundleClassLoader(String subdir, String ... resources) { super(new URL [] {}, TestProviderBundleClassLoader.class.getClassLoader()); this.prefix = TestProviderBundleClassLoader.class.getPackage().getName().replace('.', '/') + "/" + subdir + "/"; this.classPrefix = prefix.replace('/', '.'); this.resources = Arrays.asList(resources); } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { if (name.startsWith(classPrefix)) return loadClassLocal(name); return super.loadClass(name); } @Override protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (name.startsWith(classPrefix)) { Class<?> cls = loadClassLocal(name); if (resolve) resolveClass(cls); return cls; } return super.loadClass(name, resolve); } protected Class<?> loadClassLocal(String name) throws ClassNotFoundException { Class<?> prevLoaded = loadedClasses.get(name); if (prevLoaded != null) return prevLoaded; URL res = TestProviderBundleClassLoader.class.getClassLoader().getResource(name.replace('.', '/') + ".class"); try { byte[] bytes = Streams.suck(res.openStream()); Class<?> cls = defineClass(name, bytes, 0, bytes.length); loadedClasses.put(name, cls); return cls; } catch (Exception e) { throw new ClassNotFoundException(name, e); } } @Override public URL findResource(String name) { if (resources.contains(name)) { return getClass().getClassLoader().getResource(prefix + name); } else { return super.findResource(name); } } @Override public Enumeration<URL> findResources(String name) throws IOException { if (resources.contains(name)) { return getClass().getClassLoader().getResources(prefix + name); } else { return super.findResources(name); } } } private static class MyWovenClass implements WovenClass { byte [] bytes; final String className; final Bundle bundleContainingOriginalClass; List<String> dynamicImports = new ArrayList<String>(); boolean weavingComplete = false; private MyWovenClass(URL clazz, String name, Bundle bundle) throws Exception { bytes = Streams.suck(clazz.openStream()); className = name; bundleContainingOriginalClass = bundle; } @Override public byte[] getBytes() { return bytes; } @Override public void setBytes(byte[] newBytes) { bytes = newBytes; } @Override public List<String> getDynamicImports() { return dynamicImports; } @Override public boolean isWeavingComplete() { return weavingComplete; } @Override public String getClassName() { return className; } @Override public ProtectionDomain getProtectionDomain() { return null; } @Override public Class<?> getDefinedClass() { try { weavingComplete = true; return new MyWovenClassClassLoader(className, getBytes(), getClass().getClassLoader(), bundleContainingOriginalClass).loadClass(className); } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } } @Override public BundleWiring getBundleWiring() { BundleWiring bw = EasyMock.createMock(BundleWiring.class); EasyMock.expect(bw.getBundle()).andReturn(bundleContainingOriginalClass); EasyMock.replay(bw); return bw; } } private static class MyWovenClassClassLoader extends ClassLoader implements BundleReference { private final String className; private final Bundle bundle; private final byte [] bytes; private Class<?> wovenClass; public MyWovenClassClassLoader(String className, byte[] bytes, ClassLoader parent, Bundle bundle) { super(parent); this.className = className; this.bundle = bundle; this.bytes = bytes; } @Override protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (name.equals(className)) { if (wovenClass == null) wovenClass = defineClass(className, bytes, 0, bytes.length); return wovenClass; } else { return super.loadClass(name, resolve); } } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { return loadClass(name, false); } @Override public Bundle getBundle() { return bundle; } } }
spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/ClientWeavingHookTest.java
/** * 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.aries.spifly.dynamic; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Dictionary; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.aries.spifly.BaseActivator; import org.apache.aries.spifly.Streams; import org.apache.aries.spifly.api.SpiFlyConstants; import org.easymock.EasyMock; import org.easymock.IAnswer; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleReference; import org.osgi.framework.Version; import org.osgi.framework.hooks.weaving.WeavingHook; import org.osgi.framework.hooks.weaving.WovenClass; import org.osgi.framework.wiring.BundleWiring; public class ClientWeavingHookTest { DynamicWeavingActivator activator; @Before public void setUp() { activator = new DynamicWeavingActivator(); BaseActivator.activator = activator; } @After public void tearDown() { BaseActivator.activator = null; activator = null; } @Test public void testClientWeavingHookBasicServiveLoaderUsage() throws Exception { Dictionary<String, String> consumerHeaders = new Hashtable<String, String>(); consumerHeaders.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "*"); // Register the bundle that provides the SPI implementation. Bundle providerBundle = mockProviderBundle("impl1", 1); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle); Bundle consumerBundle = mockConsumerBundle(consumerHeaders, providerBundle); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle spiFlyBundle = mockSpiFlyBundle("spifly", Version.parseVersion("1.9.4"), consumerBundle, providerBundle); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); // Weave the TestClient class. URL clsUrl = getClass().getResource("TestClient.class"); Assert.assertNotNull("Precondition", clsUrl); String clientClassName = "org.apache.aries.spifly.dynamic.TestClient"; WovenClass wc = new MyWovenClass(clsUrl, clientClassName, consumerBundle); Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size()); wh.weave(wc); Assert.assertEquals(1, wc.getDynamicImports().size()); String di1 = "org.apache.aries.spifly;bundle-symbolic-name=spifly;bundle-version=1.9.4"; String di2 = "org.apache.aries.spifly;bundle-version=1.9.4;bundle-symbolic-name=spifly"; String di = wc.getDynamicImports().get(0); Assert.assertTrue("Weaving should have added a dynamic import", di1.equals(di) || di2.equals(di)); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals("olleh", result); } @Test public void testClientWeavingHookAltServiceLoaderLoadUnprocessed() throws Exception { Bundle spiFlyBundle = mockSpiFlyBundle(); Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "*"); Bundle consumerBundle = mockConsumerBundle(headers, spiFlyBundle); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); // Weave the TestClient class. URL clsUrl = getClass().getResource("UnaffectedTestClient.class"); Assert.assertNotNull("Precondition", clsUrl); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.UnaffectedTestClient", consumerBundle); Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size()); wh.weave(wc); Assert.assertEquals("The client is not affected so no additional imports should have been added", 0, wc.getDynamicImports().size()); // ok the weaving is done, now prepare the registry for the call Bundle providerBundle = mockProviderBundle("impl1", 1); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals("impl4", result); } @Test public void testClientWeavingHookMultipleProviders() throws Exception { Bundle spiFlyBundle = mockSpiFlyBundle(); Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "*"); Bundle consumerBundle = mockConsumerBundle(headers, spiFlyBundle); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); // Weave the TestClient class. URL clsUrl = getClass().getResource("TestClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle); wh.weave(wc); Bundle providerBundle1 = mockProviderBundle("impl1", 1); Bundle providerBundle2 = mockProviderBundle("impl2", 2); // Register in reverse order to make sure the order in which bundles are sorted is correct activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI files from impl1 and impl2 are visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals("All three services should be invoked in the correct order", "ollehHELLO5", result); } @Test public void testClientSpecifyingProvider() throws Exception { Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "java.util.ServiceLoader#load(java.lang.Class);bundle=impl2"); Bundle providerBundle1 = mockProviderBundle("impl1", 1); Bundle providerBundle2 = mockProviderBundle("impl2", 2); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2); Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); // Weave the TestClient class. URL clsUrl = getClass().getResource("TestClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle); wh.weave(wc); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals("Only the services from bundle impl2 should be selected", "HELLO5", result); } @Test public void testClientSpecifyingProviderVersion() throws Exception { Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "java.util.ServiceLoader#load(java.lang.Class);bundle=impl2:version=1.2.3"); Bundle providerBundle1 = mockProviderBundle("impl1", 1); Bundle providerBundle2 = mockProviderBundle("impl2", 2); Bundle providerBundle3 = mockProviderBundle("impl2_123", 3, new Version(1, 2, 3)); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle3); Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2, providerBundle3); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2, providerBundle3); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); // Weave the TestClient class. URL clsUrl = getClass().getResource("TestClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle); wh.weave(wc); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals("Only the services from bundle impl2 should be selected", "Updated!hello!Updated", result); } @Test public void testClientMultipleTargetBundles() throws Exception { Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "java.util.ServiceLoader#load(java.lang.Class);bundle=impl1|impl4"); Bundle providerBundle1 = mockProviderBundle("impl1", 1); Bundle providerBundle2 = mockProviderBundle("impl2", 2); Bundle providerBundle4 = mockProviderBundle("impl4", 4); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle4); activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle4); Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2, providerBundle4); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2, providerBundle4); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); // Weave the TestClient class. URL clsUrl = getClass().getResource("TestClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle); wh.weave(wc); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals("All providers should be selected for this one", "ollehimpl4", result); } @Test public void testClientMultipleTargetBundles2() throws Exception { Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "java.util.ServiceLoader#load(java.lang.Class);bundleId=1|4"); Bundle providerBundle1 = mockProviderBundle("impl1", 1); Bundle providerBundle2 = mockProviderBundle("impl2", 2); Bundle providerBundle4 = mockProviderBundle("impl4", 4); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle4); activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle4); Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2, providerBundle4); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2, providerBundle4); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); // Weave the TestClient class. URL clsUrl = getClass().getResource("TestClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle); wh.weave(wc); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals("All providers should be selected for this one", "ollehimpl4", result); } @Test public void testClientSpecificProviderLoadArgument() throws Exception { Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "java.util.ServiceLoader#load(java.lang.Class[org.apache.aries.mytest.MySPI])," + "java.util.ServiceLoader#load(java.lang.Class[org.apache.aries.mytest.AltSPI]);bundle=impl4"); Bundle providerBundle1 = mockProviderBundle("impl1", 1); Bundle providerBundle2 = mockProviderBundle("impl2", 2); Bundle providerBundle4 = mockProviderBundle("impl4", 4); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle4); activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle4); Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2, providerBundle4); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2, providerBundle4); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); // Weave the TestClient class. URL clsUrl = getClass().getResource("TestClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle); wh.weave(wc); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals("All providers should be selected for this one", "ollehHELLO5impl4", result); // Weave the AltTestClient class. URL cls2Url = getClass().getResource("AltTestClient.class"); WovenClass wc2 = new MyWovenClass(cls2Url, "org.apache.aries.spifly.dynamic.AltTestClient", consumerBundle); wh.weave(wc2); // Invoke the AltTestClient Class<?> cls2 = wc2.getDefinedClass(); Method method2 = cls2.getMethod("test", new Class [] {long.class}); Object result2 = method2.invoke(cls2.newInstance(), 4096); Assert.assertEquals("Only the services from bundle impl4 should be selected", -4096L*4096L, result2); } @Test public void testClientSpecifyingDifferentMethodsLimitedToDifferentProviders() throws Exception { Dictionary<String, String> headers1 = new Hashtable<String, String>(); headers1.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance();bundle=impl3," + "java.util.ServiceLoader#load(java.lang.Class[org.apache.aries.mytest.MySPI]);bundle=impl4"); Dictionary<String, String> headers2 = new Hashtable<String, String>(); headers2.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance();bundle=system.bundle," + "java.util.ServiceLoader#load;bundle=impl1"); Dictionary<String, String> headers3 = new Hashtable<String, String>(); headers3.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "org.acme.blah#someMethod();bundle=mybundle"); Bundle providerBundle1 = mockProviderBundle("impl1", 1); Bundle providerBundle2 = mockProviderBundle("impl2", 2); Bundle providerBundle3 = mockProviderBundle("impl3", 3); Bundle providerBundle4 = mockProviderBundle("impl4", 4); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2); activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle2); activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle3); activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle4); activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle4); Bundle consumerBundle1 = mockConsumerBundle(headers1, providerBundle1, providerBundle2, providerBundle3, providerBundle4); activator.addConsumerWeavingData(consumerBundle1, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle consumerBundle2 = mockConsumerBundle(headers2, providerBundle1, providerBundle2, providerBundle3, providerBundle4); activator.addConsumerWeavingData(consumerBundle2, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle consumerBundle3 = mockConsumerBundle(headers3, providerBundle1, providerBundle2, providerBundle3, providerBundle4); activator.addConsumerWeavingData(consumerBundle3, SpiFlyConstants.SPI_CONSUMER_HEADER); Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle1, consumerBundle2, consumerBundle3, providerBundle1, providerBundle2, providerBundle3, providerBundle4); WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator); testConsumerBundleWeaving(consumerBundle1, wh, "impl4", "org.apache.aries.spifly.dynamic.impl3.MyAltDocumentBuilderFactory"); testConsumerBundleWeaving(consumerBundle2, wh, "olleh", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); testConsumerBundleWeaving(consumerBundle3, wh, "", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); } private void testConsumerBundleWeaving(Bundle consumerBundle, WeavingHook wh, String testClientResult, String jaxpClientResult) throws Exception { // Weave the TestClient class. URL clsUrl = getClass().getResource("TestClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle); wh.weave(wc); // Invoke the woven class and check that it propertly sets the TCCL so that the // META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible. Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {String.class}); Object result = method.invoke(cls.newInstance(), "hello"); Assert.assertEquals(testClientResult, result); URL clsUrl2 = getClass().getResource("JaxpClient.class"); WovenClass wc2 = new MyWovenClass(clsUrl2, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle); wh.weave(wc2); Class<?> cls2 = wc2.getDefinedClass(); Method method2 = cls2.getMethod("test", new Class [] {}); Class<?> result2 = (Class<?>) method2.invoke(cls2.newInstance()); Assert.assertEquals(jaxpClientResult, result2.getName()); } @Test public void testJAXPClientWantsJREImplementation1() throws Exception { Bundle systembundle = mockSystemBundle(); Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance()"); Bundle consumerBundle = mockConsumerBundle(headers, systembundle); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, systembundle).getBundleContext(), activator); URL clsUrl = getClass().getResource("JaxpClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.JaxpClient", consumerBundle); wh.weave(wc); Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {}); Class<?> result = (Class<?>) method.invoke(cls.newInstance()); Assert.assertEquals("JAXP implementation from JRE", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl", result.getName()); } // If there is an alternate implementation it should always be favoured over the JRE one @Test public void testJAXPClientWantsAltImplementation1() throws Exception { Bundle systembundle = mockSystemBundle(); Bundle providerBundle = mockProviderBundle("impl3", 1); activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle); Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance()"); Bundle consumerBundle = mockConsumerBundle(headers, providerBundle, systembundle); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator); URL clsUrl = getClass().getResource("JaxpClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.JaxpClient", consumerBundle); wh.weave(wc); Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {}); Class<?> result = (Class<?>) method.invoke(cls.newInstance()); Assert.assertEquals("JAXP implementation from JRE", "org.apache.aries.spifly.impl3.MyAltDocumentBuilderFactory", result.getName()); } @Test public void testJAXPClientWantsJREImplementation2() throws Exception { Bundle systembundle = mockSystemBundle(); Bundle providerBundle = mockProviderBundle("impl3", 1); activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle); Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance();bundleId=0"); Bundle consumerBundle = mockConsumerBundle(headers, providerBundle, systembundle); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator); URL clsUrl = getClass().getResource("JaxpClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.JaxpClient", consumerBundle); wh.weave(wc); Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {}); Class<?> result = (Class<?>) method.invoke(cls.newInstance()); Assert.assertEquals("JAXP implementation from JRE", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl", result.getName()); } @Test public void testJAXPClientWantsAltImplementation2() throws Exception { Bundle systembundle = mockSystemBundle(); Bundle providerBundle = mockProviderBundle("impl3", 1); activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle); Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance();bundle=impl3"); Bundle consumerBundle = mockConsumerBundle(headers, providerBundle, systembundle); activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER); WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator); URL clsUrl = getClass().getResource("JaxpClient.class"); WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.JaxpClient", consumerBundle); wh.weave(wc); Class<?> cls = wc.getDefinedClass(); Method method = cls.getMethod("test", new Class [] {}); Class<?> result = (Class<?>) method.invoke(cls.newInstance()); Assert.assertEquals("JAXP implementation from alternative bundle", "org.apache.aries.spifly.impl3.MyAltDocumentBuilderFactory", result.getName()); } private Bundle mockSpiFlyBundle(Bundle ... bundles) throws Exception { return mockSpiFlyBundle("spifly", new Version(1, 0, 0), bundles); } private Bundle mockSpiFlyBundle(String bsn, Version version, Bundle ... bundles) throws Exception { Bundle spiFlyBundle = EasyMock.createMock(Bundle.class); BundleContext spiFlyBundleContext = EasyMock.createMock(BundleContext.class); EasyMock.expect(spiFlyBundleContext.getBundle()).andReturn(spiFlyBundle).anyTimes(); List<Bundle> allBundles = new ArrayList<Bundle>(Arrays.asList(bundles)); allBundles.add(spiFlyBundle); EasyMock.expect(spiFlyBundleContext.getBundles()).andReturn(allBundles.toArray(new Bundle [] {})).anyTimes(); EasyMock.replay(spiFlyBundleContext); EasyMock.expect(spiFlyBundle.getSymbolicName()).andReturn(bsn).anyTimes(); EasyMock.expect(spiFlyBundle.getVersion()).andReturn(version).anyTimes(); EasyMock.expect(spiFlyBundle.getBundleId()).andReturn(Long.MAX_VALUE).anyTimes(); EasyMock.expect(spiFlyBundle.getBundleContext()).andReturn(spiFlyBundleContext).anyTimes(); EasyMock.replay(spiFlyBundle); // Set the bundle context for testing purposes Field bcField = BaseActivator.class.getDeclaredField("bundleContext"); bcField.setAccessible(true); bcField.set(activator, spiFlyBundle.getBundleContext()); return spiFlyBundle; } private Bundle mockProviderBundle(String subdir, long id) throws Exception { return mockProviderBundle(subdir, id, Version.emptyVersion); } private Bundle mockProviderBundle(String subdir, long id, Version version) throws Exception { URL url = getClass().getResource("/" + getClass().getName().replace('.', '/') + ".class"); File classFile = new File(url.getFile()); File baseDir = new File(classFile.getParentFile(), subdir); File directory = new File(baseDir, "/META-INF/services"); final List<String> classNames = new ArrayList<String>(); // Do a directory listing of the applicable META-INF/services directory List<String> resources = new ArrayList<String>(); for (File f : directory.listFiles()) { String fileName = f.getName(); if (fileName.startsWith(".") || fileName.endsWith(".")) continue; classNames.addAll(getClassNames(f)); // Needs to be something like: META-INF/services/org.apache.aries.mytest.MySPI String path = f.getAbsolutePath().substring(baseDir.getAbsolutePath().length()); path = path.replace('\\', '/'); if (path.startsWith("/")) { path = path.substring(1); } resources.add(path); } // Set up the classloader that will be used by the ASM-generated code as the TCCL. // It can load a META-INF/services file final ClassLoader cl = new TestProviderBundleClassLoader(subdir, resources.toArray(new String [] {})); List<String> classResources = new ArrayList<String>(); for(String className : classNames) { classResources.add("/" + className.replace('.', '/') + ".class"); } Bundle providerBundle = EasyMock.createMock(Bundle.class); String bsn = subdir; int idx = bsn.indexOf('_'); if (idx > 0) { bsn = bsn.substring(0, idx); } EasyMock.expect(providerBundle.getSymbolicName()).andReturn(bsn).anyTimes(); EasyMock.expect(providerBundle.getBundleId()).andReturn(id).anyTimes(); EasyMock.expect(providerBundle.getVersion()).andReturn(version).anyTimes(); EasyMock.expect(providerBundle.getEntryPaths("/")).andReturn(Collections.enumeration(classResources)).anyTimes(); EasyMock.<Class<?>>expect(providerBundle.loadClass(EasyMock.anyObject(String.class))).andAnswer(new IAnswer<Class<?>>() { @Override public Class<?> answer() throws Throwable { String name = (String) EasyMock.getCurrentArguments()[0]; if (!classNames.contains(name)) { throw new ClassCastException(name); } return cl.loadClass(name); } }).anyTimes(); EasyMock.replay(providerBundle); return providerBundle; } private Collection<String> getClassNames(File f) throws IOException { List<String> names = new ArrayList<String>(); BufferedReader br = new BufferedReader(new FileReader(f)); try { String line = null; while((line = br.readLine()) != null) { names.add(line.trim()); } } finally { br.close(); } return names; } private Bundle mockConsumerBundle(Dictionary<String, String> headers, Bundle ... otherBundles) { // Create a mock object for the client bundle which holds the code that uses ServiceLoader.load() // or another SPI invocation. BundleContext bc = EasyMock.createMock(BundleContext.class); Bundle consumerBundle = EasyMock.createMock(Bundle.class); EasyMock.expect(consumerBundle.getSymbolicName()).andReturn("testConsumer").anyTimes(); EasyMock.expect(consumerBundle.getHeaders()).andReturn(headers).anyTimes(); EasyMock.expect(consumerBundle.getBundleContext()).andReturn(bc).anyTimes(); EasyMock.expect(consumerBundle.getBundleId()).andReturn(Long.MAX_VALUE).anyTimes(); EasyMock.replay(consumerBundle); List<Bundle> allBundles = new ArrayList<Bundle>(Arrays.asList(otherBundles)); allBundles.add(consumerBundle); EasyMock.expect(bc.getBundles()).andReturn(allBundles.toArray(new Bundle [] {})).anyTimes(); EasyMock.replay(bc); return consumerBundle; } private Bundle mockSystemBundle() { Bundle systemBundle = EasyMock.createMock(Bundle.class); EasyMock.expect(systemBundle.getBundleId()).andReturn(0L).anyTimes(); EasyMock.expect(systemBundle.getSymbolicName()).andReturn("system.bundle").anyTimes(); EasyMock.replay(systemBundle); return systemBundle; } // A classloader that loads anything starting with org.apache.aries.spifly.dynamic.impl1 from it // and the rest from the parent. This is to mimic a bundle that holds a specific SPI implementation. public static class TestProviderBundleClassLoader extends URLClassLoader { private final List<String> resources; private final String prefix; private final String classPrefix; private final Map<String, Class<?>> loadedClasses = new ConcurrentHashMap<String, Class<?>>(); public TestProviderBundleClassLoader(String subdir, String ... resources) { super(new URL [] {}, TestProviderBundleClassLoader.class.getClassLoader()); this.prefix = TestProviderBundleClassLoader.class.getPackage().getName().replace('.', '/') + "/" + subdir + "/"; this.classPrefix = prefix.replace('/', '.'); this.resources = Arrays.asList(resources); } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { if (name.startsWith(classPrefix)) return loadClassLocal(name); return super.loadClass(name); } @Override protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (name.startsWith(classPrefix)) { Class<?> cls = loadClassLocal(name); if (resolve) resolveClass(cls); return cls; } return super.loadClass(name, resolve); } protected Class<?> loadClassLocal(String name) throws ClassNotFoundException { Class<?> prevLoaded = loadedClasses.get(name); if (prevLoaded != null) return prevLoaded; URL res = TestProviderBundleClassLoader.class.getClassLoader().getResource(name.replace('.', '/') + ".class"); try { byte[] bytes = Streams.suck(res.openStream()); Class<?> cls = defineClass(name, bytes, 0, bytes.length); loadedClasses.put(name, cls); return cls; } catch (Exception e) { throw new ClassNotFoundException(name, e); } } @Override public URL findResource(String name) { if (resources.contains(name)) { return getClass().getClassLoader().getResource(prefix + name); } else { return super.findResource(name); } } @Override public Enumeration<URL> findResources(String name) throws IOException { if (resources.contains(name)) { return getClass().getClassLoader().getResources(prefix + name); } else { return super.findResources(name); } } } private static class MyWovenClass implements WovenClass { byte [] bytes; final String className; final Bundle bundleContainingOriginalClass; List<String> dynamicImports = new ArrayList<String>(); boolean weavingComplete = false; private MyWovenClass(URL clazz, String name, Bundle bundle) throws Exception { bytes = Streams.suck(clazz.openStream()); className = name; bundleContainingOriginalClass = bundle; } @Override public byte[] getBytes() { return bytes; } @Override public void setBytes(byte[] newBytes) { bytes = newBytes; } @Override public List<String> getDynamicImports() { return dynamicImports; } @Override public boolean isWeavingComplete() { return weavingComplete; } @Override public String getClassName() { return className; } @Override public ProtectionDomain getProtectionDomain() { return null; } @Override public Class<?> getDefinedClass() { try { weavingComplete = true; return new MyWovenClassClassLoader(className, getBytes(), getClass().getClassLoader(), bundleContainingOriginalClass).loadClass(className); } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } } @Override public BundleWiring getBundleWiring() { BundleWiring bw = EasyMock.createMock(BundleWiring.class); EasyMock.expect(bw.getBundle()).andReturn(bundleContainingOriginalClass); EasyMock.replay(bw); return bw; } } private static class MyWovenClassClassLoader extends ClassLoader implements BundleReference { private final String className; private final Bundle bundle; private final byte [] bytes; private Class<?> wovenClass; public MyWovenClassClassLoader(String className, byte[] bytes, ClassLoader parent, Bundle bundle) { super(parent); this.className = className; this.bundle = bundle; this.bytes = bytes; } @Override protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (name.equals(className)) { if (wovenClass == null) wovenClass = defineClass(className, bytes, 0, bytes.length); return wovenClass; } else { return super.loadClass(name, resolve); } } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { return loadClass(name, false); } @Override public Bundle getBundle() { return bundle; } } }
More SPI-Fly tests passing. git-svn-id: f3027bd689517dd712b868b0d3f5f59c3162b83d@1090726 13f79535-47bb-0310-9956-ffa450edef68
spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/ClientWeavingHookTest.java
More SPI-Fly tests passing.
<ide><path>pi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/ClientWeavingHookTest.java <ide> WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, systembundle).getBundleContext(), activator); <ide> <ide> URL clsUrl = getClass().getResource("JaxpClient.class"); <del> WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.JaxpClient", consumerBundle); <add> WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle); <ide> wh.weave(wc); <ide> <ide> Class<?> cls = wc.getDefinedClass(); <ide> WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator); <ide> <ide> URL clsUrl = getClass().getResource("JaxpClient.class"); <del> WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.JaxpClient", consumerBundle); <add> WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle); <ide> wh.weave(wc); <ide> <ide> Class<?> cls = wc.getDefinedClass(); <ide> WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator); <ide> <ide> URL clsUrl = getClass().getResource("JaxpClient.class"); <del> WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.JaxpClient", consumerBundle); <add> WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle); <ide> wh.weave(wc); <ide> <ide> Class<?> cls = wc.getDefinedClass(); <ide> WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator); <ide> <ide> URL clsUrl = getClass().getResource("JaxpClient.class"); <del> WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.JaxpClient", consumerBundle); <add> WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle); <ide> wh.weave(wc); <ide> <ide> Class<?> cls = wc.getDefinedClass();
JavaScript
mit
4217eb95e7d94c6911570cdd62c0aeee05f371a5
0
Skuznetz/28,Skuznetz/28
function fun1() { var rtl=document.getElementById('rtl').value; var rtr=document.getElementById('rtr').value; var rbl=document.getElementById('rbl').value; var rbr=document.getElementById('rbr').value; var ttl=document.getElementById('ttl'); var ttr=document.getElementById('ttr'); var tbr=document.getElementById('tbr'); var tbl=document.getElementById('tbl'); var block=document.getElementById('block') ; ttl.value = rtl; ttr.value = rtr; tbr.value = rbr; tbl.value = rbl; block.style.borderRadius = rtl + 'px ' + rtr +'px ' + rbr + 'px '+ rbl + 'px '; } function move() { var elem = document.getElementById("myBar"); var width = 10; var id = setInterval(frame,10); function frame() { if (width >= 100){ clearInterval(id); }else { width++; elem.style.width = width + '%'; document.getElementById("label").innerHTML=width*1 +'%'; } } } function myMove() { var elem =document.getElementById("myAnimation"); var pos = 0; var id = setInterva(frame,10); }
script.js
function fun1() { var rtl=document.getElementById('rtl').value; var rtr=document.getElementById('rtr').value; var rbl=document.getElementById('rbl').value; var rbr=document.getElementById('rbr').value; var ttl=document.getElementById('ttl'); var ttr=document.getElementById('ttr'); var tbr=document.getElementById('tbr'); var tbl=document.getElementById('tbl'); var block=document.getElementById('block') ; ttl.value = rtl; ttr.value = rtr; tbr.value = rbr; tbl.value = rbl; block.style.borderRadius = rtl + 'px ' + rtr +'px ' + rbr + 'px '+ rbl + 'px '; } function move() { var elem = document.getElementById("myBar"); var width = 10; var id = setInterval(frame,10); function frame() { if (width >= 100){ clearInterval(id); }else { width++; elem.style.width = width + '%'; document.getElementById("label").innerHTML=width*1 +'%'; } } }
функция myMove
script.js
функция myMove
<ide><path>cript.js <ide> } <ide> } <ide> } <add> <add>function myMove() { <add> var elem =document.getElementById("myAnimation"); <add> var pos = 0; <add> var id = setInterva(frame,10); <add>}
Java
apache-2.0
d9a56ddcf9507030806468b9f99db242b501a88d
0
inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service
/* * Copyright 2012 Shared Learning Collaborative, LLC * * 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.slc.sli.sif.reporting; import java.util.Properties; import openadk.library.ADK; import openadk.library.ADKException; import openadk.library.DataObjectOutputStream; import openadk.library.Event; import openadk.library.MessageInfo; import openadk.library.Publisher; import openadk.library.PublishingOptions; import openadk.library.Query; import openadk.library.SIFDataObject; import openadk.library.Zone; import openadk.library.student.StudentDTD; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.FileSystemXmlApplicationContext; import org.slc.sli.sif.agent.SifAgent; public class EventReporter implements Publisher { static { // Simple workaround to get logging paths set up correctly when run from the command line String catalinaHome = System.getProperty("catalina.home"); if( catalinaHome == null ){ System.setProperty("catalina.home", "target"); } String sliConf = System.getProperty("sli.conf"); if( sliConf == null ){ System.setProperty("sli.conf", "../../config/properties/sli.properties"); } } public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(EventReporter.class); try { FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext( "classpath:spring/applicationContext.xml"); context.registerShutdownHook(); SifAgent agent = context.getBean(SifAgent.class); if (args.length >= 2) { String zoneId = args[EventReporter.ZONE_ID]; String messageFile = args[EventReporter.MESSAGE_FILE]; Zone zone = agent.getZoneFactory().getZone(zoneId); EventReporter reporter = new EventReporter(zone); reporter.setEventGenerator(new CustomEventGenerator()); reporter.reportEvent(messageFile); } else { Zone zone = agent.getZoneFactory().getZone("TestZone"); EventReporter reporter = new EventReporter(zone); reporter.reportEvent(); } } catch (Exception e) { logger.error("Exception trying to report event", e); } System.exit(0); } public static final int ZONE_ID = 0; public static final int MESSAGE_FILE = 1; private static final Logger LOG = LoggerFactory.getLogger(EventReporter.class); private Zone zone; private EventGenerator generator; public EventReporter(Zone zone) throws Exception { this.zone = zone; //this.zone.setPublisher(this); this.zone.setPublisher(this, StudentDTD.SCHOOLINFO, new PublishingOptions(true)); this.zone.setPublisher(this, StudentDTD.LEAINFO, new PublishingOptions(true)); this.zone.setPublisher(this, StudentDTD.STUDENTPERSONAL, new PublishingOptions(true)); generator = new HCStudentPersonalGenerator(); } public void setEventGenerator(EventGenerator generator) { this.generator = generator; } public void reportEvent() throws ADKException { Event event = generator.generateEvent(null); if (zone.isConnected()) { zone.reportEvent(event); } else { LOG.error("Zone is not connected"); } } public void reportEvent(String messageFile) throws ADKException { Properties props = new Properties(); props.setProperty(CustomEventGenerator.MESSAGE_FILE, messageFile); Event event = generator.generateEvent(props); if (zone.isConnected()) { zone.reportEvent(event); } else { LOG.error("Zone is not connected"); } } @Override public void onRequest(DataObjectOutputStream out, Query query, Zone zone, MessageInfo info) throws ADKException { LOG.info("Received request to publish data:\n" + "\tQuery:\n" + query.toXML() + "\n" + "\tZone: " + zone.getZoneId() + "\n" + "\tInfo: " + info.getMessage()); } @SuppressWarnings("unused") private void inspectAndDestroyEvent(Event e) { LOG.info("###########################################################################"); try { SIFDataObject dataObj = e.getData().readDataObject(); LOG.info(dataObj.toString()); } catch (ADKException e1) { LOG.error("Error trying to inspect event", e1); } LOG.info("###########################################################################"); } }
sli/sif/sif-agent/src/main/java/org/slc/sli/sif/reporting/EventReporter.java
/* * Copyright 2012 Shared Learning Collaborative, LLC * * 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.slc.sli.sif.reporting; import java.util.Properties; import openadk.library.ADKException; import openadk.library.DataObjectOutputStream; import openadk.library.Event; import openadk.library.MessageInfo; import openadk.library.Publisher; import openadk.library.PublishingOptions; import openadk.library.Query; import openadk.library.SIFDataObject; import openadk.library.Zone; import openadk.library.student.StudentDTD; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.FileSystemXmlApplicationContext; import org.slc.sli.sif.agent.SifAgent; public class EventReporter implements Publisher { static { // Simple workaround to get logging paths set up correctly when run from the command line String catalinaHome = System.getProperty("catalina.home"); if( catalinaHome == null ){ System.setProperty("catalina.home", "target"); } String sliConf = System.getProperty("sli.conf"); if( sliConf == null ){ System.setProperty("sli.conf", "../../config/properties/sli.properties"); } } public static void main(String[] args) { try { FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext( "classpath:spring/applicationContext.xml"); context.registerShutdownHook(); SifAgent agent = context.getBean(SifAgent.class); if (args.length >= 2) { String zoneId = args[EventReporter.ZONE_ID]; String messageFile = args[EventReporter.MESSAGE_FILE]; Zone zone = agent.getZoneFactory().getZone(zoneId); EventReporter reporter = new EventReporter(zone); reporter.setEventGenerator(new CustomEventGenerator()); reporter.reportEvent(messageFile); } else { Zone zone = agent.getZoneFactory().getZone("TestZone"); EventReporter reporter = new EventReporter(zone); reporter.reportEvent(); } } catch (Exception e) { e.printStackTrace(); } System.exit(0); } public static final int ZONE_ID = 0; public static final int MESSAGE_FILE = 1; private static final Logger LOG = LoggerFactory.getLogger(EventReporter.class); private Zone zone; private EventGenerator generator; public EventReporter(Zone zone) throws Exception { this.zone = zone; this.zone.setPublisher(this); this.zone.setPublisher(this, StudentDTD.SCHOOLINFO, new PublishingOptions(true)); this.zone.setPublisher(this, StudentDTD.LEAINFO, new PublishingOptions(true)); this.zone.setPublisher(this, StudentDTD.STUDENTPERSONAL, new PublishingOptions(true)); generator = new HCStudentPersonalGenerator(); } public void setEventGenerator(EventGenerator generator) { this.generator = generator; } public void reportEvent() throws ADKException { Event event = generator.generateEvent(null); if (zone.isConnected()) { zone.reportEvent(event); } else { LOG.error("Zone is not connected"); } } public void reportEvent(String messageFile) throws ADKException { Properties props = new Properties(); props.setProperty(CustomEventGenerator.MESSAGE_FILE, messageFile); Event event = generator.generateEvent(props); if (zone.isConnected()) { zone.reportEvent(event); } else { LOG.error("Zone is not connected"); } } @Override public void onRequest(DataObjectOutputStream out, Query query, Zone zone, MessageInfo info) throws ADKException { LOG.info("Received request to publish data:\n" + "\tQuery:\n" + query.toXML() + "\n" + "\tZone: " + zone.getZoneId() + "\n" + "\tInfo: " + info.getMessage()); } @SuppressWarnings("unused") private void inspectAndDestroyEvent(Event e) { LOG.info("###########################################################################"); try { SIFDataObject dataObj = e.getData().readDataObject(); LOG.info(dataObj.toString()); } catch (ADKException e1) { e1.printStackTrace(); } LOG.info("###########################################################################"); } }
[US2949] removed stdout logging
sli/sif/sif-agent/src/main/java/org/slc/sli/sif/reporting/EventReporter.java
[US2949] removed stdout logging
<ide><path>li/sif/sif-agent/src/main/java/org/slc/sli/sif/reporting/EventReporter.java <ide> <ide> import java.util.Properties; <ide> <add>import openadk.library.ADK; <ide> import openadk.library.ADKException; <ide> import openadk.library.DataObjectOutputStream; <ide> import openadk.library.Event; <ide> } <ide> <ide> public static void main(String[] args) { <add> Logger logger = LoggerFactory.getLogger(EventReporter.class); <ide> <ide> try { <ide> FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext( <ide> reporter.reportEvent(); <ide> } <ide> } catch (Exception e) { <del> e.printStackTrace(); <add> logger.error("Exception trying to report event", e); <ide> } <ide> System.exit(0); <ide> } <ide> <ide> private static final Logger LOG = LoggerFactory.getLogger(EventReporter.class); <ide> <del> <ide> private Zone zone; <ide> private EventGenerator generator; <ide> <ide> public EventReporter(Zone zone) throws Exception { <ide> this.zone = zone; <del> this.zone.setPublisher(this); <add> //this.zone.setPublisher(this); <ide> this.zone.setPublisher(this, StudentDTD.SCHOOLINFO, new PublishingOptions(true)); <ide> this.zone.setPublisher(this, StudentDTD.LEAINFO, new PublishingOptions(true)); <ide> this.zone.setPublisher(this, StudentDTD.STUDENTPERSONAL, new PublishingOptions(true)); <ide> SIFDataObject dataObj = e.getData().readDataObject(); <ide> LOG.info(dataObj.toString()); <ide> } catch (ADKException e1) { <del> e1.printStackTrace(); <add> LOG.error("Error trying to inspect event", e1); <ide> } <ide> LOG.info("###########################################################################"); <ide> }
Java
apache-2.0
18e82394898352c9dcf682b2086a6145af36c06e
0
apache/accumulo,apache/accumulo,ctubbsii/accumulo,mjwall/accumulo,apache/accumulo,milleruntime/accumulo,phrocker/accumulo-1,milleruntime/accumulo,mjwall/accumulo,ctubbsii/accumulo,apache/accumulo,milleruntime/accumulo,mjwall/accumulo,phrocker/accumulo-1,milleruntime/accumulo,mjwall/accumulo,mjwall/accumulo,mjwall/accumulo,phrocker/accumulo-1,ctubbsii/accumulo,ctubbsii/accumulo,apache/accumulo,phrocker/accumulo-1,phrocker/accumulo-1,mjwall/accumulo,apache/accumulo,ctubbsii/accumulo,milleruntime/accumulo,phrocker/accumulo-1,milleruntime/accumulo,ctubbsii/accumulo,apache/accumulo,phrocker/accumulo-1,milleruntime/accumulo,ctubbsii/accumulo
/* * 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.accumulo.tserver.tablet; import java.io.IOException; import org.apache.accumulo.core.metadata.schema.DataFileValue; import org.apache.accumulo.core.trace.ProbabilitySampler; import org.apache.accumulo.core.trace.Span; import org.apache.accumulo.core.trace.Trace; import org.apache.accumulo.server.fs.FileRef; import org.apache.accumulo.tserver.MinorCompactionReason; import org.apache.accumulo.tserver.compaction.MajorCompactionReason; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class MinorCompactionTask implements Runnable { private static final Logger log = LoggerFactory.getLogger(MinorCompactionTask.class); private final Tablet tablet; private long queued; private CommitSession commitSession; private DataFileValue stats; private FileRef mergeFile; private long flushId; private MinorCompactionReason mincReason; private double tracePercent; MinorCompactionTask(Tablet tablet, FileRef mergeFile, CommitSession commitSession, long flushId, MinorCompactionReason mincReason, double tracePercent) { this.tablet = tablet; queued = System.currentTimeMillis(); tablet.minorCompactionWaitingToStart(); this.commitSession = commitSession; this.mergeFile = mergeFile; this.flushId = flushId; this.mincReason = mincReason; this.tracePercent = tracePercent; } @Override public void run() { tablet.minorCompactionStarted(); ProbabilitySampler sampler = new ProbabilitySampler(tracePercent); Span minorCompaction = Trace.on("minorCompaction", sampler); try { Span span = Trace.start("waitForCommits"); synchronized (tablet) { commitSession.waitForCommitsToFinish(); } span.stop(); span = Trace.start("start"); FileRef newMapfileLocation = null; FileRef tmpFileRef = null; while (true) { try { if (newMapfileLocation == null) { newMapfileLocation = tablet.getNextMapFilename(mergeFile == null ? "F" : "M"); tmpFileRef = new FileRef(newMapfileLocation.path() + "_tmp"); } // the purpose of the minor compaction start event is to keep track of the filename... in // the case // where the metadata table write for the minor compaction finishes and the process dies // before // writing the minor compaction finish event, then the start event+filename in metadata // table will // prevent recovery of duplicate data... the minor compaction start event could be written // at any time // before the metadata write for the minor compaction tablet.getTabletServer().minorCompactionStarted(commitSession, commitSession.getWALogSeq() + 1, newMapfileLocation.path().toString()); break; } catch (IOException e) { // An IOException could have occurred while creating the new file if (newMapfileLocation == null) log.warn("Failed to create new file for minor compaction {}", e.getMessage(), e); else log.warn("Failed to write to write ahead log {}", e.getMessage(), e); } } span.stop(); span = Trace.start("compact"); this.stats = tablet.minorCompact(tablet.getTabletServer().getFileSystem(), tablet.getTabletMemory().getMinCMemTable(), tmpFileRef, newMapfileLocation, mergeFile, true, queued, commitSession, flushId, mincReason); span.stop(); minorCompaction.data("extent", tablet.getExtent().toString()); minorCompaction.data("numEntries", Long.toString(this.stats.getNumEntries())); minorCompaction.data("size", Long.toString(this.stats.getSize())); minorCompaction.stop(); if (tablet.needsSplit()) { tablet.getTabletServer().executeSplit(tablet); } else { tablet.initiateMajorCompaction(MajorCompactionReason.NORMAL); } } catch (Throwable t) { log.error("Unknown error during minor compaction for extent: " + tablet.getExtent(), t); throw new RuntimeException(t); } finally { tablet.minorCompactionComplete(); minorCompaction.stop(); } } }
server/tserver/src/main/java/org/apache/accumulo/tserver/tablet/MinorCompactionTask.java
/* * 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.accumulo.tserver.tablet; import java.io.IOException; import org.apache.accumulo.core.metadata.schema.DataFileValue; import org.apache.accumulo.core.trace.ProbabilitySampler; import org.apache.accumulo.core.trace.Span; import org.apache.accumulo.core.trace.Trace; import org.apache.accumulo.server.fs.FileRef; import org.apache.accumulo.tserver.MinorCompactionReason; import org.apache.accumulo.tserver.compaction.MajorCompactionReason; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class MinorCompactionTask implements Runnable { private static final Logger log = LoggerFactory.getLogger(MinorCompactionTask.class); private final Tablet tablet; private long queued; private CommitSession commitSession; private DataFileValue stats; private FileRef mergeFile; private long flushId; private MinorCompactionReason mincReason; private double tracePercent; MinorCompactionTask(Tablet tablet, FileRef mergeFile, CommitSession commitSession, long flushId, MinorCompactionReason mincReason, double tracePercent) { this.tablet = tablet; queued = System.currentTimeMillis(); tablet.minorCompactionWaitingToStart(); this.commitSession = commitSession; this.mergeFile = mergeFile; this.flushId = flushId; this.mincReason = mincReason; this.tracePercent = tracePercent; } @Override public void run() { tablet.minorCompactionStarted(); ProbabilitySampler sampler = new ProbabilitySampler(tracePercent); Span minorCompaction = Trace.on("minorCompaction", sampler); try { FileRef newMapfileLocation = tablet.getNextMapFilename(mergeFile == null ? "F" : "M"); FileRef tmpFileRef = new FileRef(newMapfileLocation.path() + "_tmp"); Span span = Trace.start("waitForCommits"); synchronized (tablet) { commitSession.waitForCommitsToFinish(); } span.stop(); span = Trace.start("start"); while (true) { try { // the purpose of the minor compaction start event is to keep track of the filename... in // the case // where the metadata table write for the minor compaction finishes and the process dies // before // writing the minor compaction finish event, then the start event+filename in metadata // table will // prevent recovery of duplicate data... the minor compaction start event could be written // at any time // before the metadata write for the minor compaction tablet.getTabletServer().minorCompactionStarted(commitSession, commitSession.getWALogSeq() + 1, newMapfileLocation.path().toString()); break; } catch (IOException e) { log.warn("Failed to write to write ahead log {}", e.getMessage(), e); } } span.stop(); span = Trace.start("compact"); this.stats = tablet.minorCompact(tablet.getTabletServer().getFileSystem(), tablet.getTabletMemory().getMinCMemTable(), tmpFileRef, newMapfileLocation, mergeFile, true, queued, commitSession, flushId, mincReason); span.stop(); minorCompaction.data("extent", tablet.getExtent().toString()); minorCompaction.data("numEntries", Long.toString(this.stats.getNumEntries())); minorCompaction.data("size", Long.toString(this.stats.getSize())); minorCompaction.stop(); if (tablet.needsSplit()) { tablet.getTabletServer().executeSplit(tablet); } else { tablet.initiateMajorCompaction(MajorCompactionReason.NORMAL); } } catch (Throwable t) { log.error("Unknown error during minor compaction for extent: " + tablet.getExtent(), t); throw new RuntimeException(t); } finally { tablet.minorCompactionComplete(); minorCompaction.stop(); } } }
Move MinorCompaction method call into retry catch block. Fixes #1298 (#1675) * Fixes the situation when MinorCompactionTask creates a new File and an IOException leaves the Tablet in a bad state * Moves the new file code into the try/catch block that will retry during an IOException
server/tserver/src/main/java/org/apache/accumulo/tserver/tablet/MinorCompactionTask.java
Move MinorCompaction method call into retry catch block. Fixes #1298 (#1675)
<ide><path>erver/tserver/src/main/java/org/apache/accumulo/tserver/tablet/MinorCompactionTask.java <ide> ProbabilitySampler sampler = new ProbabilitySampler(tracePercent); <ide> Span minorCompaction = Trace.on("minorCompaction", sampler); <ide> try { <del> FileRef newMapfileLocation = tablet.getNextMapFilename(mergeFile == null ? "F" : "M"); <del> FileRef tmpFileRef = new FileRef(newMapfileLocation.path() + "_tmp"); <ide> Span span = Trace.start("waitForCommits"); <ide> synchronized (tablet) { <ide> commitSession.waitForCommitsToFinish(); <ide> } <ide> span.stop(); <ide> span = Trace.start("start"); <add> FileRef newMapfileLocation = null; <add> FileRef tmpFileRef = null; <ide> while (true) { <ide> try { <add> if (newMapfileLocation == null) { <add> newMapfileLocation = tablet.getNextMapFilename(mergeFile == null ? "F" : "M"); <add> tmpFileRef = new FileRef(newMapfileLocation.path() + "_tmp"); <add> } <ide> // the purpose of the minor compaction start event is to keep track of the filename... in <ide> // the case <ide> // where the metadata table write for the minor compaction finishes and the process dies <ide> commitSession.getWALogSeq() + 1, newMapfileLocation.path().toString()); <ide> break; <ide> } catch (IOException e) { <del> log.warn("Failed to write to write ahead log {}", e.getMessage(), e); <add> // An IOException could have occurred while creating the new file <add> if (newMapfileLocation == null) <add> log.warn("Failed to create new file for minor compaction {}", e.getMessage(), e); <add> else <add> log.warn("Failed to write to write ahead log {}", e.getMessage(), e); <ide> } <ide> } <ide> span.stop();
Java
lgpl-2.1
6947ac6fc56d29ac2ca349d7887e969f7a6ed942
0
guillaume-alvarez/ShapeOfThingsThatWere
package com.galvarez.ttw.model; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.artemis.Aspect; import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.annotations.Wire; import com.artemis.systems.EntityProcessingSystem; import com.badlogic.gdx.utils.IntIntMap; import com.badlogic.gdx.utils.IntIntMap.Entry; import com.galvarez.ttw.model.DiplomaticSystem.Action; import com.galvarez.ttw.model.DiplomaticSystem.State; import com.galvarez.ttw.model.components.AIControlled; import com.galvarez.ttw.model.components.Diplomacy; import com.galvarez.ttw.model.map.GameMap; import com.galvarez.ttw.model.map.Influence; import com.galvarez.ttw.model.map.MapPosition; import com.galvarez.ttw.rendering.components.Name; @Wire public final class AIDiplomaticSystem extends EntityProcessingSystem { private static final Logger log = LoggerFactory.getLogger(AIDiplomaticSystem.class); private ComponentMapper<Diplomacy> relations; private ComponentMapper<MapPosition> positions; private DiplomaticSystem diplomaticSystem; private final GameMap map; @SuppressWarnings("unchecked") public AIDiplomaticSystem(GameMap map) { super(Aspect.getAspectForAll(AIControlled.class, Diplomacy.class)); this.map = map; } @Override protected boolean checkProcessing() { return true; } @Override protected void process(Entity entity) { Diplomacy diplo = relations.get(entity); // TODO have a real AI algorithm for diplomacy // neighbors from the nicest to the baddest List<Entity> neighbors = getNeighboringSources(entity); if (diplo.knownStates.contains(State.TREATY) && neighbors.size() > 2) { // sign treaty with half the neighbors, not the last one (WAR for him!) for (int i = 0; i < neighbors.size() / 2 && i < neighbors.size() - 1; i++) { Entity target = neighbors.get(i); makeProposal(entity, diplo, target, Action.SIGN_TREATY); } } if (diplo.knownStates.contains(State.WAR)) { // try to be at war with somebody, and only that somebody List<Entity> atWarWith = diplo.getEmpires(State.WAR); Entity target = neighbors.isEmpty() ? null : neighbors.get(neighbors.size() - 1); // to change our war target, first make peace with preceding one for (Entity war : atWarWith) { if (target != war) makeProposal(entity, diplo, war, Action.MAKE_PEACE); } if (target != null && !atWarWith.contains(target)) makeProposal(entity, diplo, target, Action.DECLARE_WAR); } } private void makeProposal(Entity entity, Diplomacy diplo, Entity target, Action action) { if (diplomaticSystem.getPossibleActions(diplo, target).contains(action) // do not change status if same proposal is already on the table && diplo.proposals.get(target) != action // do no make proposal to ourself && entity != target) { log.debug("{} wants to {} with {}", entity.getComponent(Name.class), action.str, target.getComponent(Name.class)); diplo.proposals.put(target, action); } } /** Neighbors from the nicest to the worst. */ private List<Entity> getNeighboringSources(Entity entity) { IntIntMap neighbors = new IntIntMap(16); MapPosition pos = positions.get(entity); for (int i = 1; i < 10; i++) { // TODO really search for all tiles addInfluencer(neighbors, entity, pos.x + i, pos.y + i); addInfluencer(neighbors, entity, pos.x - i, pos.y + i); addInfluencer(neighbors, entity, pos.x + i, pos.y - i); addInfluencer(neighbors, entity, pos.x - i, pos.y - i); } List<Entry> entries = new ArrayList<>(); neighbors.entries().forEach(e -> entries.add(e)); entries.sort((e1, e2) -> Integer.compare(e1.value, e2.value)); List<Entity> res = new ArrayList<>(entries.size()); entries.forEach(e -> res.add(world.getEntity(e.key))); return res; } private void addInfluencer(IntIntMap neighbors, Entity capital, int x, int y) { Influence inf = map.getInfluenceAt(x, y); if (inf != null && !inf.isMainInfluencer(capital) && inf.hasMainInfluence()) neighbors.getAndIncrement(inf.getMainInfluenceSource(), 0, 1); } }
core/src/com/galvarez/ttw/model/AIDiplomaticSystem.java
package com.galvarez.ttw.model; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.artemis.Aspect; import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.annotations.Wire; import com.artemis.systems.EntityProcessingSystem; import com.badlogic.gdx.utils.IntIntMap; import com.badlogic.gdx.utils.IntIntMap.Entry; import com.galvarez.ttw.model.DiplomaticSystem.Action; import com.galvarez.ttw.model.DiplomaticSystem.State; import com.galvarez.ttw.model.components.AIControlled; import com.galvarez.ttw.model.components.Diplomacy; import com.galvarez.ttw.model.components.InfluenceSource; import com.galvarez.ttw.model.map.GameMap; import com.galvarez.ttw.model.map.Influence; import com.galvarez.ttw.model.map.MapPosition; import com.galvarez.ttw.rendering.components.Name; @Wire public final class AIDiplomaticSystem extends EntityProcessingSystem { private static final Logger log = LoggerFactory.getLogger(AIDiplomaticSystem.class); private ComponentMapper<Diplomacy> relations; private ComponentMapper<MapPosition> positions; private ComponentMapper<InfluenceSource> sources; private DiplomaticSystem diplomaticSystem; private final GameMap map; @SuppressWarnings("unchecked") public AIDiplomaticSystem(GameMap map) { super(Aspect.getAspectForAll(AIControlled.class, Diplomacy.class)); this.map = map; } @Override protected boolean checkProcessing() { return true; } @Override protected void process(Entity entity) { Diplomacy diplo = relations.get(entity); // TODO have a real AI algorithm for diplomacy // neighbors from the nicest to the baddest List<Entity> neighbors = getNeighboringSources(entity); if (diplo.knownStates.contains(State.TREATY) && neighbors.size() > 2) { // sign treaty with half the neighbors, not the last one (WAR for him!) for (int i = 0; i < neighbors.size() / 2 && i < neighbors.size() - 1; i++) { Entity target = neighbors.get(i); makeProposal(entity, diplo, target, Action.SIGN_TREATY); } } if (diplo.knownStates.contains(State.WAR)) { // try to be at war with somebody, and only that somebody List<Entity> atWarWith = diplo.getEmpires(State.WAR); Entity target = neighbors.isEmpty() ? null : neighbors.get(neighbors.size() - 1); // to change our war target, first make peace with preceding one for (Entity war : atWarWith) { if (target != war) makeProposal(entity, diplo, war, Action.MAKE_PEACE); } if (target != null && !atWarWith.contains(target)) makeProposal(entity, diplo, target, Action.DECLARE_WAR); } } private void makeProposal(Entity entity, Diplomacy diplo, Entity target, Action action) { if (diplomaticSystem.getPossibleActions(diplo, target).contains(action) // do not change status if same proposal is already on the table && diplo.proposals.get(target) != action // do no make proposal to ourself && entity != target) { log.debug("{} wants to {} with {}", entity.getComponent(Name.class), action.str, target.getComponent(Name.class)); diplo.proposals.put(target, action); } } /** Neighbors from the nicest to the worst. */ private List<Entity> getNeighboringSources(Entity entity) { IntIntMap neighbors = new IntIntMap(16); MapPosition pos = positions.get(entity); for (int i = 1; i < 10; i++) { // TODO really search for all tiles addInfluencer(neighbors, entity, pos.x + i, pos.y + i); addInfluencer(neighbors, entity, pos.x - i, pos.y + i); addInfluencer(neighbors, entity, pos.x + i, pos.y - i); addInfluencer(neighbors, entity, pos.x - i, pos.y - i); } List<Entry> entries = new ArrayList<>(); neighbors.entries().forEach(e -> entries.add(e)); entries.sort((e1, e2) -> Integer.compare(e1.value, e2.value)); List<Entity> res = new ArrayList<>(entries.size()); entries.forEach(e -> res.add(world.getEntity(e.key))); return res; } private void addInfluencer(IntIntMap neighbors, Entity capital, int x, int y) { Influence inf = map.getInfluenceAt(x, y); if (inf != null && !inf.isMainInfluencer(capital) && inf.hasMainInfluence()) neighbors.getAndIncrement(inf.getMainInfluenceSource(), 0, 1); } }
Remove unused field.
core/src/com/galvarez/ttw/model/AIDiplomaticSystem.java
Remove unused field.
<ide><path>ore/src/com/galvarez/ttw/model/AIDiplomaticSystem.java <ide> import com.galvarez.ttw.model.DiplomaticSystem.State; <ide> import com.galvarez.ttw.model.components.AIControlled; <ide> import com.galvarez.ttw.model.components.Diplomacy; <del>import com.galvarez.ttw.model.components.InfluenceSource; <ide> import com.galvarez.ttw.model.map.GameMap; <ide> import com.galvarez.ttw.model.map.Influence; <ide> import com.galvarez.ttw.model.map.MapPosition; <ide> private ComponentMapper<Diplomacy> relations; <ide> <ide> private ComponentMapper<MapPosition> positions; <del> <del> private ComponentMapper<InfluenceSource> sources; <ide> <ide> private DiplomaticSystem diplomaticSystem; <ide>
Java
apache-2.0
bf2aa29c14b60150cabf49d4c252aca3162e19e4
0
xjanker/akita
package com.alibaba.akita.taobao; import com.alibaba.akita.annotation.*; import com.alibaba.akita.exception.AkInvokeException; import com.alibaba.akita.exception.AkServerStatusException; import java.util.Map; /** * Created with IntelliJ IDEA. * User: justinyang * Date: 13-2-17 * Time: PM3:32 * * eg. * http://gw.api.taobao.com/router/rest?sign=719E9C5DCF2E1423702EC66822DE22E4 * &timestamp=2013-02-17+15%3A44%3A42 * &v=2.0 * &app_key=12129701 * &method=taobao.item.get * &partner_id=top-apitools * &format=json * &num_iid=16788418057 * &fields=detail_url,num_iid,title * */ public interface TopAPI { // @AkGET // @AkSignature(using = TopAPISignature.class) // @AkAPI(url="http://gw.api.taobao.com/router/rest") // String top_online( // @AkParam(value = "timestamp", encode = "utf8") String timestamp, // @AkParam("v") String v, // @AkParam("app_key") String app_key, // @AkParam("app_secret") String app_secret, // @AkParam("method") String method, // @AkParam("session") String session, // @AkParam("partner_id") String partner_id, // @AkParam("format") String format, // @AkParam("sign_method") String sign_method, // @AkParam(value = "$paramMap", encode = "utf8") Map<String, String> appLayerData // ) throws AkInvokeException, AkServerStatusException; @AkPOST @AkSignature(using = TopAPISignature.class) @AkAPI(url="http://gw.api.taobao.com/router/rest") String top_online( @AkParam(value = "timestamp") String timestamp, @AkParam("v") String v, @AkParam("app_key") String app_key, @AkParam("app_secret") String app_secret, @AkParam("method") String method, @AkParam("session") String session, @AkParam("partner_id") String partner_id, @AkParam("format") String format, @AkParam("sign_method") String sign_method, @AkParam(value = "$paramMap") Map<String, String> appLayerData ) throws AkInvokeException, AkServerStatusException; @AkPOST @AkSignature(using = TopAPISignature.class) @AkAPI(url="http://110.75.14.63/top/router/rest") String top_predeploy( @AkParam(value = "timestamp") String timestamp, @AkParam("v") String v, @AkParam("app_key") String app_key, @AkParam("app_secret") String app_secret, @AkParam("method") String method, @AkParam("session") String session, @AkParam("partner_id") String partner_id, @AkParam("format") String format, @AkParam("sign_method") String sign_method, @AkParam(value = "$paramMap") Map<String, String> appLayerData ) throws AkInvokeException, AkServerStatusException; @AkPOST @AkSignature(using = TopAPISignature.class) @AkAPI(url="http://api.daily.taobao.net/router/rest") String top_daily( @AkParam(value = "timestamp") String timestamp, @AkParam("v") String v, @AkParam("app_key") String app_key, @AkParam("app_secret") String app_secret, @AkParam("method") String method, @AkParam("session") String session, @AkParam("partner_id") String partner_id, @AkParam("format") String format, @AkParam("sign_method") String sign_method, @AkParam(value = "$paramMap") Map<String, String> appLayerData ) throws AkInvokeException, AkServerStatusException; }
akita/src/com/alibaba/akita/taobao/TopAPI.java
package com.alibaba.akita.taobao; import com.alibaba.akita.annotation.*; import com.alibaba.akita.exception.AkInvokeException; import com.alibaba.akita.exception.AkServerStatusException; import java.util.Map; /** * Created with IntelliJ IDEA. * User: justinyang * Date: 13-2-17 * Time: PM3:32 * * eg. * http://gw.api.taobao.com/router/rest?sign=719E9C5DCF2E1423702EC66822DE22E4 * &timestamp=2013-02-17+15%3A44%3A42 * &v=2.0 * &app_key=12129701 * &method=taobao.item.get * &partner_id=top-apitools * &format=json * &num_iid=16788418057 * &fields=detail_url,num_iid,title * */ public interface TopAPI { // @AkGET // @AkSignature(using = TopAPISignature.class) // @AkAPI(url="http://gw.api.taobao.com/router/rest") // String top_online( // @AkParam(value = "timestamp", encode = "utf8") String timestamp, // @AkParam("v") String v, // @AkParam("app_key") String app_key, // @AkParam("app_secret") String app_secret, // @AkParam("method") String method, // @AkParam("session") String session, // @AkParam("partner_id") String partner_id, // @AkParam("format") String format, // @AkParam("sign_method") String sign_method, // @AkParam(value = "$paramMap", encode = "utf8") Map<String, String> appLayerData // ) throws AkInvokeException, AkServerStatusException; @AkPOST @AkSignature(using = TopAPISignature.class) @AkAPI(url="http://gw.api.taobao.com/router/rest") String top_online( @AkParam(value = "timestamp") String timestamp, @AkParam("v") String v, @AkParam("app_key") String app_key, @AkParam("app_secret") String app_secret, @AkParam("method") String method, @AkParam("session") String session, @AkParam("partner_id") String partner_id, @AkParam("format") String format, @AkParam("sign_method") String sign_method, @AkParam(value = "$paramMap") Map<String, String> appLayerData ) throws AkInvokeException, AkServerStatusException; @AkPOST @AkSignature(using = TopAPISignature.class) @AkAPI(url="http://gw.api.taobao.com/router/rest") String top_predeploy( @AkParam(value = "timestamp") String timestamp, @AkParam("v") String v, @AkParam("app_key") String app_key, @AkParam("app_secret") String app_secret, @AkParam("method") String method, @AkParam("session") String session, @AkParam("partner_id") String partner_id, @AkParam("format") String format, @AkParam("sign_method") String sign_method, @AkParam(value = "$paramMap") Map<String, String> appLayerData ) throws AkInvokeException, AkServerStatusException; @AkPOST @AkSignature(using = TopAPISignature.class) @AkAPI(url="http://api.daily.taobao.net/router/rest") String top_daily( @AkParam(value = "timestamp") String timestamp, @AkParam("v") String v, @AkParam("app_key") String app_key, @AkParam("app_secret") String app_secret, @AkParam("method") String method, @AkParam("session") String session, @AkParam("partner_id") String partner_id, @AkParam("format") String format, @AkParam("sign_method") String sign_method, @AkParam(value = "$paramMap") Map<String, String> appLayerData ) throws AkInvokeException, AkServerStatusException; }
add predeply of topapi
akita/src/com/alibaba/akita/taobao/TopAPI.java
add predeply of topapi
<ide><path>kita/src/com/alibaba/akita/taobao/TopAPI.java <ide> <ide> @AkPOST <ide> @AkSignature(using = TopAPISignature.class) <del> @AkAPI(url="http://gw.api.taobao.com/router/rest") <add> @AkAPI(url="http://110.75.14.63/top/router/rest") <ide> String top_predeploy( <ide> @AkParam(value = "timestamp") String timestamp, <ide> @AkParam("v") String v,
Java
mit
764e7301a9102ee05db7dc129c6b1b4eb952eb0a
0
qiniudemo/qiniu-play-java-example,qiniudemo/qiniu-play-java-example
package controllers; import play.*; import play.mvc.*; import play.libs.Json; import play.data.*; import play.libs.*; import java.util.Map; import java.util.HashMap; import views.html.*; import static play.mvc.Results.*; import play.data.validation.*; import static play.data.validation.Constraints.*; import javax.validation.*; import util.*; import org.joda.time.LocalTime; import models.*; import com.qiniu.api.auth.digest.Mac; public class Storage extends Controller { public static Result uploadToken() { Map<String,String[]> queryString = request().queryString(); // this is demo, user get from query if (queryString.get("user") == null) { return badRequest( util.Error.Invalid.toJson() ); } String user = queryString.get("user")[0]; String bucket= Play.application().configuration().getString("qiniu.bucket"); String callbackUrl = Play.application().configuration().getString("qiniu.callback_url"); String token = util.Qiniu.uploadToken(bucket, user, callbackUrl); if (token == null) { return badRequest( util.Error.Invalid.toJson() ); } Map<String, String> resp = new HashMap<String, String>(); resp.put("token", token); return ok( Json.toJson(resp) ); } public static Result downloadToken() { Map<String,String[]> queryString = request().queryString(); if (queryString.get("key") == null || queryString.get("user") == null) { return badRequest( util.Error.Invalid.toJson() ); } String key = queryString.get("key")[0]; // this is demo, user get from query String user = queryString.get("user")[0]; File f = File.find.byId(key); if (!f.user.equals(user)) { return forbidden( util.Error.Forbiden.toJson() ); } String downTokenUrl = downloadUrl(key); Map<String, String> resp = new HashMap<String, String>(); resp.put("url", downTokenUrl); return ok( Json.toJson(resp) ); } private static String downloadUrl(String key){ String domain= Play.application().configuration().getString("qiniu.domain"); String downloadUrl = "http://"+ domain + "/" + key; return util.Qiniu.downloadToken(downloadUrl); } public static Result downloadTokens(FileCollection col){ // get files from collection // iterate files to get tokens // return download token url array return null; } public static Result delete() { Map<String,String[]> queryString = request().queryString(); String bucket= Play.application().configuration().getString("qiniu.bucket"); String key = queryString.get("key")[0]; // to do find, and check owner // File = File.Find() try { util.Qiniu.delete(bucket, key); } catch(Exception e){ e.printStackTrace(); return badRequest(Json.toJson(null)); } return ok( Json.toJson(null) ); } private static Form<File> upCallbackForm = Form.form(File.class); //bucket, key public static Result callback() { Logger.info("callbacking"); Form<File> boundCallback = upCallbackForm.bindFromRequest(); if (boundCallback.hasErrors()) { return badRequest(); } File data = boundCallback.get(); Logger.info("callback done "+ data.user); data.timestamp = LocalTime.now(); data.save(); Map<String, String> resp = new HashMap<String, String>(); resp.put("success", "true"); return ok( Json.toJson(resp) ); } }
app/controllers/Storage.java
package controllers; import play.*; import play.mvc.*; import play.libs.Json; import play.data.*; import play.libs.*; import java.util.Map; import java.util.HashMap; import views.html.*; import static play.mvc.Results.*; import play.data.validation.*; import static play.data.validation.Constraints.*; import javax.validation.*; import util.*; import org.joda.time.LocalTime; import models.*; import com.qiniu.api.auth.digest.Mac; public class Storage extends Controller { public static Result uploadToken() { Map<String,String[]> queryString = request().queryString(); // this is demo, user get from query String user = queryString.get("user")[0]; String bucket= Play.application().configuration().getString("qiniu.bucket"); String callbackUrl = Play.application().configuration().getString("qiniu.callback_url"); String token = util.Qiniu.uploadToken(bucket, user, callbackUrl); if (token == null) { return badRequest( util.Error.Invalid.toJson() ); } Map<String, String> resp = new HashMap<String, String>(); resp.put("token", token); return ok( Json.toJson(resp) ); } public static Result downloadToken() { Map<String,String[]> queryString = request().queryString(); String key = queryString.get("key")[0]; // this is demo, user get from query String user = queryString.get("user")[0]; File f = File.find.byId(key); if (!f.user.equals(user)) { return badRequest( util.Error.Forbiden.toJson() ); } String downTokenUrl = downloadUrl(key); Map<String, String> resp = new HashMap<String, String>(); resp.put("url", downTokenUrl); return ok( Json.toJson(resp) ); } private static String downloadUrl(String key){ String domain= Play.application().configuration().getString("qiniu.domain"); String downloadUrl = "http://"+ domain + "/" + key; return util.Qiniu.downloadToken(downloadUrl); } public static Result downloadTokens(FileCollection col){ // get files from collection // iterate files to get tokens // return download token url array return null; } public static Result delete() { Map<String,String[]> queryString = request().queryString(); String bucket= Play.application().configuration().getString("qiniu.bucket"); String key = queryString.get("key")[0]; // to do find, and check owner // File = File.Find() try { util.Qiniu.delete(bucket, key); } catch(Exception e){ e.printStackTrace(); return badRequest(Json.toJson(null)); } return ok( Json.toJson(null) ); } private static Form<File> upCallbackForm = Form.form(File.class); //bucket, key public static Result callback() { Form<File> boundCallback = upCallbackForm.bindFromRequest(); if (boundCallback.hasErrors()) { return badRequest(); } File data = boundCallback.get(); Logger.info("callback done"+ data.user); data.timestamp = LocalTime.now(); data.save(); Map<String, String> resp = new HashMap<String, String>(); resp.put("success", "true"); return ok( Json.toJson(resp) ); } }
add auth
app/controllers/Storage.java
add auth
<ide><path>pp/controllers/Storage.java <ide> public static Result uploadToken() { <ide> Map<String,String[]> queryString = request().queryString(); <ide> // this is demo, user get from query <add> if (queryString.get("user") == null) { <add> return badRequest( <add> util.Error.Invalid.toJson() <add> ); <add> } <ide> String user = queryString.get("user")[0]; <ide> <ide> String bucket= Play.application().configuration().getString("qiniu.bucket"); <ide> <ide> public static Result downloadToken() { <ide> Map<String,String[]> queryString = request().queryString(); <add> if (queryString.get("key") == null || queryString.get("user") == null) { <add> return badRequest( <add> util.Error.Invalid.toJson() <add> ); <add> } <ide> String key = queryString.get("key")[0]; <ide> // this is demo, user get from query <ide> String user = queryString.get("user")[0]; <ide> <ide> File f = File.find.byId(key); <ide> if (!f.user.equals(user)) { <del> return badRequest( <add> return forbidden( <ide> util.Error.Forbiden.toJson() <ide> ); <ide> } <ide> private static Form<File> upCallbackForm = Form.form(File.class); <ide> //bucket, key <ide> public static Result callback() { <add> Logger.info("callbacking"); <ide> Form<File> boundCallback = upCallbackForm.bindFromRequest(); <ide> if (boundCallback.hasErrors()) { <ide> return badRequest(); <ide> <ide> File data = boundCallback.get(); <ide> <del> Logger.info("callback done"+ data.user); <add> Logger.info("callback done "+ data.user); <ide> data.timestamp = LocalTime.now(); <ide> data.save(); <ide> Map<String, String> resp = new HashMap<String, String>();
Java
apache-2.0
4c54f3e25c3fe57b2ab76c70876f008a9e82b761
0
allotria/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,signed/intellij-community,semonte/intellij-community,ibinti/intellij-community,asedunov/intellij-community,asedunov/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,da1z/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,allotria/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,xfournet/intellij-community,asedunov/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,FHannes/intellij-community,signed/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,da1z/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,signed/intellij-community,ibinti/intellij-community,da1z/intellij-community,suncycheng/intellij-community,signed/intellij-community,allotria/intellij-community,ibinti/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,ibinti/intellij-community,allotria/intellij-community,xfournet/intellij-community,signed/intellij-community,signed/intellij-community,xfournet/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,da1z/intellij-community,da1z/intellij-community,apixandru/intellij-community,semonte/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,semonte/intellij-community,allotria/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,da1z/intellij-community,da1z/intellij-community,da1z/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,semonte/intellij-community,allotria/intellij-community,allotria/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,semonte/intellij-community,apixandru/intellij-community,FHannes/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,semonte/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,semonte/intellij-community,signed/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,allotria/intellij-community,signed/intellij-community,semonte/intellij-community,asedunov/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,semonte/intellij-community,ibinti/intellij-community,xfournet/intellij-community,da1z/intellij-community,signed/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,signed/intellij-community,da1z/intellij-community,signed/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,FHannes/intellij-community,da1z/intellij-community,FHannes/intellij-community,da1z/intellij-community,xfournet/intellij-community,allotria/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,asedunov/intellij-community,allotria/intellij-community,apixandru/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,apixandru/intellij-community,apixandru/intellij-community,signed/intellij-community,mglukhikh/intellij-community
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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.intellij.ide.projectView.impl; import com.intellij.ProjectTopics; import com.intellij.history.LocalHistory; import com.intellij.history.LocalHistoryAction; import com.intellij.icons.AllIcons; import com.intellij.ide.*; import com.intellij.ide.impl.ProjectViewSelectInTarget; import com.intellij.ide.projectView.HelpID; import com.intellij.ide.projectView.ProjectView; import com.intellij.ide.projectView.ProjectViewNode; import com.intellij.ide.projectView.impl.nodes.*; import com.intellij.ide.scopeView.ScopeViewPane; import com.intellij.ide.ui.SplitterProportionsDataImpl; import com.intellij.ide.ui.UISettings; import com.intellij.ide.util.DeleteHandler; import com.intellij.ide.util.DirectoryChooserUtil; import com.intellij.ide.util.EditorHelper; import com.intellij.ide.util.treeView.AbstractTreeBuilder; import com.intellij.ide.util.treeView.AbstractTreeNode; import com.intellij.ide.util.treeView.NodeDescriptor; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.components.StoragePathMacros; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.ui.configuration.actions.ModuleDeleteProvider; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.SimpleToolWindowPanel; import com.intellij.openapi.ui.SplitterProportionsData; import com.intellij.openapi.ui.popup.PopupChooserBuilder; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.*; import com.intellij.openapi.wm.ex.ToolWindowEx; import com.intellij.openapi.wm.ex.ToolWindowManagerAdapter; import com.intellij.openapi.wm.ex.ToolWindowManagerEx; import com.intellij.openapi.wm.impl.content.ToolWindowContentUi; import com.intellij.psi.*; import com.intellij.psi.impl.file.PsiDirectoryFactory; import com.intellij.psi.util.PsiUtilCore; import com.intellij.ui.AutoScrollFromSourceHandler; import com.intellij.ui.AutoScrollToSourceHandler; import com.intellij.ui.GuiUtils; import com.intellij.ui.components.JBList; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentManager; import com.intellij.ui.content.ContentManagerAdapter; import com.intellij.ui.content.ContentManagerEvent; import com.intellij.util.ArrayUtil; import com.intellij.util.IJSwingUtilities; import com.intellij.util.PlatformIcons; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jdom.Attribute; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import java.awt.*; import java.util.*; import java.util.List; @State(name = "ProjectView", storages = @Storage(StoragePathMacros.WORKSPACE_FILE)) public class ProjectViewImpl extends ProjectView implements PersistentStateComponent<Element>, Disposable, BusyObject { private static final Logger LOG = Logger.getInstance("#com.intellij.ide.projectView.impl.ProjectViewImpl"); private static final Key<String> ID_KEY = Key.create("pane-id"); private static final Key<String> SUB_ID_KEY = Key.create("pane-sub-id"); private final CopyPasteDelegator myCopyPasteDelegator; private boolean isInitialized; private boolean myExtensionsLoaded = false; @NotNull private final Project myProject; // + options private final Map<String, Boolean> myFlattenPackages = new THashMap<>(); private static final boolean ourFlattenPackagesDefaults = false; private final Map<String, Boolean> myShowMembers = new THashMap<>(); private static final boolean ourShowMembersDefaults = false; private final Map<String, Boolean> myManualOrder = new THashMap<>(); private static final boolean ourManualOrderDefaults = false; private final Map<String, Boolean> mySortByType = new THashMap<>(); private static final boolean ourSortByTypeDefaults = false; private final Map<String, Boolean> myShowModules = new THashMap<>(); private static final boolean ourShowModulesDefaults = true; private final Map<String, Boolean> myShowLibraryContents = new THashMap<>(); private static final boolean ourShowLibraryContentsDefaults = true; private final Map<String, Boolean> myHideEmptyPackages = new THashMap<>(); private static final boolean ourHideEmptyPackagesDefaults = true; private final Map<String, Boolean> myAbbreviatePackageNames = new THashMap<>(); private static final boolean ourAbbreviatePackagesDefaults = false; private final Map<String, Boolean> myAutoscrollToSource = new THashMap<>(); private final Map<String, Boolean> myAutoscrollFromSource = new THashMap<>(); private static final boolean ourAutoscrollFromSourceDefaults = false; private boolean myFoldersAlwaysOnTop = true; private String myCurrentViewId; private String myCurrentViewSubId; // - options private final AutoScrollToSourceHandler myAutoScrollToSourceHandler; private final MyAutoScrollFromSourceHandler myAutoScrollFromSourceHandler; private final IdeView myIdeView = new MyIdeView(); private final MyDeletePSIElementProvider myDeletePSIElementProvider = new MyDeletePSIElementProvider(); private final ModuleDeleteProvider myDeleteModuleProvider = new ModuleDeleteProvider(); private SimpleToolWindowPanel myPanel; private final Map<String, AbstractProjectViewPane> myId2Pane = new LinkedHashMap<>(); private final Collection<AbstractProjectViewPane> myUninitializedPanes = new THashSet<>(); static final DataKey<ProjectViewImpl> DATA_KEY = DataKey.create("com.intellij.ide.projectView.impl.ProjectViewImpl"); private DefaultActionGroup myActionGroup; private String mySavedPaneId = ProjectViewPane.ID; private String mySavedPaneSubId; //private static final Icon COMPACT_EMPTY_MIDDLE_PACKAGES_ICON = IconLoader.getIcon("/objectBrowser/compactEmptyPackages.png"); //private static final Icon HIDE_EMPTY_MIDDLE_PACKAGES_ICON = IconLoader.getIcon("/objectBrowser/hideEmptyPackages.png"); @NonNls private static final String ELEMENT_NAVIGATOR = "navigator"; @NonNls private static final String ELEMENT_PANES = "panes"; @NonNls private static final String ELEMENT_PANE = "pane"; @NonNls private static final String ATTRIBUTE_CURRENT_VIEW = "currentView"; @NonNls private static final String ATTRIBUTE_CURRENT_SUBVIEW = "currentSubView"; @NonNls private static final String ELEMENT_FLATTEN_PACKAGES = "flattenPackages"; @NonNls private static final String ELEMENT_SHOW_MEMBERS = "showMembers"; @NonNls private static final String ELEMENT_SHOW_MODULES = "showModules"; @NonNls private static final String ELEMENT_SHOW_LIBRARY_CONTENTS = "showLibraryContents"; @NonNls private static final String ELEMENT_HIDE_EMPTY_PACKAGES = "hideEmptyPackages"; @NonNls private static final String ELEMENT_ABBREVIATE_PACKAGE_NAMES = "abbreviatePackageNames"; @NonNls private static final String ELEMENT_AUTOSCROLL_TO_SOURCE = "autoscrollToSource"; @NonNls private static final String ELEMENT_AUTOSCROLL_FROM_SOURCE = "autoscrollFromSource"; @NonNls private static final String ELEMENT_SORT_BY_TYPE = "sortByType"; @NonNls private static final String ELEMENT_FOLDERS_ALWAYS_ON_TOP = "foldersAlwaysOnTop"; @NonNls private static final String ELEMENT_MANUAL_ORDER = "manualOrder"; private static final String ATTRIBUTE_ID = "id"; private JPanel myViewContentPanel; private static final Comparator<AbstractProjectViewPane> PANE_WEIGHT_COMPARATOR = (o1, o2) -> o1.getWeight() - o2.getWeight(); private final FileEditorManager myFileEditorManager; private final MyPanel myDataProvider; private final SplitterProportionsData splitterProportions = new SplitterProportionsDataImpl(); private final MessageBusConnection myConnection; private final Map<String, Element> myUninitializedPaneState = new HashMap<>(); private final Map<String, SelectInTarget> mySelectInTargets = new LinkedHashMap<>(); private ContentManager myContentManager; public ProjectViewImpl(@NotNull Project project, final FileEditorManager fileEditorManager, final ToolWindowManagerEx toolWindowManager) { myProject = project; constructUi(); myFileEditorManager = fileEditorManager; myConnection = project.getMessageBus().connect(); myConnection.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootAdapter() { @Override public void rootsChanged(ModuleRootEvent event) { refresh(); } }); myAutoScrollFromSourceHandler = new MyAutoScrollFromSourceHandler(); myDataProvider = new MyPanel(); myDataProvider.add(myPanel, BorderLayout.CENTER); myCopyPasteDelegator = new CopyPasteDelegator(myProject, myPanel) { @Override @NotNull protected PsiElement[] getSelectedElements() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); return viewPane == null ? PsiElement.EMPTY_ARRAY : viewPane.getSelectedPSIElements(); } }; myAutoScrollToSourceHandler = new AutoScrollToSourceHandler() { @Override protected boolean isAutoScrollMode() { return isAutoscrollToSource(myCurrentViewId); } @Override protected void setAutoScrollMode(boolean state) { setAutoscrollToSource(state, myCurrentViewId); } }; toolWindowManager.addToolWindowManagerListener(new ToolWindowManagerAdapter(){ private boolean toolWindowVisible; @Override public void stateChanged() { ToolWindow window = toolWindowManager.getToolWindow(ToolWindowId.PROJECT_VIEW); if (window == null) return; if (window.isVisible() && !toolWindowVisible) { String id = getCurrentViewId(); if (isAutoscrollToSource(id)) { AbstractProjectViewPane currentProjectViewPane = getCurrentProjectViewPane(); if (currentProjectViewPane != null) { myAutoScrollToSourceHandler.onMouseClicked(currentProjectViewPane.getTree()); } } if (isAutoscrollFromSource(id)) { myAutoScrollFromSourceHandler.setAutoScrollEnabled(true); } } toolWindowVisible = window.isVisible(); } }); } private void constructUi() { myViewContentPanel = new JPanel(); myPanel = new SimpleToolWindowPanel(true); myPanel.setContent(myViewContentPanel); } @NotNull @Deprecated public List<AnAction> getActions(boolean originalProvider) { return Collections.emptyList(); } @Override public synchronized void addProjectPane(@NotNull final AbstractProjectViewPane pane) { myUninitializedPanes.add(pane); SelectInTarget selectInTarget = pane.createSelectInTarget(); if (selectInTarget != null) { mySelectInTargets.put(pane.getId(), selectInTarget); } if (isInitialized) { doAddUninitializedPanes(); } } @Override public synchronized void removeProjectPane(@NotNull AbstractProjectViewPane pane) { ApplicationManager.getApplication().assertIsDispatchThread(); myUninitializedPanes.remove(pane); //assume we are completely initialized here String idToRemove = pane.getId(); if (!myId2Pane.containsKey(idToRemove)) return; pane.removeTreeChangeListener(); for (int i = getContentManager().getContentCount() - 1; i >= 0; i--) { Content content = getContentManager().getContent(i); String id = content != null ? content.getUserData(ID_KEY) : null; if (id != null && id.equals(idToRemove)) { getContentManager().removeContent(content, true); } } myId2Pane.remove(idToRemove); mySelectInTargets.remove(idToRemove); viewSelectionChanged(); } private synchronized void doAddUninitializedPanes() { for (AbstractProjectViewPane pane : myUninitializedPanes) { doAddPane(pane); } final Content[] contents = getContentManager().getContents(); for (int i = 1; i < contents.length; i++) { Content content = contents[i]; Content prev = contents[i - 1]; if (!StringUtil.equals(content.getUserData(ID_KEY), prev.getUserData(ID_KEY)) && prev.getUserData(SUB_ID_KEY) != null && content.getSeparator() == null) { content.setSeparator(""); } } String selectID = null; String selectSubID = null; // try to find saved selected view... for (Content content : contents) { final String id = content.getUserData(ID_KEY); final String subId = content.getUserData(SUB_ID_KEY); if (id != null && id.equals(mySavedPaneId) && StringUtil.equals(subId, mySavedPaneSubId)) { selectID = id; selectSubID = subId; break; } } // saved view not found (plugin disabled, ID changed etc.) - select first available view... if (selectID == null && contents.length > 0) { Content content = contents[0]; selectID = content.getUserData(ID_KEY); selectSubID = content.getUserData(SUB_ID_KEY); } if (selectID != null) { changeView(selectID, selectSubID); mySavedPaneId = null; mySavedPaneSubId = null; } myUninitializedPanes.clear(); } private void doAddPane(@NotNull final AbstractProjectViewPane newPane) { ApplicationManager.getApplication().assertIsDispatchThread(); int index; final ContentManager manager = getContentManager(); for (index = 0; index < manager.getContentCount(); index++) { Content content = manager.getContent(index); String id = content.getUserData(ID_KEY); AbstractProjectViewPane pane = myId2Pane.get(id); int comp = PANE_WEIGHT_COMPARATOR.compare(pane, newPane); LOG.assertTrue(comp != 0, "Project view pane " + newPane + " has the same weight as " + pane + ". Please make sure that you overload getWeight() and return a distinct weight value."); if (comp > 0) { break; } } final String id = newPane.getId(); myId2Pane.put(id, newPane); String[] subIds = newPane.getSubIds(); subIds = subIds.length == 0 ? new String[]{null} : subIds; boolean first = true; for (String subId : subIds) { final String title = subId != null ? newPane.getPresentableSubIdName(subId) : newPane.getTitle(); final Content content = getContentManager().getFactory().createContent(getComponent(), title, false); content.setTabName(title); content.putUserData(ID_KEY, id); content.putUserData(SUB_ID_KEY, subId); content.putUserData(ToolWindow.SHOW_CONTENT_ICON, Boolean.TRUE); content.setIcon(newPane.getIcon()); content.setPopupIcon(subId != null ? AllIcons.General.Bullet : newPane.getIcon()); content.setPreferredFocusedComponent(() -> { final AbstractProjectViewPane current = getCurrentProjectViewPane(); return current != null ? current.getComponentToFocus() : null; }); content.setBusyObject(this); if (first && subId != null) { content.setSeparator(newPane.getTitle()); } manager.addContent(content, index++); first = false; } } private void showPane(@NotNull AbstractProjectViewPane newPane) { AbstractProjectViewPane currentPane = getCurrentProjectViewPane(); PsiElement selectedPsiElement = null; if (currentPane != null) { if (currentPane != newPane) { currentPane.saveExpandedPaths(); } final PsiElement[] elements = currentPane.getSelectedPSIElements(); if (elements.length > 0) { selectedPsiElement = elements[0]; } } myViewContentPanel.removeAll(); JComponent component = newPane.createComponent(); UIUtil.removeScrollBorder(component); myViewContentPanel.setLayout(new BorderLayout()); myViewContentPanel.add(component, BorderLayout.CENTER); myCurrentViewId = newPane.getId(); String newSubId = myCurrentViewSubId = newPane.getSubId(); myViewContentPanel.revalidate(); myViewContentPanel.repaint(); createToolbarActions(); myAutoScrollToSourceHandler.install(newPane.myTree); IdeFocusManager.getInstance(myProject).requestFocus(newPane.getComponentToFocus(), false); newPane.restoreExpandedPaths(); if (selectedPsiElement != null && newSubId != null) { final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(selectedPsiElement); if (virtualFile != null && ((ProjectViewSelectInTarget)newPane.createSelectInTarget()).isSubIdSelectable(newSubId, new SelectInContext() { @Override @NotNull public Project getProject() { return myProject; } @Override @NotNull public VirtualFile getVirtualFile() { return virtualFile; } @Override public Object getSelectorInFile() { return null; } @Override public FileEditorProvider getFileEditorProvider() { return null; } })) { newPane.select(selectedPsiElement, virtualFile, true); } } myAutoScrollToSourceHandler.onMouseClicked(newPane.myTree); } // public for tests public synchronized void setupImpl(@NotNull ToolWindow toolWindow) { setupImpl(toolWindow, true); } // public for tests public synchronized void setupImpl(@NotNull ToolWindow toolWindow, final boolean loadPaneExtensions) { ApplicationManager.getApplication().assertIsDispatchThread(); myActionGroup = new DefaultActionGroup(); myAutoScrollFromSourceHandler.install(); myContentManager = toolWindow.getContentManager(); if (!ApplicationManager.getApplication().isUnitTestMode()) { toolWindow.setDefaultContentUiType(ToolWindowContentUiType.COMBO); ((ToolWindowEx)toolWindow).setAdditionalGearActions(myActionGroup); toolWindow.getComponent().putClientProperty(ToolWindowContentUi.HIDE_ID_LABEL, "true"); } GuiUtils.replaceJSplitPaneWithIDEASplitter(myPanel); SwingUtilities.invokeLater(() -> splitterProportions.restoreSplitterProportions(myPanel)); if (loadPaneExtensions) { ensurePanesLoaded(); } isInitialized = true; doAddUninitializedPanes(); getContentManager().addContentManagerListener(new ContentManagerAdapter() { @Override public void selectionChanged(ContentManagerEvent event) { if (event.getOperation() == ContentManagerEvent.ContentOperation.add) { viewSelectionChanged(); } } }); viewSelectionChanged(); } private void ensurePanesLoaded() { if (myExtensionsLoaded) return; myExtensionsLoaded = true; AbstractProjectViewPane[] extensions = Extensions.getExtensions(AbstractProjectViewPane.EP_NAME, myProject); Arrays.sort(extensions, PANE_WEIGHT_COMPARATOR); for(AbstractProjectViewPane pane: extensions) { if (myUninitializedPaneState.containsKey(pane.getId())) { try { pane.readExternal(myUninitializedPaneState.get(pane.getId())); } catch (InvalidDataException e) { // ignore } myUninitializedPaneState.remove(pane.getId()); } if (pane.isInitiallyVisible() && !myId2Pane.containsKey(pane.getId())) { addProjectPane(pane); } } } private boolean viewSelectionChanged() { Content content = getContentManager().getSelectedContent(); if (content == null) return false; final String id = content.getUserData(ID_KEY); String subId = content.getUserData(SUB_ID_KEY); if (content.equals(Pair.create(myCurrentViewId, myCurrentViewSubId))) return false; final AbstractProjectViewPane newPane = getProjectViewPaneById(id); if (newPane == null) return false; newPane.setSubId(subId); showPane(newPane); if (isAutoscrollFromSource(id)) { myAutoScrollFromSourceHandler.scrollFromSource(); } return true; } private void createToolbarActions() { if (myActionGroup == null) return; List<AnAction> titleActions = ContainerUtil.newSmartList(); myActionGroup.removeAll(); if (ProjectViewDirectoryHelper.getInstance(myProject).supportsFlattenPackages()) { myActionGroup.addAction(new PaneOptionAction(myFlattenPackages, IdeBundle.message("action.flatten.packages"), IdeBundle.message("action.flatten.packages"), PlatformIcons.FLATTEN_PACKAGES_ICON, ourFlattenPackagesDefaults) { @Override public void setSelected(AnActionEvent event, boolean flag) { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); final SelectionInfo selectionInfo = SelectionInfo.create(viewPane); if (isGlobalOptions()) { setFlattenPackages(flag, viewPane.getId()); } super.setSelected(event, flag); selectionInfo.apply(viewPane); } @Override public boolean isSelected(AnActionEvent event) { if (isGlobalOptions()) return getGlobalOptions().getFlattenPackages(); return super.isSelected(event); } }).setAsSecondary(true); } class FlattenPackagesDependableAction extends PaneOptionAction { FlattenPackagesDependableAction(@NotNull Map<String, Boolean> optionsMap, @NotNull String text, @NotNull String description, @NotNull Icon icon, boolean optionDefaultValue) { super(optionsMap, text, description, icon, optionDefaultValue); } @Override public void setSelected(AnActionEvent event, boolean flag) { if (isGlobalOptions()) { getGlobalOptions().setFlattenPackages(flag); } super.setSelected(event, flag); } @Override public void update(AnActionEvent e) { super.update(e); final Presentation presentation = e.getPresentation(); presentation.setVisible(isFlattenPackages(myCurrentViewId)); } } if (ProjectViewDirectoryHelper.getInstance(myProject).supportsHideEmptyMiddlePackages()) { myActionGroup.addAction(new HideEmptyMiddlePackagesAction()).setAsSecondary(true); } if (ProjectViewDirectoryHelper.getInstance(myProject).supportsFlattenPackages()) { myActionGroup.addAction(new FlattenPackagesDependableAction(myAbbreviatePackageNames, IdeBundle.message("action.abbreviate.qualified.package.names"), IdeBundle.message("action.abbreviate.qualified.package.names"), AllIcons.ObjectBrowser.AbbreviatePackageNames, ourAbbreviatePackagesDefaults) { @Override public boolean isSelected(AnActionEvent event) { return super.isSelected(event) && isAbbreviatePackageNames(myCurrentViewId); } @Override public void update(AnActionEvent e) { super.update(e); if (ScopeViewPane.ID.equals(myCurrentViewId)) { e.getPresentation().setEnabled(false); } } }).setAsSecondary(true); } if (isShowMembersOptionSupported()) { myActionGroup.addAction(new PaneOptionAction(myShowMembers, IdeBundle.message("action.show.members"), IdeBundle.message("action.show.hide.members"), AllIcons.ObjectBrowser.ShowMembers, ourShowMembersDefaults) { @Override public boolean isSelected(AnActionEvent event) { if (isGlobalOptions()) return getGlobalOptions().getShowMembers(); return super.isSelected(event); } @Override public void setSelected(AnActionEvent event, boolean flag) { if (isGlobalOptions()) { getGlobalOptions().setShowMembers(flag); } super.setSelected(event, flag); } }) .setAsSecondary(true); } myActionGroup.addAction(myAutoScrollToSourceHandler.createToggleAction()).setAsSecondary(true); myActionGroup.addAction(myAutoScrollFromSourceHandler.createToggleAction()).setAsSecondary(true); myActionGroup.addAction(new ManualOrderAction()).setAsSecondary(true); myActionGroup.addAction(new SortByTypeAction()).setAsSecondary(true); myActionGroup.addAction(new FoldersAlwaysOnTopAction()).setAsSecondary(true); if (!myAutoScrollFromSourceHandler.isAutoScrollEnabled()) { titleActions.add(new ScrollFromSourceAction()); } AnAction collapseAllAction = CommonActionsManager.getInstance().createCollapseAllAction(new TreeExpander() { @Override public void expandAll() { } @Override public boolean canExpand() { return false; } @Override public void collapseAll() { AbstractProjectViewPane pane = getCurrentProjectViewPane(); JTree tree = pane.myTree; if (tree != null) { TreeUtil.collapseAll(tree, 0); } } @Override public boolean canCollapse() { return true; } }, getComponent()); collapseAllAction.getTemplatePresentation().setIcon(AllIcons.General.CollapseAll); collapseAllAction.getTemplatePresentation().setHoveredIcon(AllIcons.General.CollapseAllHover); titleActions.add(collapseAllAction); getCurrentProjectViewPane().addToolbarActions(myActionGroup); ToolWindowEx window = (ToolWindowEx)ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.PROJECT_VIEW); if (window != null) { window.setTitleActions(titleActions.toArray(new AnAction[titleActions.size()])); } } protected boolean isShowMembersOptionSupported() { return true; } @Override public AbstractProjectViewPane getProjectViewPaneById(String id) { if (!ApplicationManager.getApplication().isUnitTestMode()) { // most tests don't need all panes to be loaded ensurePanesLoaded(); } final AbstractProjectViewPane pane = myId2Pane.get(id); if (pane != null) { return pane; } for (AbstractProjectViewPane viewPane : myUninitializedPanes) { if (viewPane.getId().equals(id)) { return viewPane; } } return null; } @Override public AbstractProjectViewPane getCurrentProjectViewPane() { return getProjectViewPaneById(myCurrentViewId); } @Override public void refresh() { AbstractProjectViewPane currentProjectViewPane = getCurrentProjectViewPane(); if (currentProjectViewPane != null) { // may be null for e.g. default project currentProjectViewPane.updateFromRoot(false); } } @Override public void select(final Object element, VirtualFile file, boolean requestFocus) { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane != null) { viewPane.select(element, file, requestFocus); } } @NotNull @Override public ActionCallback selectCB(Object element, VirtualFile file, boolean requestFocus) { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane != null && viewPane instanceof AbstractProjectViewPSIPane) { return ((AbstractProjectViewPSIPane)viewPane).selectCB(element, file, requestFocus); } select(element, file, requestFocus); return ActionCallback.DONE; } @Override public void dispose() { myConnection.disconnect(); } public JComponent getComponent() { return myDataProvider; } @Override public String getCurrentViewId() { return myCurrentViewId; } @Override public PsiElement getParentOfCurrentSelection() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane == null) { return null; } TreePath path = viewPane.getSelectedPath(); if (path == null) { return null; } path = path.getParentPath(); if (path == null) { return null; } DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); Object userObject = node.getUserObject(); if (userObject instanceof ProjectViewNode) { ProjectViewNode descriptor = (ProjectViewNode)userObject; Object element = descriptor.getValue(); if (element instanceof PsiElement) { PsiElement psiElement = (PsiElement)element; if (!psiElement.isValid()) return null; return psiElement; } else { return null; } } return null; } public ContentManager getContentManager() { if (myContentManager == null) { ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.PROJECT_VIEW).getContentManager(); } return myContentManager; } private class PaneOptionAction extends ToggleAction implements DumbAware { private final Map<String, Boolean> myOptionsMap; private final boolean myOptionDefaultValue; PaneOptionAction(@NotNull Map<String, Boolean> optionsMap, @NotNull String text, @NotNull String description, Icon icon, boolean optionDefaultValue) { super(text, description, icon); myOptionsMap = optionsMap; myOptionDefaultValue = optionDefaultValue; } @Override public boolean isSelected(AnActionEvent event) { return getPaneOptionValue(myOptionsMap, myCurrentViewId, myOptionDefaultValue); } @Override public void setSelected(AnActionEvent event, boolean flag) { setPaneOption(myOptionsMap, flag, myCurrentViewId, true); } } @Override public void changeView() { final List<AbstractProjectViewPane> views = new ArrayList<>(myId2Pane.values()); views.remove(getCurrentProjectViewPane()); Collections.sort(views, PANE_WEIGHT_COMPARATOR); final JList list = new JBList(ArrayUtil.toObjectArray(views)); list.setCellRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); AbstractProjectViewPane pane = (AbstractProjectViewPane)value; setText(pane.getTitle()); return this; } }); if (!views.isEmpty()) { list.setSelectedValue(views.get(0), true); } Runnable runnable = () -> { if (list.getSelectedIndex() < 0) return; AbstractProjectViewPane pane = (AbstractProjectViewPane)list.getSelectedValue(); changeView(pane.getId()); }; new PopupChooserBuilder(list). setTitle(IdeBundle.message("title.popup.views")). setItemChoosenCallback(runnable). createPopup().showInCenterOf(getComponent()); } @Override public void changeView(@NotNull String viewId) { changeView(viewId, null); } @Override public void changeView(@NotNull String viewId, @Nullable String subId) { changeViewCB(viewId, subId); } @NotNull @Override public ActionCallback changeViewCB(@NotNull String viewId, String subId) { AbstractProjectViewPane pane = getProjectViewPaneById(viewId); LOG.assertTrue(pane != null, "Project view pane not found: " + viewId + "; subId:" + subId); if (!viewId.equals(getCurrentViewId()) || subId != null && !subId.equals(pane.getSubId())) { for (Content content : getContentManager().getContents()) { if (viewId.equals(content.getUserData(ID_KEY)) && StringUtil.equals(subId, content.getUserData(SUB_ID_KEY))) { return getContentManager().setSelectedContentCB(content); } } } return ActionCallback.REJECTED; } private final class MyDeletePSIElementProvider implements DeleteProvider { @Override public boolean canDeleteElement(@NotNull DataContext dataContext) { final PsiElement[] elements = getElementsToDelete(); return DeleteHandler.shouldEnableDeleteAction(elements); } @Override public void deleteElement(@NotNull DataContext dataContext) { List<PsiElement> allElements = Arrays.asList(getElementsToDelete()); List<PsiElement> validElements = new ArrayList<>(); for (PsiElement psiElement : allElements) { if (psiElement != null && psiElement.isValid()) validElements.add(psiElement); } final PsiElement[] elements = PsiUtilCore.toPsiElementArray(validElements); LocalHistoryAction a = LocalHistory.getInstance().startAction(IdeBundle.message("progress.deleting")); try { DeleteHandler.deletePsiElement(elements, myProject); } finally { a.finish(); } } @NotNull private PsiElement[] getElementsToDelete() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); PsiElement[] elements = viewPane.getSelectedPSIElements(); for (int idx = 0; idx < elements.length; idx++) { final PsiElement element = elements[idx]; if (element instanceof PsiDirectory) { PsiDirectory directory = (PsiDirectory)element; final ProjectViewDirectoryHelper directoryHelper = ProjectViewDirectoryHelper.getInstance(myProject); if (isHideEmptyMiddlePackages(viewPane.getId()) && directory.getChildren().length == 0 && !directoryHelper.skipDirectory(directory)) { while (true) { PsiDirectory parent = directory.getParentDirectory(); if (parent == null) break; if (directoryHelper.skipDirectory(parent) || PsiDirectoryFactory.getInstance(myProject).getQualifiedName(parent, false).length() == 0) break; PsiElement[] children = parent.getChildren(); if (children.length == 0 || children.length == 1 && children[0] == directory) { directory = parent; } else { break; } } elements[idx] = directory; } final VirtualFile virtualFile = directory.getVirtualFile(); final String path = virtualFile.getPath(); if (path.endsWith(JarFileSystem.JAR_SEPARATOR)) { // if is jar-file root final VirtualFile vFile = LocalFileSystem.getInstance().findFileByPath(path.substring(0, path.length() - JarFileSystem.JAR_SEPARATOR.length())); if (vFile != null) { final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(vFile); if (psiFile != null) { elements[idx] = psiFile; } } } } } return elements; } } private final class MyPanel extends JPanel implements DataProvider { MyPanel() { super(new BorderLayout()); } @Nullable private Object getSelectedNodeElement() { final AbstractProjectViewPane currentProjectViewPane = getCurrentProjectViewPane(); if (currentProjectViewPane == null) { // can happen if not initialized yet return null; } DefaultMutableTreeNode node = currentProjectViewPane.getSelectedNode(); if (node == null) { return null; } Object userObject = node.getUserObject(); if (userObject instanceof AbstractTreeNode) { return ((AbstractTreeNode)userObject).getValue(); } if (!(userObject instanceof NodeDescriptor)) { return null; } return ((NodeDescriptor)userObject).getElement(); } @Override public Object getData(String dataId) { final AbstractProjectViewPane currentProjectViewPane = getCurrentProjectViewPane(); if (currentProjectViewPane != null) { final Object paneSpecificData = currentProjectViewPane.getData(dataId); if (paneSpecificData != null) return paneSpecificData; } if (CommonDataKeys.PSI_ELEMENT.is(dataId)) { if (currentProjectViewPane == null) return null; final PsiElement[] elements = currentProjectViewPane.getSelectedPSIElements(); return elements.length == 1 ? elements[0] : null; } if (LangDataKeys.PSI_ELEMENT_ARRAY.is(dataId)) { if (currentProjectViewPane == null) { return null; } PsiElement[] elements = currentProjectViewPane.getSelectedPSIElements(); return elements.length == 0 ? null : elements; } if (LangDataKeys.MODULE.is(dataId)) { VirtualFile[] virtualFiles = (VirtualFile[])getData(CommonDataKeys.VIRTUAL_FILE_ARRAY.getName()); if (virtualFiles == null || virtualFiles.length <= 1) return null; final Set<Module> modules = new HashSet<>(); for (VirtualFile virtualFile : virtualFiles) { modules.add(ModuleUtilCore.findModuleForFile(virtualFile, myProject)); } return modules.size() == 1 ? modules.iterator().next() : null; } if (LangDataKeys.TARGET_PSI_ELEMENT.is(dataId)) { return null; } if (PlatformDataKeys.CUT_PROVIDER.is(dataId)) { return myCopyPasteDelegator.getCutProvider(); } if (PlatformDataKeys.COPY_PROVIDER.is(dataId)) { return myCopyPasteDelegator.getCopyProvider(); } if (PlatformDataKeys.PASTE_PROVIDER.is(dataId)) { return myCopyPasteDelegator.getPasteProvider(); } if (LangDataKeys.IDE_VIEW.is(dataId)) { return myIdeView; } if (PlatformDataKeys.DELETE_ELEMENT_PROVIDER.is(dataId)) { final Module[] modules = getSelectedModules(); if (modules != null) { return myDeleteModuleProvider; } final LibraryOrderEntry orderEntry = getSelectedLibrary(); if (orderEntry != null) { return new DeleteProvider() { @Override public void deleteElement(@NotNull DataContext dataContext) { detachLibrary(orderEntry, myProject); } @Override public boolean canDeleteElement(@NotNull DataContext dataContext) { return true; } }; } return myDeletePSIElementProvider; } if (PlatformDataKeys.HELP_ID.is(dataId)) { return HelpID.PROJECT_VIEWS; } if (ProjectViewImpl.DATA_KEY.is(dataId)) { return ProjectViewImpl.this; } if (PlatformDataKeys.PROJECT_CONTEXT.is(dataId)) { Object selected = getSelectedNodeElement(); return selected instanceof Project ? selected : null; } if (LangDataKeys.MODULE_CONTEXT.is(dataId)) { Object selected = getSelectedNodeElement(); if (selected instanceof Module) { return !((Module)selected).isDisposed() ? selected : null; } else if (selected instanceof PsiDirectory) { return moduleBySingleContentRoot(((PsiDirectory)selected).getVirtualFile()); } else if (selected instanceof VirtualFile) { return moduleBySingleContentRoot((VirtualFile)selected); } else { return null; } } if (LangDataKeys.MODULE_CONTEXT_ARRAY.is(dataId)) { return getSelectedModules(); } if (ModuleGroup.ARRAY_DATA_KEY.is(dataId)) { final List<ModuleGroup> selectedElements = getSelectedElements(ModuleGroup.class); return selectedElements.isEmpty() ? null : selectedElements.toArray(new ModuleGroup[selectedElements.size()]); } if (LibraryGroupElement.ARRAY_DATA_KEY.is(dataId)) { final List<LibraryGroupElement> selectedElements = getSelectedElements(LibraryGroupElement.class); return selectedElements.isEmpty() ? null : selectedElements.toArray(new LibraryGroupElement[selectedElements.size()]); } if (NamedLibraryElement.ARRAY_DATA_KEY.is(dataId)) { final List<NamedLibraryElement> selectedElements = getSelectedElements(NamedLibraryElement.class); return selectedElements.isEmpty() ? null : selectedElements.toArray(new NamedLibraryElement[selectedElements.size()]); } return null; } @Nullable private LibraryOrderEntry getSelectedLibrary() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); DefaultMutableTreeNode node = viewPane != null ? viewPane.getSelectedNode() : null; if (node == null) return null; DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent(); if (parent == null) return null; Object userObject = parent.getUserObject(); if (userObject instanceof LibraryGroupNode) { userObject = node.getUserObject(); if (userObject instanceof NamedLibraryElementNode) { NamedLibraryElement element = ((NamedLibraryElementNode)userObject).getValue(); OrderEntry orderEntry = element.getOrderEntry(); return orderEntry instanceof LibraryOrderEntry ? (LibraryOrderEntry)orderEntry : null; } PsiDirectory directory = ((PsiDirectoryNode)userObject).getValue(); VirtualFile virtualFile = directory.getVirtualFile(); Module module = (Module)((AbstractTreeNode)((DefaultMutableTreeNode)parent.getParent()).getUserObject()).getValue(); if (module == null) return null; ModuleFileIndex index = ModuleRootManager.getInstance(module).getFileIndex(); OrderEntry entry = index.getOrderEntryForFile(virtualFile); if (entry instanceof LibraryOrderEntry) { return (LibraryOrderEntry)entry; } } return null; } private void detachLibrary(@NotNull final LibraryOrderEntry orderEntry, @NotNull Project project) { final Module module = orderEntry.getOwnerModule(); String message = IdeBundle.message("detach.library.from.module", orderEntry.getPresentableName(), module.getName()); String title = IdeBundle.message("detach.library"); int ret = Messages.showOkCancelDialog(project, message, title, Messages.getQuestionIcon()); if (ret != Messages.OK) return; CommandProcessor.getInstance().executeCommand(module.getProject(), () -> { final Runnable action = () -> { ModuleRootManager rootManager = ModuleRootManager.getInstance(module); OrderEntry[] orderEntries = rootManager.getOrderEntries(); ModifiableRootModel model = rootManager.getModifiableModel(); OrderEntry[] modifiableEntries = model.getOrderEntries(); for (int i = 0; i < orderEntries.length; i++) { OrderEntry entry = orderEntries[i]; if (entry instanceof LibraryOrderEntry && ((LibraryOrderEntry)entry).getLibrary() == orderEntry.getLibrary()) { model.removeOrderEntry(modifiableEntries[i]); } } model.commit(); }; ApplicationManager.getApplication().runWriteAction(action); }, title, null); } @Nullable private Module[] getSelectedModules() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane == null) return null; final Object[] elements = viewPane.getSelectedElements(); ArrayList<Module> result = new ArrayList<>(); for (Object element : elements) { if (element instanceof Module) { final Module module = (Module)element; if (!module.isDisposed()) { result.add(module); } } else if (element instanceof ModuleGroup) { Collection<Module> modules = ((ModuleGroup)element).modulesInGroup(myProject, true); result.addAll(modules); } else if (element instanceof PsiDirectory) { Module module = moduleBySingleContentRoot(((PsiDirectory)element).getVirtualFile()); if (module != null) result.add(module); } else if (element instanceof VirtualFile) { Module module = moduleBySingleContentRoot((VirtualFile)element); if (module != null) result.add(module); } } if (result.isEmpty()) { return null; } else { return result.toArray(new Module[result.size()]); } } } /** Project view has the same node for module and its single content root * => MODULE_CONTEXT data key should return the module when its content root is selected * When there are multiple content roots, they have different nodes under the module node * => MODULE_CONTEXT should be only available for the module node * otherwise VirtualFileArrayRule will return all module's content roots when just one of them is selected */ @Nullable private Module moduleBySingleContentRoot(@NotNull VirtualFile file) { if (ProjectRootsUtil.isModuleContentRoot(file, myProject)) { Module module = ProjectRootManager.getInstance(myProject).getFileIndex().getModuleForFile(file); if (module != null && !module.isDisposed() && ModuleRootManager.getInstance(module).getContentRoots().length == 1) { return module; } } return null; } @NotNull private <T> List<T> getSelectedElements(@NotNull Class<T> klass) { List<T> result = new ArrayList<>(); final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane == null) return result; final Object[] elements = viewPane.getSelectedElements(); for (Object element : elements) { //element still valid if (element != null && klass.isAssignableFrom(element.getClass())) { result.add((T)element); } } return result; } private final class MyIdeView implements IdeView { @Override public void selectElement(PsiElement element) { selectPsiElement(element, false); boolean requestFocus = true; if (element != null) { final boolean isDirectory = element instanceof PsiDirectory; if (!isDirectory) { FileEditor editor = EditorHelper.openInEditor(element, false); if (editor != null) { ToolWindowManager.getInstance(myProject).activateEditorComponent(); requestFocus = false; } } } if (requestFocus) { selectPsiElement(element, true); } } @NotNull @Override public PsiDirectory[] getDirectories() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane != null) { return viewPane.getSelectedDirectories(); } return PsiDirectory.EMPTY_ARRAY; } @Override public PsiDirectory getOrChooseDirectory() { return DirectoryChooserUtil.getOrChooseDirectory(this); } } @Override public void selectPsiElement(PsiElement element, boolean requestFocus) { if (element == null) return; VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element); select(element, virtualFile, requestFocus); } private static void readOption(Element node, @NotNull Map<String, Boolean> options) { if (node == null) return; for (Attribute attribute : node.getAttributes()) { options.put(attribute.getName(), Boolean.TRUE.toString().equals(attribute.getValue()) ? Boolean.TRUE : Boolean.FALSE); } } private static void writeOption(@NotNull Element parentNode, @NotNull Map<String, Boolean> optionsForPanes, @NotNull String optionName) { Element e = new Element(optionName); for (Map.Entry<String, Boolean> entry : optionsForPanes.entrySet()) { final String key = entry.getKey(); if (key != null) { //SCR48267 e.setAttribute(key, Boolean.toString(entry.getValue().booleanValue())); } } parentNode.addContent(e); } @Override public void loadState(Element parentNode) { Element navigatorElement = parentNode.getChild(ELEMENT_NAVIGATOR); if (navigatorElement != null) { mySavedPaneId = navigatorElement.getAttributeValue(ATTRIBUTE_CURRENT_VIEW); mySavedPaneSubId = navigatorElement.getAttributeValue(ATTRIBUTE_CURRENT_SUBVIEW); if (mySavedPaneId == null) { mySavedPaneId = ProjectViewPane.ID; mySavedPaneSubId = null; } readOption(navigatorElement.getChild(ELEMENT_FLATTEN_PACKAGES), myFlattenPackages); readOption(navigatorElement.getChild(ELEMENT_SHOW_MEMBERS), myShowMembers); readOption(navigatorElement.getChild(ELEMENT_SHOW_MODULES), myShowModules); readOption(navigatorElement.getChild(ELEMENT_SHOW_LIBRARY_CONTENTS), myShowLibraryContents); readOption(navigatorElement.getChild(ELEMENT_HIDE_EMPTY_PACKAGES), myHideEmptyPackages); readOption(navigatorElement.getChild(ELEMENT_ABBREVIATE_PACKAGE_NAMES), myAbbreviatePackageNames); readOption(navigatorElement.getChild(ELEMENT_AUTOSCROLL_TO_SOURCE), myAutoscrollToSource); readOption(navigatorElement.getChild(ELEMENT_AUTOSCROLL_FROM_SOURCE), myAutoscrollFromSource); readOption(navigatorElement.getChild(ELEMENT_SORT_BY_TYPE), mySortByType); readOption(navigatorElement.getChild(ELEMENT_MANUAL_ORDER), myManualOrder); Element foldersElement = navigatorElement.getChild(ELEMENT_FOLDERS_ALWAYS_ON_TOP); if (foldersElement != null) myFoldersAlwaysOnTop = Boolean.valueOf(foldersElement.getAttributeValue("value")); try { splitterProportions.readExternal(navigatorElement); } catch (InvalidDataException e) { // ignore } } Element panesElement = parentNode.getChild(ELEMENT_PANES); if (panesElement != null) { readPaneState(panesElement); } } private void readPaneState(@NotNull Element panesElement) { @SuppressWarnings({"unchecked"}) final List<Element> paneElements = panesElement.getChildren(ELEMENT_PANE); for (Element paneElement : paneElements) { String paneId = paneElement.getAttributeValue(ATTRIBUTE_ID); final AbstractProjectViewPane pane = myId2Pane.get(paneId); if (pane != null) { try { pane.readExternal(paneElement); } catch (InvalidDataException e) { // ignore } } else { myUninitializedPaneState.put(paneId, paneElement); } } } @Override public Element getState() { Element parentNode = new Element("projectView"); Element navigatorElement = new Element(ELEMENT_NAVIGATOR); AbstractProjectViewPane currentPane = getCurrentProjectViewPane(); if (currentPane != null) { navigatorElement.setAttribute(ATTRIBUTE_CURRENT_VIEW, currentPane.getId()); String subId = currentPane.getSubId(); if (subId != null) { navigatorElement.setAttribute(ATTRIBUTE_CURRENT_SUBVIEW, subId); } } writeOption(navigatorElement, myFlattenPackages, ELEMENT_FLATTEN_PACKAGES); writeOption(navigatorElement, myShowMembers, ELEMENT_SHOW_MEMBERS); writeOption(navigatorElement, myShowModules, ELEMENT_SHOW_MODULES); writeOption(navigatorElement, myShowLibraryContents, ELEMENT_SHOW_LIBRARY_CONTENTS); writeOption(navigatorElement, myHideEmptyPackages, ELEMENT_HIDE_EMPTY_PACKAGES); writeOption(navigatorElement, myAbbreviatePackageNames, ELEMENT_ABBREVIATE_PACKAGE_NAMES); writeOption(navigatorElement, myAutoscrollToSource, ELEMENT_AUTOSCROLL_TO_SOURCE); writeOption(navigatorElement, myAutoscrollFromSource, ELEMENT_AUTOSCROLL_FROM_SOURCE); writeOption(navigatorElement, mySortByType, ELEMENT_SORT_BY_TYPE); writeOption(navigatorElement, myManualOrder, ELEMENT_MANUAL_ORDER); Element foldersElement = new Element(ELEMENT_FOLDERS_ALWAYS_ON_TOP); foldersElement.setAttribute("value", Boolean.toString(myFoldersAlwaysOnTop)); navigatorElement.addContent(foldersElement); splitterProportions.saveSplitterProportions(myPanel); try { splitterProportions.writeExternal(navigatorElement); } catch (WriteExternalException e) { // ignore } parentNode.addContent(navigatorElement); Element panesElement = new Element(ELEMENT_PANES); writePaneState(panesElement); parentNode.addContent(panesElement); return parentNode; } private void writePaneState(@NotNull Element panesElement) { for (AbstractProjectViewPane pane : myId2Pane.values()) { Element paneElement = new Element(ELEMENT_PANE); paneElement.setAttribute(ATTRIBUTE_ID, pane.getId()); try { pane.writeExternal(paneElement); } catch (WriteExternalException e) { continue; } panesElement.addContent(paneElement); } for (Element element : myUninitializedPaneState.values()) { panesElement.addContent(element.clone()); } } boolean isGlobalOptions() { return Registry.is("ide.projectView.globalOptions"); } ProjectViewSharedSettings getGlobalOptions() { return ProjectViewSharedSettings.Companion.getInstance(); } @Override public boolean isAutoscrollToSource(String paneId) { if (isGlobalOptions()) { return getGlobalOptions().getAutoscrollToSource(); } return getPaneOptionValue(myAutoscrollToSource, paneId, UISettings.getInstance().DEFAULT_AUTOSCROLL_TO_SOURCE); } public void setAutoscrollToSource(boolean autoscrollMode, String paneId) { if (isGlobalOptions()) { getGlobalOptions().setAutoscrollToSource(autoscrollMode); } myAutoscrollToSource.put(paneId, autoscrollMode); } @Override public boolean isAutoscrollFromSource(String paneId) { if (isGlobalOptions()) { return getGlobalOptions().getAutoscrollFromSource(); } return getPaneOptionValue(myAutoscrollFromSource, paneId, ourAutoscrollFromSourceDefaults); } public void setAutoscrollFromSource(boolean autoscrollMode, String paneId) { if (isGlobalOptions()) { getGlobalOptions().setAutoscrollFromSource(autoscrollMode); } setPaneOption(myAutoscrollFromSource, autoscrollMode, paneId, false); } @Override public boolean isFlattenPackages(String paneId) { if (isGlobalOptions()) { return getGlobalOptions().getFlattenPackages(); } return getPaneOptionValue(myFlattenPackages, paneId, ourFlattenPackagesDefaults); } public void setFlattenPackages(boolean flattenPackages, String paneId) { if (isGlobalOptions()) { getGlobalOptions().setFlattenPackages(flattenPackages); for (String pane : myFlattenPackages.keySet()) { setPaneOption(myFlattenPackages, flattenPackages, pane, true); } } setPaneOption(myFlattenPackages, flattenPackages, paneId, true); } public boolean isFoldersAlwaysOnTop() { if (isGlobalOptions()) { return getGlobalOptions().getFoldersAlwaysOnTop(); } return myFoldersAlwaysOnTop; } public void setFoldersAlwaysOnTop(boolean foldersAlwaysOnTop) { if (isGlobalOptions()) { getGlobalOptions().setFoldersAlwaysOnTop(foldersAlwaysOnTop); } if (myFoldersAlwaysOnTop != foldersAlwaysOnTop) { myFoldersAlwaysOnTop = foldersAlwaysOnTop; for (AbstractProjectViewPane pane : myId2Pane.values()) { if (pane.getTree() != null) { pane.updateFromRoot(false); } } } } @Override public boolean isShowMembers(String paneId) { if (isGlobalOptions()) { return getGlobalOptions().getShowMembers(); } return getPaneOptionValue(myShowMembers, paneId, ourShowMembersDefaults); } public void setShowMembers(boolean showMembers, String paneId) { setPaneOption(myShowMembers, showMembers, paneId, true); } @Override public boolean isHideEmptyMiddlePackages(String paneId) { if (isGlobalOptions()) { return getGlobalOptions().getHideEmptyPackages(); } return getPaneOptionValue(myHideEmptyPackages, paneId, ourHideEmptyPackagesDefaults); } @Override public boolean isAbbreviatePackageNames(String paneId) { if (isGlobalOptions()) { return getGlobalOptions().getAbbreviatePackages(); } return getPaneOptionValue(myAbbreviatePackageNames, paneId, ourAbbreviatePackagesDefaults); } @Override public boolean isShowLibraryContents(String paneId) { if (isGlobalOptions()) { return getGlobalOptions().getShowLibraryContents(); } return getPaneOptionValue(myShowLibraryContents, paneId, ourShowLibraryContentsDefaults); } @Override public void setShowLibraryContents(boolean showLibraryContents, @NotNull String paneId) { if (isGlobalOptions()) { getGlobalOptions().setShowLibraryContents(showLibraryContents); } setPaneOption(myShowLibraryContents, showLibraryContents, paneId, true); } @NotNull public ActionCallback setShowLibraryContentsCB(boolean showLibraryContents, String paneId) { return setPaneOption(myShowLibraryContents, showLibraryContents, paneId, true); } @Override public boolean isShowModules(String paneId) { if (isGlobalOptions()) { return getGlobalOptions().getShowModules(); } return getPaneOptionValue(myShowModules, paneId, ourShowModulesDefaults); } @Override public void setShowModules(boolean showModules, @NotNull String paneId) { if (isGlobalOptions()) { getGlobalOptions().setShowModules(showModules); } setPaneOption(myShowModules, showModules, paneId, true); } @Override public void setHideEmptyPackages(boolean hideEmptyPackages, @NotNull String paneId) { if (isGlobalOptions()) { getGlobalOptions().setHideEmptyPackages(hideEmptyPackages); for (String pane : myHideEmptyPackages.keySet()) { setPaneOption(myHideEmptyPackages, hideEmptyPackages, pane, true); } } setPaneOption(myHideEmptyPackages, hideEmptyPackages, paneId, true); } @Override public void setAbbreviatePackageNames(boolean abbreviatePackageNames, @NotNull String paneId) { if (isGlobalOptions()) { getGlobalOptions().setAbbreviatePackages(abbreviatePackageNames); } setPaneOption(myAbbreviatePackageNames, abbreviatePackageNames, paneId, true); } @NotNull private ActionCallback setPaneOption(@NotNull Map<String, Boolean> optionsMap, boolean value, String paneId, final boolean updatePane) { if (paneId != null) { optionsMap.put(paneId, value); if (updatePane) { final AbstractProjectViewPane pane = getProjectViewPaneById(paneId); if (pane != null) { return pane.updateFromRoot(false); } } } return ActionCallback.DONE; } private static boolean getPaneOptionValue(@NotNull Map<String, Boolean> optionsMap, String paneId, boolean defaultValue) { final Boolean value = optionsMap.get(paneId); return value == null ? defaultValue : value.booleanValue(); } private class HideEmptyMiddlePackagesAction extends PaneOptionAction { private HideEmptyMiddlePackagesAction() { super(myHideEmptyPackages, "", "", null, ourHideEmptyPackagesDefaults); } @Override public void setSelected(AnActionEvent event, boolean flag) { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); final SelectionInfo selectionInfo = SelectionInfo.create(viewPane); if (isGlobalOptions()) { getGlobalOptions().setHideEmptyPackages(flag); } super.setSelected(event, flag); selectionInfo.apply(viewPane); } @Override public boolean isSelected(AnActionEvent event) { if (isGlobalOptions()) return getGlobalOptions().getHideEmptyPackages(); return super.isSelected(event); } @Override public void update(AnActionEvent e) { super.update(e); final Presentation presentation = e.getPresentation(); if (isHideEmptyMiddlePackages(myCurrentViewId)) { presentation.setText(IdeBundle.message("action.hide.empty.middle.packages")); presentation.setDescription(IdeBundle.message("action.show.hide.empty.middle.packages")); } else { presentation.setText(IdeBundle.message("action.compact.empty.middle.packages")); presentation.setDescription(IdeBundle.message("action.show.compact.empty.middle.packages")); } } } private static class SelectionInfo { private final Object[] myElements; private SelectionInfo(@NotNull Object[] elements) { myElements = elements; } public void apply(final AbstractProjectViewPane viewPane) { if (viewPane == null) { return; } AbstractTreeBuilder treeBuilder = viewPane.getTreeBuilder(); JTree tree = viewPane.myTree; DefaultTreeModel treeModel = (DefaultTreeModel)tree.getModel(); List<TreePath> paths = new ArrayList<>(myElements.length); for (final Object element : myElements) { DefaultMutableTreeNode node = treeBuilder.getNodeForElement(element); if (node == null) { treeBuilder.buildNodeForElement(element); node = treeBuilder.getNodeForElement(element); } if (node != null) { paths.add(new TreePath(treeModel.getPathToRoot(node))); } } if (!paths.isEmpty()) { tree.setSelectionPaths(paths.toArray(new TreePath[paths.size()])); } } @NotNull public static SelectionInfo create(final AbstractProjectViewPane viewPane) { List<Object> selectedElements = Collections.emptyList(); if (viewPane != null) { final TreePath[] selectionPaths = viewPane.getSelectionPaths(); if (selectionPaths != null) { selectedElements = new ArrayList<>(); for (TreePath path : selectionPaths) { final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); final Object userObject = node.getUserObject(); if (userObject instanceof NodeDescriptor) { selectedElements.add(((NodeDescriptor)userObject).getElement()); } } } } return new SelectionInfo(selectedElements.toArray()); } } private class MyAutoScrollFromSourceHandler extends AutoScrollFromSourceHandler { private MyAutoScrollFromSourceHandler() { super(ProjectViewImpl.this.myProject, myViewContentPanel, ProjectViewImpl.this); } @Override protected void selectElementFromEditor(@NotNull FileEditor fileEditor) { if (myProject.isDisposed() || !myViewContentPanel.isShowing()) return; if (isAutoscrollFromSource(getCurrentViewId())) { if (fileEditor instanceof TextEditor) { Editor editor = ((TextEditor)fileEditor).getEditor(); selectElementAtCaretNotLosingFocus(editor); } else { final VirtualFile file = FileEditorManagerEx.getInstanceEx(myProject).getFile(fileEditor); if (file != null) { final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file); if (psiFile != null) { final SelectInTarget target = mySelectInTargets.get(getCurrentViewId()); if (target != null) { final MySelectInContext selectInContext = new MySelectInContext(psiFile, null) { @Override public Object getSelectorInFile() { return psiFile; } }; if (target.canSelect(selectInContext)) { target.selectIn(selectInContext, false); } } } } } } } public void scrollFromSource() { final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject); final Editor selectedTextEditor = fileEditorManager.getSelectedTextEditor(); if (selectedTextEditor != null) { selectElementAtCaret(selectedTextEditor); return; } final FileEditor[] editors = fileEditorManager.getSelectedEditors(); for (FileEditor fileEditor : editors) { if (fileEditor instanceof TextEditor) { Editor editor = ((TextEditor)fileEditor).getEditor(); selectElementAtCaret(editor); return; } } final VirtualFile[] selectedFiles = fileEditorManager.getSelectedFiles(); if (selectedFiles.length > 0) { final PsiFile file = PsiManager.getInstance(myProject).findFile(selectedFiles[0]); if (file != null) { scrollFromFile(file, null); } } } private void selectElementAtCaretNotLosingFocus(@NotNull Editor editor) { AbstractProjectViewPane pane = getCurrentProjectViewPane(); if (pane != null && !IJSwingUtilities.hasFocus(pane.getComponentToFocus())) { selectElementAtCaret(editor); } } private void selectElementAtCaret(@NotNull Editor editor) { final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(editor.getDocument()); if (file == null) return; scrollFromFile(file, editor); } private void scrollFromFile(@NotNull PsiFile file, @Nullable Editor editor) { PsiDocumentManager.getInstance(myProject).performWhenAllCommitted(() -> { final MySelectInContext selectInContext = new MySelectInContext(file, editor); final SelectInTarget target = mySelectInTargets.get(getCurrentViewId()); if (target != null && target.canSelect(selectInContext)) { target.selectIn(selectInContext, false); } }); } @Override protected boolean isAutoScrollEnabled() { return isAutoscrollFromSource(myCurrentViewId); } @Override protected void setAutoScrollEnabled(boolean state) { setAutoscrollFromSource(state, myCurrentViewId); if (state) { final Editor editor = myFileEditorManager.getSelectedTextEditor(); if (editor != null) { selectElementAtCaretNotLosingFocus(editor); } } createToolbarActions(); } private class MySelectInContext implements SelectInContext { @NotNull private final PsiFile myPsiFile; @Nullable private final Editor myEditor; private MySelectInContext(@NotNull PsiFile psiFile, @Nullable Editor editor) { myPsiFile = psiFile; myEditor = editor; } @Override @NotNull public Project getProject() { return myProject; } @NotNull private PsiFile getPsiFile() { return myPsiFile; } @Override @NotNull public FileEditorProvider getFileEditorProvider() { return new FileEditorProvider() { @Override public FileEditor openFileEditor() { return myFileEditorManager.openFile(myPsiFile.getContainingFile().getVirtualFile(), false)[0]; } }; } @NotNull private PsiElement getPsiElement() { PsiElement e = null; if (myEditor != null) { final int offset = myEditor.getCaretModel().getOffset(); if (PsiDocumentManager.getInstance(myProject).hasUncommitedDocuments()) { PsiDocumentManager.getInstance(myProject).commitAllDocuments(); } e = getPsiFile().findElementAt(offset); } if (e == null) { e = getPsiFile(); } return e; } @Override @NotNull public VirtualFile getVirtualFile() { return getPsiFile().getVirtualFile(); } @Override public Object getSelectorInFile() { return getPsiElement(); } } } @Override public boolean isManualOrder(String paneId) { return getPaneOptionValue(myManualOrder, paneId, ourManualOrderDefaults); } @Override public void setManualOrder(@NotNull String paneId, final boolean enabled) { setPaneOption(myManualOrder, enabled, paneId, false); final AbstractProjectViewPane pane = getProjectViewPaneById(paneId); pane.installComparator(); } @Override public boolean isSortByType(String paneId) { return getPaneOptionValue(mySortByType, paneId, ourSortByTypeDefaults); } @Override public void setSortByType(@NotNull String paneId, final boolean sortByType) { setPaneOption(mySortByType, sortByType, paneId, false); final AbstractProjectViewPane pane = getProjectViewPaneById(paneId); pane.installComparator(); } private class ManualOrderAction extends ToggleAction implements DumbAware { private ManualOrderAction() { super(IdeBundle.message("action.manual.order"), IdeBundle.message("action.manual.order"), AllIcons.ObjectBrowser.Sorted); } @Override public boolean isSelected(AnActionEvent event) { return isManualOrder(getCurrentViewId()); } @Override public void setSelected(AnActionEvent event, boolean flag) { setManualOrder(getCurrentViewId(), flag); } @Override public void update(final AnActionEvent e) { super.update(e); final Presentation presentation = e.getPresentation(); AbstractProjectViewPane pane = getCurrentProjectViewPane(); presentation.setEnabledAndVisible(pane != null && pane.supportsManualOrder()); } } private class SortByTypeAction extends ToggleAction implements DumbAware { private SortByTypeAction() { super(IdeBundle.message("action.sort.by.type"), IdeBundle.message("action.sort.by.type"), AllIcons.ObjectBrowser.SortByType); } @Override public boolean isSelected(AnActionEvent event) { return isSortByType(getCurrentViewId()); } @Override public void setSelected(AnActionEvent event, boolean flag) { setSortByType(getCurrentViewId(), flag); } @Override public void update(final AnActionEvent e) { super.update(e); final Presentation presentation = e.getPresentation(); presentation.setVisible(getCurrentProjectViewPane() != null); } } private class FoldersAlwaysOnTopAction extends ToggleAction implements DumbAware { private FoldersAlwaysOnTopAction() { super("Folders Always on Top"); } @Override public boolean isSelected(AnActionEvent event) { return isFoldersAlwaysOnTop(); } @Override public void setSelected(AnActionEvent event, boolean flag) { setFoldersAlwaysOnTop(flag); } @Override public void update(final AnActionEvent e) { super.update(e); final Presentation presentation = e.getPresentation(); presentation.setEnabledAndVisible(getCurrentProjectViewPane() != null); } } private class ScrollFromSourceAction extends AnAction implements DumbAware { private ScrollFromSourceAction() { super("Scroll from Source", "Select the file open in the active editor", AllIcons.General.Locate); getTemplatePresentation().setHoveredIcon(AllIcons.General.LocateHover); } @Override public void actionPerformed(AnActionEvent e) { myAutoScrollFromSourceHandler.scrollFromSource(); } } @NotNull @Override public Collection<String> getPaneIds() { return myId2Pane.keySet(); } @NotNull @Override public Collection<SelectInTarget> getSelectInTargets() { ensurePanesLoaded(); return mySelectInTargets.values(); } @NotNull @Override public ActionCallback getReady(@NotNull Object requestor) { AbstractProjectViewPane pane = myId2Pane.get(myCurrentViewSubId); if (pane == null) { pane = myId2Pane.get(myCurrentViewId); } return pane != null ? pane.getReady(requestor) : ActionCallback.DONE; } }
platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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.intellij.ide.projectView.impl; import com.intellij.ProjectTopics; import com.intellij.history.LocalHistory; import com.intellij.history.LocalHistoryAction; import com.intellij.icons.AllIcons; import com.intellij.ide.*; import com.intellij.ide.impl.ProjectViewSelectInTarget; import com.intellij.ide.projectView.HelpID; import com.intellij.ide.projectView.ProjectView; import com.intellij.ide.projectView.ProjectViewNode; import com.intellij.ide.projectView.impl.nodes.*; import com.intellij.ide.scopeView.ScopeViewPane; import com.intellij.ide.ui.SplitterProportionsDataImpl; import com.intellij.ide.ui.UISettings; import com.intellij.ide.util.DeleteHandler; import com.intellij.ide.util.DirectoryChooserUtil; import com.intellij.ide.util.EditorHelper; import com.intellij.ide.util.treeView.AbstractTreeBuilder; import com.intellij.ide.util.treeView.AbstractTreeNode; import com.intellij.ide.util.treeView.NodeDescriptor; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.components.StoragePathMacros; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.ui.configuration.actions.ModuleDeleteProvider; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.SimpleToolWindowPanel; import com.intellij.openapi.ui.SplitterProportionsData; import com.intellij.openapi.ui.popup.PopupChooserBuilder; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.*; import com.intellij.openapi.wm.ex.ToolWindowEx; import com.intellij.openapi.wm.ex.ToolWindowManagerAdapter; import com.intellij.openapi.wm.ex.ToolWindowManagerEx; import com.intellij.openapi.wm.impl.content.ToolWindowContentUi; import com.intellij.psi.*; import com.intellij.psi.impl.file.PsiDirectoryFactory; import com.intellij.psi.util.PsiUtilCore; import com.intellij.ui.AutoScrollFromSourceHandler; import com.intellij.ui.AutoScrollToSourceHandler; import com.intellij.ui.GuiUtils; import com.intellij.ui.components.JBList; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentManager; import com.intellij.ui.content.ContentManagerAdapter; import com.intellij.ui.content.ContentManagerEvent; import com.intellij.util.ArrayUtil; import com.intellij.util.IJSwingUtilities; import com.intellij.util.PlatformIcons; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jdom.Attribute; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import java.awt.*; import java.util.*; import java.util.List; @State(name = "ProjectView", storages = @Storage(StoragePathMacros.WORKSPACE_FILE)) public class ProjectViewImpl extends ProjectView implements PersistentStateComponent<Element>, Disposable, BusyObject { private static final Logger LOG = Logger.getInstance("#com.intellij.ide.projectView.impl.ProjectViewImpl"); private static final Key<String> ID_KEY = Key.create("pane-id"); private static final Key<String> SUB_ID_KEY = Key.create("pane-sub-id"); private final CopyPasteDelegator myCopyPasteDelegator; private boolean isInitialized; private boolean myExtensionsLoaded = false; @NotNull private final Project myProject; // + options private final Map<String, Boolean> myFlattenPackages = new THashMap<>(); private static final boolean ourFlattenPackagesDefaults = false; private final Map<String, Boolean> myShowMembers = new THashMap<>(); private static final boolean ourShowMembersDefaults = false; private final Map<String, Boolean> myManualOrder = new THashMap<>(); private static final boolean ourManualOrderDefaults = false; private final Map<String, Boolean> mySortByType = new THashMap<>(); private static final boolean ourSortByTypeDefaults = false; private final Map<String, Boolean> myShowModules = new THashMap<>(); private static final boolean ourShowModulesDefaults = true; private final Map<String, Boolean> myShowLibraryContents = new THashMap<>(); private static final boolean ourShowLibraryContentsDefaults = true; private final Map<String, Boolean> myHideEmptyPackages = new THashMap<>(); private static final boolean ourHideEmptyPackagesDefaults = true; private final Map<String, Boolean> myAbbreviatePackageNames = new THashMap<>(); private static final boolean ourAbbreviatePackagesDefaults = false; private final Map<String, Boolean> myAutoscrollToSource = new THashMap<>(); private final Map<String, Boolean> myAutoscrollFromSource = new THashMap<>(); private static final boolean ourAutoscrollFromSourceDefaults = false; private boolean myFoldersAlwaysOnTop = true; private String myCurrentViewId; private String myCurrentViewSubId; // - options private final AutoScrollToSourceHandler myAutoScrollToSourceHandler; private final MyAutoScrollFromSourceHandler myAutoScrollFromSourceHandler; private final IdeView myIdeView = new MyIdeView(); private final MyDeletePSIElementProvider myDeletePSIElementProvider = new MyDeletePSIElementProvider(); private final ModuleDeleteProvider myDeleteModuleProvider = new ModuleDeleteProvider(); private SimpleToolWindowPanel myPanel; private final Map<String, AbstractProjectViewPane> myId2Pane = new LinkedHashMap<>(); private final Collection<AbstractProjectViewPane> myUninitializedPanes = new THashSet<>(); static final DataKey<ProjectViewImpl> DATA_KEY = DataKey.create("com.intellij.ide.projectView.impl.ProjectViewImpl"); private DefaultActionGroup myActionGroup; private String mySavedPaneId = ProjectViewPane.ID; private String mySavedPaneSubId; //private static final Icon COMPACT_EMPTY_MIDDLE_PACKAGES_ICON = IconLoader.getIcon("/objectBrowser/compactEmptyPackages.png"); //private static final Icon HIDE_EMPTY_MIDDLE_PACKAGES_ICON = IconLoader.getIcon("/objectBrowser/hideEmptyPackages.png"); @NonNls private static final String ELEMENT_NAVIGATOR = "navigator"; @NonNls private static final String ELEMENT_PANES = "panes"; @NonNls private static final String ELEMENT_PANE = "pane"; @NonNls private static final String ATTRIBUTE_CURRENT_VIEW = "currentView"; @NonNls private static final String ATTRIBUTE_CURRENT_SUBVIEW = "currentSubView"; @NonNls private static final String ELEMENT_FLATTEN_PACKAGES = "flattenPackages"; @NonNls private static final String ELEMENT_SHOW_MEMBERS = "showMembers"; @NonNls private static final String ELEMENT_SHOW_MODULES = "showModules"; @NonNls private static final String ELEMENT_SHOW_LIBRARY_CONTENTS = "showLibraryContents"; @NonNls private static final String ELEMENT_HIDE_EMPTY_PACKAGES = "hideEmptyPackages"; @NonNls private static final String ELEMENT_ABBREVIATE_PACKAGE_NAMES = "abbreviatePackageNames"; @NonNls private static final String ELEMENT_AUTOSCROLL_TO_SOURCE = "autoscrollToSource"; @NonNls private static final String ELEMENT_AUTOSCROLL_FROM_SOURCE = "autoscrollFromSource"; @NonNls private static final String ELEMENT_SORT_BY_TYPE = "sortByType"; @NonNls private static final String ELEMENT_FOLDERS_ALWAYS_ON_TOP = "foldersAlwaysOnTop"; @NonNls private static final String ELEMENT_MANUAL_ORDER = "manualOrder"; private static final String ATTRIBUTE_ID = "id"; private JPanel myViewContentPanel; private static final Comparator<AbstractProjectViewPane> PANE_WEIGHT_COMPARATOR = (o1, o2) -> o1.getWeight() - o2.getWeight(); private final FileEditorManager myFileEditorManager; private final MyPanel myDataProvider; private final SplitterProportionsData splitterProportions = new SplitterProportionsDataImpl(); private final MessageBusConnection myConnection; private final Map<String, Element> myUninitializedPaneState = new HashMap<>(); private final Map<String, SelectInTarget> mySelectInTargets = new LinkedHashMap<>(); private ContentManager myContentManager; public ProjectViewImpl(@NotNull Project project, final FileEditorManager fileEditorManager, final ToolWindowManagerEx toolWindowManager) { myProject = project; constructUi(); myFileEditorManager = fileEditorManager; myConnection = project.getMessageBus().connect(); myConnection.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootAdapter() { @Override public void rootsChanged(ModuleRootEvent event) { refresh(); } }); myAutoScrollFromSourceHandler = new MyAutoScrollFromSourceHandler(); myDataProvider = new MyPanel(); myDataProvider.add(myPanel, BorderLayout.CENTER); myCopyPasteDelegator = new CopyPasteDelegator(myProject, myPanel) { @Override @NotNull protected PsiElement[] getSelectedElements() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); return viewPane == null ? PsiElement.EMPTY_ARRAY : viewPane.getSelectedPSIElements(); } }; myAutoScrollToSourceHandler = new AutoScrollToSourceHandler() { @Override protected boolean isAutoScrollMode() { return isAutoscrollToSource(myCurrentViewId); } @Override protected void setAutoScrollMode(boolean state) { setAutoscrollToSource(state, myCurrentViewId); } }; toolWindowManager.addToolWindowManagerListener(new ToolWindowManagerAdapter(){ private boolean toolWindowVisible; @Override public void stateChanged() { ToolWindow window = toolWindowManager.getToolWindow(ToolWindowId.PROJECT_VIEW); if (window == null) return; if (window.isVisible() && !toolWindowVisible) { String id = getCurrentViewId(); if (isAutoscrollToSource(id)) { AbstractProjectViewPane currentProjectViewPane = getCurrentProjectViewPane(); if (currentProjectViewPane != null) { myAutoScrollToSourceHandler.onMouseClicked(currentProjectViewPane.getTree()); } } if (isAutoscrollFromSource(id)) { myAutoScrollFromSourceHandler.setAutoScrollEnabled(true); } } toolWindowVisible = window.isVisible(); } }); } private void constructUi() { myViewContentPanel = new JPanel(); myPanel = new SimpleToolWindowPanel(true); myPanel.setContent(myViewContentPanel); } @NotNull @Deprecated public List<AnAction> getActions(boolean originalProvider) { return Collections.emptyList(); } @Override public synchronized void addProjectPane(@NotNull final AbstractProjectViewPane pane) { myUninitializedPanes.add(pane); SelectInTarget selectInTarget = pane.createSelectInTarget(); if (selectInTarget != null) { mySelectInTargets.put(pane.getId(), selectInTarget); } if (isInitialized) { doAddUninitializedPanes(); } } @Override public synchronized void removeProjectPane(@NotNull AbstractProjectViewPane pane) { ApplicationManager.getApplication().assertIsDispatchThread(); myUninitializedPanes.remove(pane); //assume we are completely initialized here String idToRemove = pane.getId(); if (!myId2Pane.containsKey(idToRemove)) return; pane.removeTreeChangeListener(); for (int i = getContentManager().getContentCount() - 1; i >= 0; i--) { Content content = getContentManager().getContent(i); String id = content != null ? content.getUserData(ID_KEY) : null; if (id != null && id.equals(idToRemove)) { getContentManager().removeContent(content, true); } } myId2Pane.remove(idToRemove); mySelectInTargets.remove(idToRemove); viewSelectionChanged(); } private synchronized void doAddUninitializedPanes() { for (AbstractProjectViewPane pane : myUninitializedPanes) { doAddPane(pane); } final Content[] contents = getContentManager().getContents(); for (int i = 1; i < contents.length; i++) { Content content = contents[i]; Content prev = contents[i - 1]; if (!StringUtil.equals(content.getUserData(ID_KEY), prev.getUserData(ID_KEY)) && prev.getUserData(SUB_ID_KEY) != null && content.getSeparator() == null) { content.setSeparator(""); } } String selectID = null; String selectSubID = null; // try to find saved selected view... for (Content content : contents) { final String id = content.getUserData(ID_KEY); final String subId = content.getUserData(SUB_ID_KEY); if (id != null && id.equals(mySavedPaneId) && StringUtil.equals(subId, mySavedPaneSubId)) { selectID = id; selectSubID = subId; break; } } // saved view not found (plugin disabled, ID changed etc.) - select first available view... if (selectID == null && contents.length > 0) { Content content = contents[0]; selectID = content.getUserData(ID_KEY); selectSubID = content.getUserData(SUB_ID_KEY); } if (selectID != null) { changeView(selectID, selectSubID); mySavedPaneId = null; mySavedPaneSubId = null; } myUninitializedPanes.clear(); } private void doAddPane(@NotNull final AbstractProjectViewPane newPane) { ApplicationManager.getApplication().assertIsDispatchThread(); int index; final ContentManager manager = getContentManager(); for (index = 0; index < manager.getContentCount(); index++) { Content content = manager.getContent(index); String id = content.getUserData(ID_KEY); AbstractProjectViewPane pane = myId2Pane.get(id); int comp = PANE_WEIGHT_COMPARATOR.compare(pane, newPane); LOG.assertTrue(comp != 0, "Project view pane " + newPane + " has the same weight as " + pane + ". Please make sure that you overload getWeight() and return a distinct weight value."); if (comp > 0) { break; } } final String id = newPane.getId(); myId2Pane.put(id, newPane); String[] subIds = newPane.getSubIds(); subIds = subIds.length == 0 ? new String[]{null} : subIds; boolean first = true; for (String subId : subIds) { final String title = subId != null ? newPane.getPresentableSubIdName(subId) : newPane.getTitle(); final Content content = getContentManager().getFactory().createContent(getComponent(), title, false); content.setTabName(title); content.putUserData(ID_KEY, id); content.putUserData(SUB_ID_KEY, subId); content.putUserData(ToolWindow.SHOW_CONTENT_ICON, Boolean.TRUE); content.setIcon(newPane.getIcon()); content.setPopupIcon(subId != null ? AllIcons.General.Bullet : newPane.getIcon()); content.setPreferredFocusedComponent(() -> { final AbstractProjectViewPane current = getCurrentProjectViewPane(); return current != null ? current.getComponentToFocus() : null; }); content.setBusyObject(this); if (first && subId != null) { content.setSeparator(newPane.getTitle()); } manager.addContent(content, index++); first = false; } } private void showPane(@NotNull AbstractProjectViewPane newPane) { AbstractProjectViewPane currentPane = getCurrentProjectViewPane(); PsiElement selectedPsiElement = null; if (currentPane != null) { if (currentPane != newPane) { currentPane.saveExpandedPaths(); } final PsiElement[] elements = currentPane.getSelectedPSIElements(); if (elements.length > 0) { selectedPsiElement = elements[0]; } } myViewContentPanel.removeAll(); JComponent component = newPane.createComponent(); UIUtil.removeScrollBorder(component); myViewContentPanel.setLayout(new BorderLayout()); myViewContentPanel.add(component, BorderLayout.CENTER); myCurrentViewId = newPane.getId(); String newSubId = myCurrentViewSubId = newPane.getSubId(); myViewContentPanel.revalidate(); myViewContentPanel.repaint(); createToolbarActions(); myAutoScrollToSourceHandler.install(newPane.myTree); IdeFocusManager.getInstance(myProject).requestFocus(newPane.getComponentToFocus(), false); newPane.restoreExpandedPaths(); if (selectedPsiElement != null && newSubId != null) { final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(selectedPsiElement); if (virtualFile != null && ((ProjectViewSelectInTarget)newPane.createSelectInTarget()).isSubIdSelectable(newSubId, new SelectInContext() { @Override @NotNull public Project getProject() { return myProject; } @Override @NotNull public VirtualFile getVirtualFile() { return virtualFile; } @Override public Object getSelectorInFile() { return null; } @Override public FileEditorProvider getFileEditorProvider() { return null; } })) { newPane.select(selectedPsiElement, virtualFile, true); } } myAutoScrollToSourceHandler.onMouseClicked(newPane.myTree); } // public for tests public synchronized void setupImpl(@NotNull ToolWindow toolWindow) { setupImpl(toolWindow, true); } // public for tests public synchronized void setupImpl(@NotNull ToolWindow toolWindow, final boolean loadPaneExtensions) { ApplicationManager.getApplication().assertIsDispatchThread(); myActionGroup = new DefaultActionGroup(); myAutoScrollFromSourceHandler.install(); myContentManager = toolWindow.getContentManager(); if (!ApplicationManager.getApplication().isUnitTestMode()) { toolWindow.setDefaultContentUiType(ToolWindowContentUiType.COMBO); ((ToolWindowEx)toolWindow).setAdditionalGearActions(myActionGroup); toolWindow.getComponent().putClientProperty(ToolWindowContentUi.HIDE_ID_LABEL, "true"); } GuiUtils.replaceJSplitPaneWithIDEASplitter(myPanel); SwingUtilities.invokeLater(() -> splitterProportions.restoreSplitterProportions(myPanel)); if (loadPaneExtensions) { ensurePanesLoaded(); } isInitialized = true; doAddUninitializedPanes(); getContentManager().addContentManagerListener(new ContentManagerAdapter() { @Override public void selectionChanged(ContentManagerEvent event) { if (event.getOperation() == ContentManagerEvent.ContentOperation.add) { viewSelectionChanged(); } } }); viewSelectionChanged(); } private void ensurePanesLoaded() { if (myExtensionsLoaded) return; myExtensionsLoaded = true; AbstractProjectViewPane[] extensions = Extensions.getExtensions(AbstractProjectViewPane.EP_NAME, myProject); Arrays.sort(extensions, PANE_WEIGHT_COMPARATOR); for(AbstractProjectViewPane pane: extensions) { if (myUninitializedPaneState.containsKey(pane.getId())) { try { pane.readExternal(myUninitializedPaneState.get(pane.getId())); } catch (InvalidDataException e) { // ignore } myUninitializedPaneState.remove(pane.getId()); } if (pane.isInitiallyVisible() && !myId2Pane.containsKey(pane.getId())) { addProjectPane(pane); } } } private boolean viewSelectionChanged() { Content content = getContentManager().getSelectedContent(); if (content == null) return false; final String id = content.getUserData(ID_KEY); String subId = content.getUserData(SUB_ID_KEY); if (content.equals(Pair.create(myCurrentViewId, myCurrentViewSubId))) return false; final AbstractProjectViewPane newPane = getProjectViewPaneById(id); if (newPane == null) return false; newPane.setSubId(subId); showPane(newPane); if (isAutoscrollFromSource(id)) { myAutoScrollFromSourceHandler.scrollFromSource(); } return true; } private void createToolbarActions() { List<AnAction> titleActions = ContainerUtil.newSmartList(); myActionGroup.removeAll(); if (ProjectViewDirectoryHelper.getInstance(myProject).supportsFlattenPackages()) { myActionGroup.addAction(new PaneOptionAction(myFlattenPackages, IdeBundle.message("action.flatten.packages"), IdeBundle.message("action.flatten.packages"), PlatformIcons.FLATTEN_PACKAGES_ICON, ourFlattenPackagesDefaults) { @Override public void setSelected(AnActionEvent event, boolean flag) { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); final SelectionInfo selectionInfo = SelectionInfo.create(viewPane); if (isGlobalOptions()) { setFlattenPackages(flag, viewPane.getId()); } super.setSelected(event, flag); selectionInfo.apply(viewPane); } @Override public boolean isSelected(AnActionEvent event) { if (isGlobalOptions()) return getGlobalOptions().getFlattenPackages(); return super.isSelected(event); } }).setAsSecondary(true); } class FlattenPackagesDependableAction extends PaneOptionAction { FlattenPackagesDependableAction(@NotNull Map<String, Boolean> optionsMap, @NotNull String text, @NotNull String description, @NotNull Icon icon, boolean optionDefaultValue) { super(optionsMap, text, description, icon, optionDefaultValue); } @Override public void setSelected(AnActionEvent event, boolean flag) { if (isGlobalOptions()) { getGlobalOptions().setFlattenPackages(flag); } super.setSelected(event, flag); } @Override public void update(AnActionEvent e) { super.update(e); final Presentation presentation = e.getPresentation(); presentation.setVisible(isFlattenPackages(myCurrentViewId)); } } if (ProjectViewDirectoryHelper.getInstance(myProject).supportsHideEmptyMiddlePackages()) { myActionGroup.addAction(new HideEmptyMiddlePackagesAction()).setAsSecondary(true); } if (ProjectViewDirectoryHelper.getInstance(myProject).supportsFlattenPackages()) { myActionGroup.addAction(new FlattenPackagesDependableAction(myAbbreviatePackageNames, IdeBundle.message("action.abbreviate.qualified.package.names"), IdeBundle.message("action.abbreviate.qualified.package.names"), AllIcons.ObjectBrowser.AbbreviatePackageNames, ourAbbreviatePackagesDefaults) { @Override public boolean isSelected(AnActionEvent event) { return super.isSelected(event) && isAbbreviatePackageNames(myCurrentViewId); } @Override public void update(AnActionEvent e) { super.update(e); if (ScopeViewPane.ID.equals(myCurrentViewId)) { e.getPresentation().setEnabled(false); } } }).setAsSecondary(true); } if (isShowMembersOptionSupported()) { myActionGroup.addAction(new PaneOptionAction(myShowMembers, IdeBundle.message("action.show.members"), IdeBundle.message("action.show.hide.members"), AllIcons.ObjectBrowser.ShowMembers, ourShowMembersDefaults) { @Override public boolean isSelected(AnActionEvent event) { if (isGlobalOptions()) return getGlobalOptions().getShowMembers(); return super.isSelected(event); } @Override public void setSelected(AnActionEvent event, boolean flag) { if (isGlobalOptions()) { getGlobalOptions().setShowMembers(flag); } super.setSelected(event, flag); } }) .setAsSecondary(true); } myActionGroup.addAction(myAutoScrollToSourceHandler.createToggleAction()).setAsSecondary(true); myActionGroup.addAction(myAutoScrollFromSourceHandler.createToggleAction()).setAsSecondary(true); myActionGroup.addAction(new ManualOrderAction()).setAsSecondary(true); myActionGroup.addAction(new SortByTypeAction()).setAsSecondary(true); myActionGroup.addAction(new FoldersAlwaysOnTopAction()).setAsSecondary(true); if (!myAutoScrollFromSourceHandler.isAutoScrollEnabled()) { titleActions.add(new ScrollFromSourceAction()); } AnAction collapseAllAction = CommonActionsManager.getInstance().createCollapseAllAction(new TreeExpander() { @Override public void expandAll() { } @Override public boolean canExpand() { return false; } @Override public void collapseAll() { AbstractProjectViewPane pane = getCurrentProjectViewPane(); JTree tree = pane.myTree; if (tree != null) { TreeUtil.collapseAll(tree, 0); } } @Override public boolean canCollapse() { return true; } }, getComponent()); collapseAllAction.getTemplatePresentation().setIcon(AllIcons.General.CollapseAll); collapseAllAction.getTemplatePresentation().setHoveredIcon(AllIcons.General.CollapseAllHover); titleActions.add(collapseAllAction); getCurrentProjectViewPane().addToolbarActions(myActionGroup); ToolWindowEx window = (ToolWindowEx)ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.PROJECT_VIEW); if (window != null) { window.setTitleActions(titleActions.toArray(new AnAction[titleActions.size()])); } } protected boolean isShowMembersOptionSupported() { return true; } @Override public AbstractProjectViewPane getProjectViewPaneById(String id) { if (!ApplicationManager.getApplication().isUnitTestMode()) { // most tests don't need all panes to be loaded ensurePanesLoaded(); } final AbstractProjectViewPane pane = myId2Pane.get(id); if (pane != null) { return pane; } for (AbstractProjectViewPane viewPane : myUninitializedPanes) { if (viewPane.getId().equals(id)) { return viewPane; } } return null; } @Override public AbstractProjectViewPane getCurrentProjectViewPane() { return getProjectViewPaneById(myCurrentViewId); } @Override public void refresh() { AbstractProjectViewPane currentProjectViewPane = getCurrentProjectViewPane(); if (currentProjectViewPane != null) { // may be null for e.g. default project currentProjectViewPane.updateFromRoot(false); } } @Override public void select(final Object element, VirtualFile file, boolean requestFocus) { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane != null) { viewPane.select(element, file, requestFocus); } } @NotNull @Override public ActionCallback selectCB(Object element, VirtualFile file, boolean requestFocus) { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane != null && viewPane instanceof AbstractProjectViewPSIPane) { return ((AbstractProjectViewPSIPane)viewPane).selectCB(element, file, requestFocus); } select(element, file, requestFocus); return ActionCallback.DONE; } @Override public void dispose() { myConnection.disconnect(); } public JComponent getComponent() { return myDataProvider; } @Override public String getCurrentViewId() { return myCurrentViewId; } @Override public PsiElement getParentOfCurrentSelection() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane == null) { return null; } TreePath path = viewPane.getSelectedPath(); if (path == null) { return null; } path = path.getParentPath(); if (path == null) { return null; } DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); Object userObject = node.getUserObject(); if (userObject instanceof ProjectViewNode) { ProjectViewNode descriptor = (ProjectViewNode)userObject; Object element = descriptor.getValue(); if (element instanceof PsiElement) { PsiElement psiElement = (PsiElement)element; if (!psiElement.isValid()) return null; return psiElement; } else { return null; } } return null; } public ContentManager getContentManager() { if (myContentManager == null) { ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.PROJECT_VIEW).getContentManager(); } return myContentManager; } private class PaneOptionAction extends ToggleAction implements DumbAware { private final Map<String, Boolean> myOptionsMap; private final boolean myOptionDefaultValue; PaneOptionAction(@NotNull Map<String, Boolean> optionsMap, @NotNull String text, @NotNull String description, Icon icon, boolean optionDefaultValue) { super(text, description, icon); myOptionsMap = optionsMap; myOptionDefaultValue = optionDefaultValue; } @Override public boolean isSelected(AnActionEvent event) { return getPaneOptionValue(myOptionsMap, myCurrentViewId, myOptionDefaultValue); } @Override public void setSelected(AnActionEvent event, boolean flag) { setPaneOption(myOptionsMap, flag, myCurrentViewId, true); } } @Override public void changeView() { final List<AbstractProjectViewPane> views = new ArrayList<>(myId2Pane.values()); views.remove(getCurrentProjectViewPane()); Collections.sort(views, PANE_WEIGHT_COMPARATOR); final JList list = new JBList(ArrayUtil.toObjectArray(views)); list.setCellRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); AbstractProjectViewPane pane = (AbstractProjectViewPane)value; setText(pane.getTitle()); return this; } }); if (!views.isEmpty()) { list.setSelectedValue(views.get(0), true); } Runnable runnable = () -> { if (list.getSelectedIndex() < 0) return; AbstractProjectViewPane pane = (AbstractProjectViewPane)list.getSelectedValue(); changeView(pane.getId()); }; new PopupChooserBuilder(list). setTitle(IdeBundle.message("title.popup.views")). setItemChoosenCallback(runnable). createPopup().showInCenterOf(getComponent()); } @Override public void changeView(@NotNull String viewId) { changeView(viewId, null); } @Override public void changeView(@NotNull String viewId, @Nullable String subId) { changeViewCB(viewId, subId); } @NotNull @Override public ActionCallback changeViewCB(@NotNull String viewId, String subId) { AbstractProjectViewPane pane = getProjectViewPaneById(viewId); LOG.assertTrue(pane != null, "Project view pane not found: " + viewId + "; subId:" + subId); if (!viewId.equals(getCurrentViewId()) || subId != null && !subId.equals(pane.getSubId())) { for (Content content : getContentManager().getContents()) { if (viewId.equals(content.getUserData(ID_KEY)) && StringUtil.equals(subId, content.getUserData(SUB_ID_KEY))) { return getContentManager().setSelectedContentCB(content); } } } return ActionCallback.REJECTED; } private final class MyDeletePSIElementProvider implements DeleteProvider { @Override public boolean canDeleteElement(@NotNull DataContext dataContext) { final PsiElement[] elements = getElementsToDelete(); return DeleteHandler.shouldEnableDeleteAction(elements); } @Override public void deleteElement(@NotNull DataContext dataContext) { List<PsiElement> allElements = Arrays.asList(getElementsToDelete()); List<PsiElement> validElements = new ArrayList<>(); for (PsiElement psiElement : allElements) { if (psiElement != null && psiElement.isValid()) validElements.add(psiElement); } final PsiElement[] elements = PsiUtilCore.toPsiElementArray(validElements); LocalHistoryAction a = LocalHistory.getInstance().startAction(IdeBundle.message("progress.deleting")); try { DeleteHandler.deletePsiElement(elements, myProject); } finally { a.finish(); } } @NotNull private PsiElement[] getElementsToDelete() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); PsiElement[] elements = viewPane.getSelectedPSIElements(); for (int idx = 0; idx < elements.length; idx++) { final PsiElement element = elements[idx]; if (element instanceof PsiDirectory) { PsiDirectory directory = (PsiDirectory)element; final ProjectViewDirectoryHelper directoryHelper = ProjectViewDirectoryHelper.getInstance(myProject); if (isHideEmptyMiddlePackages(viewPane.getId()) && directory.getChildren().length == 0 && !directoryHelper.skipDirectory(directory)) { while (true) { PsiDirectory parent = directory.getParentDirectory(); if (parent == null) break; if (directoryHelper.skipDirectory(parent) || PsiDirectoryFactory.getInstance(myProject).getQualifiedName(parent, false).length() == 0) break; PsiElement[] children = parent.getChildren(); if (children.length == 0 || children.length == 1 && children[0] == directory) { directory = parent; } else { break; } } elements[idx] = directory; } final VirtualFile virtualFile = directory.getVirtualFile(); final String path = virtualFile.getPath(); if (path.endsWith(JarFileSystem.JAR_SEPARATOR)) { // if is jar-file root final VirtualFile vFile = LocalFileSystem.getInstance().findFileByPath(path.substring(0, path.length() - JarFileSystem.JAR_SEPARATOR.length())); if (vFile != null) { final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(vFile); if (psiFile != null) { elements[idx] = psiFile; } } } } } return elements; } } private final class MyPanel extends JPanel implements DataProvider { MyPanel() { super(new BorderLayout()); } @Nullable private Object getSelectedNodeElement() { final AbstractProjectViewPane currentProjectViewPane = getCurrentProjectViewPane(); if (currentProjectViewPane == null) { // can happen if not initialized yet return null; } DefaultMutableTreeNode node = currentProjectViewPane.getSelectedNode(); if (node == null) { return null; } Object userObject = node.getUserObject(); if (userObject instanceof AbstractTreeNode) { return ((AbstractTreeNode)userObject).getValue(); } if (!(userObject instanceof NodeDescriptor)) { return null; } return ((NodeDescriptor)userObject).getElement(); } @Override public Object getData(String dataId) { final AbstractProjectViewPane currentProjectViewPane = getCurrentProjectViewPane(); if (currentProjectViewPane != null) { final Object paneSpecificData = currentProjectViewPane.getData(dataId); if (paneSpecificData != null) return paneSpecificData; } if (CommonDataKeys.PSI_ELEMENT.is(dataId)) { if (currentProjectViewPane == null) return null; final PsiElement[] elements = currentProjectViewPane.getSelectedPSIElements(); return elements.length == 1 ? elements[0] : null; } if (LangDataKeys.PSI_ELEMENT_ARRAY.is(dataId)) { if (currentProjectViewPane == null) { return null; } PsiElement[] elements = currentProjectViewPane.getSelectedPSIElements(); return elements.length == 0 ? null : elements; } if (LangDataKeys.MODULE.is(dataId)) { VirtualFile[] virtualFiles = (VirtualFile[])getData(CommonDataKeys.VIRTUAL_FILE_ARRAY.getName()); if (virtualFiles == null || virtualFiles.length <= 1) return null; final Set<Module> modules = new HashSet<>(); for (VirtualFile virtualFile : virtualFiles) { modules.add(ModuleUtilCore.findModuleForFile(virtualFile, myProject)); } return modules.size() == 1 ? modules.iterator().next() : null; } if (LangDataKeys.TARGET_PSI_ELEMENT.is(dataId)) { return null; } if (PlatformDataKeys.CUT_PROVIDER.is(dataId)) { return myCopyPasteDelegator.getCutProvider(); } if (PlatformDataKeys.COPY_PROVIDER.is(dataId)) { return myCopyPasteDelegator.getCopyProvider(); } if (PlatformDataKeys.PASTE_PROVIDER.is(dataId)) { return myCopyPasteDelegator.getPasteProvider(); } if (LangDataKeys.IDE_VIEW.is(dataId)) { return myIdeView; } if (PlatformDataKeys.DELETE_ELEMENT_PROVIDER.is(dataId)) { final Module[] modules = getSelectedModules(); if (modules != null) { return myDeleteModuleProvider; } final LibraryOrderEntry orderEntry = getSelectedLibrary(); if (orderEntry != null) { return new DeleteProvider() { @Override public void deleteElement(@NotNull DataContext dataContext) { detachLibrary(orderEntry, myProject); } @Override public boolean canDeleteElement(@NotNull DataContext dataContext) { return true; } }; } return myDeletePSIElementProvider; } if (PlatformDataKeys.HELP_ID.is(dataId)) { return HelpID.PROJECT_VIEWS; } if (ProjectViewImpl.DATA_KEY.is(dataId)) { return ProjectViewImpl.this; } if (PlatformDataKeys.PROJECT_CONTEXT.is(dataId)) { Object selected = getSelectedNodeElement(); return selected instanceof Project ? selected : null; } if (LangDataKeys.MODULE_CONTEXT.is(dataId)) { Object selected = getSelectedNodeElement(); if (selected instanceof Module) { return !((Module)selected).isDisposed() ? selected : null; } else if (selected instanceof PsiDirectory) { return moduleBySingleContentRoot(((PsiDirectory)selected).getVirtualFile()); } else if (selected instanceof VirtualFile) { return moduleBySingleContentRoot((VirtualFile)selected); } else { return null; } } if (LangDataKeys.MODULE_CONTEXT_ARRAY.is(dataId)) { return getSelectedModules(); } if (ModuleGroup.ARRAY_DATA_KEY.is(dataId)) { final List<ModuleGroup> selectedElements = getSelectedElements(ModuleGroup.class); return selectedElements.isEmpty() ? null : selectedElements.toArray(new ModuleGroup[selectedElements.size()]); } if (LibraryGroupElement.ARRAY_DATA_KEY.is(dataId)) { final List<LibraryGroupElement> selectedElements = getSelectedElements(LibraryGroupElement.class); return selectedElements.isEmpty() ? null : selectedElements.toArray(new LibraryGroupElement[selectedElements.size()]); } if (NamedLibraryElement.ARRAY_DATA_KEY.is(dataId)) { final List<NamedLibraryElement> selectedElements = getSelectedElements(NamedLibraryElement.class); return selectedElements.isEmpty() ? null : selectedElements.toArray(new NamedLibraryElement[selectedElements.size()]); } return null; } @Nullable private LibraryOrderEntry getSelectedLibrary() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); DefaultMutableTreeNode node = viewPane != null ? viewPane.getSelectedNode() : null; if (node == null) return null; DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent(); if (parent == null) return null; Object userObject = parent.getUserObject(); if (userObject instanceof LibraryGroupNode) { userObject = node.getUserObject(); if (userObject instanceof NamedLibraryElementNode) { NamedLibraryElement element = ((NamedLibraryElementNode)userObject).getValue(); OrderEntry orderEntry = element.getOrderEntry(); return orderEntry instanceof LibraryOrderEntry ? (LibraryOrderEntry)orderEntry : null; } PsiDirectory directory = ((PsiDirectoryNode)userObject).getValue(); VirtualFile virtualFile = directory.getVirtualFile(); Module module = (Module)((AbstractTreeNode)((DefaultMutableTreeNode)parent.getParent()).getUserObject()).getValue(); if (module == null) return null; ModuleFileIndex index = ModuleRootManager.getInstance(module).getFileIndex(); OrderEntry entry = index.getOrderEntryForFile(virtualFile); if (entry instanceof LibraryOrderEntry) { return (LibraryOrderEntry)entry; } } return null; } private void detachLibrary(@NotNull final LibraryOrderEntry orderEntry, @NotNull Project project) { final Module module = orderEntry.getOwnerModule(); String message = IdeBundle.message("detach.library.from.module", orderEntry.getPresentableName(), module.getName()); String title = IdeBundle.message("detach.library"); int ret = Messages.showOkCancelDialog(project, message, title, Messages.getQuestionIcon()); if (ret != Messages.OK) return; CommandProcessor.getInstance().executeCommand(module.getProject(), () -> { final Runnable action = () -> { ModuleRootManager rootManager = ModuleRootManager.getInstance(module); OrderEntry[] orderEntries = rootManager.getOrderEntries(); ModifiableRootModel model = rootManager.getModifiableModel(); OrderEntry[] modifiableEntries = model.getOrderEntries(); for (int i = 0; i < orderEntries.length; i++) { OrderEntry entry = orderEntries[i]; if (entry instanceof LibraryOrderEntry && ((LibraryOrderEntry)entry).getLibrary() == orderEntry.getLibrary()) { model.removeOrderEntry(modifiableEntries[i]); } } model.commit(); }; ApplicationManager.getApplication().runWriteAction(action); }, title, null); } @Nullable private Module[] getSelectedModules() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane == null) return null; final Object[] elements = viewPane.getSelectedElements(); ArrayList<Module> result = new ArrayList<>(); for (Object element : elements) { if (element instanceof Module) { final Module module = (Module)element; if (!module.isDisposed()) { result.add(module); } } else if (element instanceof ModuleGroup) { Collection<Module> modules = ((ModuleGroup)element).modulesInGroup(myProject, true); result.addAll(modules); } else if (element instanceof PsiDirectory) { Module module = moduleBySingleContentRoot(((PsiDirectory)element).getVirtualFile()); if (module != null) result.add(module); } else if (element instanceof VirtualFile) { Module module = moduleBySingleContentRoot((VirtualFile)element); if (module != null) result.add(module); } } if (result.isEmpty()) { return null; } else { return result.toArray(new Module[result.size()]); } } } /** Project view has the same node for module and its single content root * => MODULE_CONTEXT data key should return the module when its content root is selected * When there are multiple content roots, they have different nodes under the module node * => MODULE_CONTEXT should be only available for the module node * otherwise VirtualFileArrayRule will return all module's content roots when just one of them is selected */ @Nullable private Module moduleBySingleContentRoot(@NotNull VirtualFile file) { if (ProjectRootsUtil.isModuleContentRoot(file, myProject)) { Module module = ProjectRootManager.getInstance(myProject).getFileIndex().getModuleForFile(file); if (module != null && !module.isDisposed() && ModuleRootManager.getInstance(module).getContentRoots().length == 1) { return module; } } return null; } @NotNull private <T> List<T> getSelectedElements(@NotNull Class<T> klass) { List<T> result = new ArrayList<>(); final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane == null) return result; final Object[] elements = viewPane.getSelectedElements(); for (Object element : elements) { //element still valid if (element != null && klass.isAssignableFrom(element.getClass())) { result.add((T)element); } } return result; } private final class MyIdeView implements IdeView { @Override public void selectElement(PsiElement element) { selectPsiElement(element, false); boolean requestFocus = true; if (element != null) { final boolean isDirectory = element instanceof PsiDirectory; if (!isDirectory) { FileEditor editor = EditorHelper.openInEditor(element, false); if (editor != null) { ToolWindowManager.getInstance(myProject).activateEditorComponent(); requestFocus = false; } } } if (requestFocus) { selectPsiElement(element, true); } } @NotNull @Override public PsiDirectory[] getDirectories() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane != null) { return viewPane.getSelectedDirectories(); } return PsiDirectory.EMPTY_ARRAY; } @Override public PsiDirectory getOrChooseDirectory() { return DirectoryChooserUtil.getOrChooseDirectory(this); } } @Override public void selectPsiElement(PsiElement element, boolean requestFocus) { if (element == null) return; VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element); select(element, virtualFile, requestFocus); } private static void readOption(Element node, @NotNull Map<String, Boolean> options) { if (node == null) return; for (Attribute attribute : node.getAttributes()) { options.put(attribute.getName(), Boolean.TRUE.toString().equals(attribute.getValue()) ? Boolean.TRUE : Boolean.FALSE); } } private static void writeOption(@NotNull Element parentNode, @NotNull Map<String, Boolean> optionsForPanes, @NotNull String optionName) { Element e = new Element(optionName); for (Map.Entry<String, Boolean> entry : optionsForPanes.entrySet()) { final String key = entry.getKey(); if (key != null) { //SCR48267 e.setAttribute(key, Boolean.toString(entry.getValue().booleanValue())); } } parentNode.addContent(e); } @Override public void loadState(Element parentNode) { Element navigatorElement = parentNode.getChild(ELEMENT_NAVIGATOR); if (navigatorElement != null) { mySavedPaneId = navigatorElement.getAttributeValue(ATTRIBUTE_CURRENT_VIEW); mySavedPaneSubId = navigatorElement.getAttributeValue(ATTRIBUTE_CURRENT_SUBVIEW); if (mySavedPaneId == null) { mySavedPaneId = ProjectViewPane.ID; mySavedPaneSubId = null; } readOption(navigatorElement.getChild(ELEMENT_FLATTEN_PACKAGES), myFlattenPackages); readOption(navigatorElement.getChild(ELEMENT_SHOW_MEMBERS), myShowMembers); readOption(navigatorElement.getChild(ELEMENT_SHOW_MODULES), myShowModules); readOption(navigatorElement.getChild(ELEMENT_SHOW_LIBRARY_CONTENTS), myShowLibraryContents); readOption(navigatorElement.getChild(ELEMENT_HIDE_EMPTY_PACKAGES), myHideEmptyPackages); readOption(navigatorElement.getChild(ELEMENT_ABBREVIATE_PACKAGE_NAMES), myAbbreviatePackageNames); readOption(navigatorElement.getChild(ELEMENT_AUTOSCROLL_TO_SOURCE), myAutoscrollToSource); readOption(navigatorElement.getChild(ELEMENT_AUTOSCROLL_FROM_SOURCE), myAutoscrollFromSource); readOption(navigatorElement.getChild(ELEMENT_SORT_BY_TYPE), mySortByType); readOption(navigatorElement.getChild(ELEMENT_MANUAL_ORDER), myManualOrder); Element foldersElement = navigatorElement.getChild(ELEMENT_FOLDERS_ALWAYS_ON_TOP); if (foldersElement != null) myFoldersAlwaysOnTop = Boolean.valueOf(foldersElement.getAttributeValue("value")); try { splitterProportions.readExternal(navigatorElement); } catch (InvalidDataException e) { // ignore } } Element panesElement = parentNode.getChild(ELEMENT_PANES); if (panesElement != null) { readPaneState(panesElement); } } private void readPaneState(@NotNull Element panesElement) { @SuppressWarnings({"unchecked"}) final List<Element> paneElements = panesElement.getChildren(ELEMENT_PANE); for (Element paneElement : paneElements) { String paneId = paneElement.getAttributeValue(ATTRIBUTE_ID); final AbstractProjectViewPane pane = myId2Pane.get(paneId); if (pane != null) { try { pane.readExternal(paneElement); } catch (InvalidDataException e) { // ignore } } else { myUninitializedPaneState.put(paneId, paneElement); } } } @Override public Element getState() { Element parentNode = new Element("projectView"); Element navigatorElement = new Element(ELEMENT_NAVIGATOR); AbstractProjectViewPane currentPane = getCurrentProjectViewPane(); if (currentPane != null) { navigatorElement.setAttribute(ATTRIBUTE_CURRENT_VIEW, currentPane.getId()); String subId = currentPane.getSubId(); if (subId != null) { navigatorElement.setAttribute(ATTRIBUTE_CURRENT_SUBVIEW, subId); } } writeOption(navigatorElement, myFlattenPackages, ELEMENT_FLATTEN_PACKAGES); writeOption(navigatorElement, myShowMembers, ELEMENT_SHOW_MEMBERS); writeOption(navigatorElement, myShowModules, ELEMENT_SHOW_MODULES); writeOption(navigatorElement, myShowLibraryContents, ELEMENT_SHOW_LIBRARY_CONTENTS); writeOption(navigatorElement, myHideEmptyPackages, ELEMENT_HIDE_EMPTY_PACKAGES); writeOption(navigatorElement, myAbbreviatePackageNames, ELEMENT_ABBREVIATE_PACKAGE_NAMES); writeOption(navigatorElement, myAutoscrollToSource, ELEMENT_AUTOSCROLL_TO_SOURCE); writeOption(navigatorElement, myAutoscrollFromSource, ELEMENT_AUTOSCROLL_FROM_SOURCE); writeOption(navigatorElement, mySortByType, ELEMENT_SORT_BY_TYPE); writeOption(navigatorElement, myManualOrder, ELEMENT_MANUAL_ORDER); Element foldersElement = new Element(ELEMENT_FOLDERS_ALWAYS_ON_TOP); foldersElement.setAttribute("value", Boolean.toString(myFoldersAlwaysOnTop)); navigatorElement.addContent(foldersElement); splitterProportions.saveSplitterProportions(myPanel); try { splitterProportions.writeExternal(navigatorElement); } catch (WriteExternalException e) { // ignore } parentNode.addContent(navigatorElement); Element panesElement = new Element(ELEMENT_PANES); writePaneState(panesElement); parentNode.addContent(panesElement); return parentNode; } private void writePaneState(@NotNull Element panesElement) { for (AbstractProjectViewPane pane : myId2Pane.values()) { Element paneElement = new Element(ELEMENT_PANE); paneElement.setAttribute(ATTRIBUTE_ID, pane.getId()); try { pane.writeExternal(paneElement); } catch (WriteExternalException e) { continue; } panesElement.addContent(paneElement); } for (Element element : myUninitializedPaneState.values()) { panesElement.addContent(element.clone()); } } boolean isGlobalOptions() { return Registry.is("ide.projectView.globalOptions"); } ProjectViewSharedSettings getGlobalOptions() { return ProjectViewSharedSettings.Companion.getInstance(); } @Override public boolean isAutoscrollToSource(String paneId) { if (isGlobalOptions()) { return getGlobalOptions().getAutoscrollToSource(); } return getPaneOptionValue(myAutoscrollToSource, paneId, UISettings.getInstance().DEFAULT_AUTOSCROLL_TO_SOURCE); } public void setAutoscrollToSource(boolean autoscrollMode, String paneId) { if (isGlobalOptions()) { getGlobalOptions().setAutoscrollToSource(autoscrollMode); } myAutoscrollToSource.put(paneId, autoscrollMode); } @Override public boolean isAutoscrollFromSource(String paneId) { if (isGlobalOptions()) { return getGlobalOptions().getAutoscrollFromSource(); } return getPaneOptionValue(myAutoscrollFromSource, paneId, ourAutoscrollFromSourceDefaults); } public void setAutoscrollFromSource(boolean autoscrollMode, String paneId) { if (isGlobalOptions()) { getGlobalOptions().setAutoscrollFromSource(autoscrollMode); } setPaneOption(myAutoscrollFromSource, autoscrollMode, paneId, false); } @Override public boolean isFlattenPackages(String paneId) { if (isGlobalOptions()) { return getGlobalOptions().getFlattenPackages(); } return getPaneOptionValue(myFlattenPackages, paneId, ourFlattenPackagesDefaults); } public void setFlattenPackages(boolean flattenPackages, String paneId) { if (isGlobalOptions()) { getGlobalOptions().setFlattenPackages(flattenPackages); for (String pane : myFlattenPackages.keySet()) { setPaneOption(myFlattenPackages, flattenPackages, pane, true); } } setPaneOption(myFlattenPackages, flattenPackages, paneId, true); } public boolean isFoldersAlwaysOnTop() { if (isGlobalOptions()) { return getGlobalOptions().getFoldersAlwaysOnTop(); } return myFoldersAlwaysOnTop; } public void setFoldersAlwaysOnTop(boolean foldersAlwaysOnTop) { if (isGlobalOptions()) { getGlobalOptions().setFoldersAlwaysOnTop(foldersAlwaysOnTop); } if (myFoldersAlwaysOnTop != foldersAlwaysOnTop) { myFoldersAlwaysOnTop = foldersAlwaysOnTop; for (AbstractProjectViewPane pane : myId2Pane.values()) { if (pane.getTree() != null) { pane.updateFromRoot(false); } } } } @Override public boolean isShowMembers(String paneId) { if (isGlobalOptions()) { return getGlobalOptions().getShowMembers(); } return getPaneOptionValue(myShowMembers, paneId, ourShowMembersDefaults); } public void setShowMembers(boolean showMembers, String paneId) { setPaneOption(myShowMembers, showMembers, paneId, true); } @Override public boolean isHideEmptyMiddlePackages(String paneId) { if (isGlobalOptions()) { return getGlobalOptions().getHideEmptyPackages(); } return getPaneOptionValue(myHideEmptyPackages, paneId, ourHideEmptyPackagesDefaults); } @Override public boolean isAbbreviatePackageNames(String paneId) { if (isGlobalOptions()) { return getGlobalOptions().getAbbreviatePackages(); } return getPaneOptionValue(myAbbreviatePackageNames, paneId, ourAbbreviatePackagesDefaults); } @Override public boolean isShowLibraryContents(String paneId) { if (isGlobalOptions()) { return getGlobalOptions().getShowLibraryContents(); } return getPaneOptionValue(myShowLibraryContents, paneId, ourShowLibraryContentsDefaults); } @Override public void setShowLibraryContents(boolean showLibraryContents, @NotNull String paneId) { if (isGlobalOptions()) { getGlobalOptions().setShowLibraryContents(showLibraryContents); } setPaneOption(myShowLibraryContents, showLibraryContents, paneId, true); } @NotNull public ActionCallback setShowLibraryContentsCB(boolean showLibraryContents, String paneId) { return setPaneOption(myShowLibraryContents, showLibraryContents, paneId, true); } @Override public boolean isShowModules(String paneId) { if (isGlobalOptions()) { return getGlobalOptions().getShowModules(); } return getPaneOptionValue(myShowModules, paneId, ourShowModulesDefaults); } @Override public void setShowModules(boolean showModules, @NotNull String paneId) { if (isGlobalOptions()) { getGlobalOptions().setShowModules(showModules); } setPaneOption(myShowModules, showModules, paneId, true); } @Override public void setHideEmptyPackages(boolean hideEmptyPackages, @NotNull String paneId) { if (isGlobalOptions()) { getGlobalOptions().setHideEmptyPackages(hideEmptyPackages); for (String pane : myHideEmptyPackages.keySet()) { setPaneOption(myHideEmptyPackages, hideEmptyPackages, pane, true); } } setPaneOption(myHideEmptyPackages, hideEmptyPackages, paneId, true); } @Override public void setAbbreviatePackageNames(boolean abbreviatePackageNames, @NotNull String paneId) { if (isGlobalOptions()) { getGlobalOptions().setAbbreviatePackages(abbreviatePackageNames); } setPaneOption(myAbbreviatePackageNames, abbreviatePackageNames, paneId, true); } @NotNull private ActionCallback setPaneOption(@NotNull Map<String, Boolean> optionsMap, boolean value, String paneId, final boolean updatePane) { if (paneId != null) { optionsMap.put(paneId, value); if (updatePane) { final AbstractProjectViewPane pane = getProjectViewPaneById(paneId); if (pane != null) { return pane.updateFromRoot(false); } } } return ActionCallback.DONE; } private static boolean getPaneOptionValue(@NotNull Map<String, Boolean> optionsMap, String paneId, boolean defaultValue) { final Boolean value = optionsMap.get(paneId); return value == null ? defaultValue : value.booleanValue(); } private class HideEmptyMiddlePackagesAction extends PaneOptionAction { private HideEmptyMiddlePackagesAction() { super(myHideEmptyPackages, "", "", null, ourHideEmptyPackagesDefaults); } @Override public void setSelected(AnActionEvent event, boolean flag) { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); final SelectionInfo selectionInfo = SelectionInfo.create(viewPane); if (isGlobalOptions()) { getGlobalOptions().setHideEmptyPackages(flag); } super.setSelected(event, flag); selectionInfo.apply(viewPane); } @Override public boolean isSelected(AnActionEvent event) { if (isGlobalOptions()) return getGlobalOptions().getHideEmptyPackages(); return super.isSelected(event); } @Override public void update(AnActionEvent e) { super.update(e); final Presentation presentation = e.getPresentation(); if (isHideEmptyMiddlePackages(myCurrentViewId)) { presentation.setText(IdeBundle.message("action.hide.empty.middle.packages")); presentation.setDescription(IdeBundle.message("action.show.hide.empty.middle.packages")); } else { presentation.setText(IdeBundle.message("action.compact.empty.middle.packages")); presentation.setDescription(IdeBundle.message("action.show.compact.empty.middle.packages")); } } } private static class SelectionInfo { private final Object[] myElements; private SelectionInfo(@NotNull Object[] elements) { myElements = elements; } public void apply(final AbstractProjectViewPane viewPane) { if (viewPane == null) { return; } AbstractTreeBuilder treeBuilder = viewPane.getTreeBuilder(); JTree tree = viewPane.myTree; DefaultTreeModel treeModel = (DefaultTreeModel)tree.getModel(); List<TreePath> paths = new ArrayList<>(myElements.length); for (final Object element : myElements) { DefaultMutableTreeNode node = treeBuilder.getNodeForElement(element); if (node == null) { treeBuilder.buildNodeForElement(element); node = treeBuilder.getNodeForElement(element); } if (node != null) { paths.add(new TreePath(treeModel.getPathToRoot(node))); } } if (!paths.isEmpty()) { tree.setSelectionPaths(paths.toArray(new TreePath[paths.size()])); } } @NotNull public static SelectionInfo create(final AbstractProjectViewPane viewPane) { List<Object> selectedElements = Collections.emptyList(); if (viewPane != null) { final TreePath[] selectionPaths = viewPane.getSelectionPaths(); if (selectionPaths != null) { selectedElements = new ArrayList<>(); for (TreePath path : selectionPaths) { final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); final Object userObject = node.getUserObject(); if (userObject instanceof NodeDescriptor) { selectedElements.add(((NodeDescriptor)userObject).getElement()); } } } } return new SelectionInfo(selectedElements.toArray()); } } private class MyAutoScrollFromSourceHandler extends AutoScrollFromSourceHandler { private MyAutoScrollFromSourceHandler() { super(ProjectViewImpl.this.myProject, myViewContentPanel, ProjectViewImpl.this); } @Override protected void selectElementFromEditor(@NotNull FileEditor fileEditor) { if (myProject.isDisposed() || !myViewContentPanel.isShowing()) return; if (isAutoscrollFromSource(getCurrentViewId())) { if (fileEditor instanceof TextEditor) { Editor editor = ((TextEditor)fileEditor).getEditor(); selectElementAtCaretNotLosingFocus(editor); } else { final VirtualFile file = FileEditorManagerEx.getInstanceEx(myProject).getFile(fileEditor); if (file != null) { final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file); if (psiFile != null) { final SelectInTarget target = mySelectInTargets.get(getCurrentViewId()); if (target != null) { final MySelectInContext selectInContext = new MySelectInContext(psiFile, null) { @Override public Object getSelectorInFile() { return psiFile; } }; if (target.canSelect(selectInContext)) { target.selectIn(selectInContext, false); } } } } } } } public void scrollFromSource() { final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject); final Editor selectedTextEditor = fileEditorManager.getSelectedTextEditor(); if (selectedTextEditor != null) { selectElementAtCaret(selectedTextEditor); return; } final FileEditor[] editors = fileEditorManager.getSelectedEditors(); for (FileEditor fileEditor : editors) { if (fileEditor instanceof TextEditor) { Editor editor = ((TextEditor)fileEditor).getEditor(); selectElementAtCaret(editor); return; } } final VirtualFile[] selectedFiles = fileEditorManager.getSelectedFiles(); if (selectedFiles.length > 0) { final PsiFile file = PsiManager.getInstance(myProject).findFile(selectedFiles[0]); if (file != null) { scrollFromFile(file, null); } } } private void selectElementAtCaretNotLosingFocus(@NotNull Editor editor) { AbstractProjectViewPane pane = getCurrentProjectViewPane(); if (pane != null && !IJSwingUtilities.hasFocus(pane.getComponentToFocus())) { selectElementAtCaret(editor); } } private void selectElementAtCaret(@NotNull Editor editor) { final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(editor.getDocument()); if (file == null) return; scrollFromFile(file, editor); } private void scrollFromFile(@NotNull PsiFile file, @Nullable Editor editor) { PsiDocumentManager.getInstance(myProject).performWhenAllCommitted(() -> { final MySelectInContext selectInContext = new MySelectInContext(file, editor); final SelectInTarget target = mySelectInTargets.get(getCurrentViewId()); if (target != null && target.canSelect(selectInContext)) { target.selectIn(selectInContext, false); } }); } @Override protected boolean isAutoScrollEnabled() { return isAutoscrollFromSource(myCurrentViewId); } @Override protected void setAutoScrollEnabled(boolean state) { setAutoscrollFromSource(state, myCurrentViewId); if (state) { final Editor editor = myFileEditorManager.getSelectedTextEditor(); if (editor != null) { selectElementAtCaretNotLosingFocus(editor); } } createToolbarActions(); } private class MySelectInContext implements SelectInContext { @NotNull private final PsiFile myPsiFile; @Nullable private final Editor myEditor; private MySelectInContext(@NotNull PsiFile psiFile, @Nullable Editor editor) { myPsiFile = psiFile; myEditor = editor; } @Override @NotNull public Project getProject() { return myProject; } @NotNull private PsiFile getPsiFile() { return myPsiFile; } @Override @NotNull public FileEditorProvider getFileEditorProvider() { return new FileEditorProvider() { @Override public FileEditor openFileEditor() { return myFileEditorManager.openFile(myPsiFile.getContainingFile().getVirtualFile(), false)[0]; } }; } @NotNull private PsiElement getPsiElement() { PsiElement e = null; if (myEditor != null) { final int offset = myEditor.getCaretModel().getOffset(); if (PsiDocumentManager.getInstance(myProject).hasUncommitedDocuments()) { PsiDocumentManager.getInstance(myProject).commitAllDocuments(); } e = getPsiFile().findElementAt(offset); } if (e == null) { e = getPsiFile(); } return e; } @Override @NotNull public VirtualFile getVirtualFile() { return getPsiFile().getVirtualFile(); } @Override public Object getSelectorInFile() { return getPsiElement(); } } } @Override public boolean isManualOrder(String paneId) { return getPaneOptionValue(myManualOrder, paneId, ourManualOrderDefaults); } @Override public void setManualOrder(@NotNull String paneId, final boolean enabled) { setPaneOption(myManualOrder, enabled, paneId, false); final AbstractProjectViewPane pane = getProjectViewPaneById(paneId); pane.installComparator(); } @Override public boolean isSortByType(String paneId) { return getPaneOptionValue(mySortByType, paneId, ourSortByTypeDefaults); } @Override public void setSortByType(@NotNull String paneId, final boolean sortByType) { setPaneOption(mySortByType, sortByType, paneId, false); final AbstractProjectViewPane pane = getProjectViewPaneById(paneId); pane.installComparator(); } private class ManualOrderAction extends ToggleAction implements DumbAware { private ManualOrderAction() { super(IdeBundle.message("action.manual.order"), IdeBundle.message("action.manual.order"), AllIcons.ObjectBrowser.Sorted); } @Override public boolean isSelected(AnActionEvent event) { return isManualOrder(getCurrentViewId()); } @Override public void setSelected(AnActionEvent event, boolean flag) { setManualOrder(getCurrentViewId(), flag); } @Override public void update(final AnActionEvent e) { super.update(e); final Presentation presentation = e.getPresentation(); AbstractProjectViewPane pane = getCurrentProjectViewPane(); presentation.setEnabledAndVisible(pane != null && pane.supportsManualOrder()); } } private class SortByTypeAction extends ToggleAction implements DumbAware { private SortByTypeAction() { super(IdeBundle.message("action.sort.by.type"), IdeBundle.message("action.sort.by.type"), AllIcons.ObjectBrowser.SortByType); } @Override public boolean isSelected(AnActionEvent event) { return isSortByType(getCurrentViewId()); } @Override public void setSelected(AnActionEvent event, boolean flag) { setSortByType(getCurrentViewId(), flag); } @Override public void update(final AnActionEvent e) { super.update(e); final Presentation presentation = e.getPresentation(); presentation.setVisible(getCurrentProjectViewPane() != null); } } private class FoldersAlwaysOnTopAction extends ToggleAction implements DumbAware { private FoldersAlwaysOnTopAction() { super("Folders Always on Top"); } @Override public boolean isSelected(AnActionEvent event) { return isFoldersAlwaysOnTop(); } @Override public void setSelected(AnActionEvent event, boolean flag) { setFoldersAlwaysOnTop(flag); } @Override public void update(final AnActionEvent e) { super.update(e); final Presentation presentation = e.getPresentation(); presentation.setEnabledAndVisible(getCurrentProjectViewPane() != null); } } private class ScrollFromSourceAction extends AnAction implements DumbAware { private ScrollFromSourceAction() { super("Scroll from Source", "Select the file open in the active editor", AllIcons.General.Locate); getTemplatePresentation().setHoveredIcon(AllIcons.General.LocateHover); } @Override public void actionPerformed(AnActionEvent e) { myAutoScrollFromSourceHandler.scrollFromSource(); } } @NotNull @Override public Collection<String> getPaneIds() { return myId2Pane.keySet(); } @NotNull @Override public Collection<SelectInTarget> getSelectInTargets() { ensurePanesLoaded(); return mySelectInTargets.values(); } @NotNull @Override public ActionCallback getReady(@NotNull Object requestor) { AbstractProjectViewPane pane = myId2Pane.get(myCurrentViewSubId); if (pane == null) { pane = myId2Pane.get(myCurrentViewId); } return pane != null ? pane.getReady(requestor) : ActionCallback.DONE; } }
NPE fix (IDEA-164074)
platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java
NPE fix (IDEA-164074)
<ide><path>latform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java <ide> } <ide> <ide> private void createToolbarActions() { <add> if (myActionGroup == null) return; <ide> List<AnAction> titleActions = ContainerUtil.newSmartList(); <ide> myActionGroup.removeAll(); <ide> if (ProjectViewDirectoryHelper.getInstance(myProject).supportsFlattenPackages()) {
Java
apache-2.0
1d3bed5ab0db77c0dbeb679d8b8f06cd21348085
0
mosoft521/curator,serranom/curator,serranom/curator,apache/curator,oza/curator,oza/curator,mosoft521/curator,apache/curator
/** * 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.curator.framework.imps; import org.apache.curator.CuratorZookeeperClient; import org.apache.curator.RetryLoop; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.EnsurePath; import org.apache.curator.utils.PathUtils; import org.apache.curator.utils.ThreadUtils; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.ZooDefs; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicBoolean; class NamespaceImpl { private final CuratorFrameworkImpl client; private final String namespace; private final AtomicBoolean ensurePathNeeded; NamespaceImpl(CuratorFrameworkImpl client, String namespace) { if ( namespace != null ) { try { PathUtils.validatePath("/" + namespace); } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException("Invalid namespace: " + namespace + ", " + e.getMessage()); } } this.client = client; this.namespace = namespace; ensurePathNeeded = new AtomicBoolean(namespace != null); } String getNamespace() { return namespace; } String unfixForNamespace(String path) { if ( (namespace != null) && (path != null) ) { String namespacePath = ZKPaths.makePath(namespace, null); if ( path.startsWith(namespacePath) ) { path = (path.length() > namespacePath.length()) ? path.substring(namespacePath.length()) : "/"; } } return path; } String fixForNamespace(String path, boolean isSequential) { if ( ensurePathNeeded.get() ) { try { final CuratorZookeeperClient zookeeperClient = client.getZookeeperClient(); RetryLoop.callWithRetry ( zookeeperClient, new Callable<Object>() { @Override public Object call() throws Exception { ZKPaths.mkdirs(zookeeperClient.getZooKeeper(), ZKPaths.makePath("/", namespace), true, client.getAclProvider(), true); return null; } } ); ensurePathNeeded.set(false); } catch ( Exception e ) { ThreadUtils.checkInterrupted(e); client.logError("Ensure path threw exception", e); } } return ZKPaths.fixForNamespace(namespace, path, isSequential); } EnsurePath newNamespaceAwareEnsurePath(String path) { return new EnsurePath(fixForNamespace(path, false), client.getAclProvider()); } }
curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceImpl.java
/** * 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.curator.framework.imps; import org.apache.curator.CuratorZookeeperClient; import org.apache.curator.RetryLoop; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.EnsurePath; import org.apache.curator.utils.PathUtils; import org.apache.curator.utils.ThreadUtils; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.ZooDefs; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicBoolean; class NamespaceImpl { private final CuratorFrameworkImpl client; private final String namespace; private final AtomicBoolean ensurePathNeeded; NamespaceImpl(CuratorFrameworkImpl client, String namespace) { if ( namespace != null ) { try { PathUtils.validatePath("/" + namespace); } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException("Invalid namespace: " + namespace); } } this.client = client; this.namespace = namespace; ensurePathNeeded = new AtomicBoolean(namespace != null); } String getNamespace() { return namespace; } String unfixForNamespace(String path) { if ( (namespace != null) && (path != null) ) { String namespacePath = ZKPaths.makePath(namespace, null); if ( path.startsWith(namespacePath) ) { path = (path.length() > namespacePath.length()) ? path.substring(namespacePath.length()) : "/"; } } return path; } String fixForNamespace(String path, boolean isSequential) { if ( ensurePathNeeded.get() ) { try { final CuratorZookeeperClient zookeeperClient = client.getZookeeperClient(); RetryLoop.callWithRetry ( zookeeperClient, new Callable<Object>() { @Override public Object call() throws Exception { ZKPaths.mkdirs(zookeeperClient.getZooKeeper(), ZKPaths.makePath("/", namespace), true, client.getAclProvider(), true); return null; } } ); ensurePathNeeded.set(false); } catch ( Exception e ) { ThreadUtils.checkInterrupted(e); client.logError("Ensure path threw exception", e); } } return ZKPaths.fixForNamespace(namespace, path, isSequential); } EnsurePath newNamespaceAwareEnsurePath(String path) { return new EnsurePath(fixForNamespace(path, false), client.getAclProvider()); } }
Fixes incomplete error message sent to caller
curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceImpl.java
Fixes incomplete error message sent to caller
<ide><path>urator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceImpl.java <ide> } <ide> catch ( IllegalArgumentException e ) <ide> { <del> throw new IllegalArgumentException("Invalid namespace: " + namespace); <add> throw new IllegalArgumentException("Invalid namespace: " + namespace + ", " + e.getMessage()); <ide> } <ide> } <ide>
JavaScript
isc
4858d3c61974376df072460fcc2600e1524a8472
0
cameronjacoby/globe_tweet,cameronjacoby/globetweet,cameronjacoby/globetweet,sahash182/globetweet
var express = require('express'), app = express(), http = require('http'), server = http.createServer(app), ejs = require('ejs'), bodyParser = require('body-parser'), Twit = require('twit'), io = require('socket.io').listen(server), config = require('./config/config.js'); server.listen(3000, function(){ console.log('server started on localhost:3000'); }); app.set('view engine', 'ejs'); app.use(express.static(__dirname + '/public')); app.use(bodyParser.urlencoded({extended: true})); app.get('/', function(req, res) { res.render('site/index', {location: ''}); }); var T = new Twit({ consumer_key: config.twitter.consumer_key, consumer_secret: config.twitter.consumer_secret, access_token: config.twitter.access_token, access_token_secret: config.twitter.access_token_secret }); var coord1 = '-122.75'; var coord2 = '36.8'; var coord3 = '-121.75'; var coord4 = '37.8'; var loc = [coord1, coord2, coord3, coord4]; var newLocation = null; var stream; var startSocNewLoc = function() { io.sockets.on('connection', function (socket) { console.log('CONNECTED'); stream = T.stream("statuses/filter", {locations: newLocation}); stream.on('tweet', function (tweet) { io.sockets.emit('stream', tweet.text + ":::::" + tweet.place.full_name); }); }); }; var startSocket = function() { io.sockets.on('connection', function (socket) { console.log('CONNECTED'); if (newLocation === null) { stream = T.stream("statuses/filter", {locations: loc}); stream.on('tweet', function (tweet) { io.sockets.emit('stream', tweet.text + ":::::" + tweet.place.full_name); }); } else { socket.disconnect(); console.log('STOPPED!!!'); startSocNewLoc(); } socket.on('location', function(loc) { console.log('Updating location to: ', loc); newLocation = loc; console.log('New location: ', newLocation); }); }); }; startSocket(); app.post('/search', function(req, res) { var location = req.body.location; console.log(location); res.render('site/index', {location: location}); }); app.get('/*', function(req, res) { res.status(404); res.render('site/404'); });
app.js
var express = require('express'), app = express(), http = require('http'), server = http.createServer(app), ejs = require('ejs'), bodyParser = require('body-parser'), Twit = require('twit'), io = require('socket.io').listen(server), config = require('./config/config.js'); server.listen(3000, function(){ console.log('server started on localhost:3000'); }); app.set('view engine', 'ejs'); app.use(express.static(__dirname + '/public')); app.use(bodyParser.urlencoded({extended: true})); app.get('/', function(req, res) { res.render('site/index', {location: ''}); }); var T = new Twit({ consumer_key: config.twitter.consumer_key, consumer_secret: config.twitter.consumer_secret, access_token: config.twitter.access_token, access_token_secret: config.twitter.access_token_secret }); var coord1 = '-122.75'; var coord2 = '36.8'; var coord3 = '-121.75'; var coord4 = '37.8'; var loc = [coord1, coord2, coord3, coord4]; io.sockets.on('connection', function (socket) { console.log('CONNECTED'); var stream = T.stream("statuses/filter", {locations: loc}); stream.on('tweet', function (tweet) { io.sockets.emit('stream', tweet.text + ":::::" + tweet.place.full_name); }); }); app.post('/search', function(req, res) { var location = req.body.location; console.log(location); res.render('site/index', {location: location}); }); app.get('/*', function(req, res) { res.status(404); res.render('site/404'); });
disconnect socket when new loc is searched
app.js
disconnect socket when new loc is searched
<ide><path>pp.js <ide> var coord3 = '-121.75'; <ide> var coord4 = '37.8'; <ide> var loc = [coord1, coord2, coord3, coord4]; <add>var newLocation = null; <add>var stream; <ide> <del>io.sockets.on('connection', function (socket) { <del> console.log('CONNECTED'); <del> var stream = T.stream("statuses/filter", {locations: loc}); <del> stream.on('tweet', function (tweet) { <del> io.sockets.emit('stream', tweet.text + ":::::" + tweet.place.full_name); <add> <add>var startSocNewLoc = function() { <add> io.sockets.on('connection', function (socket) { <add> console.log('CONNECTED'); <add> stream = T.stream("statuses/filter", {locations: newLocation}); <add> stream.on('tweet', function (tweet) { <add> io.sockets.emit('stream', tweet.text + ":::::" + tweet.place.full_name); <add> }); <ide> }); <del>}); <add>}; <add> <add> <add>var startSocket = function() { <add> <add> io.sockets.on('connection', function (socket) { <add> console.log('CONNECTED'); <add> <add> if (newLocation === null) { <add> <add> stream = T.stream("statuses/filter", {locations: loc}); <add> stream.on('tweet', function (tweet) { <add> io.sockets.emit('stream', tweet.text + ":::::" + tweet.place.full_name); <add> }); <add> <add> } else { <add> socket.disconnect(); <add> console.log('STOPPED!!!'); <add> startSocNewLoc(); <add> } <add> <add> socket.on('location', function(loc) { <add> console.log('Updating location to: ', loc); <add> newLocation = loc; <add> console.log('New location: ', newLocation); <add> }); <add> <add> }); <add>}; <add> <add>startSocket(); <ide> <ide> <ide> app.post('/search', function(req, res) {
Java
apache-2.0
82db2abbafdd8eb444d7bd3410e40fab138a515e
0
alexlehm/vertx-mail-client,alexlehm/vertx-mail-client
package io.vertx.ext.mail; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.impl.LoggerFactory; import io.vertx.core.net.NetClient; import io.vertx.core.net.NetClientOptions; import io.vertx.core.net.NetSocket; import io.vertx.ext.mail.mailutil.BounceGetter; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.mail.MessagingException; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.apache.commons.mail.Email; import org.apache.commons.mail.EmailException; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.digests.MD5Digest; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.params.KeyParameter; /* first implementation of a SMTP client */ // TODO: this is not really a verticle yet /** * @author <a href="http://oss.lehmann.cx/">Alexander Lehmann</a> * */ public class MailVerticle { private Vertx vertx; public MailVerticle(Vertx vertx, Handler<AsyncResult<JsonObject>> finishedHandler) { this.vertx = vertx; mailResult=Future.future(); mailResult.setHandler(finishedHandler); } private void write(NetSocket netSocket, String str) { write(netSocket, str, str); } // avoid logging password data private void write(NetSocket netSocket, String str, String logStr) { // avoid logging large mail body if(logStr.length()<1000) { log.info("command: " + logStr); } else { log.info("command: " + logStr.substring(0,1000)+"..."); } netSocket.write(str + "\r\n"); } private static final Logger log = LoggerFactory.getLogger(MailVerticle.class); NetSocket ns; Future<String> commandResult; Future<JsonObject> mailResult; private boolean capaStartTLS = false; private Set<String> capaAuth = Collections.emptySet(); // 8BITMIME can be used if the server supports it, currently this is not // implemented private boolean capa8BitMime = false; // PIPELINING is not yet used private boolean capaPipelining = false; private int capaSize = 0; Email email; String username; String pw; LoginOption login; public void sendMail(Email email, String username, String password, LoginOption login) { this.email = email; this.username = username; pw = password; this.login=login; NetClientOptions netClientOptions = new NetClientOptions().setSsl(email.isSSLOnConnect()); NetClient client = vertx.createNetClient(netClientOptions); client.connect(Integer.parseInt(email.getSmtpPort()), email.getHostName(), asyncResult -> { if (asyncResult.succeeded()) { ns = asyncResult.result(); commandResult = Future.future(); commandResult.setHandler(message -> serverGreeting(message)); final Handler<Buffer> mlp = new MultilineParser( buffer -> commandResult.complete(buffer.toString())); ns.handler(mlp); } else { log.error("exception", asyncResult.cause()); throwAsyncResult(asyncResult.cause()); } }); } private void serverGreeting(AsyncResult<String> result) { String message = result.result(); log.info("server greeting: " + message); if(isStatusOk(message)) { if(isEsmtpSupported(message)) { ehloCmd(); } else { heloCmd(); } } else { throwAsyncResult("got error response "+message); } } private boolean isEsmtpSupported(String message) { return message.contains("ESMTP"); } private int getStatusCode(String message) { if(message.length()<4) { return 500; } if(!message.substring(3,4).equals(" ") && !message.substring(3,4).equals("-")) { return 500; } try { return Integer.valueOf(message.substring(0,3)); } catch(NumberFormatException n) { return 500; } } private boolean isStatusOk(String message) { int statusCode=getStatusCode(message); return statusCode>=200 && statusCode<400; } private boolean isStatusFatal(String message) { return getStatusCode(message)>=500; } private boolean isStatusTemporary(String message) { int statusCode=getStatusCode(message); return statusCode>=400 && statusCode<500; } private void ehloCmd() { // TODO: get real hostname write(ns, "EHLO windows7"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("EHLO result: " + message); if(isStatusOk(message)) { setCapabilities(message); if (capaStartTLS && !ns.isSsl() && (email.isStartTLSRequired() || email.isStartTLSEnabled())) { // do not start TLS if we are connected with SSL // or are already in TLS startTLSCmd(); } else { if (!ns.isSsl() && email.isStartTLSRequired()) { log.warn("STARTTLS required but not supported by server"); commandResult.fail("STARTTLS required but not supported by server"); } else { if (login!=LoginOption.DISABLED && username != null && pw != null && !capaAuth.isEmpty()) { authCmd(); } else { if(login==LoginOption.REQUIRED) { if(username != null && pw != null) { throwAsyncResult("login is required, but no AUTH methods available. You may need do to STARTTLS"); } else { throwAsyncResult("login is required, but no credentials supplied"); } } else { mailFromCmd(); } } } } } else { // if EHLO fails, assume we have to do HELO heloCmd(); } }); } /** * @param message */ private void setCapabilities(String message) { List<String> capabilities = parseEhlo(message); for (String c : capabilities) { if (c.equals("STARTTLS")) { capaStartTLS = true; } if (c.startsWith("AUTH ")) { capaAuth = new HashSet<String>(Arrays.asList(c.substring(5) .split(" "))); } if (c.equals("8BITMIME")) { capa8BitMime = true; } if (c.startsWith("SIZE ")) { try { capaSize = Integer.parseInt(c.substring(5)); } catch(NumberFormatException n) { capaSize=0; } } } } private void heloCmd() { // TODO: get real hostname write(ns, "HELO windows7"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("HELO result: " + message); mailFromCmd(); }); } /** * */ private void startTLSCmd() { write(ns, "STARTTLS"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("STARTTLS result: " + message); upgradeTLS(); }); } private void upgradeTLS() { ns.upgradeToSsl(v -> { log.info("ssl started"); // capabilities may have changed, e.g. // if a service only announces PLAIN/LOGIN // on secure channel ehloCmd(); }); } private List<String> parseEhlo(String message) { // parse ehlo and other multiline replies List<String> v = new ArrayList<String>(); String resultCode = message.substring(0, 3); for (String l : message.split("\n")) { if (!l.startsWith(resultCode) || l.charAt(3) != '-' && l.charAt(3) != ' ') { log.error("format error in multiline response"); throwAsyncResult("format error in multiline response"); } else { v.add(l.substring(4)); } } return v; } private void authCmd() { if (capaAuth.contains("CRAM-MD5")) { write(ns, "AUTH CRAM-MD5"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("AUTH result: " + message); cramMD5Step1(message.substring(4)); }); } else if (capaAuth.contains("PLAIN")) { String authdata = base64("\0" + username + "\0" + pw); String authdummy = base64("\0dummy\0XXX"); write(ns, "AUTH PLAIN " + authdata, "AUTH PLAIN " + authdummy); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("AUTH result: " + message); if (!message.toString().startsWith("2")) { log.warn("authentication failed"); throwAsyncResult("authentication failed"); } else { mailFromCmd(); } }); } else if (capaAuth.contains("LOGIN")) { write(ns, "AUTH LOGIN"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("AUTH result: " + message); sendUsername(); }); } else { log.warn("cannot find supported auth method"); throwAsyncResult("cannot find supported auth method"); } } private void cramMD5Step1(String string) { String message = decodeb64(string); log.info("message " + message); String reply = hmacMD5hex(message, pw); write(ns, base64(username + " " + reply), base64("dummy XXX")); commandResult = Future.future(); commandResult.setHandler(result -> { String message2 = result.result(); log.info("AUTH step 2 result: " + message2); cramMD5Step2(message2); }); } private String hmacMD5hex(String message, String pw) { KeyParameter keyparameter; try { keyparameter = new KeyParameter(pw.getBytes("utf-8")); Mac mac = new HMac(new MD5Digest()); mac.init(keyparameter); byte[] messageBytes = message.getBytes("utf-8"); mac.update(messageBytes, 0, messageBytes.length); byte[] outBytes = new byte[mac.getMacSize()]; mac.doFinal(outBytes, 0); return Hex.encodeHexString(outBytes); } catch (UnsupportedEncodingException e) { // doesn't happen, auth will fail in that case return ""; } } private void cramMD5Step2(String message) { log.info(message); if (isStatusOk(message)) { mailFromCmd(); } else { log.warn("authentication failed"); throwAsyncResult("authentication failed"); } } private void sendUsername() { write(ns, base64(username), base64("dummy")); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("username result: " + message); sendPw(); }); } private void sendPw() { write(ns, base64(pw), base64("XXX")); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("pw result: " + message); if (isStatusOk(message)) { mailFromCmd(); } else { log.warn("authentication failed"); throwAsyncResult("authentication failed"); } }); } private void mailFromCmd() { try { // prefer bounce address over from address // currently (1.3.3) commons mail is missing the getter for bounceAddress // I have requested that https://issues.apache.org/jira/browse/EMAIL-146 String fromAddr = email.getFromAddress().getAddress(); if (email instanceof BounceGetter) { String bounceAddr = ((BounceGetter) email).getBounceAddress(); if (bounceAddr != null && !bounceAddr.isEmpty()) { fromAddr = bounceAddr; } } InternetAddress.parse(fromAddr, true); write(ns, "MAIL FROM:<" + fromAddr + ">"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("MAIL FROM result: " + message); if(isStatusOk(message)) { rcptToCmd(); } else { log.warn("sender address not accepted: "+message); throwAsyncResult("sender address not accepted: "+message); } }); } catch (AddressException e) { log.error("address exception", e); throwAsyncResult(e); } } private void rcptToCmd() { try { // FIXME: have to handle all addresses String toAddr = email.getToAddresses().get(0).getAddress(); InternetAddress.parse(toAddr, true); write(ns, "RCPT TO:<" + toAddr + ">"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("RCPT TO result: " + message); if(isStatusOk(message)) { dataCmd(); } else { log.warn("recipient address not accepted: "+message); throwAsyncResult("recipient address not accepted: "+message); } }); } catch (AddressException e) { log.error("address exception", e); throwAsyncResult(e); } } private void dataCmd() { write(ns, "DATA"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("DATA result: " + message); if(isStatusOk(message)) { sendMaildata(); } else { log.warn("DATA command not accepted: "+message); throwAsyncResult("DATA command not accepted: "+message); } }); } private void sendMaildata() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { email.buildMimeMessage(); email.getMimeMessage().writeTo(bos); } catch (IOException | MessagingException | EmailException e) { log.error("cannot create mime message", e); throwAsyncResult("cannot create mime message"); } String message=bos.toString(); // fail delivery if we exceed size // TODO: we should do that earlier after the EHLO reply if(capaSize>0 && message.length()>capaSize) { throwAsyncResult("message exceeds allowed size"); } // convert message to escape . at the start of line // TODO: this is probably bad for large messages write(ns, message.replaceAll("\n\\.", "\n..") + "\r\n."); commandResult = Future.future(); commandResult.setHandler(result -> { String messageReply=result.result(); log.info("maildata result: " + messageReply); if(isStatusOk(messageReply)) { quitCmd(); } else { log.warn("sending data failed: "+messageReply); throwAsyncResult("sending data failed: "+messageReply); } }); } private void quitCmd() { write(ns, "QUIT"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("QUIT result: " + message); if(isStatusOk(message)) { shutdownConnection(); } else { log.warn("quit failed: "+message); throwAsyncResult("quit failed: "+message); } }); } private void shutdownConnection() { ns.close(); JsonObject result=new JsonObject(); result.put("result", "success"); mailResult.complete(result); } private void throwAsyncResult(Throwable throwable) { mailResult.fail(throwable); } private void throwAsyncResult(String message) { mailResult.fail(message); } private String base64(String string) { try { // this call does not create multi-line base64 data // (if someone uses a password longer than 57 chars or // one of the other SASL replies is longer than 76 chars) return Base64.encodeBase64String(string.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // doesn't happen return ""; } } private String decodeb64(String string) { try { return new String(Base64.decodeBase64(string), "UTF-8"); } catch (UnsupportedEncodingException e) { // doesn't happen return ""; } } }
src/main/java/io/vertx/ext/mail/MailVerticle.java
package io.vertx.ext.mail; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.impl.LoggerFactory; import io.vertx.core.net.NetClient; import io.vertx.core.net.NetClientOptions; import io.vertx.core.net.NetSocket; import io.vertx.ext.mail.mailutil.BounceGetter; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.mail.MessagingException; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.apache.commons.mail.Email; import org.apache.commons.mail.EmailException; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.digests.MD5Digest; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.params.KeyParameter; /* first implementation of a SMTP client */ // TODO: this is not really a verticle yet /** * @author <a href="http://oss.lehmann.cx/">Alexander Lehmann</a> * */ public class MailVerticle { private Vertx vertx; public MailVerticle(Vertx vertx, Handler<AsyncResult<JsonObject>> finishedHandler) { this.vertx = vertx; mailResult=Future.future(); mailResult.setHandler(finishedHandler); } private void write(NetSocket netSocket, String str) { write(netSocket, str, str); } // avoid logging password data private void write(NetSocket netSocket, String str, String logStr) { log.info("command: " + logStr); netSocket.write(str + "\r\n"); } private static final Logger log = LoggerFactory.getLogger(MailVerticle.class); NetSocket ns; Future<String> commandResult; Future<JsonObject> mailResult; private boolean capaStartTLS = false; private Set<String> capaAuth = Collections.emptySet(); // 8BITMIME can be used if the server supports it, currently this is not // implemented private boolean capa8BitMime = false; // PIPELINING is not yet used private boolean capaPipelining = false; private int capaSize = 0; Email email; String username; String pw; LoginOption login; public void sendMail(Email email, String username, String password, LoginOption login) { this.email = email; this.username = username; pw = password; this.login=login; NetClientOptions netClientOptions = new NetClientOptions().setSsl(email.isSSLOnConnect()); NetClient client = vertx.createNetClient(netClientOptions); client.connect(Integer.parseInt(email.getSmtpPort()), email.getHostName(), asyncResult -> { if (asyncResult.succeeded()) { ns = asyncResult.result(); commandResult = Future.future(); commandResult.setHandler(message -> serverGreeting(message)); final Handler<Buffer> mlp = new MultilineParser( buffer -> commandResult.complete(buffer.toString())); ns.handler(mlp); } else { log.error("exception", asyncResult.cause()); throwAsyncResult(asyncResult.cause()); } }); } private void serverGreeting(AsyncResult<String> result) { String message = result.result(); log.info("server greeting: " + message); if(isStatusOk(message)) { if(isEsmtpSupported(message)) { ehloCmd(); } else { heloCmd(); } } else { throwAsyncResult("got error response "+message); } } private boolean isEsmtpSupported(String message) { return message.contains("ESMTP"); } private int getStatusCode(String message) { if(message.length()<4) { return 500; } if(!message.substring(3,4).equals(" ") && !message.substring(3,4).equals("-")) { return 500; } try { return Integer.valueOf(message.substring(0,3)); } catch(NumberFormatException n) { return 500; } } private boolean isStatusOk(String message) { int statusCode=getStatusCode(message); return statusCode>=200 && statusCode<400; } private boolean isStatusFatal(String message) { return getStatusCode(message)>=500; } private boolean isStatusTemporary(String message) { int statusCode=getStatusCode(message); return statusCode>=400 && statusCode<500; } private void ehloCmd() { // TODO: get real hostname write(ns, "EHLO windows7"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("EHLO result: " + message); if(isStatusOk(message)) { setCapabilities(message); if (capaStartTLS && !ns.isSsl() && (email.isStartTLSRequired() || email.isStartTLSEnabled())) { // do not start TLS if we are connected with SSL // or are already in TLS startTLSCmd(); } else { if (!ns.isSsl() && email.isStartTLSRequired()) { log.warn("STARTTLS required but not supported by server"); commandResult.fail("STARTTLS required but not supported by server"); } else { if (login!=LoginOption.DISABLED && username != null && pw != null && !capaAuth.isEmpty()) { authCmd(); } else { if(login==LoginOption.REQUIRED) { if(username != null && pw != null) { throwAsyncResult("login is required, but no AUTH methods available. You may need do to STARTTLS"); } else { throwAsyncResult("login is required, but no credentials supplied"); } } else { mailFromCmd(); } } } } } else { // if EHLO fails, assume we have to do HELO heloCmd(); } }); } /** * @param message */ private void setCapabilities(String message) { List<String> capabilities = parseEhlo(message); for (String c : capabilities) { if (c.equals("STARTTLS")) { capaStartTLS = true; } if (c.startsWith("AUTH ")) { capaAuth = new HashSet<String>(Arrays.asList(c.substring(5) .split(" "))); } if (c.equals("8BITMIME")) { capa8BitMime = true; } if (c.startsWith("SIZE ")) { try { capaSize = Integer.parseInt(c.substring(5)); } catch(NumberFormatException n) { capaSize=0; } } } } private void heloCmd() { // TODO: get real hostname write(ns, "HELO windows7"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("HELO result: " + message); mailFromCmd(); }); } /** * */ private void startTLSCmd() { write(ns, "STARTTLS"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("STARTTLS result: " + message); upgradeTLS(); }); } private void upgradeTLS() { ns.upgradeToSsl(v -> { log.info("ssl started"); // capabilities may have changed, e.g. // if a service only announces PLAIN/LOGIN // on secure channel ehloCmd(); }); } private List<String> parseEhlo(String message) { // parse ehlo and other multiline replies List<String> v = new ArrayList<String>(); String resultCode = message.substring(0, 3); for (String l : message.split("\n")) { if (!l.startsWith(resultCode) || l.charAt(3) != '-' && l.charAt(3) != ' ') { log.error("format error in multiline response"); throwAsyncResult("format error in multiline response"); } else { v.add(l.substring(4)); } } return v; } private void authCmd() { if (capaAuth.contains("CRAM-MD5")) { write(ns, "AUTH CRAM-MD5"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("AUTH result: " + message); cramMD5Step1(message.substring(4)); }); } else if (capaAuth.contains("PLAIN")) { String authdata = base64("\0" + username + "\0" + pw); String authdummy = base64("\0dummy\0XXX"); write(ns, "AUTH PLAIN " + authdata, "AUTH PLAIN " + authdummy); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("AUTH result: " + message); if (!message.toString().startsWith("2")) { log.warn("authentication failed"); throwAsyncResult("authentication failed"); } else { mailFromCmd(); } }); } else if (capaAuth.contains("LOGIN")) { write(ns, "AUTH LOGIN"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("AUTH result: " + message); sendUsername(); }); } else { log.warn("cannot find supported auth method"); throwAsyncResult("cannot find supported auth method"); } } private void cramMD5Step1(String string) { String message = decodeb64(string); log.info("message " + message); String reply = hmacMD5hex(message, pw); write(ns, base64(username + " " + reply), base64("dummy XXX")); commandResult = Future.future(); commandResult.setHandler(result -> { String message2 = result.result(); log.info("AUTH step 2 result: " + message2); cramMD5Step2(message2); }); } private String hmacMD5hex(String message, String pw) { KeyParameter keyparameter; try { keyparameter = new KeyParameter(pw.getBytes("utf-8")); Mac mac = new HMac(new MD5Digest()); mac.init(keyparameter); byte[] messageBytes = message.getBytes("utf-8"); mac.update(messageBytes, 0, messageBytes.length); byte[] outBytes = new byte[mac.getMacSize()]; mac.doFinal(outBytes, 0); return Hex.encodeHexString(outBytes); } catch (UnsupportedEncodingException e) { // doesn't happen, auth will fail in that case return ""; } } private void cramMD5Step2(String message) { log.info(message); if (isStatusOk(message)) { mailFromCmd(); } else { log.warn("authentication failed"); throwAsyncResult("authentication failed"); } } private void sendUsername() { write(ns, base64(username), base64("dummy")); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("username result: " + message); sendPw(); }); } private void sendPw() { write(ns, base64(pw), base64("XXX")); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("pw result: " + message); if (isStatusOk(message)) { mailFromCmd(); } else { log.warn("authentication failed"); throwAsyncResult("authentication failed"); } }); } private void mailFromCmd() { try { // prefer bounce address over from address // currently (1.3.3) commons mail is missing the getter for bounceAddress // I have requested that https://issues.apache.org/jira/browse/EMAIL-146 String fromAddr = email.getFromAddress().getAddress(); if (email instanceof BounceGetter) { String bounceAddr = ((BounceGetter) email).getBounceAddress(); if (bounceAddr != null && !bounceAddr.isEmpty()) { fromAddr = bounceAddr; } } InternetAddress.parse(fromAddr, true); write(ns, "MAIL FROM:<" + fromAddr + ">"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("MAIL FROM result: " + message); if(isStatusOk(message)) { rcptToCmd(); } else { log.warn("sender address not accepted: "+message); throwAsyncResult("sender address not accepted: "+message); } }); } catch (AddressException e) { log.error("address exception", e); throwAsyncResult(e); } } private void rcptToCmd() { try { // FIXME: have to handle all addresses String toAddr = email.getToAddresses().get(0).getAddress(); InternetAddress.parse(toAddr, true); write(ns, "RCPT TO:<" + toAddr + ">"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("RCPT TO result: " + message); if(isStatusOk(message)) { dataCmd(); } else { log.warn("recipient address not accepted: "+message); throwAsyncResult("recipient address not accepted: "+message); } }); } catch (AddressException e) { log.error("address exception", e); throwAsyncResult(e); } } private void dataCmd() { write(ns, "DATA"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("DATA result: " + message); if(isStatusOk(message)) { sendMaildata(); } else { log.warn("DATA command not accepted: "+message); throwAsyncResult("DATA command not accepted: "+message); } }); } private void sendMaildata() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { email.buildMimeMessage(); email.getMimeMessage().writeTo(bos); } catch (IOException | MessagingException | EmailException e) { log.error("cannot create mime message", e); throwAsyncResult("cannot create mime message"); } String message=bos.toString(); // fail delivery if we exceed size // TODO: we should do that earlier after the EHLO reply if(capaSize>0 && message.length()>capaSize) { throwAsyncResult("message exceeds allowed size"); } // convert message to escape . at the start of line // TODO: this is probably bad for large messages write(ns, message.replaceAll("\n\\.", "\n..") + "\r\n."); commandResult = Future.future(); commandResult.setHandler(result -> { String messageReply=result.result(); log.info("maildata result: " + messageReply); if(isStatusOk(messageReply)) { quitCmd(); } else { log.warn("sending data failed: "+messageReply); throwAsyncResult("sending data failed: "+messageReply); } }); } private void quitCmd() { write(ns, "QUIT"); commandResult = Future.future(); commandResult.setHandler(result -> { String message=result.result(); log.info("QUIT result: " + message); if(isStatusOk(message)) { shutdownConnection(); } else { log.warn("quit failed: "+message); throwAsyncResult("quit failed: "+message); } }); } private void shutdownConnection() { ns.close(); JsonObject result=new JsonObject(); result.put("result", "success"); mailResult.complete(result); } private void throwAsyncResult(Throwable throwable) { mailResult.fail(throwable); } private void throwAsyncResult(String message) { mailResult.fail(message); } private String base64(String string) { try { // this call does not create multi-line base64 data // (if someone uses a password longer than 57 chars or // one of the other SASL replies is longer than 76 chars) return Base64.encodeBase64String(string.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // doesn't happen return ""; } } private String decodeb64(String string) { try { return new String(Base64.decodeBase64(string), "UTF-8"); } catch (UnsupportedEncodingException e) { // doesn't happen return ""; } } }
avoid logging large mail body Signed-off-by: alexlehm <[email protected]>
src/main/java/io/vertx/ext/mail/MailVerticle.java
avoid logging large mail body
<ide><path>rc/main/java/io/vertx/ext/mail/MailVerticle.java <ide> <ide> // avoid logging password data <ide> private void write(NetSocket netSocket, String str, String logStr) { <del> log.info("command: " + logStr); <add> // avoid logging large mail body <add> if(logStr.length()<1000) { <add> log.info("command: " + logStr); <add> } else { <add> log.info("command: " + logStr.substring(0,1000)+"..."); <add> } <ide> netSocket.write(str + "\r\n"); <ide> } <ide>
JavaScript
isc
dbd57b23b81a75c4ace35f399323662c91e03dc2
0
ph0bos/express-microservice-starter
'use strict'; /* * Dependencies */ var VitalSigns = require('vitalsigns'); var zoologist = require('./zoologist'); /** * Initialize Vitals * * @returns {VitalSigns} */ module.exports = function() { var vitals = new VitalSigns(); // Standard Vitals vitals.monitor('mem', { units: 'MB' }); vitals.monitor('uptime'); if (zoologist.isInitialised()) { // ZooKeeper Vitals vitals.monitor({ name: 'zookeeper', report: function() { return { status: (zoologist.getClient().getClient().getState().name === 'SYNC_CONNECTED') ? 'UP' : 'DOWN', connectionState: zoologist.getClient().getClient().getState().name, connecionString: zoologist.getClient().getClient().connectionManager.connectionStringParser.connectionString } } }); // Microservice Vitals vitals.monitor({ name: 'microservice', report: function() { if (!zoologist.getServiceDiscovery() || !zoologist.getServiceDiscovery().getData()) { return { status: (zoologist.getClient().getClient().getState().name === 'SYNC_CONNECTED') ? 'UP' : 'DOWN' } } return { id: zoologist.getServiceDiscovery().getData().id, status: (zoologist.getClient().getClient().getState().name === 'SYNC_CONNECTED') ? 'UP' : 'DOWN', name: zoologist.getServiceInstance().getData().name, basePath: zoologist.getServiceInstance().basePath, address: zoologist.getServiceInstance().getData().address, port: zoologist.getServiceInstance().getData().port, registrationTime: new Date(zoologist.getServiceInstance().getData().registrationTimeUTC) } } }); vitals.unhealthyWhen('zookeeper', 'status').equals("DOWN"); vitals.unhealthyWhen('microservice', 'status').equals("DOWN"); } return vitals; }
lib/vital-signs.js
'use strict'; /* * Dependencies */ var VitalSigns = require('vitalsigns'); var zoologist = require('./zoologist'); /** * Initialize Vitals * * @returns {VitalSigns} */ module.exports = function() { var vitals = new VitalSigns(); // Standard Vitals vitals.monitor('cpu'); vitals.monitor('mem', {units: 'MB'}); vitals.monitor('tick'); vitals.monitor('uptime'); if (zoologist.isInitialised()) { // ZooKeeper Vitals vitals.monitor({ name: 'zookeeper', report: function() { return { status: (zoologist.getClient().getClient().getState().name === 'SYNC_CONNECTED') ? 'UP' : 'DOWN', connectionState: zoologist.getClient().getClient().getState().name, connecionString: zoologist.getClient().getClient().connectionManager.connectionStringParser.connectionString } } }); // Microservice Vitals vitals.monitor({ name: 'microservice', report: function() { if (!zoologist.getServiceDiscovery() || !zoologist.getServiceDiscovery().getData()) { return { status: (zoologist.getClient().getClient().getState().name === 'SYNC_CONNECTED') ? 'UP' : 'DOWN' } } return { id: zoologist.getServiceDiscovery().getData().id, status: (zoologist.getClient().getClient().getState().name === 'SYNC_CONNECTED') ? 'UP' : 'DOWN', name: zoologist.getServiceInstance().getData().name, basePath: zoologist.getServiceInstance().basePath, address: zoologist.getServiceInstance().getData().address, port: zoologist.getServiceInstance().getData().port, registrationTime: new Date(zoologist.getServiceInstance().getData().registrationTimeUTC) } } }); vitals.unhealthyWhen('zookeeper', 'status').equals("DOWN"); vitals.unhealthyWhen('microservice', 'status').equals("DOWN"); } // Health Checks vitals.unhealthyWhen('cpu', 'usage').equals(100); vitals.unhealthyWhen('tick', 'maxMs').greaterThan(500); return vitals; }
Remove cpu health checks to reduce overall CPU utilisation On profiling the CPU this health check caused ~7% CPU usage continuously.
lib/vital-signs.js
Remove cpu health checks to reduce overall CPU utilisation
<ide><path>ib/vital-signs.js <ide> var vitals = new VitalSigns(); <ide> <ide> // Standard Vitals <del> vitals.monitor('cpu'); <del> vitals.monitor('mem', {units: 'MB'}); <del> vitals.monitor('tick'); <add> vitals.monitor('mem', { units: 'MB' }); <ide> vitals.monitor('uptime'); <ide> <ide> if (zoologist.isInitialised()) { <ide> vitals.unhealthyWhen('microservice', 'status').equals("DOWN"); <ide> } <ide> <del> // Health Checks <del> vitals.unhealthyWhen('cpu', 'usage').equals(100); <del> vitals.unhealthyWhen('tick', 'maxMs').greaterThan(500); <del> <ide> return vitals; <ide> }
JavaScript
mit
5cd2d6a79fdec07376000721a9edc1443e07c551
0
Luceos/core,datitisev/core,datitisev/core,malayladu/core,Albert221/core,flarum/core,kirkbushell/core,Albert221/core,datitisev/core,renyuneyun/core,kirkbushell/core,flarum/core,Albert221/core,renyuneyun/core,renyuneyun/core,Luceos/core,flarum/core,renyuneyun/core,datitisev/core,malayladu/core,malayladu/core,Luceos/core,kirkbushell/core,malayladu/core,Luceos/core,kirkbushell/core,Albert221/core
import Modal from 'flarum/components/Modal'; import Button from 'flarum/components/Button'; import Badge from 'flarum/components/Badge'; import Group from 'flarum/models/Group'; /** * The `EditGroupModal` component shows a modal dialog which allows the user * to create or edit a group. */ export default class EditGroupModal extends Modal { init() { this.group = this.props.group || app.store.createRecord('groups'); this.nameSingular = m.prop(this.group.nameSingular() || ''); this.namePlural = m.prop(this.group.namePlural() || ''); this.icon = m.prop(this.group.icon() || ''); this.color = m.prop(this.group.color() || ''); } className() { return 'EditGroupModal Modal--small'; } title() { return [ this.color() || this.icon() ? Badge.component({ icon: this.icon(), style: {backgroundColor: this.color()} }) : '', ' ', this.namePlural() || app.trans('core.admin.edit_group_title') ]; } content() { return ( <div className="Modal-body"> <div className="Form"> <div className="Form-group"> <label>{app.trans('core.admin.edit_group_name_label')}</label> <div className="EditGroupModal-name-input"> <input className="FormControl" placeholder="Singular (e.g. Mod)" value={this.nameSingular()} oninput={m.withAttr('value', this.nameSingular)}/> <input className="FormControl" placeholder="Plural (e.g. Mods)" value={this.namePlural()} oninput={m.withAttr('value', this.namePlural)}/> </div> </div> <div className="Form-group"> <label>{app.trans('core.admin.edit_group_color_label')}</label> <input className="FormControl" placeholder="#aaaaaa" value={this.color()} oninput={m.withAttr('value', this.color)}/> </div> <div className="Form-group"> <label>{app.trans('core.admin.edit_group_icon_label')}</label> <div className="helpText"> {app.trans('core.admin.edit_group_icon_text', {a: <a href="http://fortawesome.github.io/Font-Awesome/icons/" tabindex="-1"/>}, {em: <em/>}, {code: <code/>})} </div> <input className="FormControl" placeholder="bolt" value={this.icon()} oninput={m.withAttr('value', this.icon)}/> </div> <div className="Form-group"> {Button.component({ type: 'submit', className: 'Button Button--primary EditGroupModal-save', loading: this.loading, children: app.trans('core.admin.edit_group_submit_button') })} {this.group.exists && this.group.id() !== Group.ADMINISTRATOR_ID ? ( <button type="button" className="Button EditGroupModal-delete" onclick={this.deleteGroup.bind(this)}> {app.trans('core.admin.edit_group_delete_button')} </button> ) : ''} </div> </div> </div> ); } onsubmit(e) { e.preventDefault(); this.loading = true; this.group.save({ nameSingular: this.nameSingular(), namePlural: this.namePlural(), color: this.color(), icon: this.icon() }).then( () => this.hide(), (response) => { this.loading = false; this.handleErrors(response); } ); } deleteGroup() { if (confirm(app.trans('core.admin.edit_group_delete_confirmation'))) { this.group.delete().then(() => m.redraw()); this.hide(); } } }
js/admin/src/components/EditGroupModal.js
import Modal from 'flarum/components/Modal'; import Button from 'flarum/components/Button'; import Badge from 'flarum/components/Badge'; import Group from 'flarum/models/Group'; /** * The `EditGroupModal` component shows a modal dialog which allows the user * to create or edit a group. */ export default class EditGroupModal extends Modal { init() { this.group = this.props.group || app.store.createRecord('groups'); this.nameSingular = m.prop(this.group.nameSingular() || ''); this.namePlural = m.prop(this.group.namePlural() || ''); this.icon = m.prop(this.group.icon() || ''); this.color = m.prop(this.group.color() || ''); } className() { return 'EditGroupModal Modal--small'; } title() { return [ this.color() || this.icon() ? Badge.component({ icon: this.icon(), style: {backgroundColor: this.color()} }) : '', ' ', this.namePlural() || app.trans('core.admin.edit_group_title') ]; } content() { return ( <div className="Modal-body"> <div className="Form"> <div className="Form-group"> <label>{app.trans('core.admin.edit_group_name_label')}</label> <div className="EditGroupModal-name-input"> <input className="FormControl" placeholder="Singular (e.g. Mod)" value={this.nameSingular()} oninput={m.withAttr('value', this.nameSingular)}/> <input className="FormControl" placeholder="Plural (e.g. Mods)" value={this.namePlural()} oninput={m.withAttr('value', this.namePlural)}/> </div> </div> <div className="Form-group"> <label>{app.trans('core.admin.edit_group_color_label')}</label> <input className="FormControl" placeholder="#aaaaaa" value={this.color()} oninput={m.withAttr('value', this.color)}/> </div> <div className="Form-group"> <label>{app.trans('core.admin.edit_group_icon_label')}</label> <div className="helpText"> {app.trans('core.admin.edit_group_icon_text', {a: <a href="http://fortawesome.github.io/Font-Awesome/icons/" tabindex="-1"/>}, {em: <em/>}, {code: <code/>})} </div> <input className="FormControl" placeholder="bolt" value={this.icon()} oninput={m.withAttr('value', this.icon)}/> </div> <div className="Form-group"> {Button.component({ type: 'submit', className: 'Button Button--primary EditGroupModal-save', loading: this.loading, children: app.trans('core.admin.edit_group_submit_button') })} {this.group.exists && this.group.id() !== Group.ADMINISTRATOR_ID ? ( <button type="button" className="Button EditGroupModal-delete" onclick={this.delete.bind(this)}> {app.trans('core.admin.edit_group_delete_button')} </button> ) : ''} </div> </div> </div> ); } onsubmit(e) { e.preventDefault(); this.loading = true; this.group.save({ nameSingular: this.nameSingular(), namePlural: this.namePlural(), color: this.color(), icon: this.icon() }).then( () => this.hide(), () => { this.loading = false; m.redraw(); } ); } delete() { if (confirm(app.trans('core.admin.edit_group_delete_confirmation'))) { this.group.delete().then(() => m.redraw()); this.hide(); } } }
Add error handling to edit group modal
js/admin/src/components/EditGroupModal.js
Add error handling to edit group modal
<ide><path>s/admin/src/components/EditGroupModal.js <ide> children: app.trans('core.admin.edit_group_submit_button') <ide> })} <ide> {this.group.exists && this.group.id() !== Group.ADMINISTRATOR_ID ? ( <del> <button type="button" className="Button EditGroupModal-delete" onclick={this.delete.bind(this)}> <add> <button type="button" className="Button EditGroupModal-delete" onclick={this.deleteGroup.bind(this)}> <ide> {app.trans('core.admin.edit_group_delete_button')} <ide> </button> <ide> ) : ''} <ide> icon: this.icon() <ide> }).then( <ide> () => this.hide(), <del> () => { <add> (response) => { <ide> this.loading = false; <del> m.redraw(); <add> this.handleErrors(response); <ide> } <ide> ); <ide> } <ide> <del> delete() { <add> deleteGroup() { <ide> if (confirm(app.trans('core.admin.edit_group_delete_confirmation'))) { <ide> this.group.delete().then(() => m.redraw()); <ide> this.hide();
Java
apache-2.0
error: pathspec 'ph-oton-uicore/src/main/java/com/helger/photon/uicore/html/HCExtImg.java' did not match any file(s) known to git
c871f4e3fb5d83b09cdb7b9c34bb1387b21fb6f1
1
phax/ph-oton,phax/ph-oton,phax/ph-oton
/** * Copyright (C) 2015-2017 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * 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.helger.photon.uicore.html; import javax.annotation.Nonnull; import com.helger.commons.gfx.ImageDataManager; import com.helger.commons.url.ISimpleURL; import com.helger.commons.url.SimpleURL; import com.helger.html.hc.html.embedded.AbstractHCImg; import com.helger.photon.basic.app.io.WebFileIO; import com.helger.servlet.request.RequestHelper; public class HCExtImg extends AbstractHCImg <HCExtImg> { public HCExtImg (@Nonnull final ISimpleURL aSrc) { setSrc (aSrc); // Remove the session ID (if any) final String sPureSrc = new SimpleURL (RequestHelper.getWithoutSessionID (aSrc.getPath ()), aSrc.params (), aSrc.getAnchor ()).getAsStringWithEncodedParameters (); setExtent (ImageDataManager.getInstance ().getImageSize (WebFileIO.getServletContextIO ().getResource (sPureSrc))); } }
ph-oton-uicore/src/main/java/com/helger/photon/uicore/html/HCExtImg.java
Image with extent
ph-oton-uicore/src/main/java/com/helger/photon/uicore/html/HCExtImg.java
Image with extent
<ide><path>h-oton-uicore/src/main/java/com/helger/photon/uicore/html/HCExtImg.java <add>/** <add> * Copyright (C) 2015-2017 Philip Helger (www.helger.com) <add> * philip[at]helger[dot]com <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package com.helger.photon.uicore.html; <add> <add>import javax.annotation.Nonnull; <add> <add>import com.helger.commons.gfx.ImageDataManager; <add>import com.helger.commons.url.ISimpleURL; <add>import com.helger.commons.url.SimpleURL; <add>import com.helger.html.hc.html.embedded.AbstractHCImg; <add>import com.helger.photon.basic.app.io.WebFileIO; <add>import com.helger.servlet.request.RequestHelper; <add> <add>public class HCExtImg extends AbstractHCImg <HCExtImg> <add>{ <add> public HCExtImg (@Nonnull final ISimpleURL aSrc) <add> { <add> setSrc (aSrc); <add> <add> // Remove the session ID (if any) <add> final String sPureSrc = new SimpleURL (RequestHelper.getWithoutSessionID (aSrc.getPath ()), <add> aSrc.params (), <add> aSrc.getAnchor ()).getAsStringWithEncodedParameters (); <add> setExtent (ImageDataManager.getInstance ().getImageSize (WebFileIO.getServletContextIO ().getResource (sPureSrc))); <add> } <add>}
JavaScript
mit
95469c530b4953ac85a8ec2defc70b038913e7d5
0
ClinGen/clincoded,ClinGen/clincoded,ClinGen/clincoded,ClinGen/clincoded,ClinGen/clincoded
"use strict"; import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; import { FormMixin, Input } from '../../libs/bootstrap/form'; import { external_url_map } from '../globals'; import { DiseaseModal } from './modal'; import ModalComponent from '../../libs/bootstrap/modal'; var curator = require('../curator'); var CuratorHistory = require('../curator_history'); var RestMixin = require('../rest').RestMixin; var parseAndLogError = require('../mixins').parseAndLogError; /** * Component for adding/deleting disease associated with an interpretation in VCI */ const InterpretationDisease = module.exports.InterpretationDisease = createReactClass({ mixins: [RestMixin, FormMixin, CuratorHistory], propTypes: { interpretation: PropTypes.object, variantData: PropTypes.object, hasAssociatedDisease: PropTypes.bool, editKey: PropTypes.string, updateInterpretationObj: PropTypes.func, calculatedAssertion: PropTypes.string, provisionalPathogenicity: PropTypes.string, diseaseObj: PropTypes.object, updateDiseaseObj: PropTypes.func, session: PropTypes.object }, getInitialState() { return { interpretation: this.props.interpretation, diseaseObj: this.props.diseaseObj, diseaseId: '', diseaseTerm: null, diseaseDescription: null, synonyms: [], phenotypes: [], diseaseFreeTextConfirm: false, submitResourceBusy: false }; }, componentDidMount() { let interpretation = this.props.interpretation; if (interpretation && interpretation.disease) { this.setDiseaseObjectStates(interpretation.disease); } }, componentWillReceiveProps(nextProps) { if (nextProps.interpretation) { this.setState({interpretation: nextProps.interpretation}); } if (nextProps.diseaseObj) { this.setState({diseaseObj: nextProps.diseaseObj}, () => { let diseaseObj = this.state.diseaseObj; if (Object.keys(diseaseObj).length) { this.setDiseaseObjectStates(diseaseObj); } }); } }, /** * Shared method called by componentDidMount(), componentWillReceiveProps(nextProps) * @param {*} disease */ setDiseaseObjectStates(disease) { if (disease.diseaseId) { this.setState({diseaseId: disease.diseaseId}); } if (disease.term) { this.setState({diseaseTerm: disease.term}); } if (disease.description) { this.setState({diseaseDescription: disease.description}); } if (disease.synonyms) { this.setState({synonyms: disease.synonyms}); } if (disease.phenotypes) { this.setState({phenotypes: disease.phenotypes}); } if (disease.freetext) { this.setState({diseaseFreeTextConfirm: disease.freetext}); } }, passDataToParent(diseaseId, term, description, synonyms, phenotypes, freetext) { let diseaseObj = this.state.diseaseObj; if (diseaseId) { /** * Changing colon to underscore in id string for database */ diseaseObj['diseaseId'] = diseaseId.replace(':', '_'); this.setState({diseaseId: diseaseId}); } if (term) { diseaseObj['term'] = term; this.setState({diseaseTerm: term}); } if (description) { diseaseObj['description'] = description; this.setState({diseaseDescription: description}); } else { if (diseaseObj['description']) { delete diseaseObj['description']; } this.setState({diseaseDescription: null}); } if (synonyms && synonyms.length) { diseaseObj['synonyms'] = synonyms; this.setState({synonyms: synonyms}); } else { if (diseaseObj['synonyms']) { delete diseaseObj['synonyms']; } this.setState({synonyms: []}); } if (phenotypes && phenotypes.length) { diseaseObj['phenotypes'] = phenotypes; this.setState({phenotypes: phenotypes}); } else { if (diseaseObj['phenotypes']) { delete diseaseObj['phenotypes']; } this.setState({phenotypes: []}); } if (freetext) { diseaseObj['freetext'] = true; this.setState({diseaseFreeTextConfirm: true}); } else { if (diseaseObj['freetext']) { delete diseaseObj['freetext']; } this.setState({diseaseFreeTextConfirm: false}); } this.setState({diseaseObj: diseaseObj}, () => { this.updateInterpretationWithDisease(); // Pass data object back to parent this.props.updateDiseaseObj(this.state.diseaseObj); }); }, // When the form is submitted... updateInterpretationWithDisease() { this.setState({submitResourceBusy: true}); let diseaseObj = this.state.diseaseObj; let interpretationDisease, currInterpretation, flatInterpretation; if (diseaseObj && diseaseObj.term) { this.getRestData('/search?type=disease&diseaseId=' + diseaseObj.diseaseId).then(diseaseSearch => { let diseaseUuid; if (diseaseSearch.total === 0) { return this.postRestData('/diseases/', diseaseObj).then(result => { let newDisease = result['@graph'][0]; diseaseUuid = newDisease['uuid']; this.setState({diseaseUuid: diseaseUuid}, () => { interpretationDisease = diseaseUuid; return Promise.resolve(result); }); }); } else { let _id = diseaseSearch['@graph'][0]['@id']; diseaseUuid = _id.slice(10, -1); this.setState({diseaseUuid: diseaseUuid}, () => { interpretationDisease = diseaseUuid; }); } }, e => { // The given disease couldn't be retrieved for some reason. this.setState({submitResourceBusy: false}); // submit error; re-enable submit button this.setState({diseaseError: 'Error on validating disease.'}); throw e; }).then(data => { this.getRestData('/interpretation/' + this.props.interpretation.uuid).then(interpretation => { currInterpretation = interpretation; // get up-to-date copy of interpretation object and flatten it flatInterpretation = curator.flatten(currInterpretation); // if the interpretation object does not have a disease object, create it if (!('disease' in flatInterpretation)) { flatInterpretation.disease = ''; // Return the newly flattened interpretation object in a Promise return Promise.resolve(flatInterpretation); } else { return Promise.resolve(flatInterpretation); } }).then(interpretationObj => { if (interpretationDisease) { // Set the disease '@id' to the newly flattened interpretation object's 'disease' property interpretationObj.disease = interpretationDisease; // Update the intepretation object partially with the new disease property value return this.putRestData('/interpretation/' + this.props.interpretation.uuid, interpretationObj).then(result => { this.props.updateInterpretationObj(); var meta = { interpretation: { variant: this.props.variantData['@id'], disease: interpretationDisease, mode: 'edit-disease' } }; if (flatInterpretation.modeInheritance) { meta.interpretation.modeInheritance = flatInterpretation.modeInheritance; } return this.recordHistory('modify', currInterpretation, meta).then(result => { this.setState({submitResourceBusy: false}); }); }); } }); }).catch(e => { // Some unexpected error happened this.setState({submitResourceBusy: false}); parseAndLogError.bind(undefined, 'fetchedRequest'); }); } else { this.getRestData('/interpretation/' + this.props.interpretation.uuid).then(interpretation => { currInterpretation = interpretation; // get up-to-date copy of interpretation object and flatten it var flatInterpretation = curator.flatten(currInterpretation); // if the interpretation object does not have a disease object, create it if ('disease' in flatInterpretation) { delete flatInterpretation['disease']; let provisionalPathogenicity = this.props.provisionalPathogenicity; let calculatedAssertion = this.props.calculatedAssertion; if (provisionalPathogenicity === 'Likely pathogenic' || provisionalPathogenicity === 'Pathogenic') { flatInterpretation['markAsProvisional'] = false; } else if (!provisionalPathogenicity) { if (calculatedAssertion === 'Likely pathogenic' || calculatedAssertion === 'Pathogenic' ) { flatInterpretation['markAsProvisional'] = false; } } // Update the intepretation object partially with the new disease property value this.putRestData('/interpretation/' + this.props.interpretation.uuid, flatInterpretation).then(result => { var meta = { interpretation: { variant: this.props.variantData['@id'], disease: interpretationDisease, mode: 'edit-disease' } }; this.recordHistory('modify', currInterpretation, meta).then(result => { this.setState({submitResourceBusy: false}, () => { // Need 'submitResourceBusy' state to proceed closing modal this.props.updateInterpretationObj(); }); }); }); } else { this.setState({submitResourceBusy: false}); } }).catch(e => { // Some unexpected error happened this.setState({submitResourceBusy: false}); parseAndLogError.bind(undefined, 'fetchedRequest'); }); } }, /** * Handler for button press event to delete disease from the evidence */ handleDeleteDisease() { let diseaseObj = this.state.diseaseObj; this.setState({ diseaseId: '', diseaseTerm: null, diseaseDescription: null, synonyms: [], phenotypes: [], diseaseFreeTextConfirm: false, diseaseObj: {}, error: null }, () => { this.updateInterpretationWithDisease(); // Pass data object back to parent this.props.updateDiseaseObj(this.state.diseaseObj); }); }, /** * Called when either one of the alert modal buttons is clicked. * True if the 'Confirm' button was clicked. * False if the 'Cancel' button was clicked. */ handleDeleteConfirm(confirm, e) { if (confirm) { this.handleDeleteDisease(); } this.confirm.closeModal(); }, /** * Handler for button press event to alert/confirm disease deletion * if the interpretation had been marked as 'Provisional' */ renderDeleteDiseaseBtn() { let interpretation = this.props.interpretation; if (interpretation && interpretation.markAsProvisional) { return ( <ModalComponent modalTitle="Confirm disease deletion" modalClass="modal-default" modalWrapperClass="confirm-interpretation-delete-disease-modal pull-right" bootstrapBtnClass="btn btn-primary disease-delete " actuatorClass="interpretation-delete-disease-btn" actuatorTitle={<span>Disease<i className="icon icon-trash-o"></i></span>} onRef={ref => (this.confirm = ref)}> <div> <div className="modal-body"> <p> Warning: This interpretation is marked as "Provisional." If it has a Modified Pathogenicity of "Likely pathogenic" or "Pathogenic," or no Modified Pathogenicity but a Calculated Pathogenicity of "Likely pathogenic" or "Pathogenic," it must be associated with a disease.<br/><br/> <strong>If you still wish to delete the disease, select "Cancel," then select "View Summary" and remove the "Provisional" selection </strong> - otherwise, deleting the disease will automatically remove the "Provisional" status. </p> </div> <div className='modal-footer'> <Input type="button" inputClassName="btn-default btn-inline-spacer" clickHandler={this.handleDeleteConfirm.bind(null, false)} title="Cancel" /> <Input type="button" inputClassName="btn-primary btn-inline-spacer" clickHandler={this.handleDeleteConfirm.bind(null, true)} title="Confirm" /> </div> </div> </ModalComponent> ); } else if (interpretation && !interpretation.markAsProvisional) { return ( <a className="btn btn-danger pull-right disease-delete" onClick={this.handleDeleteDisease}> <span>Disease<i className="icon icon-trash-o"></i></span> </a> ); } }, render() { let diseaseId = this.state.diseaseId; let diseaseTerm = this.state.diseaseTerm; let diseaseDescription = this.state.diseaseDescription; let diseaseFreeTextConfirm = this.state.diseaseFreeTextConfirm; let phenotypes = this.state.phenotypes; let synonyms = this.state.synonyms; let addDiseaseModalBtn = diseaseTerm ? <span>Disease<i className="icon icon-pencil"></i></span> : <span>Disease<i className="icon icon-plus-circle"></i></span>; return ( <div className="add-disease-interpretation" id="add-disease-interpretation"> {!diseaseTerm ? <div className="add-disease-button"> <DiseaseModal addDiseaseModalBtn={addDiseaseModalBtn} diseaseId={diseaseId} diseaseTerm={diseaseTerm} diseaseDescription={diseaseDescription} diseaseFreeTextConfirm={diseaseFreeTextConfirm} phenotypes={phenotypes} synonyms={synonyms} passDataToParent={this.passDataToParent} addDiseaseModalBtnLayoutClass=" evidence-disease pull-right" /> </div> : <div className="delete-disease-button"> {this.renderDeleteDiseaseBtn()} </div> } </div> ); } });
src/clincoded/static/components/disease/interpretation.js
"use strict"; import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; import { FormMixin, Input } from '../../libs/bootstrap/form'; import { external_url_map } from '../globals'; import { DiseaseModal } from './modal'; import ModalComponent from '../../libs/bootstrap/modal'; var curator = require('../curator'); var CuratorHistory = require('../curator_history'); var RestMixin = require('../rest').RestMixin; var parseAndLogError = require('../mixins').parseAndLogError; /** * Component for adding/deleting disease associated with an interpretation in VCI */ const InterpretationDisease = module.exports.InterpretationDisease = createReactClass({ mixins: [RestMixin, FormMixin, CuratorHistory], propTypes: { interpretation: PropTypes.object, variantData: PropTypes.object, hasAssociatedDisease: PropTypes.bool, editKey: PropTypes.string, updateInterpretationObj: PropTypes.func, calculatedAssertion: PropTypes.string, provisionalPathogenicity: PropTypes.string, diseaseObj: PropTypes.object, updateDiseaseObj: PropTypes.func, session: PropTypes.object }, getInitialState() { return { interpretation: this.props.interpretation, diseaseObj: this.props.diseaseObj, diseaseId: '', diseaseTerm: null, diseaseOntology: null, diseaseDescription: null, synonyms: [], phenotypes: [], diseaseFreeTextConfirm: false, submitResourceBusy: false }; }, componentDidMount() { let interpretation = this.props.interpretation; if (interpretation && interpretation.disease) { this.setDiseaseObjectStates(interpretation.disease); } }, componentWillReceiveProps(nextProps) { if (nextProps.interpretation) { this.setState({interpretation: nextProps.interpretation}); } if (nextProps.diseaseObj) { this.setState({diseaseObj: nextProps.diseaseObj}, () => { let diseaseObj = this.state.diseaseObj; if (Object.keys(diseaseObj).length) { this.setDiseaseObjectStates(diseaseObj); } }); } }, /** * Shared method called by componentDidMount(), componentWillReceiveProps(nextProps) * @param {*} disease */ setDiseaseObjectStates(disease) { if (disease.diseaseId) { this.setState({diseaseId: disease.diseaseId}); } if (disease.term) { this.setState({diseaseTerm: disease.term}); } if (disease.ontology) { this.setState({diseaseOntology: disease.ontology}); } if (disease.description) { this.setState({diseaseDescription: disease.description}); } if (disease.synonyms) { this.setState({synonyms: disease.synonyms}); } if (disease.phenotypes) { this.setState({phenotypes: disease.phenotypes}); } if (disease.freetext) { this.setState({diseaseFreeTextConfirm: disease.freetext}); } }, passDataToParent(diseaseId, term, ontology, description, synonyms, phenotypes, freetext) { let diseaseObj = this.state.diseaseObj; if (diseaseId) { /** * Changing colon to underscore in id string for database */ diseaseObj['diseaseId'] = diseaseId.replace(':', '_'); this.setState({diseaseId: diseaseId}); } if (term) { diseaseObj['term'] = term; this.setState({diseaseTerm: term}); } if (ontology) { diseaseObj['ontology'] = ontology; this.setState({diseaseOntology: ontology}); } if (description) { diseaseObj['description'] = description; this.setState({diseaseDescription: description}); } else { if (diseaseObj['description']) { delete diseaseObj['description']; } this.setState({diseaseDescription: null}); } if (synonyms && synonyms.length) { diseaseObj['synonyms'] = synonyms; this.setState({synonyms: synonyms}); } else { if (diseaseObj['synonyms']) { delete diseaseObj['synonyms']; } this.setState({synonyms: []}); } if (phenotypes && phenotypes.length) { diseaseObj['phenotypes'] = phenotypes; this.setState({phenotypes: phenotypes}); } else { if (diseaseObj['phenotypes']) { delete diseaseObj['phenotypes']; } this.setState({phenotypes: []}); } if (freetext) { diseaseObj['freetext'] = true; this.setState({diseaseFreeTextConfirm: true}); } else { if (diseaseObj['freetext']) { delete diseaseObj['freetext']; } this.setState({diseaseFreeTextConfirm: false}); } this.setState({diseaseObj: diseaseObj}, () => { this.updateInterpretationWithDisease(); // Pass data object back to parent this.props.updateDiseaseObj(this.state.diseaseObj); }); }, // When the form is submitted... updateInterpretationWithDisease() { this.setState({submitResourceBusy: true}); let diseaseObj = this.state.diseaseObj; let interpretationDisease, currInterpretation, flatInterpretation; if (diseaseObj && diseaseObj.term) { this.getRestData('/search?type=disease&diseaseId=' + diseaseObj.diseaseId).then(diseaseSearch => { let diseaseUuid; if (diseaseSearch.total === 0) { return this.postRestData('/diseases/', diseaseObj).then(result => { let newDisease = result['@graph'][0]; diseaseUuid = newDisease['uuid']; this.setState({diseaseUuid: diseaseUuid}, () => { interpretationDisease = diseaseUuid; return Promise.resolve(result); }); }); } else { let _id = diseaseSearch['@graph'][0]['@id']; diseaseUuid = _id.slice(10, -1); this.setState({diseaseUuid: diseaseUuid}, () => { interpretationDisease = diseaseUuid; }); } }, e => { // The given disease couldn't be retrieved for some reason. this.setState({submitResourceBusy: false}); // submit error; re-enable submit button this.setState({diseaseError: 'Error on validating disease.'}); throw e; }).then(data => { this.getRestData('/interpretation/' + this.props.interpretation.uuid).then(interpretation => { currInterpretation = interpretation; // get up-to-date copy of interpretation object and flatten it flatInterpretation = curator.flatten(currInterpretation); // if the interpretation object does not have a disease object, create it if (!('disease' in flatInterpretation)) { flatInterpretation.disease = ''; // Return the newly flattened interpretation object in a Promise return Promise.resolve(flatInterpretation); } else { return Promise.resolve(flatInterpretation); } }).then(interpretationObj => { if (interpretationDisease) { // Set the disease '@id' to the newly flattened interpretation object's 'disease' property interpretationObj.disease = interpretationDisease; // Update the intepretation object partially with the new disease property value return this.putRestData('/interpretation/' + this.props.interpretation.uuid, interpretationObj).then(result => { this.props.updateInterpretationObj(); var meta = { interpretation: { variant: this.props.variantData['@id'], disease: interpretationDisease, mode: 'edit-disease' } }; if (flatInterpretation.modeInheritance) { meta.interpretation.modeInheritance = flatInterpretation.modeInheritance; } return this.recordHistory('modify', currInterpretation, meta).then(result => { this.setState({submitResourceBusy: false}); }); }); } }); }).catch(e => { // Some unexpected error happened this.setState({submitResourceBusy: false}); parseAndLogError.bind(undefined, 'fetchedRequest'); }); } else { this.getRestData('/interpretation/' + this.props.interpretation.uuid).then(interpretation => { currInterpretation = interpretation; // get up-to-date copy of interpretation object and flatten it var flatInterpretation = curator.flatten(currInterpretation); // if the interpretation object does not have a disease object, create it if ('disease' in flatInterpretation) { delete flatInterpretation['disease']; let provisionalPathogenicity = this.props.provisionalPathogenicity; let calculatedAssertion = this.props.calculatedAssertion; if (provisionalPathogenicity === 'Likely pathogenic' || provisionalPathogenicity === 'Pathogenic') { flatInterpretation['markAsProvisional'] = false; } else if (!provisionalPathogenicity) { if (calculatedAssertion === 'Likely pathogenic' || calculatedAssertion === 'Pathogenic' ) { flatInterpretation['markAsProvisional'] = false; } } // Update the intepretation object partially with the new disease property value this.putRestData('/interpretation/' + this.props.interpretation.uuid, flatInterpretation).then(result => { var meta = { interpretation: { variant: this.props.variantData['@id'], disease: interpretationDisease, mode: 'edit-disease' } }; this.recordHistory('modify', currInterpretation, meta).then(result => { this.setState({submitResourceBusy: false}, () => { // Need 'submitResourceBusy' state to proceed closing modal this.props.updateInterpretationObj(); }); }); }); } else { this.setState({submitResourceBusy: false}); } }).catch(e => { // Some unexpected error happened this.setState({submitResourceBusy: false}); parseAndLogError.bind(undefined, 'fetchedRequest'); }); } }, /** * Handler for button press event to delete disease from the evidence */ handleDeleteDisease() { let diseaseObj = this.state.diseaseObj; this.setState({ diseaseId: '', diseaseTerm: null, diseaseOntology: null, diseaseDescription: null, synonyms: [], phenotypes: [], diseaseFreeTextConfirm: false, diseaseObj: {}, error: null }, () => { this.updateInterpretationWithDisease(); // Pass data object back to parent this.props.updateDiseaseObj(this.state.diseaseObj); }); }, /** * Called when either one of the alert modal buttons is clicked. * True if the 'Confirm' button was clicked. * False if the 'Cancel' button was clicked. */ handleDeleteConfirm(confirm, e) { if (confirm) { this.handleDeleteDisease(); } this.confirm.closeModal(); }, /** * Handler for button press event to alert/confirm disease deletion * if the interpretation had been marked as 'Provisional' */ renderDeleteDiseaseBtn() { let interpretation = this.props.interpretation; if (interpretation && interpretation.markAsProvisional) { return ( <ModalComponent modalTitle="Confirm disease deletion" modalClass="modal-default" modalWrapperClass="confirm-interpretation-delete-disease-modal pull-right" bootstrapBtnClass="btn btn-primary disease-delete " actuatorClass="interpretation-delete-disease-btn" actuatorTitle={<span>Disease<i className="icon icon-trash-o"></i></span>} onRef={ref => (this.confirm = ref)}> <div> <div className="modal-body"> <p> Warning: This interpretation is marked as "Provisional." If it has a Modified Pathogenicity of "Likely pathogenic" or "Pathogenic," or no Modified Pathogenicity but a Calculated Pathogenicity of "Likely pathogenic" or "Pathogenic," it must be associated with a disease.<br/><br/> <strong>If you still wish to delete the disease, select "Cancel," then select "View Summary" and remove the "Provisional" selection </strong> - otherwise, deleting the disease will automatically remove the "Provisional" status. </p> </div> <div className='modal-footer'> <Input type="button" inputClassName="btn-default btn-inline-spacer" clickHandler={this.handleDeleteConfirm.bind(null, false)} title="Cancel" /> <Input type="button" inputClassName="btn-primary btn-inline-spacer" clickHandler={this.handleDeleteConfirm.bind(null, true)} title="Confirm" /> </div> </div> </ModalComponent> ); } else if (interpretation && !interpretation.markAsProvisional) { return ( <a className="btn btn-danger pull-right disease-delete" onClick={this.handleDeleteDisease}> <span>Disease<i className="icon icon-trash-o"></i></span> </a> ); } }, render() { let diseaseId = this.state.diseaseId; let diseaseTerm = this.state.diseaseTerm; let diseaseOntology = this.state.diseaseOntology; let diseaseDescription = this.state.diseaseDescription; let diseaseFreeTextConfirm = this.state.diseaseFreeTextConfirm; let phenotypes = this.state.phenotypes; let synonyms = this.state.synonyms; let addDiseaseModalBtn = diseaseTerm ? <span>Disease<i className="icon icon-pencil"></i></span> : <span>Disease<i className="icon icon-plus-circle"></i></span>; return ( <div className="add-disease-interpretation" id="add-disease-interpretation"> {!diseaseTerm ? <div className="add-disease-button"> <DiseaseModal addDiseaseModalBtn={addDiseaseModalBtn} diseaseId={diseaseId} diseaseTerm={diseaseTerm} diseaseOntology={diseaseOntology} diseaseDescription={diseaseDescription} diseaseFreeTextConfirm={diseaseFreeTextConfirm} phenotypes={phenotypes} synonyms={synonyms} passDataToParent={this.passDataToParent} addDiseaseModalBtnLayoutClass=" evidence-disease pull-right" /> </div> : <div className="delete-disease-button"> {this.renderDeleteDiseaseBtn()} </div> } </div> ); } });
No longer need the 'ontology' field and its data in the disease object
src/clincoded/static/components/disease/interpretation.js
No longer need the 'ontology' field and its data in the disease object
<ide><path>rc/clincoded/static/components/disease/interpretation.js <ide> diseaseObj: this.props.diseaseObj, <ide> diseaseId: '', <ide> diseaseTerm: null, <del> diseaseOntology: null, <ide> diseaseDescription: null, <ide> synonyms: [], <ide> phenotypes: [], <ide> setDiseaseObjectStates(disease) { <ide> if (disease.diseaseId) { this.setState({diseaseId: disease.diseaseId}); } <ide> if (disease.term) { this.setState({diseaseTerm: disease.term}); } <del> if (disease.ontology) { this.setState({diseaseOntology: disease.ontology}); } <ide> if (disease.description) { this.setState({diseaseDescription: disease.description}); } <ide> if (disease.synonyms) { this.setState({synonyms: disease.synonyms}); } <ide> if (disease.phenotypes) { this.setState({phenotypes: disease.phenotypes}); } <ide> if (disease.freetext) { this.setState({diseaseFreeTextConfirm: disease.freetext}); } <ide> }, <ide> <del> passDataToParent(diseaseId, term, ontology, description, synonyms, phenotypes, freetext) { <add> passDataToParent(diseaseId, term, description, synonyms, phenotypes, freetext) { <ide> let diseaseObj = this.state.diseaseObj; <ide> <ide> if (diseaseId) { <ide> if (term) { <ide> diseaseObj['term'] = term; <ide> this.setState({diseaseTerm: term}); <del> } <del> if (ontology) { <del> diseaseObj['ontology'] = ontology; <del> this.setState({diseaseOntology: ontology}); <ide> } <ide> if (description) { <ide> diseaseObj['description'] = description; <ide> this.setState({ <ide> diseaseId: '', <ide> diseaseTerm: null, <del> diseaseOntology: null, <ide> diseaseDescription: null, <ide> synonyms: [], <ide> phenotypes: [], <ide> render() { <ide> let diseaseId = this.state.diseaseId; <ide> let diseaseTerm = this.state.diseaseTerm; <del> let diseaseOntology = this.state.diseaseOntology; <ide> let diseaseDescription = this.state.diseaseDescription; <ide> let diseaseFreeTextConfirm = this.state.diseaseFreeTextConfirm; <ide> let phenotypes = this.state.phenotypes; <ide> addDiseaseModalBtn={addDiseaseModalBtn} <ide> diseaseId={diseaseId} <ide> diseaseTerm={diseaseTerm} <del> diseaseOntology={diseaseOntology} <ide> diseaseDescription={diseaseDescription} <ide> diseaseFreeTextConfirm={diseaseFreeTextConfirm} <ide> phenotypes={phenotypes} <ide> addDiseaseModalBtnLayoutClass=" evidence-disease pull-right" <ide> /> <ide> </div> <del> : <add> : <ide> <div className="delete-disease-button"> <ide> {this.renderDeleteDiseaseBtn()} <ide> </div>
Java
apache-2.0
c67055cc8ec4986ba9ded9fe97915b25c3e012c6
0
darranl/directory-server,darranl/directory-server,apache/directory-server,drankye/directory-server,lucastheisen/apache-directory-server,apache/directory-server,lucastheisen/apache-directory-server,drankye/directory-server
/* * 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.server.core.event; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.directory.server.core.DirectoryService; import org.apache.directory.server.core.entry.ClonedServerEntry; import org.apache.directory.server.core.entry.ServerEntry; import org.apache.directory.server.core.interceptor.BaseInterceptor; import org.apache.directory.server.core.interceptor.NextInterceptor; import org.apache.directory.server.core.interceptor.context.AddOperationContext; import org.apache.directory.server.core.interceptor.context.DeleteOperationContext; import org.apache.directory.server.core.interceptor.context.ModifyOperationContext; import org.apache.directory.server.core.interceptor.context.MoveAndRenameOperationContext; import org.apache.directory.server.core.interceptor.context.MoveOperationContext; import org.apache.directory.server.core.interceptor.context.OperationContext; import org.apache.directory.server.core.interceptor.context.RenameOperationContext; import org.apache.directory.server.core.normalization.FilterNormalizingVisitor; import org.apache.directory.server.core.partition.ByPassConstants; import org.apache.directory.shared.ldap.filter.ExprNode; import org.apache.directory.shared.ldap.name.LdapDN; import org.apache.directory.shared.ldap.name.NameComponentNormalizer; import org.apache.directory.shared.ldap.schema.SchemaManager; import org.apache.directory.shared.ldap.schema.normalizers.ConcreteNameComponentNormalizer; import org.apache.directory.shared.ldap.schema.registries.OidRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An {@link Interceptor} based service for notifying {@link * DirectoryListener}s of changes to the DIT. * * @org.apache.xbean.XBean * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev: 666516 $ */ public class EventInterceptor extends BaseInterceptor { private final static Logger LOG = LoggerFactory.getLogger( EventInterceptor.class ); private List<RegistrationEntry> registrations = new CopyOnWriteArrayList<RegistrationEntry>(); private DirectoryService ds; private FilterNormalizingVisitor filterNormalizer; private Evaluator evaluator; private ExecutorService executor; @Override public void init( DirectoryService ds ) throws Exception { LOG.info( "Initializing ..." ); super.init( ds ); this.ds = ds; OidRegistry oidRegistry = ds.getSchemaManager().getGlobalOidRegistry(); SchemaManager schemaManager = ds.getSchemaManager(); NameComponentNormalizer ncn = new ConcreteNameComponentNormalizer( schemaManager ); filterNormalizer = new FilterNormalizingVisitor( ncn, schemaManager ); evaluator = new ExpressionEvaluator( oidRegistry, schemaManager ); executor = new ThreadPoolExecutor( 1, 10, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>( 100 ) ); this.ds.setEventService( new DefaultEventService() ); LOG.info( "Initialization complete." ); } private void fire( final OperationContext opContext, EventType type, final DirectoryListener listener ) { switch ( type ) { case ADD: executor.execute( new Runnable() { public void run() { listener.entryAdded( ( AddOperationContext ) opContext ); } }); break; case DELETE: executor.execute( new Runnable() { public void run() { listener.entryDeleted( ( DeleteOperationContext ) opContext ); } }); break; case MODIFY: executor.execute( new Runnable() { public void run() { listener.entryModified( ( ModifyOperationContext ) opContext ); } }); break; case MOVE: executor.execute( new Runnable() { public void run() { listener.entryMoved( ( MoveOperationContext ) opContext ); } }); break; case RENAME: executor.execute( new Runnable() { public void run() { listener.entryRenamed( ( RenameOperationContext ) opContext ); } }); break; } } public void add( NextInterceptor next, final AddOperationContext opContext ) throws Exception { next.add( opContext ); List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), opContext.getEntry() ); if ( selecting.isEmpty() ) { return; } for ( final RegistrationEntry registration : selecting ) { if ( EventType.isAdd( registration.getCriteria().getEventMask() ) ) { fire( opContext, EventType.ADD, registration.getListener() ); } } } public void delete( NextInterceptor next, final DeleteOperationContext opContext ) throws Exception { List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), opContext.getEntry() ); next.delete( opContext ); if ( selecting.isEmpty() ) { return; } for ( final RegistrationEntry registration : selecting ) { if ( EventType.isDelete( registration.getCriteria().getEventMask() ) ) { fire( opContext, EventType.DELETE, registration.getListener() ); } } } public void modify( NextInterceptor next, final ModifyOperationContext opContext ) throws Exception { ClonedServerEntry oriEntry = opContext.lookup( opContext.getDn(), ByPassConstants.LOOKUP_BYPASS ); List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), oriEntry ); next.modify( opContext ); if ( selecting.isEmpty() ) { return; } // Get the modified entry ClonedServerEntry alteredEntry = opContext.lookup( opContext.getDn(), ByPassConstants.LOOKUP_BYPASS ); opContext.setAlteredEntry( alteredEntry ); for ( final RegistrationEntry registration : selecting ) { if ( EventType.isModify( registration.getCriteria().getEventMask() ) ) { fire( opContext, EventType.MODIFY, registration.getListener() ); } } } public void rename( NextInterceptor next, RenameOperationContext opContext ) throws Exception { ClonedServerEntry oriEntry = opContext.lookup( opContext.getDn(), ByPassConstants.LOOKUP_BYPASS ); List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), oriEntry ); next.rename( opContext ); if ( selecting.isEmpty() ) { return; } // Get the modifed entry ClonedServerEntry alteredEntry = opContext.lookup( opContext.getNewDn(), ByPassConstants.LOOKUP_BYPASS ); opContext.setAlteredEntry( alteredEntry ); for ( final RegistrationEntry registration : selecting ) { if ( EventType.isRename( registration.getCriteria().getEventMask() ) ) { fire( opContext, EventType.RENAME, registration.getListener() ); } } } public void moveAndRename( NextInterceptor next, final MoveAndRenameOperationContext opContext ) throws Exception { ClonedServerEntry oriEntry = opContext.lookup( opContext.getDn(), ByPassConstants.LOOKUP_BYPASS ); List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), oriEntry ); next.moveAndRename( opContext ); if ( selecting.isEmpty() ) { return; } opContext.setAlteredEntry( opContext.lookup( opContext.getNewDn(), ByPassConstants.LOOKUP_BYPASS ) ); for ( final RegistrationEntry registration : selecting ) { if ( EventType.isMoveAndRename( registration.getCriteria().getEventMask() ) ) { executor.execute( new Runnable() { public void run() { registration.getListener().entryMovedAndRenamed( opContext ); } }); } } } public void move( NextInterceptor next, MoveOperationContext opContext ) throws Exception { ClonedServerEntry oriEntry = opContext.lookup( opContext.getDn(), ByPassConstants.LOOKUP_BYPASS ); List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), oriEntry ); next.move( opContext ); if ( selecting.isEmpty() ) { return; } for ( final RegistrationEntry registration : selecting ) { if ( EventType.isMove( registration.getCriteria().getEventMask() ) ) { fire( opContext, EventType.MOVE, registration.getListener() ); } } } List<RegistrationEntry> getSelectingRegistrations( LdapDN name, ServerEntry entry ) throws Exception { if ( registrations.isEmpty() ) { return Collections.emptyList(); } List<RegistrationEntry> selecting = new ArrayList<RegistrationEntry>(); for ( RegistrationEntry registration : registrations ) { NotificationCriteria criteria = registration.getCriteria(); if ( evaluator.evaluate( criteria.getFilter(), criteria.getBase().toNormName(), entry ) ) { selecting.add( registration ); } } return selecting; } // ----------------------------------------------------------------------- // EventService Inner Class // ----------------------------------------------------------------------- class DefaultEventService implements EventService { /* * Does not need normalization since default values in criteria is used. */ public void addListener( DirectoryListener listener ) { registrations.add( new RegistrationEntry( listener ) ); } /* * Normalizes the criteria filter and the base. */ public void addListener( DirectoryListener listener, NotificationCriteria criteria ) throws Exception { criteria.getBase().normalize( ds.getSchemaManager().getNormalizerMapping() ); ExprNode result = ( ExprNode ) criteria.getFilter().accept( filterNormalizer ); criteria.setFilter( result ); registrations.add( new RegistrationEntry( listener, criteria ) ); } public void removeListener( DirectoryListener listener ) { for ( RegistrationEntry entry : registrations ) { if ( entry.getListener() == listener ) { registrations.remove( entry ); } } } public List<RegistrationEntry> getRegistrationEntries() { return Collections.unmodifiableList( registrations ); } } }
core/src/main/java/org/apache/directory/server/core/event/EventInterceptor.java
/* * 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.server.core.event; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.directory.server.core.DirectoryService; import org.apache.directory.server.core.entry.ClonedServerEntry; import org.apache.directory.server.core.entry.ServerEntry; import org.apache.directory.server.core.interceptor.BaseInterceptor; import org.apache.directory.server.core.interceptor.NextInterceptor; import org.apache.directory.server.core.interceptor.context.AddOperationContext; import org.apache.directory.server.core.interceptor.context.DeleteOperationContext; import org.apache.directory.server.core.interceptor.context.ModifyOperationContext; import org.apache.directory.server.core.interceptor.context.MoveAndRenameOperationContext; import org.apache.directory.server.core.interceptor.context.MoveOperationContext; import org.apache.directory.server.core.interceptor.context.OperationContext; import org.apache.directory.server.core.interceptor.context.RenameOperationContext; import org.apache.directory.server.core.normalization.FilterNormalizingVisitor; import org.apache.directory.server.core.partition.ByPassConstants; import org.apache.directory.shared.ldap.filter.ExprNode; import org.apache.directory.shared.ldap.name.LdapDN; import org.apache.directory.shared.ldap.name.NameComponentNormalizer; import org.apache.directory.shared.ldap.schema.SchemaManager; import org.apache.directory.shared.ldap.schema.normalizers.ConcreteNameComponentNormalizer; import org.apache.directory.shared.ldap.schema.registries.OidRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An {@link Interceptor} based service for notifying {@link * DirectoryListener}s of changes to the DIT. * * @org.apache.xbean.XBean * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev: 666516 $ */ public class EventInterceptor extends BaseInterceptor { private final static Logger LOG = LoggerFactory.getLogger( EventInterceptor.class ); private List<RegistrationEntry> registrations = new CopyOnWriteArrayList<RegistrationEntry>(); private DirectoryService ds; private FilterNormalizingVisitor filterNormalizer; private Evaluator evaluator; private ExecutorService executor; @Override public void init( DirectoryService ds ) throws Exception { LOG.info( "Initializing ..." ); super.init( ds ); this.ds = ds; OidRegistry oidRegistry = ds.getSchemaManager().getGlobalOidRegistry(); SchemaManager schemaManager = ds.getSchemaManager(); NameComponentNormalizer ncn = new ConcreteNameComponentNormalizer( schemaManager ); filterNormalizer = new FilterNormalizingVisitor( ncn, schemaManager ); evaluator = new ExpressionEvaluator( oidRegistry, schemaManager ); executor = new ThreadPoolExecutor( 1, 10, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>( 100 ) ); this.ds.setEventService( new DefaultEventService() ); LOG.info( "Initialization complete." ); } private void fire( final OperationContext opContext, EventType type, final DirectoryListener listener ) { switch ( type ) { case ADD: executor.execute( new Runnable() { public void run() { listener.entryAdded( ( AddOperationContext ) opContext ); } }); break; case DELETE: executor.execute( new Runnable() { public void run() { listener.entryDeleted( ( DeleteOperationContext ) opContext ); } }); break; case MODIFY: executor.execute( new Runnable() { public void run() { listener.entryModified( ( ModifyOperationContext ) opContext ); } }); break; case MOVE: executor.execute( new Runnable() { public void run() { listener.entryMoved( ( MoveOperationContext ) opContext ); } }); break; case RENAME: executor.execute( new Runnable() { public void run() { listener.entryRenamed( ( RenameOperationContext ) opContext ); } }); break; } } public void add( NextInterceptor next, final AddOperationContext opContext ) throws Exception { next.add( opContext ); List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), opContext.getEntry() ); if ( selecting.isEmpty() ) { return; } for ( final RegistrationEntry registration : selecting ) { if ( EventType.isAdd( registration.getCriteria().getEventMask() ) ) { fire( opContext, EventType.ADD, registration.getListener() ); } } } public void delete( NextInterceptor next, final DeleteOperationContext opContext ) throws Exception { List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), opContext.getEntry() ); next.delete( opContext ); if ( selecting.isEmpty() ) { return; } for ( final RegistrationEntry registration : selecting ) { if ( EventType.isDelete( registration.getCriteria().getEventMask() ) ) { fire( opContext, EventType.DELETE, registration.getListener() ); } } } public void modify( NextInterceptor next, final ModifyOperationContext opContext ) throws Exception { List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), opContext.getEntry() ); next.modify( opContext ); if ( selecting.isEmpty() ) { return; } // Get the modifed entry ClonedServerEntry alteredEntry = opContext.lookup( opContext.getDn(), ByPassConstants.LOOKUP_BYPASS ); opContext.setAlteredEntry( alteredEntry ); for ( final RegistrationEntry registration : selecting ) { if ( EventType.isModify( registration.getCriteria().getEventMask() ) ) { fire( opContext, EventType.MODIFY, registration.getListener() ); } } } public void rename( NextInterceptor next, RenameOperationContext opContext ) throws Exception { List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), opContext.getEntry() ); next.rename( opContext ); if ( selecting.isEmpty() ) { return; } // Get the modifed entry ClonedServerEntry alteredEntry = opContext.lookup( opContext.getNewDn(), ByPassConstants.LOOKUP_BYPASS ); opContext.setAlteredEntry( alteredEntry ); for ( final RegistrationEntry registration : selecting ) { if ( EventType.isRename( registration.getCriteria().getEventMask() ) ) { fire( opContext, EventType.RENAME, registration.getListener() ); } } } public void moveAndRename( NextInterceptor next, final MoveAndRenameOperationContext opContext ) throws Exception { ClonedServerEntry oriEntry = opContext.lookup( opContext.getDn(), ByPassConstants.LOOKUP_BYPASS ); List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), oriEntry ); next.moveAndRename( opContext ); if ( selecting.isEmpty() ) { return; } opContext.setAlteredEntry( opContext.lookup( opContext.getNewDn(), ByPassConstants.LOOKUP_BYPASS ) ); for ( final RegistrationEntry registration : selecting ) { if ( EventType.isMoveAndRename( registration.getCriteria().getEventMask() ) ) { executor.execute( new Runnable() { public void run() { registration.getListener().entryMovedAndRenamed( opContext ); } }); } } } public void move( NextInterceptor next, MoveOperationContext opContext ) throws Exception { List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), opContext.getEntry() ); next.move( opContext ); ClonedServerEntry alteredEntry = opContext.lookup( opContext.getDn(), ByPassConstants.LOOKUP_BYPASS ); if ( selecting.isEmpty() ) { return; } for ( final RegistrationEntry registration : selecting ) { if ( EventType.isMove( registration.getCriteria().getEventMask() ) ) { fire( opContext, EventType.MOVE, registration.getListener() ); } } } List<RegistrationEntry> getSelectingRegistrations( LdapDN name, ServerEntry entry ) throws Exception { if ( registrations.isEmpty() ) { return Collections.emptyList(); } List<RegistrationEntry> selecting = new ArrayList<RegistrationEntry>(); for ( RegistrationEntry registration : registrations ) { NotificationCriteria criteria = registration.getCriteria(); if ( evaluator.evaluate( criteria.getFilter(), criteria.getBase().toNormName(), entry ) ) { selecting.add( registration ); } } return selecting; } // ----------------------------------------------------------------------- // EventService Inner Class // ----------------------------------------------------------------------- class DefaultEventService implements EventService { /* * Does not need normalization since default values in criteria is used. */ public void addListener( DirectoryListener listener ) { registrations.add( new RegistrationEntry( listener ) ); } /* * Normalizes the criteria filter and the base. */ public void addListener( DirectoryListener listener, NotificationCriteria criteria ) throws Exception { criteria.getBase().normalize( ds.getSchemaManager().getNormalizerMapping() ); ExprNode result = ( ExprNode ) criteria.getFilter().accept( filterNormalizer ); criteria.setFilter( result ); registrations.add( new RegistrationEntry( listener, criteria ) ); } public void removeListener( DirectoryListener listener ) { for ( RegistrationEntry entry : registrations ) { if ( entry.getListener() == listener ) { registrations.remove( entry ); } } } public List<RegistrationEntry> getRegistrationEntries() { return Collections.unmodifiableList( registrations ); } } }
Fixed a regression introduced while fixing PersistentSearch git-svn-id: 0e35ed151ed664c68b0cbbfc0d55a7f45990ca10@895848 13f79535-47bb-0310-9956-ffa450edef68
core/src/main/java/org/apache/directory/server/core/event/EventInterceptor.java
Fixed a regression introduced while fixing PersistentSearch
<ide><path>ore/src/main/java/org/apache/directory/server/core/event/EventInterceptor.java <ide> <ide> public void modify( NextInterceptor next, final ModifyOperationContext opContext ) throws Exception <ide> { <del> List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), opContext.getEntry() ); <add> ClonedServerEntry oriEntry = opContext.lookup( opContext.getDn(), ByPassConstants.LOOKUP_BYPASS ); <add> List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), oriEntry ); <add> <ide> next.modify( opContext ); <ide> <ide> if ( selecting.isEmpty() ) <ide> return; <ide> } <ide> <del> // Get the modifed entry <add> // Get the modified entry <ide> ClonedServerEntry alteredEntry = opContext.lookup( opContext.getDn(), ByPassConstants.LOOKUP_BYPASS ); <ide> opContext.setAlteredEntry( alteredEntry ); <ide> <ide> <ide> public void rename( NextInterceptor next, RenameOperationContext opContext ) throws Exception <ide> { <del> List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), opContext.getEntry() ); <add> ClonedServerEntry oriEntry = opContext.lookup( opContext.getDn(), ByPassConstants.LOOKUP_BYPASS ); <add> List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), oriEntry ); <add> <ide> next.rename( opContext ); <ide> <ide> if ( selecting.isEmpty() ) <ide> <ide> public void move( NextInterceptor next, MoveOperationContext opContext ) throws Exception <ide> { <del> List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), opContext.getEntry() ); <add> ClonedServerEntry oriEntry = opContext.lookup( opContext.getDn(), ByPassConstants.LOOKUP_BYPASS ); <add> List<RegistrationEntry> selecting = getSelectingRegistrations( opContext.getDn(), oriEntry ); <add> <ide> next.move( opContext ); <del> <del> ClonedServerEntry alteredEntry = opContext.lookup( opContext.getDn(), ByPassConstants.LOOKUP_BYPASS ); <ide> <ide> if ( selecting.isEmpty() ) <ide> {
JavaScript
mit
266464a06eac958d9791e0f9b3c1dc72143dfcdf
0
entrylabs/entry-hw,kjsii123/entry-hw,entrylabs/entry-hw,entrylabs/entry-hw,kjsii123/entry-hw,entrylabs/entry-hw,entrylabs/entry-hw,kjsii123/entry-hw,entrylabs/entry-hw,kjsii123/entry-hw
const { app, ipcMain, shell } = require('electron'); const path = require('path'); const fs = require('fs'); const Scanner = require('./scanner'); const Flasher = require('./flasher'); const Utils = require('./utils/fileUtils'); const rendererConsole = require('./utils/rendererConsole'); const HardwareListManager = require('./hardwareListManager'); const HandlerCreator = require('./datahandler/handler'); /** * scanner, server, connector 를 총괄하는 중앙 클래스. * 해당 클래스는 renderer 의 router 와 통신한다. * 아래의 클래스들은 ipc 통신을 하지 않는다. * * scanner : 포트 검색 과 종료 * server : entry workspace 와 통신하는 http/ws 서버 * connector : 연결 성공 후의 실제 시리얼포트 */ class MainRouter { get roomIds() { return global.sharedObject.roomIds || []; } constructor(mainWindow, entryServer) { global.$ = require('lodash'); rendererConsole.initialize(mainWindow); this.browser = mainWindow; this.scanner = new Scanner(this); this.server = entryServer; this.flasher = new Flasher(); this.hardwareListManager = new HardwareListManager(this); this.config = undefined; /** @type {Connector} */ this.connector = undefined; this.hwModule = undefined; /** @type {Object} */ this.handler = undefined; entryServer.setRouter(this); this.server.open(); ipcMain.on('state', (e, state) => { this.onChangeState(state); }); ipcMain.on('startScan', async (e, config) => { try { await this.startScan(config); } catch (e) { rendererConsole.error(`startScan err : `, e); } }); ipcMain.on('stopScan', () => { this.stopScan(); }); ipcMain.on('close', () => { this.close(); }); ipcMain.on('requestFlash', (e, firmwareName) => { this.flashFirmware(firmwareName) .then(() => { if (!e.sender.isDestroyed()) { e.sender.send('requestFlash'); } }) .catch((e) => { if (!e.sender.isDestroyed()) { e.sender.send('requestFlash', e); } }); }); ipcMain.on('executeDriver', (e, driverPath) => { this.executeDriver(driverPath); }); ipcMain.on('getCurrentServerModeSync', (e) => { e.returnValue = this.currentServerRunningMode; }); ipcMain.on('getCurrentCloudModeSync', (e) => { e.returnValue = this.currentCloudMode; }); ipcMain.on('requestHardwareListSync', (e) => { e.returnValue = this.hardwareListManager.allHardwareList; }); } /** * 펌웨어를 업로드한다. * 펌웨어는 커넥터가 닫힌 상태에서 작업되어야 한다. (COMPort 점유) * 실패시 tryFlasherNumber 만큼 반복한다. 기본값은 10번이다. * 로직 종료시 재스캔하여 연결을 수립한다. * @param firmwareName 다중 펌웨어 존재시 펌웨어명을 명시 * @returns {Promise<void|Error>} */ flashFirmware(firmwareName) { if (this.connector && this.connector.serialPort && this.config) { let firmware = firmwareName; const { configfirmware, firmwareBaudRate: baudRate, firmwareMCUType: MCUType, tryFlasherNumber: maxFlashTryCount = 10, } = this.config; const lastSerialPortCOMPort = this.connector.serialPort.path; this.firmwareTryCount = 0; if (firmwareName === undefined || firmwareName === '') { firmware = configfirmware; } this.close(); // 서버 통신 중지, 시리얼포트 연결 해제 const flashFunction = () => new Promise((resolve, reject) => { setTimeout(() => { //연결 해제 완료시간까지 잠시 대기 후 로직 수행한다. this.flasher.flash(firmware, lastSerialPortCOMPort, { baudRate, MCUType }) .then(([error, ...args]) => { if (error) { rendererConsole.error('flashError', error, ...args); if (error === 'exit') { // 에러 메세지 없이 프로세스 종료 reject(new Error()); } else if (++this.firmwareTryCount <= maxFlashTryCount) { setTimeout(() => { flashFunction().then(resolve); }, 100); } else { reject(new Error('Failed Firmware Upload')); } } else { resolve(); } }) .catch(reject); }, 500); }); // 에러가 발생하거나, 정상종료가 되어도 일단 startScan 을 재시작한다. return flashFunction() .then(() => { console.log('flash successed'); }) .catch((e) => { rendererConsole.error('flash failed', e); console.log('flash failed'); throw e; }) .finally(async () => { this.flasher.kill(); if (firmware.afterDelay) { await new Promise((resolve) => setTimeout(resolve, firmware.afterDelay)); } await this.startScan(this.config); }); } else { return Promise.reject(new Error('Hardware Device Is Not Connected')); } } /** * 연결을 끊고 새로 수립한다. * disconnect 혹은 lost state 상태이고, config 에 reconnect: true 인 경우 발생한다. * startScan 의 결과는 기다리지 않는다. */ reconnect() { this.close(); this.startScan(this.config); } /** * renderer 에 state 인자를 보낸다. 주로 ui 변경을 위해 사용된다. * @param {string} state 변경된 state * @param {...*} args 추가로 보낼 인자 */ sendState(state, ...args) { let resultState = state; if (state === 'lost' || state === 'disconnect') { if (this.config && this.config.reconnect) { this.reconnect(); } else { // 연결 잃은 후 재연결 속성 없으면 연결해제처리 resultState = 'disconnect'; this.close(); } } this.sendEventToMainWindow('state', resultState, ...args); } notifyCloudModeChanged(mode) { this.sendEventToMainWindow('cloudMode', mode); this.currentCloudMode = mode; } notifyServerRunningModeChanged(mode) { this.sendEventToMainWindow('serverMode', mode); this.currentServerRunningMode = mode; } sendEventToMainWindow(eventName, ...args) { if (!this.browser.isDestroyed()) { this.browser.webContents.send(eventName, ...args); } } /** * ipcMain.on('state', ...) 처리함수 * @param state */ onChangeState(state) { console.log('server state', state); // this.server.setState(state); } /** * 현재 컴퓨터에 연결된 포트들을 검색한다. * 특정 시간(Scanner.SCAN_INTERVAL_MILLS) 마다 체크한다. * 연결성공시 'state' 이벤트가 발생된다. * @param config */ async startScan(config) { this.config = config; if (this.scanner) { this.hwModule = require(`../../modules/${config.module}`); const connector = await this.scanner.startScan(this.hwModule, this.config); if (connector) { this.sendState('connected'); this.connector = connector; connector.setRouter(this); this._connect(connector); } else { console.log('connector not found! [debug]'); } } } /** * 클라우드 모드 동작용. * 신규 클라이언트 소켓생성되어 호스트에 연결되는 경우, * 호스트 서버에서 관리하기 위해 해당 클라이언트용 roomId 를 추가한다. * @param roomId */ addRoomId(roomId) { this.server.addRoomIdsOnSecondInstance(roomId); } stopScan() { if (this.scanner) { this.scanner.stopScan(); } } /** * 연결이 정상적으로 된 경우 startScan 의 callback 에서 호출된다. * @param connector */ _connect(connector) { this.connector = connector; /* 해당 프로퍼티가 세팅된 경우는 - flashfirmware 가 config 에 세팅되어있고, - 3000ms 동안 checkInitialData 가 정상적으로 이루어지지 않은 경우이다. */ if (this.connector.executeFlash) { this.sendState('flash'); delete this.connector.executeFlash; return; } // 엔트리측, 하드웨어측이 정상적으로 준비된 경우 if (this.hwModule && this.server) { // 엔트리쪽으로 송수신시 변환할 방식. 현재 json 만 지원한다. this.handler = HandlerCreator.create(this.config); this._connectToServer(); this.connector.connect(); // router 설정 후 실제 기기와의 통신 시작 } } /** * 엔트리 워크스페이스와의 연결 담당 로직 * * @private */ _connectToServer() { const hwModule = this.hwModule; const server = this.server; // server.removeAllListeners(); if (hwModule.init) { hwModule.init(this.handler, this.config); } if (hwModule.setSocket) { hwModule.setSocket(server); } // 신규 연결시 해당 메세지 전송 // server.on('connection', () => { // if (hwModule.socketReconnection) { // hwModule.socketReconnection(); // } // }); // 엔트리 실행이 종료된 경우 reset 명령어 호출 // server.on('close', () => { // if (hwModule.reset) { // hwModule.reset(); // } // }); } // 엔트리 측에서 데이터를 받아온 경우 전달 handleServerData({ data, type }) { const hwModule = this.hwModule; const handler = this.handler; if (!hwModule || !handler) { return; } handler.decode(data, type); if (hwModule.handleRemoteData) { hwModule.handleRemoteData(handler); } } /** * 서버로 인코딩된 데이터를 보낸다. */ sendEncodedDataToServer() { const data = this.handler.encode(); if (data) { this.server.send(data); } } /** * 하드웨어 모듈의 requestRemoteData 를 통해 핸들러 내 데이터를 세팅한다. */ setHandlerData() { if (this.hwModule.requestRemoteData) { this.hwModule.requestRemoteData(this.handler); } } close() { if (this.server) { this.server.disconnectHardware(); } if (this.scanner) { this.scanner.stopScan(); } if (this.connector) { rendererConsole.log('disconnect'); if (this.hwModule.disconnect) { this.hwModule.disconnect(this.connector); } else { this.connector.close(); } this.connector = undefined; } if (this.handler) { this.handler = undefined; } }; /** * 드라이버를 실행한다. 최초 실행시 app.asar 에 파일이 들어가있는 경우, * 외부로 복사하여 외부 파일을 사용한다. * @param driverPath */ executeDriver(driverPath) { if (!this.config) { return; } const asarIndex = app.getAppPath().indexOf(`${path.sep}app.asar`); let sourcePath = ''; if (asarIndex > -1) { const asarPath = app.getAppPath().substr(0, asarIndex); const externalDriverPath = path.join(asarPath, 'drivers'); const internalDriverPath = path.resolve(app.getAppPath(), __dirname, '..', '..', 'drivers'); if (!fs.existsSync(externalDriverPath)) { Utils.copyRecursiveSync(internalDriverPath, externalDriverPath); } sourcePath = externalDriverPath; } else { sourcePath = path.resolve(__dirname, '..', '..', 'drivers'); } shell.openItem(path.resolve(sourcePath, driverPath)); } } module.exports = MainRouter;
app/src/main/mainRouter.js
const { app, ipcMain, shell } = require('electron'); const path = require('path'); const fs = require('fs'); const Scanner = require('./scanner'); const Flasher = require('./flasher'); const Utils = require('./utils/fileUtils'); const rendererConsole = require('./utils/rendererConsole'); const HardwareListManager = require('./hardwareListManager'); const HandlerCreator = require('./datahandler/handler'); /** * scanner, server, connector 를 총괄하는 중앙 클래스. * 해당 클래스는 renderer 의 router 와 통신한다. * 아래의 클래스들은 ipc 통신을 하지 않는다. * * scanner : 포트 검색 과 종료 * server : entry workspace 와 통신하는 http/ws 서버 * connector : 연결 성공 후의 실제 시리얼포트 */ class MainRouter { get roomIds() { return global.sharedObject.roomIds || []; } constructor(mainWindow, entryServer) { global.$ = require('lodash'); rendererConsole.initialize(mainWindow); this.browser = mainWindow; this.scanner = new Scanner(this); this.server = entryServer; this.flasher = new Flasher(); this.hardwareListManager = new HardwareListManager(this); this.config = undefined; /** @type {Connector} */ this.connector = undefined; this.hwModule = undefined; /** @type {Object} */ this.handler = undefined; entryServer.setRouter(this); this.server.open(); ipcMain.on('state', (e, state) => { this.onChangeState(state); }); ipcMain.on('startScan', async (e, config) => { try { await this.startScan(config); } catch (e) { rendererConsole.error(`startScan err : `, e); } }); ipcMain.on('stopScan', () => { this.stopScan(); }); ipcMain.on('close', () => { this.close(); }); ipcMain.on('requestFlash', (e, firmwareName) => { this.flashFirmware(firmwareName) .then(() => { if (!e.sender.isDestroyed()) { e.sender.send('requestFlash'); } }) .catch((e) => { if (!e.sender.isDestroyed()) { e.sender.send('requestFlash', e); } }); }); ipcMain.on('executeDriver', (e, driverPath) => { this.executeDriver(driverPath); }); ipcMain.on('getCurrentServerModeSync', (e) => { e.returnValue = this.currentServerRunningMode; }); ipcMain.on('getCurrentCloudModeSync', (e) => { e.returnValue = this.currentCloudMode; }); ipcMain.on('requestHardwareListSync', (e) => { e.returnValue = this.hardwareListManager.allHardwareList; }); } /** * 펌웨어를 업로드한다. * 펌웨어는 커넥터가 닫힌 상태에서 작업되어야 한다. (COMPort 점유) * 실패시 tryFlasherNumber 만큼 반복한다. 기본값은 10번이다. * 로직 종료시 재스캔하여 연결을 수립한다. * @param firmwareName 다중 펌웨어 존재시 펌웨어명을 명시 * @returns {Promise<void|Error>} */ flashFirmware(firmwareName) { if (this.connector && this.connector.serialPort && this.config) { let firmware = firmwareName; const { configfirmware, firmwareBaudRate: baudRate, firmwareMCUType: MCUType, tryFlasherNumber: maxFlashTryCount = 10, } = this.config; const lastSerialPortCOMPort = this.connector.serialPort.path; this.firmwareTryCount = 0; if (firmwareName === undefined || firmwareName === '') { firmware = configfirmware; } this.close(); // 서버 통신 중지, 시리얼포트 연결 해제 const flashFunction = () => new Promise((resolve, reject) => { setTimeout(() => { //연결 해제 완료시간까지 잠시 대기 후 로직 수행한다. this.flasher.flash(firmware, lastSerialPortCOMPort, { baudRate, MCUType }) .then(([error, ...args]) => { if (error) { rendererConsole.error('flashError', error, ...args); if (error === 'exit') { // 에러 메세지 없이 프로세스 종료 reject(new Error()); } else if (++this.firmwareTryCount <= maxFlashTryCount) { setTimeout(() => { flashFunction().then(resolve); }, 100); } else { reject(new Error('Failed Firmware Upload')); } } else { resolve(); } }) .catch(reject); }, 500); }); // 에러가 발생하거나, 정상종료가 되어도 일단 startScan 을 재시작한다. return flashFunction() .then(() => { console.log('flash successed'); }) .catch((e) => { rendererConsole.error('flash failed', e); console.log('flash failed'); throw e; }) .finally(async () => { this.flasher.kill(); if (firmware.afterDelay) { await new Promise((resolve) => setTimeout(resolve, firmware.afterDelay)); } await this.startScan(this.config); }); } else { return Promise.reject(new Error('Hardware Device Is Not Connected')); } } /** * 연결을 끊고 새로 수립한다. * disconnect 혹은 lost state 상태이고, config 에 reconnect: true 인 경우 발생한다. * startScan 의 결과는 기다리지 않는다. */ reconnect() { this.close(); this.startScan(this.config); } /** * renderer 에 state 인자를 보낸다. 주로 ui 변경을 위해 사용된다. * @param {string} state 변경된 state * @param {...*} args 추가로 보낼 인자 */ sendState(state, ...args) { let resultState = state; if (state === 'lost' || state === 'disconnect') { if (this.config && this.config.reconnect) { this.reconnect(); } else { // 연결 잃은 후 재연결 속성 없으면 연결해제처리 resultState = 'disconnect'; this.close(); } } this.sendEventToMainWindow('state', resultState, ...args); } notifyCloudModeChanged(mode) { this.sendEventToMainWindow('cloudMode', mode); this.currentCloudMode = mode; } notifyServerRunningModeChanged(mode) { this.sendEventToMainWindow('serverMode', mode); this.currentServerRunningMode = mode; } sendEventToMainWindow(eventName, ...args) { if (!this.browser.isDestroyed()) { this.browser.webContents.send(eventName, args); } } /** * ipcMain.on('state', ...) 처리함수 * @param state */ onChangeState(state) { console.log('server state', state); // this.server.setState(state); } /** * 현재 컴퓨터에 연결된 포트들을 검색한다. * 특정 시간(Scanner.SCAN_INTERVAL_MILLS) 마다 체크한다. * 연결성공시 'state' 이벤트가 발생된다. * @param config */ async startScan(config) { this.config = config; if (this.scanner) { this.hwModule = require(`../../modules/${config.module}`); const connector = await this.scanner.startScan(this.hwModule, this.config); if (connector) { this.sendState('connected'); this.connector = connector; connector.setRouter(this); this._connect(connector); } else { console.log('connector not found! [debug]'); } } } /** * 클라우드 모드 동작용. * 신규 클라이언트 소켓생성되어 호스트에 연결되는 경우, * 호스트 서버에서 관리하기 위해 해당 클라이언트용 roomId 를 추가한다. * @param roomId */ addRoomId(roomId) { this.server.addRoomIdsOnSecondInstance(roomId); } stopScan() { if (this.scanner) { this.scanner.stopScan(); } } /** * 연결이 정상적으로 된 경우 startScan 의 callback 에서 호출된다. * @param connector */ _connect(connector) { this.connector = connector; /* 해당 프로퍼티가 세팅된 경우는 - flashfirmware 가 config 에 세팅되어있고, - 3000ms 동안 checkInitialData 가 정상적으로 이루어지지 않은 경우이다. */ if (this.connector.executeFlash) { this.sendState('flash'); delete this.connector.executeFlash; return; } // 엔트리측, 하드웨어측이 정상적으로 준비된 경우 if (this.hwModule && this.server) { // 엔트리쪽으로 송수신시 변환할 방식. 현재 json 만 지원한다. this.handler = HandlerCreator.create(this.config); this._connectToServer(); this.connector.connect(); // router 설정 후 실제 기기와의 통신 시작 } } /** * 엔트리 워크스페이스와의 연결 담당 로직 * * @private */ _connectToServer() { const hwModule = this.hwModule; const server = this.server; // server.removeAllListeners(); if (hwModule.init) { hwModule.init(this.handler, this.config); } if (hwModule.setSocket) { hwModule.setSocket(server); } // 신규 연결시 해당 메세지 전송 // server.on('connection', () => { // if (hwModule.socketReconnection) { // hwModule.socketReconnection(); // } // }); // 엔트리 실행이 종료된 경우 reset 명령어 호출 // server.on('close', () => { // if (hwModule.reset) { // hwModule.reset(); // } // }); } // 엔트리 측에서 데이터를 받아온 경우 전달 handleServerData({ data, type }) { const hwModule = this.hwModule; const handler = this.handler; if (!hwModule || !handler) { return; } handler.decode(data, type); if (hwModule.handleRemoteData) { hwModule.handleRemoteData(handler); } } /** * 서버로 인코딩된 데이터를 보낸다. */ sendEncodedDataToServer() { const data = this.handler.encode(); if (data) { this.server.send(data); } } /** * 하드웨어 모듈의 requestRemoteData 를 통해 핸들러 내 데이터를 세팅한다. */ setHandlerData() { if (this.hwModule.requestRemoteData) { this.hwModule.requestRemoteData(this.handler); } } close() { if (this.server) { this.server.disconnectHardware(); } if (this.scanner) { this.scanner.stopScan(); } if (this.connector) { rendererConsole.log('disconnect'); if (this.hwModule.disconnect) { this.hwModule.disconnect(this.connector); } else { this.connector.close(); } this.connector = undefined; } if (this.handler) { this.handler = undefined; } }; /** * 드라이버를 실행한다. 최초 실행시 app.asar 에 파일이 들어가있는 경우, * 외부로 복사하여 외부 파일을 사용한다. * @param driverPath */ executeDriver(driverPath) { if (!this.config) { return; } const asarIndex = app.getAppPath().indexOf(`${path.sep}app.asar`); let sourcePath = ''; if (asarIndex > -1) { const asarPath = app.getAppPath().substr(0, asarIndex); const externalDriverPath = path.join(asarPath, 'drivers'); const internalDriverPath = path.resolve(app.getAppPath(), __dirname, '..', '..', 'drivers'); if (!fs.existsSync(externalDriverPath)) { Utils.copyRecursiveSync(internalDriverPath, externalDriverPath); } sourcePath = externalDriverPath; } else { sourcePath = path.resolve(__dirname, '..', '..', 'drivers'); } shell.openItem(path.resolve(sourcePath, driverPath)); } } module.exports = MainRouter;
[feature/react_renderer] 잘못된 인자 수정
app/src/main/mainRouter.js
[feature/react_renderer] 잘못된 인자 수정
<ide><path>pp/src/main/mainRouter.js <ide> <ide> sendEventToMainWindow(eventName, ...args) { <ide> if (!this.browser.isDestroyed()) { <del> this.browser.webContents.send(eventName, args); <add> this.browser.webContents.send(eventName, ...args); <ide> } <ide> } <ide>
Java
apache-2.0
184a9fb084ee62d04a7dc29ef372aa550cdade35
0
wso2-extensions/identity-inbound-auth-saml,wso2-extensions/identity-inbound-auth-saml
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.identity.sso.saml.extension.eidas; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.opensaml.saml1.core.NameIdentifier; import org.opensaml.saml2.common.Extensions; import org.opensaml.saml2.core.Assertion; import org.opensaml.saml2.core.AttributeStatement; import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration; import org.opensaml.saml2.core.AuthnRequest; import org.opensaml.saml2.core.NameID; import org.opensaml.saml2.core.RequestAbstractType; import org.opensaml.saml2.core.Response; import org.opensaml.saml2.core.StatusResponseType; import org.opensaml.saml2.core.impl.NameIDBuilder; import org.opensaml.xml.XMLObject; import org.opensaml.xml.schema.impl.XSAnyImpl; import org.w3c.dom.NodeList; import org.wso2.carbon.identity.application.common.model.Claim; import org.wso2.carbon.identity.application.common.model.ClaimMapping; import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.sso.saml.SAMLSSOConstants; import org.wso2.carbon.identity.sso.saml.builders.SignKeyDataHolder; import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOAuthnReqDTO; import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOReqValidationResponseDTO; import org.wso2.carbon.identity.sso.saml.exception.IdentitySAML2SSOException; import org.wso2.carbon.identity.sso.saml.extension.SAMLExtensionProcessor; import org.wso2.carbon.identity.sso.saml.extension.eidas.model.RequestedAttributes; import org.wso2.carbon.identity.sso.saml.extension.eidas.model.SPType; import org.wso2.carbon.identity.sso.saml.extension.eidas.util.EidasConstants; import org.wso2.carbon.identity.sso.saml.util.SAMLSSOUtil; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import static org.apache.commons.collections.CollectionUtils.isNotEmpty; /** * This class is used to process and validate the eIDAS SAML extensions. */ public class EidasExtensionProcessor implements SAMLExtensionProcessor { private static Log log = LogFactory.getLog(EidasExtensionProcessor.class); private static String errorMsg = "Mandatory Attribute not found."; /** * Check whether the SAML authentication request can be handled by the eIDAS extension processor. * * @param request SAML request * @return true if the request can be handled * @throws IdentitySAML2SSOException */ @Override public boolean canHandle(RequestAbstractType request) throws IdentitySAML2SSOException { boolean canHandle = request.getNamespaces().stream().anyMatch(namespace -> EidasConstants.EIDAS_NS.equals( namespace.getNamespaceURI())); if (canHandle) { if (log.isDebugEnabled()) { log.debug("Request in type: " + request.getClass().getSimpleName() + " can be handled by the " + "EidasExtensionProcessor."); } } return canHandle; } /** * Check whether the SAML response can be handled by the eIDAS extension processor. * * @param authReqDTO Authentication request data object * @return true if the request can be handled * @throws IdentitySAML2SSOException */ @Override public boolean canHandle(StatusResponseType response, Assertion assertion, SAMLSSOAuthnReqDTO authReqDTO) throws IdentitySAML2SSOException { String requestType = authReqDTO.getProperty(EidasConstants.EIDAS_REQUEST); boolean canHandle = false; if (requestType != null) { canHandle = EidasConstants.EIDAS_PREFIX.equals(requestType); if (canHandle) { if (log.isDebugEnabled()) { log.debug("Response in type: " + response.getClass().getSimpleName() + " can be handled by the " + "EidasExtensionProcessor."); } } } return canHandle; } /** * Process and Validate the SAML extensions in authentication request for EIDAS message format. * * @param request Authentication request * @param validationResp reqValidationResponseDTO * @throws IdentityException */ @Override public void processSAMLExtensions(RequestAbstractType request, SAMLSSOReqValidationResponseDTO validationResp) throws IdentitySAML2SSOException { if (request instanceof AuthnRequest) { if (log.isDebugEnabled()) { log.debug("Process and validate the extensions in SAML request from the issuer : " + validationResp.getIssuer() + " for EIDAS message format."); } Extensions extensions = request.getExtensions(); if (extensions != null) { validateForceAuthn(validationResp); validateIsPassive(validationResp); validateAuthnContextComparison(validationResp); validateSPType(validationResp, extensions); processRequestedAttributes(validationResp, extensions); } } } /** * Process and Validate a response against the SAML request with extensions for EIDAS message format. * * @param response SAML response * @param assertion SAML assertion * @param authReqDTO Authentication request data object * @throws IdentitySAML2SSOException */ @Override public void processSAMLExtensions(StatusResponseType response, Assertion assertion, SAMLSSOAuthnReqDTO authReqDTO) throws IdentitySAML2SSOException { if (response instanceof Response) { if (log.isDebugEnabled()) { log.debug("Process and validate a response against the SAML request with extensions" + " for EIDAS message format"); } assertion.setSignature(null); validateMandatoryRequestedAttr((Response) response, assertion, authReqDTO); setAuthnContextClassRef(assertion, authReqDTO); if (authReqDTO.getDoSignAssertions()) { try { SAMLSSOUtil.setSignature(assertion, authReqDTO.getSigningAlgorithmUri(), authReqDTO .getDigestAlgorithmUri(), new SignKeyDataHolder(authReqDTO.getUser() .getAuthenticatedSubjectIdentifier())); } catch (IdentityException e) { throw new IdentitySAML2SSOException("Error in signing SAML Assertion.", e); } } } } private void validateMandatoryRequestedAttr(Response response, Assertion assertion, SAMLSSOAuthnReqDTO authReqDTO) { List<String> mandatoryClaims = getMandatoryAttributes(authReqDTO); boolean isMandatoryClaimPresent = validateMandatoryClaims(assertion, mandatoryClaims); if (!isMandatoryClaimPresent) { response.setStatus(SAMLSSOUtil.buildResponseStatus(SAMLSSOConstants.StatusCodes.IDENTITY_PROVIDER_ERROR, errorMsg)); if (CollectionUtils.isNotEmpty(assertion.getAttributeStatements())) { assertion.getAttributeStatements().clear(); } NameID nameId = new NameIDBuilder().buildObject(); nameId.setValue("NotAvailable"); nameId.setFormat(NameIdentifier.UNSPECIFIED); assertion.getSubject().setNameID(nameId); return; } setAttributeNameFormat(assertion.getAttributeStatements()); } private void setAuthnContextClassRef(Assertion assertion, SAMLSSOAuthnReqDTO authReqDTO) { assertion.getAuthnStatements().get(0).getAuthnContext().getAuthnContextClassRef() .setAuthnContextClassRef(authReqDTO.getAuthenticationContextClassRefList().get(0) .getAuthenticationContextClassReference()); } private void processRequestedAttributes(SAMLSSOReqValidationResponseDTO validationResp, Extensions extensions) throws IdentitySAML2SSOException { if (isNotEmpty(extensions.getUnknownXMLObjects(RequestedAttributes.DEFAULT_ELEMENT_NAME))) { XMLObject requestedAttrs = extensions.getUnknownXMLObjects(RequestedAttributes.DEFAULT_ELEMENT_NAME).get(0); NodeList nodeList = requestedAttrs.getDOM().getChildNodes(); validationResp.setRequestedAttributes(new ArrayList<>()); validationResp.getProperties().put(EidasConstants.EIDAS_REQUEST, EidasConstants.EIDAS_PREFIX); for (int i = 0; i < nodeList.getLength(); i++) { ClaimMapping claimMapping = new ClaimMapping(); Claim remoteClaim = new Claim(); String nameFormat = nodeList.item(i).getAttributes().getNamedItem( EidasConstants.EIDAS_ATTRIBUTE_NAME_FORMAT).getNodeValue(); validateAttributeNameFormat(validationResp, nameFormat); remoteClaim.setClaimUri(nodeList.item(i).getAttributes().getNamedItem( EidasConstants.EIDAS_ATTRIBUTE_NAME).getNodeValue()); claimMapping.setRemoteClaim(remoteClaim); claimMapping.setRequested(true); claimMapping.setMandatory(Boolean.parseBoolean(nodeList.item(i).getAttributes().getNamedItem( EidasConstants.EIDAS_ATTRIBUTE_REQUIRED).getNodeValue())); validationResp.getRequestedAttributes().add(claimMapping); } } } private void validateAttributeNameFormat(SAMLSSOReqValidationResponseDTO validationResp, String nameFormat) throws IdentitySAML2SSOException { if (!nameFormat.equals(EidasConstants.EIDAS_ATTRIBUTE_NAME_FORMAT_URI)) { String errorResp; try { errorResp = SAMLSSOUtil.buildErrorResponse( SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR, "NameFormat should be " + EidasConstants.EIDAS_ATTRIBUTE_NAME_FORMAT_URI, validationResp.getDestination()); } catch (IOException | IdentityException e) { throw new IdentitySAML2SSOException("Issue in building error response.", e); } if (log.isDebugEnabled()) { log.debug("Invalid Request message. NameFormat found " + nameFormat); } validationResp.setResponse(errorResp); validationResp.setValid(false); } } private void validateSPType(SAMLSSOReqValidationResponseDTO validationResp, Extensions extensions) throws IdentitySAML2SSOException { if (isNotEmpty(extensions.getUnknownXMLObjects(SPType.DEFAULT_ELEMENT_NAME))) { XMLObject spType = extensions.getUnknownXMLObjects(SPType.DEFAULT_ELEMENT_NAME).get(0); if (log.isDebugEnabled()) { log.debug("Process the SP Type: " + spType + " in the EIDAS message"); } if (spType != null && isValidSPType((XSAnyImpl) spType)) { String errorResp; try { errorResp = SAMLSSOUtil.buildErrorResponse( SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR, "SP Type should be either public or private.", validationResp.getDestination()); } catch (IOException | IdentityException e) { throw new IdentitySAML2SSOException("Issue in building error response.", e); } if (log.isDebugEnabled()) { log.debug("Invalid Request message. SP Type found " + spType.getDOM().getNodeValue()); } validationResp.setResponse(errorResp); validationResp.setValid(false); } } } private boolean isValidSPType(XSAnyImpl spType) { return !spType.getTextContent().equals(EidasConstants.EIDAS_SP_TYPE_PUBLIC) && !spType.getTextContent().equals(EidasConstants.EIDAS_SP_TYPE_PRIVATE); } private boolean validateMandatoryClaims(Assertion assertion, List<String> mandatoryClaims) { boolean isMandatoryClaimPresent = false; List<AttributeStatement> attributeStatements = assertion.getAttributeStatements(); if (isNotEmpty(attributeStatements)) { for (String mandatoryClaim : mandatoryClaims) { if (log.isDebugEnabled()) { log.debug("Validating the mandatory claim :" + mandatoryClaim); } for (AttributeStatement attributeStatement : attributeStatements) { if (isNotEmpty(attributeStatement.getAttributes())) { if (attributeStatement.getAttributes().stream().anyMatch(attribute -> attribute.getName() .equals(mandatoryClaim))) { isMandatoryClaimPresent = true; } if (isMandatoryClaimPresent) { break; } } } if (!isMandatoryClaimPresent) { break; } } } return isMandatoryClaimPresent; } private List<String> getMandatoryAttributes(SAMLSSOAuthnReqDTO authReqDTO) { return authReqDTO.getRequestedAttributes().stream().filter(ClaimMapping::isMandatory) .map(requestedClaim -> requestedClaim.getRemoteClaim().getClaimUri()).collect(Collectors.toList()); } private void setAttributeNameFormat(List<AttributeStatement> attributeStatements) { attributeStatements.forEach(attributeStatement -> attributeStatement.getAttributes().forEach(attribute -> attribute.setNameFormat(EidasConstants.EIDAS_ATTRIBUTE_NAME_FORMAT_URI))); } private void validateIsPassive(SAMLSSOReqValidationResponseDTO validationResponseDTO) throws IdentitySAML2SSOException { String errorResp; if (validationResponseDTO.isPassive()) { try { errorResp = SAMLSSOUtil.buildErrorResponse( SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR, "isPassive SHOULD be set to false.", validationResponseDTO.getDestination()); } catch (IOException | IdentityException e) { throw new IdentitySAML2SSOException("Issue in building error response.", e); } if (log.isDebugEnabled()) { log.debug("Invalid Request message. isPassive found " + validationResponseDTO.isPassive()); } setErrorResponse(validationResponseDTO, errorResp); } } private void validateForceAuthn(SAMLSSOReqValidationResponseDTO validationResponseDTO) throws IdentitySAML2SSOException { String errorResp; if (!validationResponseDTO.isForceAuthn()) { try { errorResp = SAMLSSOUtil.buildErrorResponse( SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR, "ForceAuthn MUST be set to true", validationResponseDTO.getDestination()); } catch (IOException | IdentityException e) { throw new IdentitySAML2SSOException("Issue in building error response.", e); } if (log.isDebugEnabled()) { log.debug("Invalid Request message. ForceAuthn is " + validationResponseDTO.isForceAuthn()); } setErrorResponse(validationResponseDTO, errorResp); } } private void validateAuthnContextComparison(SAMLSSOReqValidationResponseDTO validationResponseDTO) throws IdentitySAML2SSOException { String errorResp; if (!AuthnContextComparisonTypeEnumeration.MINIMUM.toString().equals(validationResponseDTO .getRequestedAuthnContextComparison())) { try { errorResp = SAMLSSOUtil.buildErrorResponse( SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR, "Comparison of RequestedAuthnContext should be minimum.", validationResponseDTO.getDestination()); } catch (IOException | IdentityException e) { throw new IdentitySAML2SSOException("Issue in building error response.", e); } if (log.isDebugEnabled()) { log.debug("Invalid Request message. Comparison of RequestedAuthnContext is " + validationResponseDTO.getRequestedAuthnContextComparison()); } setErrorResponse(validationResponseDTO, errorResp); } } private void setErrorResponse(SAMLSSOReqValidationResponseDTO validationResponseDTO, String errorResp) { validationResponseDTO.setValid(false); validationResponseDTO.setResponse(errorResp); validationResponseDTO.setValid(false); } }
components/org.wso2.carbon.identity.sso.saml/src/main/java/org/wso2/carbon/identity/sso/saml/extension/eidas/EidasExtensionProcessor.java
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.identity.sso.saml.extension.eidas; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.opensaml.saml1.core.NameIdentifier; import org.opensaml.saml2.common.Extensions; import org.opensaml.saml2.core.Assertion; import org.opensaml.saml2.core.AttributeStatement; import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration; import org.opensaml.saml2.core.AuthnRequest; import org.opensaml.saml2.core.NameID; import org.opensaml.saml2.core.RequestAbstractType; import org.opensaml.saml2.core.Response; import org.opensaml.saml2.core.StatusResponseType; import org.opensaml.saml2.core.impl.NameIDBuilder; import org.opensaml.xml.XMLObject; import org.opensaml.xml.schema.impl.XSAnyImpl; import org.w3c.dom.NodeList; import org.wso2.carbon.identity.application.common.model.Claim; import org.wso2.carbon.identity.application.common.model.ClaimMapping; import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.sso.saml.SAMLSSOConstants; import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOAuthnReqDTO; import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOReqValidationResponseDTO; import org.wso2.carbon.identity.sso.saml.exception.IdentitySAML2SSOException; import org.wso2.carbon.identity.sso.saml.extension.SAMLExtensionProcessor; import org.wso2.carbon.identity.sso.saml.extension.eidas.model.RequestedAttributes; import org.wso2.carbon.identity.sso.saml.extension.eidas.model.SPType; import org.wso2.carbon.identity.sso.saml.extension.eidas.util.EidasConstants; import org.wso2.carbon.identity.sso.saml.util.SAMLSSOUtil; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import static org.apache.commons.collections.CollectionUtils.isNotEmpty; /** * This class is used to process and validate the eIDAS SAML extensions. */ public class EidasExtensionProcessor implements SAMLExtensionProcessor { private static Log log = LogFactory.getLog(EidasExtensionProcessor.class); private static String errorMsg = "Mandatory Attribute not found."; /** * Check whether the SAML authentication request can be handled by the eIDAS extension processor. * * @param request SAML request * @return true if the request can be handled * @throws IdentitySAML2SSOException */ @Override public boolean canHandle(RequestAbstractType request) throws IdentitySAML2SSOException { boolean canHandle = request.getNamespaces().stream().anyMatch(namespace -> EidasConstants.EIDAS_NS.equals( namespace.getNamespaceURI())); if (canHandle) { if (log.isDebugEnabled()) { log.debug("Request in type: " + request.getClass().getSimpleName() + " can be handled by the " + "EidasExtensionProcessor."); } } return canHandle; } /** * Check whether the SAML response can be handled by the eIDAS extension processor. * * @param authReqDTO Authentication request data object * @return true if the request can be handled * @throws IdentitySAML2SSOException */ @Override public boolean canHandle(StatusResponseType response, Assertion assertion, SAMLSSOAuthnReqDTO authReqDTO) throws IdentitySAML2SSOException { String requestType = authReqDTO.getProperty(EidasConstants.EIDAS_REQUEST); boolean canHandle = false; if (requestType != null) { canHandle = EidasConstants.EIDAS_PREFIX.equals(requestType); if (canHandle) { if (log.isDebugEnabled()) { log.debug("Response in type: " + response.getClass().getSimpleName() + " can be handled by the " + "EidasExtensionProcessor."); } } } return canHandle; } /** * Process and Validate the SAML extensions in authentication request for EIDAS message format. * * @param request Authentication request * @param validationResp reqValidationResponseDTO * @throws IdentityException */ @Override public void processSAMLExtensions(RequestAbstractType request, SAMLSSOReqValidationResponseDTO validationResp) throws IdentitySAML2SSOException { if (request instanceof AuthnRequest) { if (log.isDebugEnabled()) { log.debug("Process and validate the extensions in SAML request from the issuer : " + validationResp.getIssuer() + " for EIDAS message format."); } Extensions extensions = request.getExtensions(); if (extensions != null) { validateForceAuthn(validationResp); validateIsPassive(validationResp); validateAuthnContextComparison(validationResp); validateSPType(validationResp, extensions); processRequestedAttributes(validationResp, extensions); } } } /** * Process and Validate a response against the SAML request with extensions for EIDAS message format. * * @param response SAML response * @param assertion SAML assertion * @param authReqDTO Authentication request data object * @throws IdentitySAML2SSOException */ @Override public void processSAMLExtensions(StatusResponseType response, Assertion assertion, SAMLSSOAuthnReqDTO authReqDTO) throws IdentitySAML2SSOException { if (response instanceof Response) { if (log.isDebugEnabled()) { log.debug("Process and validate a response against the SAML request with extensions" + " for EIDAS message format"); } validateMandatoryRequestedAttr((Response) response, assertion, authReqDTO); setAuthnContextClassRef(assertion, authReqDTO); } } private void validateMandatoryRequestedAttr(Response response, Assertion assertion, SAMLSSOAuthnReqDTO authReqDTO) { List<String> mandatoryClaims = getMandatoryAttributes(authReqDTO); boolean isMandatoryClaimPresent = validateMandatoryClaims(assertion, mandatoryClaims); if (!isMandatoryClaimPresent) { response.setStatus(SAMLSSOUtil.buildResponseStatus(SAMLSSOConstants.StatusCodes.IDENTITY_PROVIDER_ERROR, errorMsg)); if (CollectionUtils.isNotEmpty(assertion.getAttributeStatements())) { assertion.getAttributeStatements().clear(); } NameID nameId = new NameIDBuilder().buildObject(); nameId.setValue("NotAvailable"); nameId.setFormat(NameIdentifier.UNSPECIFIED); assertion.getSubject().setNameID(nameId); return; } setAttributeNameFormat(assertion.getAttributeStatements()); } private void setAuthnContextClassRef(Assertion assertion, SAMLSSOAuthnReqDTO authReqDTO) { assertion.getAuthnStatements().get(0).getAuthnContext().getAuthnContextClassRef() .setAuthnContextClassRef(authReqDTO.getAuthenticationContextClassRefList().get(0) .getAuthenticationContextClassReference()); } private void processRequestedAttributes(SAMLSSOReqValidationResponseDTO validationResp, Extensions extensions) throws IdentitySAML2SSOException { if (isNotEmpty(extensions.getUnknownXMLObjects(RequestedAttributes.DEFAULT_ELEMENT_NAME))) { XMLObject requestedAttrs = extensions.getUnknownXMLObjects(RequestedAttributes.DEFAULT_ELEMENT_NAME).get(0); NodeList nodeList = requestedAttrs.getDOM().getChildNodes(); validationResp.setRequestedAttributes(new ArrayList<>()); validationResp.getProperties().put(EidasConstants.EIDAS_REQUEST, EidasConstants.EIDAS_PREFIX); for (int i = 0; i < nodeList.getLength(); i++) { ClaimMapping claimMapping = new ClaimMapping(); Claim remoteClaim = new Claim(); String nameFormat = nodeList.item(i).getAttributes().getNamedItem( EidasConstants.EIDAS_ATTRIBUTE_NAME_FORMAT).getNodeValue(); validateAttributeNameFormat(validationResp, nameFormat); remoteClaim.setClaimUri(nodeList.item(i).getAttributes().getNamedItem( EidasConstants.EIDAS_ATTRIBUTE_NAME).getNodeValue()); claimMapping.setRemoteClaim(remoteClaim); claimMapping.setRequested(true); claimMapping.setMandatory(Boolean.parseBoolean(nodeList.item(i).getAttributes().getNamedItem( EidasConstants.EIDAS_ATTRIBUTE_REQUIRED).getNodeValue())); validationResp.getRequestedAttributes().add(claimMapping); } } } private void validateAttributeNameFormat(SAMLSSOReqValidationResponseDTO validationResp, String nameFormat) throws IdentitySAML2SSOException { if (!nameFormat.equals(EidasConstants.EIDAS_ATTRIBUTE_NAME_FORMAT_URI)) { String errorResp; try { errorResp = SAMLSSOUtil.buildErrorResponse( SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR, "NameFormat should be " + EidasConstants.EIDAS_ATTRIBUTE_NAME_FORMAT_URI, validationResp.getDestination()); } catch (IOException | IdentityException e) { throw new IdentitySAML2SSOException("Issue in building error response.", e); } if (log.isDebugEnabled()) { log.debug("Invalid Request message. NameFormat found " + nameFormat); } validationResp.setResponse(errorResp); validationResp.setValid(false); } } private void validateSPType(SAMLSSOReqValidationResponseDTO validationResp, Extensions extensions) throws IdentitySAML2SSOException { if (isNotEmpty(extensions.getUnknownXMLObjects(SPType.DEFAULT_ELEMENT_NAME))) { XMLObject spType = extensions.getUnknownXMLObjects(SPType.DEFAULT_ELEMENT_NAME).get(0); if (log.isDebugEnabled()) { log.debug("Process the SP Type: " + spType + " in the EIDAS message"); } if (spType != null && isValidSPType((XSAnyImpl) spType)) { String errorResp; try { errorResp = SAMLSSOUtil.buildErrorResponse( SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR, "SP Type should be either public or private.", validationResp.getDestination()); } catch (IOException | IdentityException e) { throw new IdentitySAML2SSOException("Issue in building error response.", e); } if (log.isDebugEnabled()) { log.debug("Invalid Request message. SP Type found " + spType.getDOM().getNodeValue()); } validationResp.setResponse(errorResp); validationResp.setValid(false); } } } private boolean isValidSPType(XSAnyImpl spType) { return !spType.getTextContent().equals(EidasConstants.EIDAS_SP_TYPE_PUBLIC) && !spType.getTextContent().equals(EidasConstants.EIDAS_SP_TYPE_PRIVATE); } private boolean validateMandatoryClaims(Assertion assertion, List<String> mandatoryClaims) { boolean isMandatoryClaimPresent = false; List<AttributeStatement> attributeStatements = assertion.getAttributeStatements(); if (isNotEmpty(attributeStatements)) { for (String mandatoryClaim : mandatoryClaims) { if (log.isDebugEnabled()) { log.debug("Validating the mandatory claim :" + mandatoryClaim); } for (AttributeStatement attributeStatement : attributeStatements) { if (isNotEmpty(attributeStatement.getAttributes())) { if (attributeStatement.getAttributes().stream().anyMatch(attribute -> attribute.getName() .equals(mandatoryClaim))) { isMandatoryClaimPresent = true; } if (isMandatoryClaimPresent) { break; } } } if (!isMandatoryClaimPresent) { break; } } } return isMandatoryClaimPresent; } private List<String> getMandatoryAttributes(SAMLSSOAuthnReqDTO authReqDTO) { return authReqDTO.getRequestedAttributes().stream().filter(ClaimMapping::isMandatory) .map(requestedClaim -> requestedClaim.getRemoteClaim().getClaimUri()).collect(Collectors.toList()); } private void setAttributeNameFormat(List<AttributeStatement> attributeStatements) { attributeStatements.forEach(attributeStatement -> attributeStatement.getAttributes().forEach(attribute -> attribute.setNameFormat(EidasConstants.EIDAS_ATTRIBUTE_NAME_FORMAT_URI))); } private void validateIsPassive(SAMLSSOReqValidationResponseDTO validationResponseDTO) throws IdentitySAML2SSOException { String errorResp; if (validationResponseDTO.isPassive()) { try { errorResp = SAMLSSOUtil.buildErrorResponse( SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR, "isPassive SHOULD be set to false.", validationResponseDTO.getDestination()); } catch (IOException | IdentityException e) { throw new IdentitySAML2SSOException("Issue in building error response.", e); } if (log.isDebugEnabled()) { log.debug("Invalid Request message. isPassive found " + validationResponseDTO.isPassive()); } setErrorResponse(validationResponseDTO, errorResp); } } private void validateForceAuthn(SAMLSSOReqValidationResponseDTO validationResponseDTO) throws IdentitySAML2SSOException { String errorResp; if (!validationResponseDTO.isForceAuthn()) { try { errorResp = SAMLSSOUtil.buildErrorResponse( SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR, "ForceAuthn MUST be set to true", validationResponseDTO.getDestination()); } catch (IOException | IdentityException e) { throw new IdentitySAML2SSOException("Issue in building error response.", e); } if (log.isDebugEnabled()) { log.debug("Invalid Request message. ForceAuthn is " + validationResponseDTO.isForceAuthn()); } setErrorResponse(validationResponseDTO, errorResp); } } private void validateAuthnContextComparison(SAMLSSOReqValidationResponseDTO validationResponseDTO) throws IdentitySAML2SSOException { String errorResp; if (!AuthnContextComparisonTypeEnumeration.MINIMUM.toString().equals(validationResponseDTO .getRequestedAuthnContextComparison())) { try { errorResp = SAMLSSOUtil.buildErrorResponse( SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR, "Comparison of RequestedAuthnContext should be minimum.", validationResponseDTO.getDestination()); } catch (IOException | IdentityException e) { throw new IdentitySAML2SSOException("Issue in building error response.", e); } if (log.isDebugEnabled()) { log.debug("Invalid Request message. Comparison of RequestedAuthnContext is " + validationResponseDTO.getRequestedAuthnContextComparison()); } setErrorResponse(validationResponseDTO, errorResp); } } private void setErrorResponse(SAMLSSOReqValidationResponseDTO validationResponseDTO, String errorResp) { validationResponseDTO.setValid(false); validationResponseDTO.setResponse(errorResp); validationResponseDTO.setValid(false); } }
Code improvement for eIDAS profile support
components/org.wso2.carbon.identity.sso.saml/src/main/java/org/wso2/carbon/identity/sso/saml/extension/eidas/EidasExtensionProcessor.java
Code improvement for eIDAS profile support
<ide><path>omponents/org.wso2.carbon.identity.sso.saml/src/main/java/org/wso2/carbon/identity/sso/saml/extension/eidas/EidasExtensionProcessor.java <ide> import org.wso2.carbon.identity.application.common.model.ClaimMapping; <ide> import org.wso2.carbon.identity.base.IdentityException; <ide> import org.wso2.carbon.identity.sso.saml.SAMLSSOConstants; <add>import org.wso2.carbon.identity.sso.saml.builders.SignKeyDataHolder; <ide> import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOAuthnReqDTO; <ide> import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOReqValidationResponseDTO; <ide> import org.wso2.carbon.identity.sso.saml.exception.IdentitySAML2SSOException; <ide> /** <ide> * Process and Validate a response against the SAML request with extensions for EIDAS message format. <ide> * <del> * @param response SAML response <del> * @param assertion SAML assertion <add> * @param response SAML response <add> * @param assertion SAML assertion <ide> * @param authReqDTO Authentication request data object <ide> * @throws IdentitySAML2SSOException <ide> */ <ide> log.debug("Process and validate a response against the SAML request with extensions" + <ide> " for EIDAS message format"); <ide> } <add> assertion.setSignature(null); <ide> validateMandatoryRequestedAttr((Response) response, assertion, authReqDTO); <ide> setAuthnContextClassRef(assertion, authReqDTO); <add> if (authReqDTO.getDoSignAssertions()) { <add> try { <add> SAMLSSOUtil.setSignature(assertion, authReqDTO.getSigningAlgorithmUri(), authReqDTO <add> .getDigestAlgorithmUri(), new SignKeyDataHolder(authReqDTO.getUser() <add> .getAuthenticatedSubjectIdentifier())); <add> } catch (IdentityException e) { <add> throw new IdentitySAML2SSOException("Error in signing SAML Assertion.", e); <add> } <add> } <ide> } <ide> } <ide>
JavaScript
mit
4edfdedbfb63cc5a11f6ddd44463a053ba021a8d
0
skatejs/skatejs,chrisdarroch/skatejs,skatejs/skatejs,skatejs/skatejs,chrisdarroch/skatejs
import { Component, define, symbols } from '../../../src/index'; import { customElementsV0, customElementsV1 } from '../../../src/util/support'; const { name: $name } = symbols; function mockDefine(name) { if (customElementsV1) { window.customElements.define(name, function customElemMock() {}); // eslint-disable-line prefer-arrow-callback } else if (customElementsV0) { document.registerElement(name, function customElemMock() {}); // eslint-disable-line prefer-arrow-callback } } describe('api/define', () => { it('should not register without any properties', () => { expect(() => { define('x-test'); }).to.throw(Error); }); it('should add ____skate_name to the constructor to allow itself (and other versions of skate) to identify it as a component', () => { const elem = define('x-test-skate-name', {}); expect(elem.____skate_name).to.equal('x-test-skate-name'); }); it('should register components with unique names', () => { const elem1 = define('x-test-api-define', {}); const elem2 = define('x-test-api-define', {}); const elem3 = define('x-test-api-define', {}); // the first one is registered by its own name // the rest is registered by the name plus random string expect(elem1[$name]).to.equal('x-test-api-define'); expect(elem2[$name]).not.to.equal('x-test-api-define'); expect(elem2[$name].indexOf('x-test-api-define') === 0).to.equal(true); expect(elem3[$name]).not.to.equal('x-test-api-define'); expect(elem3[$name].indexOf('x-test-api-define') === 0).to.equal(true); }); it('should register components with unique names with multiple versions of skate', () => { mockDefine('x-test-api-define-multi'); expect(() => { define('x-test-api-define-multi', {}); }).to.not.throw(); }); it('should take an object and extend Component', () => { expect(define('x-test', {}).prototype).to.be.an.instanceof(Component); }); it('should be able to take an ES5 extension of Component', () => { expect(define('x-test', Component.extend({})).prototype).to.be.an.instanceof(Component); }); it('should take a constructor that extends Component', () => { expect(define('x-test', class extends Component {}).prototype).to.be.an.instanceof(Component); // eslint-disable-line react/prefer-stateless-function, max-len }); });
test/unit/api/define.js
import { Component, define, symbols } from '../../../src/index'; import { customElementsV0, customElementsV1 } from '../../../src/util/support'; const { name: $name } = symbols; function mockDefine(name) { if (customElementsV1) { window.customElements.define(name, function customElemMock() {}); // eslint-disable-line prefer-arrow-callback } else if (customElementsV0) { document.registerElement(name, function customElemMock() {}); // eslint-disable-line prefer-arrow-callback } } describe('api/define', () => { it('should not register without any properties', () => { expect(() => { define('x-test'); }).to.throw(Error); }); it('should register components with unique names', () => { const elem1 = define('x-test-api-define', {}); const elem2 = define('x-test-api-define', {}); const elem3 = define('x-test-api-define', {}); // the first one is registered by its own name // the rest is registered by the name plus random string expect(elem1[$name]).to.equal('x-test-api-define'); expect(elem2[$name]).not.to.equal('x-test-api-define'); expect(elem2[$name].indexOf('x-test-api-define') === 0).to.equal(true); expect(elem3[$name]).not.to.equal('x-test-api-define'); expect(elem3[$name].indexOf('x-test-api-define') === 0).to.equal(true); }); it('should register components with unique names with multiple versions of skate', () => { mockDefine('x-test-api-define-multi'); expect(() => { define('x-test-api-define-multi', {}); }).to.not.throw(); }); it('should take an object and extend Component', () => { expect(define('x-test', {}).prototype).to.be.an.instanceof(Component); }); it('should be able to take an ES5 extension of Component', () => { expect(define('x-test', Component.extend({})).prototype).to.be.an.instanceof(Component); }); it('should take a constructor that extends Component', () => { expect(define('x-test', class extends Component {}).prototype).to.be.an.instanceof(Component); // eslint-disable-line react/prefer-stateless-function, max-len }); });
test: Add a test for ____skate_name presence.
test/unit/api/define.js
test: Add a test for ____skate_name presence.
<ide><path>est/unit/api/define.js <ide> expect(() => { <ide> define('x-test'); <ide> }).to.throw(Error); <add> }); <add> <add> it('should add ____skate_name to the constructor to allow itself (and other versions of skate) to identify it as a component', () => { <add> const elem = define('x-test-skate-name', {}); <add> expect(elem.____skate_name).to.equal('x-test-skate-name'); <ide> }); <ide> <ide> it('should register components with unique names', () => {
Java
artistic-2.0
2dc35d6be8999e7d4c2f4a04b94536e3829b6197
0
Horstman/AppWorkUtils
/** * Copyright (c) 2009 - 2010 AppWork UG(haftungsbeschränkt) <[email protected]> * * This file is part of org.appwork.utils.event.queue * * This software is licensed under the Artistic License 2.0, * see the LICENSE file or http://www.opensource.org/licenses/artistic-license-2.0.php * for details */ package org.appwork.utils.event.queue; import java.util.ArrayList; import java.util.HashMap; /** * @author daniel * */ public class Queue extends Thread { public enum QueuePriority { HIGH, NORM, LOW } protected HashMap<QueuePriority, ArrayList<QueueItem>> queue = new HashMap<QueuePriority, ArrayList<QueueItem>>(); protected final Object queueLock = new Object(); protected boolean waitFlag = true; protected QueueItem item = null; protected Thread thread = null; protected QueuePriority[] prios; /* * this functions returns true if the current running Thread is our * QueueThread OR the SourceQueueItem chain is rooted in current running * QueueItem */ public boolean isQueueThread(QueueItem item) { if (currentThread() == thread) return true; QueueItem source = item.getSourceQueueItem(); while (source != null) { if (source.gotStarted()) return true; source = source.getSourceQueueItem(); } return false; } public Queue(String id) { super(id); /* init queue */ prios = QueuePriority.values(); for (QueuePriority prio : prios) { queue.put(prio, new ArrayList<QueueItem>()); } start(); } public boolean isWaiting() { return waitFlag; } public void add(QueueItem item) { if (isQueueThread(item)) { /* * call comes from current running item, so lets start item */ startItem(item); } else { /* call does not come from current running item, so lets queue it */ internalAdd(item); } } public void enqueue(QueueItem item) { internalAdd(item); } protected void internalAdd(QueueItem item) { synchronized (queueLock) { queue.get(item.getQueuePrio()).add(item); } synchronized (this) { if (waitFlag) { waitFlag = false; notify(); } } } public Object addWait(QueueItem item) throws Exception { if (isQueueThread(item)) { /* * call comes from current running item, so lets start item */ startItem(item); } else { /* call does not come from current running item, so lets queue it */ internalAdd(item); /* wait till item is finished */ while (!item.isFinished()) { synchronized (item) { item.wait(1000); } } } if (item.gotKilled()) throw new Exception("Queue got killed!"); if (item.getException() != null) throw item.getException(); return item.getResult(); } public boolean isEmpty() { synchronized (queueLock) { for (QueuePriority prio : prios) { if (!queue.get(prio).isEmpty()) return false; } return true; } } public void killQueue() { synchronized (queueLock) { for (QueuePriority prio : prios) { for (QueueItem item : queue.get(prio)) { /* kill item */ item.kill(); synchronized (item) { item.notify(); } } /* clear queue */ queue.get(prio).clear(); } } } public void run() { if (thread != null) return; thread = this; while (true) { synchronized (this) { while (waitFlag) { try { wait(); } catch (Exception e) { org.appwork.utils.logging.Log.exception(e); } } } synchronized (queueLock) { item = null; for (QueuePriority prio : prios) { if (queue.get(prio).size() > 0) { item = queue.get(prio).remove(0); break; } } if (item == null) { waitFlag = true; } } if (item == null || waitFlag) continue; startItem(item); } } /* if you override this, DON'T forget to notify item when its done! */ protected void startItem(QueueItem item) { try { item.start(this); } catch (Exception e) { try { item.exceptionHandler(e); } catch (Exception e2) { org.appwork.utils.logging.Log.exception(e2); } } finally { synchronized (item) { item.notify(); } } } }
src/org/appwork/utils/event/queue/Queue.java
/** * Copyright (c) 2009 - 2010 AppWork UG(haftungsbeschränkt) <[email protected]> * * This file is part of org.appwork.utils.event.queue * * This software is licensed under the Artistic License 2.0, * see the LICENSE file or http://www.opensource.org/licenses/artistic-license-2.0.php * for details */ package org.appwork.utils.event.queue; import java.util.ArrayList; import java.util.HashMap; /** * @author daniel * */ public class Queue extends Thread { public enum QueuePriority { HIGH, NORM, LOW } protected HashMap<QueuePriority, ArrayList<QueueItem>> queue = new HashMap<QueuePriority, ArrayList<QueueItem>>(); protected final Object queueLock = new Object(); protected boolean waitFlag = true; protected QueueItem item = null; protected Thread thread = null; protected QueuePriority[] prios; /* * this functions returns true if the current running Thread is our * QueueThread OR the SourceQueueItem chain is rooted in current running * QueueItem */ public boolean isQueueThread(QueueItem item) { if (currentThread() == thread) return true; QueueItem source = item.getSourceQueueItem(); while (source != null) { if (source.gotStarted()) return true; source = source.getSourceQueueItem(); } return false; } public Queue(String id) { super(id); /* init queue */ prios = QueuePriority.values(); for (QueuePriority prio : prios) { queue.put(prio, new ArrayList<QueueItem>()); } start(); } public boolean isWaiting() { return waitFlag; } public void add(QueueItem item) { if (isQueueThread(item)) { /* * call comes from current running item, so lets start item */ startItem(item); } else { /* call does not come from current running item, so lets queue it */ internalAdd(item); } } protected void internalAdd(QueueItem item) { synchronized (queueLock) { queue.get(item.getQueuePrio()).add(item); } synchronized (this) { if (waitFlag) { waitFlag = false; notify(); } } } public Object addWait(QueueItem item) throws Exception { if (isQueueThread(item)) { /* * call comes from current running item, so lets start item */ startItem(item); } else { /* call does not come from current running item, so lets queue it */ internalAdd(item); /* wait till item is finished */ while (!item.isFinished()) { synchronized (item) { item.wait(1000); } } } if (item.gotKilled()) throw new Exception("Queue got killed!"); if (item.getException() != null) throw item.getException(); return item.getResult(); } public boolean isEmpty() { synchronized (queueLock) { for (QueuePriority prio : prios) { if (!queue.get(prio).isEmpty()) return false; } return true; } } public void killQueue() { synchronized (queueLock) { for (QueuePriority prio : prios) { for (QueueItem item : queue.get(prio)) { /* kill item */ item.kill(); synchronized (item) { item.notify(); } } /* clear queue */ queue.get(prio).clear(); } } } public void run() { if (thread != null) return; thread = this; while (true) { synchronized (this) { while (waitFlag) { try { wait(); } catch (Exception e) { org.appwork.utils.logging.Log.exception(e); } } } synchronized (queueLock) { item = null; for (QueuePriority prio : prios) { if (queue.get(prio).size() > 0) { item = queue.get(prio).remove(0); break; } } if (item == null) { waitFlag = true; } } if (item == null || waitFlag) continue; startItem(item); } } /* if you override this, DON'T forget to notify item when its done! */ protected void startItem(QueueItem item) { try { item.start(this); } catch (Exception e) { try { item.exceptionHandler(e); } catch (Exception e2) { org.appwork.utils.logging.Log.exception(e2); } } finally { synchronized (item) { item.notify(); } } } }
git-svn-id: svn://svn.appwork.org/utils@165 21714237-3853-44ef-a1f0-ef8f03a7d1fe
src/org/appwork/utils/event/queue/Queue.java
<ide><path>rc/org/appwork/utils/event/queue/Queue.java <ide> /* call does not come from current running item, so lets queue it */ <ide> internalAdd(item); <ide> } <add> } <add> <add> public void enqueue(QueueItem item) { <add> internalAdd(item); <ide> } <ide> <ide> protected void internalAdd(QueueItem item) {
Java
mit
cfff4b5c9291521446404fe1f88c840786a72d1f
0
Musician101/Common
package io.musician101.musicianlibrary.java.minecraft.sponge.mixin; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import io.musician101.musicianlibrary.java.minecraft.sponge.event.AffectBookEvent.EditBookEvent; import io.musician101.musicianlibrary.java.minecraft.sponge.event.AffectBookEvent.SignBookEvent; import java.util.ArrayList; import java.util.Collections; import java.util.List; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.inventory.Slot; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; import net.minecraft.network.play.client.CPacketCustomPayload; import net.minecraft.network.play.server.SPacketSetSlot; import org.spongepowered.api.Sponge; import org.spongepowered.api.data.Transaction; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.cause.EventContext; import org.spongepowered.api.event.cause.EventContextKeys; import org.spongepowered.api.item.ItemTypes; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.text.Text; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; @Mixin(value = NetHandlerPlayServer.class, priority = 1001) public abstract class MixinNetHandlerPlayServer implements INetHandlerPlayServer { @Shadow public EntityPlayerMP player; private ItemStackSnapshot getSnapshot(net.minecraft.item.ItemStack itemStack) { return org.spongepowered.api.item.inventory.ItemStack.class.cast(itemStack).createSnapshot(); } @Inject(method = "processCustomPayload", at = @At(value = "INVOKE", target = "Lnet/minecraft/item/ItemStack;setTagInfo(Ljava/lang/String;Lnet/minecraft/nbt/NBTBase;)V", ordinal = 0), locals = LocalCapture.CAPTURE_FAILEXCEPTION, cancellable = true) public void onBookEdit(CPacketCustomPayload packetIn, CallbackInfo ci, String channelName, PacketBuffer packetBuffer, net.minecraft.item.ItemStack itemStack, net.minecraft.item.ItemStack itemStack1) { Player spongePlayer = (Player) player; Transaction<ItemStackSnapshot> transaction = new Transaction<>(getSnapshot(itemStack1), getSnapshot(itemStack)); EditBookEvent event = new EditBookEvent(spongePlayer, transaction, Cause.of(EventContext.builder().add(EventContextKeys.PLAYER, spongePlayer).build(), player)); Sponge.getEventManager().post(event); if (!event.isCancelled()) { Transaction<ItemStackSnapshot> postEventTransaction = event.getTransaction(); NBTTagList pages = new NBTTagList(); postEventTransaction.getFinal().createStack().get(Keys.BOOK_PAGES).orElse(Collections.emptyList()).forEach(page -> pages.appendTag(processJson(page.toPlain()))); itemStack1.setTagInfo("pages", pages); } updateInventory(player, itemStack1); ci.cancel(); } @Inject(method = "processCustomPayload", at = @At(value = "NEW", target = "net/minecraft/item/ItemStack", ordinal = 0), locals = LocalCapture.CAPTURE_FAILEXCEPTION, cancellable = true) public void onBookSign(CPacketCustomPayload packetIn, CallbackInfo ci, String channelName, PacketBuffer packetBuffer, net.minecraft.item.ItemStack itemStack, net.minecraft.item.ItemStack itemStack1) { Player spongePlayer = (Player) player; NBTTagCompound tag = itemStack.getTagCompound(); if (tag == null) { tag = new NBTTagCompound(); } NBTTagList pagesNBT = tag.getTagList("pages", 8); List<Text> pagesText = new ArrayList<>(); for (int i = 0; i < pagesNBT.tagCount(); i++) { pagesText.add(Text.of(pagesNBT.getStringTagAt(i))); } org.spongepowered.api.item.inventory.ItemStack writtenBook = org.spongepowered.api.item.inventory.ItemStack.builder().fromSnapshot(getSnapshot(itemStack)).itemType(ItemTypes.WRITTEN_BOOK).add(Keys.BOOK_AUTHOR, Text.of(player.getName())).add(Keys.DISPLAY_NAME, Text.of(itemStack.getTagCompound().getString("title"))).add(Keys.BOOK_PAGES, pagesText).build(); Transaction<ItemStackSnapshot> transaction = new Transaction<>(getSnapshot(itemStack1), writtenBook.createSnapshot()); SignBookEvent event = new SignBookEvent(spongePlayer, transaction, Cause.of(EventContext.builder().add(EventContextKeys.PLAYER, spongePlayer).build(), player)); Sponge.getEventManager().post(event); if (!event.isCancelled()) { Transaction<ItemStackSnapshot> postEventTransaction = event.getTransaction(); NBTTagList pages = new NBTTagList(); org.spongepowered.api.item.inventory.ItemStack finalStack = postEventTransaction.getFinal().createStack(); finalStack.get(Keys.BOOK_PAGES).orElse(Collections.emptyList()).forEach(page -> { String s = page.toPlain(); JsonElement initialJson = new Gson().fromJson(s, JsonObject.class).get("text"); try { pages.appendTag(processJson(initialJson.getAsString())); } catch (JsonParseException e) { pages.appendTag(new NBTTagString(initialJson.getAsString())); } }); itemStack1 = net.minecraft.item.ItemStack.class.cast(postEventTransaction.getFinal().createStack()); itemStack1.setTagInfo("pages", pages); player.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, itemStack1); } updateInventory(player, itemStack1); ci.cancel(); } private NBTTagString processJson(String json) throws JsonParseException { JsonObject jsonObject = new Gson().fromJson(json.replace("\\", ""), JsonObject.class); return new NBTTagString(jsonObject.get("text").getAsString()); } @Shadow public abstract void sendPacket(Packet<?> packetIn); private void updateInventory(EntityPlayerMP player, net.minecraft.item.ItemStack itemStack) { Slot slot = player.openContainer.getSlotFromInventory(player.inventory, player.inventory.currentItem); if (slot != null) { sendPacket(new SPacketSetSlot(player.openContainer.windowId, slot.slotNumber, itemStack)); } } }
musicianlibrary-sponge/src/main/java/io/musician101/musicianlibrary/java/minecraft/sponge/mixin/MixinNetHandlerPlayServer.java
package io.musician101.musicianlibrary.java.minecraft.sponge.mixin; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import io.musician101.musicianlibrary.java.minecraft.sponge.event.AffectBookEvent.EditBookEvent; import io.musician101.musicianlibrary.java.minecraft.sponge.event.AffectBookEvent.SignBookEvent; import java.util.ArrayList; import java.util.Collections; import java.util.List; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.inventory.Slot; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; import net.minecraft.network.play.client.CPacketCustomPayload; import net.minecraft.network.play.server.SPacketSetSlot; import org.spongepowered.api.Sponge; import org.spongepowered.api.data.Transaction; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.cause.EventContext; import org.spongepowered.api.event.cause.EventContextKeys; import org.spongepowered.api.item.ItemTypes; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.text.Text; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; @Mixin(value = NetHandlerPlayServer.class, priority = 1001) public abstract class MixinNetHandlerPlayServer implements INetHandlerPlayServer { @Shadow public EntityPlayerMP player; private ItemStackSnapshot getSnapshot(net.minecraft.item.ItemStack itemStack) { return org.spongepowered.api.item.inventory.ItemStack.class.cast(itemStack).createSnapshot(); } @Inject(method = "processCustomPayload", at = @At(value = "INVOKE", target = "Lnet/minecraft/item/ItemStack;setTagInfo(Ljava/lang/String;Lnet/minecraft/nbt/NBTBase;)V", ordinal = 0), locals = LocalCapture.CAPTURE_FAILEXCEPTION, cancellable = true) public void onBookEdit(CPacketCustomPayload packetIn, CallbackInfo ci, String channelName, PacketBuffer packetBuffer, net.minecraft.item.ItemStack itemStack, net.minecraft.item.ItemStack itemStack1) { Player spongePlayer = (Player) player; Transaction<ItemStackSnapshot> transaction = new Transaction<>(getSnapshot(itemStack1), getSnapshot(itemStack)); EditBookEvent event = new EditBookEvent(spongePlayer, transaction, Cause.of(EventContext.builder().add(EventContextKeys.PLAYER, spongePlayer).build(), player)); Sponge.getEventManager().post(event); if (!event.isCancelled()) { Transaction<ItemStackSnapshot> postEventTransaction = event.getTransaction(); NBTTagList pages = new NBTTagList(); postEventTransaction.getFinal().createStack().get(Keys.BOOK_PAGES).orElse(Collections.emptyList()).forEach(page -> pages.appendTag(processJson(page.toPlain()))); itemStack1.setTagInfo("pages", pages); } updateInventory(player, itemStack1); ci.cancel(); } @Inject(method = "processCustomPayload", at = @At(value = "NEW", target = "net/minecraft/item/ItemStack", ordinal = 0), locals = LocalCapture.CAPTURE_FAILEXCEPTION, cancellable = true) public void onBookSign(CPacketCustomPayload packetIn, CallbackInfo ci, String channelName, PacketBuffer packetBuffer, net.minecraft.item.ItemStack itemStack, net.minecraft.item.ItemStack itemStack1) { Player spongePlayer = (Player) player; NBTTagList pagesNBT = itemStack.getTagCompound().getTagList("pages", 8); List<Text> pagesText = new ArrayList<>(); for (int i = 0; i < pagesNBT.tagCount(); i++) { pagesText.add(Text.of(pagesNBT.getStringTagAt(i))); } org.spongepowered.api.item.inventory.ItemStack writtenBook = org.spongepowered.api.item.inventory.ItemStack.builder().fromSnapshot(getSnapshot(itemStack)).itemType(ItemTypes.WRITTEN_BOOK).add(Keys.BOOK_AUTHOR, Text.of(player.getName())).add(Keys.DISPLAY_NAME, Text.of(itemStack.getTagCompound().getString("title"))).add(Keys.BOOK_PAGES, pagesText).build(); Transaction<ItemStackSnapshot> transaction = new Transaction<>(getSnapshot(itemStack1), writtenBook.createSnapshot()); SignBookEvent event = new SignBookEvent(spongePlayer, transaction, Cause.of(EventContext.builder().add(EventContextKeys.PLAYER, spongePlayer).build(), player)); Sponge.getEventManager().post(event); if (!event.isCancelled()) { Transaction<ItemStackSnapshot> postEventTransaction = event.getTransaction(); NBTTagList pages = new NBTTagList(); org.spongepowered.api.item.inventory.ItemStack finalStack = postEventTransaction.getFinal().createStack(); finalStack.get(Keys.BOOK_PAGES).orElse(Collections.emptyList()).forEach(page -> { String s = page.toPlain(); JsonElement initialJson = new Gson().fromJson(s, JsonObject.class).get("text"); try { pages.appendTag(processJson(initialJson.getAsString())); } catch (JsonParseException e) { pages.appendTag(new NBTTagString(initialJson.getAsString())); } }); itemStack1 = net.minecraft.item.ItemStack.class.cast(postEventTransaction.getFinal().createStack()); itemStack1.setTagInfo("pages", pages); player.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, itemStack1); } updateInventory(player, itemStack1); ci.cancel(); } private NBTTagString processJson(String json) throws JsonParseException { JsonObject jsonObject = new Gson().fromJson(json.replace("\\", ""), JsonObject.class); return new NBTTagString(jsonObject.get("text").getAsString()); } @Shadow public abstract void sendPacket(Packet<?> packetIn); private void updateInventory(EntityPlayerMP player, net.minecraft.item.ItemStack itemStack) { Slot slot = player.openContainer.getSlotFromInventory(player.inventory, player.inventory.currentItem); sendPacket(new SPacketSetSlot(player.openContainer.windowId, slot.slotNumber, itemStack)); } }
Add some null checks.
musicianlibrary-sponge/src/main/java/io/musician101/musicianlibrary/java/minecraft/sponge/mixin/MixinNetHandlerPlayServer.java
Add some null checks.
<ide><path>usicianlibrary-sponge/src/main/java/io/musician101/musicianlibrary/java/minecraft/sponge/mixin/MixinNetHandlerPlayServer.java <ide> import net.minecraft.entity.player.EntityPlayerMP; <ide> import net.minecraft.inventory.EntityEquipmentSlot; <ide> import net.minecraft.inventory.Slot; <add>import net.minecraft.nbt.NBTTagCompound; <ide> import net.minecraft.nbt.NBTTagList; <ide> import net.minecraft.nbt.NBTTagString; <ide> import net.minecraft.network.NetHandlerPlayServer; <ide> @Inject(method = "processCustomPayload", at = @At(value = "NEW", target = "net/minecraft/item/ItemStack", ordinal = 0), locals = LocalCapture.CAPTURE_FAILEXCEPTION, cancellable = true) <ide> public void onBookSign(CPacketCustomPayload packetIn, CallbackInfo ci, String channelName, PacketBuffer packetBuffer, net.minecraft.item.ItemStack itemStack, net.minecraft.item.ItemStack itemStack1) { <ide> Player spongePlayer = (Player) player; <del> NBTTagList pagesNBT = itemStack.getTagCompound().getTagList("pages", 8); <add> NBTTagCompound tag = itemStack.getTagCompound(); <add> if (tag == null) { <add> tag = new NBTTagCompound(); <add> } <add> <add> NBTTagList pagesNBT = tag.getTagList("pages", 8); <ide> List<Text> pagesText = new ArrayList<>(); <ide> for (int i = 0; i < pagesNBT.tagCount(); i++) { <ide> pagesText.add(Text.of(pagesNBT.getStringTagAt(i))); <ide> <ide> private void updateInventory(EntityPlayerMP player, net.minecraft.item.ItemStack itemStack) { <ide> Slot slot = player.openContainer.getSlotFromInventory(player.inventory, player.inventory.currentItem); <del> sendPacket(new SPacketSetSlot(player.openContainer.windowId, slot.slotNumber, itemStack)); <add> if (slot != null) { <add> sendPacket(new SPacketSetSlot(player.openContainer.windowId, slot.slotNumber, itemStack)); <add> } <ide> } <ide> }
Java
apache-2.0
bd156f32f6aca8e8a76e27f01ab8129827e45e31
0
boundary/boundary-event-sdk,boundary/boundary-event-sdk,boundary/boundary-event-sdk,boundary/boundary-event-sdk,boundary/boundary-event-sdk,boundary/boundary-event-sdk,boundary/boundary-event-sdk
package com.boundary.sdk.event; import java.util.ArrayList; import java.util.LinkedHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Common properties between RawEvent and Event * * @author davidg * */ public class BaseEvent { final static int MAXIMUM_STRING_LENGTH = 255; private static Logger LOG = LoggerFactory.getLogger(BaseEvent.class); /** * Default constructor for BaseEvent */ public BaseEvent() { } /** * Helper method that truncates {@link String} * to the maximum allowed by the Boundary Event API * * @param str * @return String */ public static String truncateToMaximumLength(String str) { int length = Math.min(str.length(),MAXIMUM_STRING_LENGTH); String truncStr = str.substring(0, length); if (length < str.length() ) { LOG.warn("String truncated from {} to {}", str,truncStr); } return truncStr; } /** * Helper method that truncates an {@link ArrayList} of {@link String} * to the maximum allowed by the Boundary Event API * * @param array * @return {@link ArrayList} of {@link String} */ public static ArrayList<String> truncateToMaximumLength(ArrayList<String> array) { ArrayList<String> truncatedArray = new ArrayList<String>(array.size()); for (String s : array) { truncatedArray.add(truncateToMaximumLength(s)); } return truncatedArray; } /** * Helper method that truncates an {@link Object} if it is a {@link String} * to the maximum allowed by the Boundary Event API * @param obj * @return {@link Object} */ public static Object truncateToMaximumLength(Object obj) { String s = ""; Object truncatedObj = obj; if (obj instanceof String) { s = truncateToMaximumLength((String)obj); truncatedObj = s; } return truncatedObj; } /** * Helper method that truncates a {@link LinkedHashMap} with keys of {@link String} * and values of {@link Object} that are instances of {@link String} * to the maximum allowed by the Boundary Event API * * @param prop * @return {@link LinkedHashMap} with key {@link String} and value {@link Object} */ public static LinkedHashMap<String,Object> truncateToMaximumLength(LinkedHashMap<String,Object> prop) { LinkedHashMap<String,Object> truncatedProp = new LinkedHashMap<String,Object>(prop.size()); for (String key : prop.keySet()) { truncatedProp.put(key, truncateToMaximumLength(prop.get(key))); } return truncatedProp; } }
src/main/java/com/boundary/sdk/event/BaseEvent.java
package com.boundary.sdk.event; import java.util.ArrayList; import java.util.LinkedHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Common properties between RawEvent and Event * * @author davidg * */ public class BaseEvent { final static int MAXIMUM_STRING_LENGTH = 255; private static Logger LOG = LoggerFactory.getLogger(BaseEvent.class); /** * Default constructor for BaseEvent */ public BaseEvent() { } /** * Helper method that truncates {@link String} * to the maximum allowed by the Boundary Event API * * @param str * @return String */ public static String truncateToMaximumLength(String str) { int length = Math.min(str.length(),MAXIMUM_STRING_LENGTH); String truncStr = str.substring(0, length); if (length < str.length() ) { LOG.warn("String truncated from {} to {}", str,truncStr); } return truncStr; } /** * Helper method that truncates an {@link ArrayList} of {@link String} * to the maximum allowed by the Boundary Event API * * @param array * @return */ public static ArrayList<String> truncateToMaximumLength(ArrayList<String> array) { ArrayList<String> truncatedArray = new ArrayList<String>(array.size()); for (String s : array) { truncatedArray.add(truncateToMaximumLength(s)); } return truncatedArray; } /** * Helper method that truncates an {@link Object} if it is a {@link String} * to the maximum allowed by the Boundary Event API * @param obj * @return */ public static Object truncateToMaximumLength(Object obj) { String s = ""; Object truncatedObj = obj; if (obj instanceof String) { s = truncateToMaximumLength((String)obj); truncatedObj = s; } return truncatedObj; } /** * Helper method that truncates a {@link LinkedHashMap} with keys of {@link String} * and values of {@link Object} that are instances of {@link String} * to the maximum allowed by the Boundary Event API * * @param prop * @return */ public static LinkedHashMap<String,Object> truncateToMaximumLength(LinkedHashMap<String,Object> prop) { LinkedHashMap<String,Object> truncatedProp = new LinkedHashMap<String,Object>(prop.size()); for (String key : prop.keySet()) { truncatedProp.put(key, truncateToMaximumLength(prop.get(key))); } return truncatedProp; } }
Changes to remove javadoc generation warning
src/main/java/com/boundary/sdk/event/BaseEvent.java
Changes to remove javadoc generation warning
<ide><path>rc/main/java/com/boundary/sdk/event/BaseEvent.java <ide> * to the maximum allowed by the Boundary Event API <ide> * <ide> * @param array <del> * @return <add> * @return {@link ArrayList} of {@link String} <ide> */ <ide> public static ArrayList<String> truncateToMaximumLength(ArrayList<String> array) { <ide> ArrayList<String> truncatedArray = new ArrayList<String>(array.size()); <ide> * Helper method that truncates an {@link Object} if it is a {@link String} <ide> * to the maximum allowed by the Boundary Event API <ide> * @param obj <del> * @return <add> * @return {@link Object} <ide> */ <ide> public static Object truncateToMaximumLength(Object obj) { <ide> String s = ""; <ide> * to the maximum allowed by the Boundary Event API <ide> * <ide> * @param prop <del> * @return <add> * @return {@link LinkedHashMap} with key {@link String} and value {@link Object} <ide> */ <ide> public static LinkedHashMap<String,Object> truncateToMaximumLength(LinkedHashMap<String,Object> prop) { <ide> LinkedHashMap<String,Object> truncatedProp = new LinkedHashMap<String,Object>(prop.size());
JavaScript
bsd-3-clause
befe5d1c88dc15803310f73f36375bca43403511
0
tonioloewald/Bind-O-Matic.js,tonioloewald/Bind-O-Matic.js
/** # Require Copyright ©2016-2017 Tonio Loewald Simple implementation of CommonJS *require*. Usage: const module = require('path/to/module.js'); Relative paths are supported within a file, so, assuming we're inside `path/to/module.js` and `another_module.js` is also in `path/to/`: const another_module = require('./another_module.js'); If you don't want synchronous requires (and, you don't): require.lazy('path/to/module.js').then(module => { // you're good to go! }); And finally, if you need to use some primordial library that wants to be global: require.viaTag('path/to/babylon.min.js').then(() => { const engine = new BABYLON.Engine(canvas, true); ... }); ## Quick and Dirty Async Delivery Naive use of require will result in console spam about how synchronous XHR requests are bad. Rather than using a compile phase to avoid them, you can do this in the console: require.preloadData(); This will produce an array of data (in essence the inferred dependency graph unspooled as "waves" of modules that can be loaded asynchronously) which you can pass to: require.preload([ ... ]).then(() => { // write the code you would have written before, // everything will have loaded asynchronously! }); E.g. if module A requires modules B, and C, and module B requires modules D, and E you might get something like this: [ [C, D, E], // modules with no dependencies [B], // B depends on D and E, already loaded [A] // A relies on B, and C, already loaded ] > ### Room for Improvement > > In the preceding example, module C did not need to load in the first > wave, and could have been loaded in the second wave. > > `preload` loads each "wave" of dependencies as a set of promises and > waits for the entire wave to load before proceeding. A finer-grained > approach would make the tree of promises finer-grained (so a module > with no dependencies that can be loaded early doesn't slow down > modules waiting for other modules) > > Right now, nothing I'm working on has noticeable performance issues > w.r.t. loading to optimizing this further is not a priority. ### That was boring, let's do this all automatically! require.autoPreload().then(() => { // write the code you would have written before, // everything will have loaded asynchronously after the first time! }); The first time this runs you'll see all the sync loading warnings, and then it just goes away. Sometimes a code change will cause the preload data to be automatically updated. Now, this isn't quite as good as working perfectly the first time, which would require doing this on the server. It would be pretty easy to integrate this with your devops workflow if it came to that. require.autoPreload(10000).then(...); // you can change the throttle delay Note that the storing of preloadData is throttled because calculating dependencies could get expensive for sufficiently complex projects. It defaults to 2000ms which should be fine for anything but truly byzantine apps. It takes < 1ms on a reasonably modern device for the b8r demo page, but if I recall correctly calculating the dependencies is O(n^2). ### Compatibility Hack It seems that some implementations of require pass module.exports with a truthy value which the module overwrites. (Why?!?) Anyway, most libraries don't care whether module.exports exists, but those that do tend to malfunction (set up a window global) if they don't see something there. Since it seems that more modules expect module.exports and fail than those that don't see it and fail, require now passes an empty object. But, for those modules that malfunction if module.exports is there, you can suppress it by appending a tilde to your path. In other words: require('path/to/module.js'); // module will be {exports:{}} require('path/to/module.js~'); // the ~ will be stripped; module will be {} This allows more libraries to be loaded unmodified without polluting global namespace and is thus a Good Thing™. Note that the tilde is supported by `require.lazy`, and the name is preserved by `require.preloadData()`. */ /* jshint latedef:false */ /* global console */ (function(global) { 'use strict'; let modules = {}; const dependency_map = {}; const modules_loaded_synchronously = []; const require_utils = {}; const _global_require = global.require; let autoPreload_enabled = 0; // also used to throttle saving of preload data const auto_preload_path = `_require_preloadData_${window.location.pathname}`; function define(module_name, source_code) { const path = module_name.split('/'); path.pop(); /* jshint evil:true */ if (!modules[module_name]) { let module = module_name.substr(-1) === '~' ? {} : {exports:{}}; let factory = new Function( 'module', 'require', `${source_code}\n//# sourceURL=${module_name}`); /* jshint evil:false */ const local_require = _relative(path, module_name); Object.assign(local_require, require_utils); factory(module, local_require); modules[module_name] = module; } return modules[module_name]; } function _relative_path(path, module) { if (module.substr(0, 2) === './') { module = path.join('/') + module.substr(1); } else if (module.substr(0, 3) === '../') { const _path = path.slice(0); while (module.substr(0, 3) === '../') { _path.pop(); module = module.substr(3); } module = _path.length ? _path.join('/') + '/' + module : module; } return module; } function _relative(path, module_name) { let path_string; if (typeof path === 'string') { path_string = path; path = path.split('/'); } else if (Array.isArray(path)) { path_string = path.join('/'); } else { console.error('_relative require needs a path!'); debugger; // jshint ignore:line } const _r = (module) => { module = _relative_path(path, module); // map dependencies if (module_name) { if (!dependency_map[module_name]) { dependency_map[module_name] = []; } if (dependency_map[module_name].indexOf(module) === -1) { dependency_map[module_name].push(module); } } return _require(module); }; _r._path = path_string; Object.assign(_r, require_utils); _r.lazy = module_name => _lazy(_relative_path(path, module_name)); return _r; } function _require(module_name) { if (module_name.substr(0, 2) === './') { module_name = module_name.substr(2); } if (!modules[module_name]) { let request = new XMLHttpRequest(); modules_loaded_synchronously.push(module_name); console.warn(module_name, 'was loaded synchronously'); if (autoPreload_enabled) { _savePreloadData(); } request.open('GET', module_name.substr(-1) === '~' ? module_name.slice(0,-1) : module_name, false); request.send(null); if (request.status === 200) { define(module_name, request.responseText); } else { console.error('could not load required module', module_name); return {}; } } return modules[module_name].exports; } const _lazy_module_promises = {}; function _lazy(module_name) { if (module_name.substr(0, 2) === './') { module_name = module_name.substr(2); } if (!_lazy_module_promises[module_name]) { _lazy_module_promises[module_name] = new Promise(function(resolve, reject) { if (!modules[module_name]) { let request = new XMLHttpRequest(); request.open('GET', module_name.substr(-1) !== '~' ? module_name : module_name.slice(0, -1), true); request.onload = function(data) { if (request.readyState === 4) { if (request.status === 200) { resolve(define(module_name, request.responseText).exports); } else { reject(request, data); } } }; request.onerror = function(data) { reject(request, data); }; request.send(null); } else { setTimeout(() => resolve(modules[module_name].exports)); } }); } return _lazy_module_promises[module_name]; } const scriptTags = {}; const _viaTag = script_path => { if(!scriptTags[script_path]) { scriptTags[script_path] = new Promise((resolve) => { const script = document.createElement('script'); script.setAttribute('src', script_path); script.addEventListener('load', resolve); document.body.appendChild(script); }).catch(() => console.error(`${script_path} failed to load`)); } return scriptTags[script_path]; }; let savePreloadDataTimeout = 0; const _savePreloadData = () => { if (savePreloadDataTimeout) { clearTimeout(savePreloadDataTimeout); } savePreloadDataTimeout = setTimeout(() => { console.time('savePreloadData'); localStorage.setItem(auto_preload_path, _preloadData(false)); console.timeEnd('savePreloadData'); }, autoPreload_enabled); }; const _preloadData = prettify => { let available = []; let module_list = Object.keys(modules); const not_available = module => available.indexOf(module) === -1; // note that this is O(n^2) so if you have many, many modules it could get slow (but it should never be run by user) const no_deps = module => !dependency_map[module] || dependency_map[module].filter(not_available).length === 0; const waves = []; while(module_list.filter(not_available).length) { let wave = module_list.filter(not_available).filter(no_deps); waves.push(wave); if(wave.length === 0) { console.error('dependency deadlock', module_list); break; } available = available.concat(wave); } return JSON.stringify(waves, false, prettify ? 2 : false); }; const _preload = waves => { function preload(waves) { if (waves.length) { const wave = waves.length ? waves.shift() : []; return Promise.all(wave.map(_lazy)). then(() => waves.length ? preload(waves) : null). catch(e => { console.error('preload failed', e); if (localStorage.getItem(auto_preload_path)) { localStorage.removeItem(auto_preload_path); window.location.reload(); } }); } } return preload(waves); }; const _autoPreload = (save_preload_data_throttle_ms) => { autoPreload_enabled = save_preload_data_throttle_ms || 2000; return new Promise(resolve => { const waves = localStorage.getItem(auto_preload_path); if (waves) { console.log('autoPreload data found'); _preload(JSON.parse(waves)).then(resolve); } else { console.warn('no preload data found'); resolve(); } }); }; global.__d = define; Object.assign(require_utils, { report() { console.table(modules_loaded_synchronously); }, data () { return { modules: Object.keys(modules), modules_loaded_synchronously, dependency_map }; }, isDefined (module_name) { return !!modules[module_name]; }, relative: _relative, preloadData: _preloadData, preload: _preload, autoPreload: _autoPreload, viaTag: _viaTag, electron: global.process && global.process.versions.electron, globalRequire: _global_require, modules: () => modules, }); /* Electron exposes "module" global that confuses scripts imported via tag */ if (global.module) { _require._global_module = global.module; delete global.module; } _require.lazy = _lazy; global.require = _require; Object.assign(global.require, require_utils); }(this));
lib/require.js
/** # Require Copyright ©2016-2017 Tonio Loewald Simple implementation of CommonJS *require*. Usage: const module = require('path/to/module.js'); Relative paths are supported within a file, so, assuming we're inside `path/to/module.js` and `another_module.js` is also in `path/to/`: const another_module = require('./another_module.js'); If you don't want synchronous requires (and, you don't): require.lazy('path/to/module.js').then(module => { // you're good to go! }); And finally, if you need to use some primordial library that wants to be global: require.viaTag('path/to/babylon.min.js').then(() => { const engine = new BABYLON.Engine(canvas, true); ... }); ## Quick and Dirty Async Delivery Naive use of require will result in console spam about how synchronous XHR requests are bad. Rather than using a compile phase to avoid them, you can do this in the console: require.preloadData(); This will produce an array of data (in essence the inferred dependency graph unspooled as "waves" of modules that can be loaded asynchronously) which you can pass to: require.preload([ ... ]).then(() => { // write the code you would have written before, // everything will have loaded asynchronously! }); E.g. if module A requires modules B, and C, and module B requires modules D, and E you might get something like this: [ [C, D, E], // modules with no dependencies [B], // B depends on D and E, already loaded [A] // A relies on B, and C, already loaded ] > ### Room for Improvement > > In the preceding example, module C did not need to load in the first > wave, and could have been loaded in the second wave. > > `preload` loads each "wave" of dependencies as a set of promises and > waits for the entire wave to load before proceeding. A finer-grained > approach would make the tree of promises finer-grained (so a module > with no dependencies that can be loaded early doesn't slow down > modules waiting for other modules) > > Right now, nothing I'm working on has noticeable performance issues > w.r.t. loading to optimizing this further is not a priority. ### That was boring, let's do this all automatically! require.autoPreload().then(() => { // write the code you would have written before, // everything will have loaded asynchronously after the first time! }); The first time this runs you'll see all the sync loading warnings, and then it just goes away. Sometimes a code change will cause the preload data to be automatically updated. Now, this isn't quite as good as working perfectly the first time, which would require doing this on the server. It would be pretty easy to integrate this with your devops workflow if it came to that. require.autoPreload(10000).then(...); // you can change the throttle delay Note that the storing of preloadData is throttled because calculating dependencies could get expensive for sufficiently complex projects. It defaults to 2000ms which should be fine for anything but truly byzantine apps. It takes < 1ms on a reasonably modern device for the b8r demo page, but if I recall correctly calculating the dependencies is O(n^2). ### Compatibility Hack It seems that some implementations of require pass module.exports with a truthy value which the module overwrites. (Why?!?) Anyway, most libraries don't care whether module.exports exists, but those that do tend to malfunction (set up a window global) if they don't see something there. Since it seems that more modules expect module.exports and fail than those that don't see it and fail, require now passes an empty object. But, for those modules that malfunction if module.exports is there, you can suppress it by appending a tilde to your path. In other words: require('path/to/module.js'); // module will be {exports:{}} require('path/to/module.js~'); // the ~ will be stripped; module will be {} This allows more libraries to be loaded unmodified without polluting global namespace and is thus a Good Thing™. Note that the tilde is supported by `require.lazy`, and the name is preserved by `require.preloadData()`. */ /* jshint latedef:false */ /* global console */ (function(global) { 'use strict'; let modules = {}; const dependency_map = {}; const modules_loaded_synchronously = []; const require_utils = {}; const _global_require = global.require; let autoPreload_enabled = 0; // also used to throttle saving of preload data function define(module_name, source_code) { const path = module_name.split('/'); path.pop(); /* jshint evil:true */ if (!modules[module_name]) { let module = module_name.substr(-1) === '~' ? {} : {exports:{}}; let factory = new Function( 'module', 'require', `${source_code}\n//# sourceURL=${module_name}`); /* jshint evil:false */ const local_require = _relative(path, module_name); Object.assign(local_require, require_utils); factory(module, local_require); modules[module_name] = module; } return modules[module_name]; } function _relative_path(path, module) { if (module.substr(0, 2) === './') { module = path.join('/') + module.substr(1); } else if (module.substr(0, 3) === '../') { const _path = path.slice(0); while (module.substr(0, 3) === '../') { _path.pop(); module = module.substr(3); } module = _path.length ? _path.join('/') + '/' + module : module; } return module; } function _relative(path, module_name) { let path_string; if (typeof path === 'string') { path_string = path; path = path.split('/'); } else if (Array.isArray(path)) { path_string = path.join('/'); } else { console.error('_relative require needs a path!'); debugger; // jshint ignore:line } const _r = (module) => { module = _relative_path(path, module); // map dependencies if (module_name) { if (!dependency_map[module_name]) { dependency_map[module_name] = []; } if (dependency_map[module_name].indexOf(module) === -1) { dependency_map[module_name].push(module); } } return _require(module); }; _r._path = path_string; Object.assign(_r, require_utils); _r.lazy = module_name => _lazy(_relative_path(path, module_name)); return _r; } function _require(module_name) { if (module_name.substr(0, 2) === './') { module_name = module_name.substr(2); } if (!modules[module_name]) { let request = new XMLHttpRequest(); modules_loaded_synchronously.push(module_name); console.warn(module_name, 'was loaded synchronously'); if (autoPreload_enabled) { _savePreloadData(); } request.open('GET', module_name.substr(-1) === '~' ? module_name.slice(0,-1) : module_name, false); request.send(null); if (request.status === 200) { define(module_name, request.responseText); } else { console.error('could not load required module', module_name); return {}; } } return modules[module_name].exports; } const _lazy_module_promises = {}; function _lazy(module_name) { if (module_name.substr(0, 2) === './') { module_name = module_name.substr(2); } if (!_lazy_module_promises[module_name]) { _lazy_module_promises[module_name] = new Promise(function(resolve, reject) { if (!modules[module_name]) { let request = new XMLHttpRequest(); request.open('GET', module_name.substr(-1) !== '~' ? module_name : module_name.slice(0, -1), true); request.onload = function(data) { if (request.readyState === 4) { if (request.status === 200) { resolve(define(module_name, request.responseText).exports); } else { reject(request, data); } } }; request.onerror = function(data) { reject(request, data); }; request.send(null); } else { setTimeout(() => resolve(modules[module_name].exports)); } }); } return _lazy_module_promises[module_name]; } const scriptTags = {}; const _viaTag = script_path => { if(!scriptTags[script_path]) { scriptTags[script_path] = new Promise((resolve) => { const script = document.createElement('script'); script.setAttribute('src', script_path); script.addEventListener('load', resolve); document.body.appendChild(script); }).catch(() => console.error(`${script_path} failed to load`)); } return scriptTags[script_path]; }; let savePreloadDataTimeout = 0; const _savePreloadData = () => { if (savePreloadDataTimeout) { clearTimeout(savePreloadDataTimeout); } savePreloadDataTimeout = setTimeout(() => { console.time('savePreloadData'); localStorage.setItem(`_require_preloadData_${window.location.pathname}`, _preloadData(false)); console.timeEnd('savePreloadData'); }, autoPreload_enabled); }; const _preloadData = prettify => { let available = []; let module_list = Object.keys(modules); const not_available = module => available.indexOf(module) === -1; // note that this is O(n^2) so if you have many, many modules it could get slow (but it should never be run by user) const no_deps = module => !dependency_map[module] || dependency_map[module].filter(not_available).length === 0; const waves = []; while(module_list.filter(not_available).length) { let wave = module_list.filter(not_available).filter(no_deps); waves.push(wave); if(wave.length === 0) { console.error('dependency deadlock', module_list); break; } available = available.concat(wave); } return JSON.stringify(waves, false, prettify ? 2 : false); }; const _preload = waves => { function preload(waves) { if (waves.length) { const wave = waves.length ? waves.shift() : []; return Promise.all(wave.map(_lazy)) .then(() => waves.length ? preload(waves) : null); } } return preload(waves); }; const _autoPreload = (save_preload_data_throttle_ms) => { autoPreload_enabled = save_preload_data_throttle_ms || 2000; return new Promise(resolve => { const waves = localStorage.getItem(`_require_preloadData_${window.location.pathname}`); if (waves) { console.log('autoPreload data found'); _preload(JSON.parse(waves)).then(resolve); } else { console.warn('no preload data found'); resolve(); } }); }; global.__d = define; Object.assign(require_utils, { report() { console.table(modules_loaded_synchronously); }, data () { return { modules: Object.keys(modules), modules_loaded_synchronously, dependency_map }; }, isDefined (module_name) { return !!modules[module_name]; }, relative: _relative, preloadData: _preloadData, preload: _preload, autoPreload: _autoPreload, viaTag: _viaTag, electron: global.process && global.process.versions.electron, globalRequire: _global_require, modules: () => modules, }); /* Electron exposes "module" global that confuses scripts imported via tag */ if (global.module) { _require._global_module = global.module; delete global.module; } _require.lazy = _lazy; global.require = _require; Object.assign(global.require, require_utils); }(this));
fix — autoPreload should recover from fatal errors
lib/require.js
fix — autoPreload should recover from fatal errors
<ide><path>ib/require.js <ide> const require_utils = {}; <ide> const _global_require = global.require; <ide> let autoPreload_enabled = 0; // also used to throttle saving of preload data <add> const auto_preload_path = `_require_preloadData_${window.location.pathname}`; <ide> <ide> function define(module_name, source_code) { <ide> const path = module_name.split('/'); <ide> } <ide> savePreloadDataTimeout = setTimeout(() => { <ide> console.time('savePreloadData'); <del> localStorage.setItem(`_require_preloadData_${window.location.pathname}`, _preloadData(false)); <add> localStorage.setItem(auto_preload_path, _preloadData(false)); <ide> console.timeEnd('savePreloadData'); <ide> }, autoPreload_enabled); <ide> }; <ide> function preload(waves) { <ide> if (waves.length) { <ide> const wave = waves.length ? waves.shift() : []; <del> return Promise.all(wave.map(_lazy)) <del> .then(() => waves.length ? preload(waves) : null); <add> return Promise.all(wave.map(_lazy)). <add> then(() => waves.length ? preload(waves) : null). <add> catch(e => { <add> console.error('preload failed', e); <add> if (localStorage.getItem(auto_preload_path)) { <add> localStorage.removeItem(auto_preload_path); <add> window.location.reload(); <add> } <add> }); <ide> } <ide> } <ide> return preload(waves); <ide> const _autoPreload = (save_preload_data_throttle_ms) => { <ide> autoPreload_enabled = save_preload_data_throttle_ms || 2000; <ide> return new Promise(resolve => { <del> const waves = localStorage.getItem(`_require_preloadData_${window.location.pathname}`); <add> const waves = localStorage.getItem(auto_preload_path); <ide> if (waves) { <ide> console.log('autoPreload data found'); <ide> _preload(JSON.parse(waves)).then(resolve);
JavaScript
bsd-3-clause
cf982b4b011d8fb8844df0a3e078daf193b33847
0
xaero-26/HKTVMall_JB_Custom_Activity,xaero-26/HKTVMall_JB_Custom_Activity
'use strict'; var https = require( 'https' ); var crypto = require('crypto'); var activityUtils = require('./activityUtils'); /* * POST Handler for / route of Activity (this is the edit route). */ exports.edit = function( req, res ) { // Data from the req and put it in an array accessible to the main app. //console.log( req.body ); activityUtils.logData( req ); res.send( 200, 'Edit' ); }; /* * POST Handler for /save/ route of Activity. * This gets called when the journey is activated in the JB UI (and before /validate/ and /publish/) */ exports.save = function( req, res ) { // Data from the req and put it in an array accessible to the main app. //console.log( req.body ); activityUtils.logData( req ); res.send( 200, 'Save' ); }; /* * POST Handler for /publish/ route of Activity. * Run any code here that you need to run to prepare the activity for execution. * This gets called when the journey is activated in JB (and after /save/ and /validate/) */ exports.publish = function( req, res ) { // Data from the req and put it in an array accessible to the main app. //console.log( req.body ); activityUtils.logData( req ); res.send( 200, 'Publish' ); }; /* * POST Handler for /validate/ route of Activity. * This method should validate the configuration inputs. * This gets called when the journey is activated in the JB UI (and after /save/ but before /publish/) * Respond with 200 for valid, 500 for invalid */ exports.validate = function( req, res ) { // Data from the req and put it in an array accessible to the main app. //console.log( req.body ); activityUtils.logData( req ); res.send( 200, 'Validate' ); /* If validation passes then call res.send( 200, 'Validate' ); If validation fails then call res.send( 500, 'Validate' ); */ }; /* * POST Handler for /execute/ route of Activity. * Runs each time the activity executes. This is the main workhorse of the custom activity * Caller expects a 200 response back. Can return any custom data also. */ exports.execute = function( req, res ) { // Data from the req and put it in an array accessible to the main app. activityUtils.logData( req ); console.log('serena: url=' + activityUtils.endpOintcreds.host); //merge the array of objects for easy access in code. var aArgs = req.body.inArguments; console.log( aArgs ); var oArgs = {}; for (var i=0; i<aArgs.length; i++) { for (var key in aArgs[i]) { oArgs[key] = aArgs[i][key]; } } var contactKey = req.body.keyValue; // these values come from the config.json var EmailAddress = oArgs.EmailAddress; var Name = oArgs.Name; var muid = oArgs.muid; var SubscriberKey = oArgs.SubscriberKey; console.log('Serena: EmailAddress=' + EmailAddress); console.log('Serena: Name=' + Name); console.log('Serena: muid=' + muid); console.log('Serena: SubscriberKey=' + SubscriberKey); // these values come from the custom activity form inputs var pushMessage = oArgs.pushMessage; console.log('Serena: pushMessage=' + pushMessage); // Template Engine for personalisation var SFMCTemplateEngine = function(tpl, data) { var re = /<%([^%>]+)?%>/g, match; while(match = re.exec(tpl)) { tpl = tpl.replace(match[0], data[match[1]]) } return tpl; } var template = pushMessage; //var pushMessageText = SFMCTemplateEngine(template, {Name: Name}); // Prepare post data for remote API var pushInfo = JSON.stringify({ "pushInfo": [{"muid": muid, msg: pushMessage}] }); var endpoint = activityUtils.endpOintcreds.host + '/posts'; var secret = "NLNVFS9x7qmKrWWYLbUAq3TgQH8JjUFW"; var signature = endpoint + pushInfo + secret; var hash_signature = crypto.createHash('md5').update(signature).digest('hex'); console.log('Serena: pushInfo=' + pushInfo); console.log('Serena: signature=' + signature); console.log('Serena: hash_signature=' + hash_signature); var post_data = JSON.stringify({ "pushInfo": pushInfo, "s": hash_signature }); console.log(post_data); var options = { 'hostname': activityUtils.endpOintcreds.host, 'path': '/posts', 'method': 'POST', 'headers': { 'Accept': 'application/json', 'Content-Type': 'application/json, charset=\"utf-16\"', //'Authorization':'Basic '+activityUtils.endpOintcreds.token, 'Content-Length': Buffer.byteLength(post_data) }, }; console.log(options); var httpsCall = https.request(options, function(response) { var data = ''; var error = ''; response.on( 'data' , function( chunk ) { data += chunk; }); response.on( 'end' , function() { console.log("data:",data); if (response.statusCode == 201) { data = JSON.parse(data); console.log('onEND PushResponse:', response.statusCode, data); res.send( 200, {"pushId": data.id} ); } else { console.log('onEND fail:', response.statusCode); res.send(response.statusCode); } }); }); httpsCall.on( 'error', function( e ) { console.error(e); res.send(500, 'createCase', {}, { error: e }); }); httpsCall.write(post_data); httpsCall.end(); };
routes/activityOffer.js
'use strict'; var https = require( 'https' ); var crypto = require('crypto'); var activityUtils = require('./activityUtils'); /* * POST Handler for / route of Activity (this is the edit route). */ exports.edit = function( req, res ) { // Data from the req and put it in an array accessible to the main app. //console.log( req.body ); activityUtils.logData( req ); res.send( 200, 'Edit' ); }; /* * POST Handler for /save/ route of Activity. * This gets called when the journey is activated in the JB UI (and before /validate/ and /publish/) */ exports.save = function( req, res ) { // Data from the req and put it in an array accessible to the main app. //console.log( req.body ); activityUtils.logData( req ); res.send( 200, 'Save' ); }; /* * POST Handler for /publish/ route of Activity. * Run any code here that you need to run to prepare the activity for execution. * This gets called when the journey is activated in JB (and after /save/ and /validate/) */ exports.publish = function( req, res ) { // Data from the req and put it in an array accessible to the main app. //console.log( req.body ); activityUtils.logData( req ); res.send( 200, 'Publish' ); }; /* * POST Handler for /validate/ route of Activity. * This method should validate the configuration inputs. * This gets called when the journey is activated in the JB UI (and after /save/ but before /publish/) * Respond with 200 for valid, 500 for invalid */ exports.validate = function( req, res ) { // Data from the req and put it in an array accessible to the main app. //console.log( req.body ); activityUtils.logData( req ); res.send( 200, 'Validate' ); /* If validation passes then call res.send( 200, 'Validate' ); If validation fails then call res.send( 500, 'Validate' ); */ }; /* * POST Handler for /execute/ route of Activity. * Runs each time the activity executes. This is the main workhorse of the custom activity * Caller expects a 200 response back. Can return any custom data also. */ exports.execute = function( req, res ) { // Data from the req and put it in an array accessible to the main app. activityUtils.logData( req ); console.log('serena: url=' + activityUtils.endpOintcreds.host); //merge the array of objects for easy access in code. /*var aArgs = req.body.inArguments; console.log( aArgs ); var oArgs = {}; for (var i=0; i<aArgs.length; i++) { for (var key in aArgs[i]) { oArgs[key] = aArgs[i][key]; } } var contactKey = req.body.keyValue; // these values come from the config.json var EmailAddress = oArgs.EmailAddress; var Name = oArgs.Name; var muid = oArgs.muid; var SubscriberKey = oArgs.SubscriberKey; activityUtils.logData('Serena: EmailAddress=' + EmailAddress); activityUtils.logData('Serena: Name=' + Name); activityUtils.logData('Serena: muid=' + muid); activityUtils.logData('Serena: SubscriberKey=' + SubscriberKey); // these values come from the custom activity form inputs var pushMessage = oArgs.pushMessage; // Template Engine for personalisation var SFMCTemplateEngine = function(tpl, data) { var re = /<%([^%>]+)?%>/g, match; while(match = re.exec(tpl)) { tpl = tpl.replace(match[0], data[match[1]]) } return tpl; } var template = pushMessage; //var pushMessageText = SFMCTemplateEngine(template, {Name: Name}); // Prepare post data for remote API var pushInfo = JSON.stringify({ "pushInfo": [{"muid": muid, msg: pushMessage}] }); var endpoint = activityUtils.endpOintcreds.host + '/posts'; var secret = "NLNVFS9x7qmKrWWYLbUAq3TgQH8JjUFW"; var signature = endpoint + pushInfo + secret; var hash_signature = crypto.createHash('md5').update(signature).digest('hex'); activityUtils.logData('Serena: pushInfo=' + pushInfo); activityUtils.logData('Serena: signature=' + signature); activityUtils.logData('Serena: hash_signature=' + hash_signature); var post_data = JSON.stringify({ "pushInfo": pushInfo, "s": hash_signature }); console.log(post_data);*/ var options = { 'hostname': activityUtils.endpOintcreds.host, 'path': '/posts', 'method': 'POST', 'headers': { 'Accept': 'application/json', 'Content-Type': 'application/json, charset=\"utf-16\"', //'Authorization':'Basic '+activityUtils.endpOintcreds.token, //'Content-Length': Buffer.byteLength(post_data) }, }; console.log(options); var httpsCall = https.request(options, function(response) { var data = ''; var error = ''; response.on( 'data' , function( chunk ) { data += chunk; }); response.on( 'end' , function() { console.log("data:",data); if (response.statusCode == 201) { data = JSON.parse(data); console.log('onEND PushResponse:', response.statusCode, data); res.send( 200, {"pushId": data.id} ); } else { console.log('onEND fail:', response.statusCode); res.send(response.statusCode); } }); }); httpsCall.on( 'error', function( e ) { console.error(e); res.send(500, 'createCase', {}, { error: e }); }); //httpsCall.write(post_data); httpsCall.end(); };
modify code
routes/activityOffer.js
modify code
<ide><path>outes/activityOffer.js <ide> console.log('serena: url=' + activityUtils.endpOintcreds.host); <ide> <ide> //merge the array of objects for easy access in code. <del> /*var aArgs = req.body.inArguments; <add> var aArgs = req.body.inArguments; <ide> console.log( aArgs ); <ide> var oArgs = {}; <ide> for (var i=0; i<aArgs.length; i++) { <ide> var Name = oArgs.Name; <ide> var muid = oArgs.muid; <ide> var SubscriberKey = oArgs.SubscriberKey; <del> activityUtils.logData('Serena: EmailAddress=' + EmailAddress); <del> activityUtils.logData('Serena: Name=' + Name); <del> activityUtils.logData('Serena: muid=' + muid); <del> activityUtils.logData('Serena: SubscriberKey=' + SubscriberKey); <add> console.log('Serena: EmailAddress=' + EmailAddress); <add> console.log('Serena: Name=' + Name); <add> console.log('Serena: muid=' + muid); <add> console.log('Serena: SubscriberKey=' + SubscriberKey); <ide> <ide> // these values come from the custom activity form inputs <ide> var pushMessage = oArgs.pushMessage; <add> console.log('Serena: pushMessage=' + pushMessage); <ide> <ide> <ide> // Template Engine for personalisation <ide> var secret = "NLNVFS9x7qmKrWWYLbUAq3TgQH8JjUFW"; <ide> var signature = endpoint + pushInfo + secret; <ide> var hash_signature = crypto.createHash('md5').update(signature).digest('hex'); <del> activityUtils.logData('Serena: pushInfo=' + pushInfo); <del> activityUtils.logData('Serena: signature=' + signature); <del> activityUtils.logData('Serena: hash_signature=' + hash_signature); <add> console.log('Serena: pushInfo=' + pushInfo); <add> console.log('Serena: signature=' + signature); <add> console.log('Serena: hash_signature=' + hash_signature); <ide> <ide> var post_data = JSON.stringify({ <ide> "pushInfo": pushInfo, <ide> "s": hash_signature <ide> }); <ide> <del> console.log(post_data);*/ <add> console.log(post_data); <ide> <ide> var options = { <ide> 'hostname': activityUtils.endpOintcreds.host, <ide> 'Accept': 'application/json', <ide> 'Content-Type': 'application/json, charset=\"utf-16\"', <ide> //'Authorization':'Basic '+activityUtils.endpOintcreds.token, <del> //'Content-Length': Buffer.byteLength(post_data) <add> 'Content-Length': Buffer.byteLength(post_data) <ide> }, <ide> }; <ide> <ide> res.send(500, 'createCase', {}, { error: e }); <ide> }); <ide> <del> //httpsCall.write(post_data); <add> httpsCall.write(post_data); <ide> httpsCall.end(); <ide> <ide> };
JavaScript
mit
9ff9dab838b443b32425cf8e56fd027faf942646
0
hechunwen/node-nanomsg,nickdesaulniers/node-nanomsg,kkoopa/node-nanomsg,kkoopa/node-nanomsg,nickdesaulniers/node-nanomsg,nickdesaulniers/node-nanomsg,tempbottle/node-nanomsg,nickdesaulniers/node-nanomsg,hechunwen/node-nanomsg,kkoopa/node-nanomsg,tempbottle/node-nanomsg,hechunwen/node-nanomsg,tempbottle/node-nanomsg,kkoopa/node-nanomsg,tempbottle/node-nanomsg,hechunwen/node-nanomsg
var nn = require('bindings')('node_nanomsg.node'); var util = require('util'); var EventEmitter = require('events').EventEmitter; /** * Socket implementation */ function Socket (domain, type) { // DO NOT attempt to rename to this.domain, unless you like EventEmitter pain! this.af_domain = domain; this.type = type; if((domain != nn.AF_SP) && (domain != nn.AF_SP_RAW)) { throw new Error('unrecognised socket domain'); } switch(type) { case 'req': this.protocol = nn.NN_REQ; this.sender=true; this.receiver=true; break; case 'rep': this.protocol = nn.NN_REP; this.sender = true; this.receiver = true; break; case 'pair': this.protocol = nn.NN_PAIR; this.sender = true; this.receiver = true; break; case 'push': this.protocol = nn.NN_PUSH; this.sender = true; this.receiver = false; break; case 'pull': this.protocol = nn.NN_PULL; this.sender = false; this.receiver = true; break; case 'pub': this.protocol = nn.NN_PUB; this.sender = true; this.receiver = false; break; case 'sub': this.protocol = nn.NN_SUB; this.sender = false; this.receiver = true; break; case 'bus': this.protocol = nn.NN_BUS; this.sender = true; this.receiver = true; break; case 'surveyor': this.protocol = nn.NN_SURVEYOR; this.sender = true; this.receiver = false; break; case 'respondent': this.protocol = nn.NN_RESPONDENT; this.sender = true; this.receiver = true; break; default: throw new Error('unrecognised socket type ' + type); break; } this.binding = nn.Socket(this.af_domain, this.protocol); this.queue = []; if(this.af_domain == nn.AF_SP) { if (this.receiver) this._startPollReceive(); } } util.inherits(Socket, EventEmitter); Socket.prototype._protect = function (ret, unwind) { if(ret < 0) { if (unwind) unwind.call(this); this.emit('error', new Error(nn.Strerr(nn.Errno()))); return null; } return ret; }; /* like _protect, but ret is an array where the first element * is the error code (0=good, <0=bad), and the second element * is the value to return if there was no error. */ Socket.prototype._protectArray = function (ret, unwind) { if(ret[0] < 0) { if (unwind) unwind.call(this); this.emit('error', new Error(nn.Strerr(nn.Errno()))); return null; } return ret[1]; }; Socket.prototype._send = function (buf, flags) { if (this.closed) return; if(this.type == 'surveyor') { this._startPollReceive(); } if (this.transform && typeof this.transform === 'function') buf = this.transform(buf); if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); return this._protect(nn.Send(this.binding, buf, flags), function () { this.queue.unshift([buf, flags]); }); }; Socket.prototype._receive = function () { if (this.closed) return; var msg = nn.Recv(this.binding, 0); if(this.type == 'surveyor') { if(msg < 0 && nn.Errno() == nn.EFSM) { this._stopPollSend(); this._stopPollReceive(); this.emit('survey-timeout'); return; } } if (msg == -1) return; if (this.restore && typeof this.restore === 'function') msg = this.restore(msg); this.emit('message', msg); }; Socket.prototype._startPollSend = function () { if (!this._pollSend) { this._pollSend = nn.PollSendSocket(this.binding, function (events) { if (events) this.flush(); }.bind(this)); } } Socket.prototype._startPollReceive = function () { if (!this._pollReceive) { this._pollReceive = nn.PollReceiveSocket(this.binding, function (events) { if (events) this._receive(); }.bind(this)); } } Socket.prototype._stopPollSend = function () { if (this._pollSend) nn.PollStop(this._pollSend); this._pollSend = null; } Socket.prototype._stopPollReceive = function () { if (this._pollReceive) nn.PollStop(this._pollReceive); this._pollReceive = null; } /** * Socket API */ Socket.prototype.bind = function (addr) { return this._protect(nn.Bind(this.binding, addr)); } Socket.prototype.connect = function (addr) { return this._protect(nn.Connect(this.binding, addr)); } Socket.prototype.flush = function () { while(this.queue.length) { var entry = this.queue.shift(); this._send(entry[0], Number(entry[1]) || 0); } this._stopPollSend(); }; Socket.prototype.close = function () { if(!this.closed) { // Prevent "Bad file descriptor" from recursively firing "error" event this.closed_status = nn.Close(this.binding); this.closed = true; this._stopPollSend(); this._stopPollReceive(); return this.closed_status; } // TODO: AJS: in the event of multiple close, we remember // the return code from the first valid close, and return // it for all subsequent close attempts. This appears to be // in the spirit of the original author's intention, but // perhaps it would be better to return EBADF or some other // error? return this.closed_status; }; Socket.prototype.send = function (buf, flags) { this.queue.push([buf, flags]); this._startPollSend(); return buf.length; }; /* returns an int, a string, or throws EBADF, ENOPROTOOPT, ETERM */ Socket.prototype.getsockopt = function (level, option) { return this._protectArray(nn.Getsockopt(this.binding, level, option)); }; Socket.prototype.setsockopt = function (level, option, value) { return this._protect(nn.Setsockopt(this.binding, level, option, value)); }; Socket.prototype.shutdown = function (how) { return this._protect(nn.Shutdown(this.binding, how)); }; /** * Type-specific API */ Socket.prototype.survey = function (buf, callback) { if (!this.type == 'surveyor') { throw new Error('Only surveyor sockets can survey.'); } var responses = []; function listener (buf) { responses.push(buf); } this.once('survey-timeout', function () { this.removeListener('message', listener); callback(responses); }) this.on('message', listener) this.send(buf); } /** * Device implementation */ function Device (sock1,sock2) { var that = this; this.sock1= sock1; this.sock2 = sock2; this.s1 = -1; this.s2 = -1; if(sock1 instanceof Socket) { this.s1 = sock1.binding; if(sock2 instanceof Socket) { this.s2 = sock2.binding; } this._timer = setImmediate(function () { nn.DeviceWorker(that.s1, that.s2, function (err) { that.emit('error', new Error(nn.Strerr(err))); }); }); } else { throw new Error('expected at least one Socket argument'); } } util.inherits(Device, EventEmitter); /** * module API */ function createSocket (type, opts) { var domain = (opts || {}).raw ? nn.AF_SP_RAW : nn.AF_SP; return new Socket(domain, type); } function symbolInfo (symbol) { return nn.SymbolInfo(symbol); } function symbol (symbol) { return nn.Symbol(symbol); } function term () { return nn.Term(); } function createDevice (sock1, sock2) { return new Device(sock1, sock2); } exports._bindings = nn; exports.Socket = Socket; exports.createSocket = createSocket; exports.symbolInfo = symbolInfo; exports.symbol = symbol; exports.term = term; exports.socket = createSocket; exports.createDevice = createDevice; exports.device = createDevice;
lib/index.js
var nn = require('bindings')('node_nanomsg.node'); var util = require('util'); var EventEmitter = require('events').EventEmitter; /** * Socket implementation */ function Socket (domain, type) { // DO NOT attempt to rename to this.domain, unless you like EventEmitter pain! this.af_domain = domain; this.type = type; if((domain != nn.AF_SP) && (domain != nn.AF_SP_RAW)) { throw new Error('unrecognised socket domain'); } switch(type) { case 'req': this.protocol = nn.NN_REQ; this.sender=true; this.receiver=true; break; case 'rep': this.protocol = nn.NN_REP; this.sender = true; this.receiver = true; break; case 'pair': this.protocol = nn.NN_PAIR; this.sender = true; this.receiver = true; break; case 'push': this.protocol = nn.NN_PUSH; this.sender = true; this.receiver = false; break; case 'pull': this.protocol = nn.NN_PULL; this.sender = false; this.receiver = true; break; case 'pub': this.protocol = nn.NN_PUB; this.sender = true; this.receiver = false; break; case 'sub': this.protocol = nn.NN_SUB; this.sender = false; this.receiver = true; break; case 'bus': this.protocol = nn.NN_BUS; this.sender = true; this.receiver = true; break; case 'surveyor': this.protocol = nn.NN_SURVEYOR; this.sender = true; this.receiver = false; break; case 'respondent': this.protocol = nn.NN_RESPONDENT; this.sender = true; this.receiver = true; break; default: throw new Error('unrecognised socket type ' + type); break; } this.binding = nn.Socket(this.af_domain, this.protocol); this.queue = []; if(this.af_domain == nn.AF_SP) { if (this.receiver) this._startPollReceive(); } } util.inherits(Socket, EventEmitter); Socket.prototype._protect = function (ret, unwind) { if(ret < 0) { if (unwind) unwind.call(this); this.emit('error', new Error(nn.Strerr(nn.Errno()))); return null; } return ret; }; /* like _protect, but ret is an array where the first element * is the error code (0=good, <0=bad), and the second element * is the value to return if there was no error. */ Socket.prototype._protectArray = function (ret, unwind) { if(ret[0] < 0) { if (unwind) unwind.call(this); this.emit('error', new Error(nn.Strerr(nn.Errno()))); return null; } return ret[1]; }; Socket.prototype._send = function (buf, flags) { if (this.closed) { return; } if(this.type == 'surveyor') { this._startPollReceive(); } if (this.transform && typeof this.transform === 'function') buf = this.transform(buf); if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); return this._protect(nn.Send(this.binding, buf, flags), function () { this.queue.unshift([buf, flags]); }); }; Socket.prototype._receive = function () { if (this.closed) { return; } var msg = nn.Recv(this.binding, 0); if(this.type == 'surveyor') { if(msg < 0 && nn.Errno() == nn.EFSM) { this._stopPollSend(); this._stopPollReceive(); this.emit('survey-timeout'); return; } } if (msg == -1) { return; } if (this.restore && typeof this.restore === 'function') msg = this.restore(msg); this.emit('message', msg); }; Socket.prototype._startPollSend = function () { var self = this; if (!this._pollSend) { this._pollSend = nn.PollSendSocket(self.binding, function (events) { if (events) self.flush(); }); } } Socket.prototype._startPollReceive = function () { var self = this; if (!this._pollReceive) { this._pollReceive = nn.PollReceiveSocket(self.binding, function (events) { if (events) self._receive(); }); } } Socket.prototype._stopPollSend = function () { if (this._pollSend) nn.PollStop(this._pollSend); this._pollSend = null; } Socket.prototype._stopPollReceive = function () { if (this._pollReceive) nn.PollStop(this._pollReceive); this._pollReceive = null; } /** * Socket API */ Socket.prototype.bind = function (addr) { return this._protect(nn.Bind(this.binding, addr)); } Socket.prototype.connect = function (addr) { return this._protect(nn.Connect(this.binding, addr)); } Socket.prototype.flush = function () { while(this.queue.length) { var entry = this.queue.shift(); this._send(entry[0], Number(entry[1]) || 0); } this._stopPollSend(); }; Socket.prototype.close = function () { if(!this.closed) { // Prevent "Bad file descriptor" from recursively firing "error" event this.closed_status = nn.Close(this.binding); this.closed = true; this._stopPollSend(); this._stopPollReceive(); return this.closed_status; } // TODO: AJS: in the event of multiple close, we remember // the return code from the first valid close, and return // it for all subsequent close attempts. This appears to be // in the spirit of the original author's intention, but // perhaps it would be better to return EBADF or some other // error? return this.closed_status; }; Socket.prototype.send = function (buf, flags) { this.queue.push([buf, flags]); this._startPollSend(); return buf.length; }; /* returns an int, a string, or throws EBADF, ENOPROTOOPT, ETERM */ Socket.prototype.getsockopt = function (level, option) { return this._protectArray(nn.Getsockopt(this.binding, level, option)); }; Socket.prototype.setsockopt = function (level, option, value) { return this._protect(nn.Setsockopt(this.binding, level, option, value)); }; Socket.prototype.shutdown = function (how) { return this._protect(nn.Shutdown(this.binding, how)); }; /** * Type-specific API */ Socket.prototype.survey = function (buf, callback) { if (!this.type == 'surveyor') { throw new Error('Only surveyor sockets can survey.'); } var responses = []; function listener (buf) { responses.push(buf); } this.once('survey-timeout', function () { this.removeListener('message', listener); callback(responses); }) this.on('message', listener) this.send(buf); } /** * Device implementation */ function Device (sock1,sock2) { var that = this; this.sock1= sock1; this.sock2 = sock2; this.s1 = -1; this.s2 = -1; if(sock1 instanceof Socket) { this.s1 = sock1.binding; if(sock2 instanceof Socket) { this.s2 = sock2.binding; } this._timer = setImmediate(function () { nn.DeviceWorker(that.s1, that.s2, function (err) { that.emit('error', new Error(nn.Strerr(err))); }); }); } else { throw new Error('expected at least one Socket argument'); } } util.inherits(Device, EventEmitter); /** * module API */ function createSocket (type, opts) { var domain = (opts || {}).raw ? nn.AF_SP_RAW : nn.AF_SP; return new Socket(domain, type); } function symbolInfo (symbol) { return nn.SymbolInfo(symbol); } function symbol (symbol) { return nn.Symbol(symbol); } function term () { return nn.Term(); } function createDevice (sock1, sock2) { return new Device(sock1, sock2); } exports._bindings = nn; exports.Socket = Socket; exports.createSocket = createSocket; exports.symbolInfo = symbolInfo; exports.symbol = symbol; exports.term = term; exports.socket = createSocket; exports.createDevice = createDevice; exports.device = createDevice;
Replaces self with bind, adds one-liners.
lib/index.js
Replaces self with bind, adds one-liners.
<ide><path>ib/index.js <ide> }; <ide> <ide> Socket.prototype._send = function (buf, flags) { <del> if (this.closed) { <del> return; <del> } <add> if (this.closed) return; <add> <ide> if(this.type == 'surveyor') { <ide> this._startPollReceive(); <ide> } <ide> }; <ide> <ide> Socket.prototype._receive = function () { <del> if (this.closed) { <del> return; <del> } <add> if (this.closed) return; <ide> <ide> var msg = nn.Recv(this.binding, 0); <ide> <ide> return; <ide> } <ide> } <del> if (msg == -1) { <del> return; <del> } <add> if (msg == -1) return; <add> <ide> if (this.restore && typeof this.restore === 'function') msg = this.restore(msg); <ide> this.emit('message', msg); <ide> }; <ide> <ide> Socket.prototype._startPollSend = function () { <del> var self = this; <ide> if (!this._pollSend) { <del> this._pollSend = nn.PollSendSocket(self.binding, function (events) { <del> if (events) self.flush(); <del> }); <add> this._pollSend = nn.PollSendSocket(this.binding, function (events) { <add> if (events) this.flush(); <add> }.bind(this)); <ide> } <ide> } <ide> <ide> Socket.prototype._startPollReceive = function () { <del> var self = this; <ide> if (!this._pollReceive) { <del> this._pollReceive = nn.PollReceiveSocket(self.binding, function (events) { <del> if (events) self._receive(); <del> }); <add> this._pollReceive = nn.PollReceiveSocket(this.binding, function (events) { <add> if (events) this._receive(); <add> }.bind(this)); <ide> } <ide> } <ide>
Java
apache-2.0
bb277d28771798363542ce7a9bbf42b2535743ac
0
literacyapp-org/literacyapp-appstore
package ai.elimu.appstore.onboarding; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Text; import java.io.IOException; import ai.elimu.appstore.BaseApplication; import ai.elimu.appstore.R; import ai.elimu.appstore.service.LicenseService; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import timber.log.Timber; public class LicenseNumberActivity extends AppCompatActivity { public static final String PREF_LICENSE_EMAIL = "pref_license_email"; public static final String PREF_LICENSE_NUMBER = "pref_license_number"; public static final String PREF_APP_COLLECTION_ID = "pref_app_collection_id"; private LicenseService licenseService; private EditText editTextLicenseEmail; private EditText editTextLicenseNumber; private Button buttonLicenseNumber; @Override protected void onCreate(Bundle savedInstanceState) { Timber.i("onCreate"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_license_number); BaseApplication baseApplication = (BaseApplication) getApplication(); licenseService = baseApplication.getRetrofit().create(LicenseService.class); editTextLicenseEmail = findViewById(R.id.editTextLicenseEmail); editTextLicenseNumber = findViewById(R.id.editTextLicenseNumber); buttonLicenseNumber = findViewById(R.id.buttonLicenseNumber); } @Override protected void onStart() { Timber.i("onStart"); super.onStart(); editTextLicenseEmail.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { Timber.i("editTextLicenseEmail onTextChanged"); updateSubmitButton(); } @Override public void afterTextChanged(Editable editable) { } }); editTextLicenseNumber.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { Timber.i("editTextLicenseNumber onTextChanged"); updateSubmitButton(); } @Override public void afterTextChanged(Editable editable) { } }); buttonLicenseNumber.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Timber.i("onClick"); final String licenseEmail = editTextLicenseEmail.getText().toString(); final String licenseNumber = editTextLicenseNumber.getText().toString(); if (!TextUtils.isEmpty(licenseEmail) && !TextUtils.isEmpty(licenseNumber)) { // Submit License details to REST API for validation Call<ResponseBody> call = licenseService.getLicense(licenseEmail, licenseNumber); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { Timber.i("onResponse"); try { String jsonBody = response.body().string(); JSONObject jsonObject = new JSONObject(jsonBody); if (jsonObject.has("appCollectionId")) { // The License submitted was valid Long appCollectionId = jsonObject.getLong("appCollectionId"); Timber.i("appCollectionId: " + appCollectionId); // Store details in SharedPreferences SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); sharedPreferences.edit().putString(PREF_LICENSE_EMAIL, licenseEmail).commit(); sharedPreferences.edit().putString(PREF_LICENSE_NUMBER, licenseNumber).commit(); sharedPreferences.edit().putLong(PREF_APP_COLLECTION_ID, appCollectionId).commit(); // Redirect user to AppListActivity // TODO } else { // TODO: display error message } } catch (IOException | JSONException e) { Timber.e(e); // TODO: display error message } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Timber.e(t, "onFailure"); // TODO: display error message } }); } } }); } /** * Keep submit button disabled until all required fields have been filled */ private void updateSubmitButton() { Timber.i("updateSubmitButton"); if (TextUtils.isEmpty(editTextLicenseEmail.getText().toString()) || TextUtils.isEmpty(editTextLicenseNumber.getText().toString())) { buttonLicenseNumber.setEnabled(false); } else { buttonLicenseNumber.setEnabled(true); } } }
app/src/main/java/ai/elimu/appstore/onboarding/LicenseNumberActivity.java
package ai.elimu.appstore.onboarding; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Text; import java.io.IOException; import ai.elimu.appstore.BaseApplication; import ai.elimu.appstore.R; import ai.elimu.appstore.service.LicenseService; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import timber.log.Timber; public class LicenseNumberActivity extends AppCompatActivity { public static final String PREF_LICENSE_EMAIL = "pref_license_email"; public static final String PREF_LICENSE_NUMBER = "pref_license_number"; public static final String PREF_APP_COLLECTION_ID = "pref_app_collection_id"; private LicenseService licenseService; private EditText editTextLicenseEmail; private EditText editTextLicenseNumber; private Button buttonLicenseNumber; @Override protected void onCreate(Bundle savedInstanceState) { Timber.i("onCreate"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_license_number); BaseApplication baseApplication = (BaseApplication) getApplication(); licenseService = baseApplication.getRetrofit().create(LicenseService.class); editTextLicenseEmail = findViewById(R.id.editTextLicenseEmail); editTextLicenseNumber = findViewById(R.id.editTextLicenseNumber); buttonLicenseNumber = findViewById(R.id.buttonLicenseNumber); } @Override protected void onStart() { Timber.i("onStart"); super.onStart(); editTextLicenseEmail.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { Timber.i("editTextLicenseEmail onKey"); updateSubmitButton(); return false; } }); editTextLicenseNumber.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { Timber.i("editTextLicenseNumber onKey"); updateSubmitButton(); return false; } }); buttonLicenseNumber.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Timber.i("onClick"); final String licenseEmail = editTextLicenseEmail.getText().toString(); final String licenseNumber = editTextLicenseNumber.getText().toString(); if (!TextUtils.isEmpty(licenseEmail) && !TextUtils.isEmpty(licenseNumber)) { // Submit License details to REST API for validation Call<ResponseBody> call = licenseService.getLicense(licenseEmail, licenseNumber); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { Timber.i("onResponse"); try { String jsonBody = response.body().string(); JSONObject jsonObject = new JSONObject(jsonBody); if (jsonObject.has("appCollectionId")) { // The License submitted was valid Long appCollectionId = jsonObject.getLong("appCollectionId"); Timber.i("appCollectionId: " + appCollectionId); // Store details in SharedPreferences SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); sharedPreferences.edit().putString(PREF_LICENSE_EMAIL, licenseEmail).commit(); sharedPreferences.edit().putString(PREF_LICENSE_NUMBER, licenseNumber).commit(); sharedPreferences.edit().putLong(PREF_APP_COLLECTION_ID, appCollectionId).commit(); // Redirect user to AppListActivity // TODO } else { // TODO: display error message } } catch (IOException | JSONException e) { Timber.e(e); // TODO: display error message } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Timber.e(t, "onFailure"); // TODO: display error message } }); } } }); } /** * Keep submit button disabled until all required fields have been filled */ private void updateSubmitButton() { if (TextUtils.isEmpty(editTextLicenseEmail.getText().toString()) || TextUtils.isEmpty(editTextLicenseNumber.getText().toString())) { buttonLicenseNumber.setEnabled(false); } else { buttonLicenseNumber.setEnabled(true); } } }
#75 Use TextWatcher instead of OnKeyListener
app/src/main/java/ai/elimu/appstore/onboarding/LicenseNumberActivity.java
#75 Use TextWatcher instead of OnKeyListener
<ide><path>pp/src/main/java/ai/elimu/appstore/onboarding/LicenseNumberActivity.java <ide> import android.os.Bundle; <ide> import android.preference.PreferenceManager; <ide> import android.support.v7.app.AppCompatActivity; <add>import android.text.Editable; <ide> import android.text.TextUtils; <add>import android.text.TextWatcher; <ide> import android.util.Log; <ide> import android.view.KeyEvent; <ide> import android.view.View; <ide> Timber.i("onStart"); <ide> super.onStart(); <ide> <del> editTextLicenseEmail.setOnKeyListener(new View.OnKeyListener() { <add> editTextLicenseEmail.addTextChangedListener(new TextWatcher() { <ide> @Override <del> public boolean onKey(View v, int keyCode, KeyEvent event) { <del> Timber.i("editTextLicenseEmail onKey"); <add> public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { <add> <add> } <add> <add> @Override <add> public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { <add> Timber.i("editTextLicenseEmail onTextChanged"); <ide> <ide> updateSubmitButton(); <add> } <ide> <del> return false; <add> @Override <add> public void afterTextChanged(Editable editable) { <add> <ide> } <ide> }); <ide> <del> editTextLicenseNumber.setOnKeyListener(new View.OnKeyListener() { <add> editTextLicenseNumber.addTextChangedListener(new TextWatcher() { <ide> @Override <del> public boolean onKey(View v, int keyCode, KeyEvent event) { <del> Timber.i("editTextLicenseNumber onKey"); <add> public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { <add> <add> } <add> <add> @Override <add> public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { <add> Timber.i("editTextLicenseNumber onTextChanged"); <ide> <ide> updateSubmitButton(); <add> } <ide> <del> return false; <add> @Override <add> public void afterTextChanged(Editable editable) { <add> <ide> } <ide> }); <ide> <ide> * Keep submit button disabled until all required fields have been filled <ide> */ <ide> private void updateSubmitButton() { <add> Timber.i("updateSubmitButton"); <add> <ide> if (TextUtils.isEmpty(editTextLicenseEmail.getText().toString()) <ide> || TextUtils.isEmpty(editTextLicenseNumber.getText().toString())) { <ide> buttonLicenseNumber.setEnabled(false);
Java
bsd-3-clause
1cbfb1a0747f602398d4f326e33f41bab9ef6797
0
jbobnar/TwelveMonkeys,haraldk/TwelveMonkeys,jbobnar/TwelveMonkeys,jbobnar/TwelveMonkeys,haraldk/TwelveMonkeys,jbobnar/TwelveMonkeys,haraldk/TwelveMonkeys
/* * Copyright (c) 2014, Harald Kuhr * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name "TwelveMonkeys" nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.twelvemonkeys.imageio.path; import com.twelvemonkeys.imageio.metadata.CompoundDirectory; import com.twelvemonkeys.imageio.metadata.Directory; import com.twelvemonkeys.imageio.metadata.Entry; import com.twelvemonkeys.imageio.metadata.exif.EXIFReader; import com.twelvemonkeys.imageio.metadata.exif.TIFF; import com.twelvemonkeys.imageio.metadata.jpeg.JPEG; import com.twelvemonkeys.imageio.metadata.jpeg.JPEGSegment; import com.twelvemonkeys.imageio.metadata.jpeg.JPEGSegmentUtil; import com.twelvemonkeys.imageio.metadata.psd.PSD; import com.twelvemonkeys.imageio.metadata.psd.PSDReader; import com.twelvemonkeys.imageio.stream.ByteArrayImageInputStream; import com.twelvemonkeys.imageio.stream.SubImageInputStream; import javax.imageio.ImageIO; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.MemoryCacheImageInputStream; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Path2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static com.twelvemonkeys.lang.Validate.isTrue; import static com.twelvemonkeys.lang.Validate.notNull; /** * Support for various Adobe Photoshop Path related operations: * <ul> * <li>Extract a path from an image input stream, {@link #readPath}</li> * <li>Apply a given path to a given {@code BufferedImage} {@link #applyClippingPath}</li> * <li>Read an image with path applied {@link #readClipped}</li> * </ul> * * @see <a href="http://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577409_17587">Adobe Photoshop Path resource format</a> * @see com.twelvemonkeys.imageio.path.AdobePathBuilder * @author <a href="mailto:[email protected]">Jason Palmer, itemMaster LLC</a> * @author <a href="mailto:[email protected]">Harald Kuhr</a> * @author last modified by $Author: harald.kuhr$ * @version $Id: Paths.java,v 1.0 08/12/14 harald.kuhr Exp$ */ public final class Paths { private Paths() {} /** * Reads the clipping path from the given input stream, if any. * Supports PSD, JPEG and TIFF as container formats for Photoshop resources, * or a "bare" PSD Image Resource Block. * * @param stream the input stream to read from, not {@code null}. * @return the path, or {@code null} if no path is found * @throws IOException if a general I/O exception occurs during reading. * @throws javax.imageio.IIOException if the input contains a bad path data. * @throws java.lang.IllegalArgumentException is {@code stream} is {@code null}. * * @see com.twelvemonkeys.imageio.path.AdobePathBuilder */ public static Path2D readPath(final ImageInputStream stream) throws IOException { notNull(stream, "stream"); int magic = readMagic(stream); if (magic == PSD.RESOURCE_TYPE) { // This is a PSD Image Resource BLock, we can parse directly return buildPathFromPhotoshopResources(stream); } else if (magic == PSD.SIGNATURE_8BPS) { // PSD version // 4 byte magic, 2 byte version, 6 bytes reserved, 2 byte channels, // 4 byte height, 4 byte width, 2 byte bit depth, 2 byte mode stream.skipBytes(26); // 4 byte color mode data length + n byte color mode data long colorModeLen = stream.readUnsignedInt(); stream.skipBytes(colorModeLen); // 4 byte image resources length long imageResourcesLen = stream.readUnsignedInt(); // Image resources return buildPathFromPhotoshopResources(new SubImageInputStream(stream, imageResourcesLen)); } else if (magic >>> 16 == JPEG.SOI && (magic & 0xff00) == 0xff00) { // JPEG version Map<Integer, java.util.List<String>> segmentIdentifiers = new LinkedHashMap<Integer, java.util.List<String>>(); segmentIdentifiers.put(JPEG.APP13, Arrays.asList("Photoshop 3.0")); List<JPEGSegment> photoshop = JPEGSegmentUtil.readSegments(stream, segmentIdentifiers); if (!photoshop.isEmpty()) { return buildPathFromPhotoshopResources(new MemoryCacheImageInputStream(photoshop.get(0).data())); } } else if (magic >>> 16 == TIFF.BYTE_ORDER_MARK_BIG_ENDIAN && (magic & 0xffff) == TIFF.TIFF_MAGIC || magic >>> 16 == TIFF.BYTE_ORDER_MARK_LITTLE_ENDIAN && (magic & 0xffff) == TIFF.TIFF_MAGIC << 8) { // TIFF version CompoundDirectory IFDs = (CompoundDirectory) new EXIFReader().read(stream); Directory directory = IFDs.getDirectory(0); Entry photoshop = directory.getEntryById(TIFF.TAG_PHOTOSHOP); if (photoshop != null) { return buildPathFromPhotoshopResources(new ByteArrayImageInputStream((byte[]) photoshop.getValue())); } } // Unknown file format, or no path found return null; } private static int readMagic(final ImageInputStream stream) throws IOException { stream.mark(); try { return stream.readInt(); } finally { stream.reset(); } } private static Path2D buildPathFromPhotoshopResources(final ImageInputStream stream) throws IOException { Directory resourceBlocks = new PSDReader().read(stream); if (AdobePathBuilder.DEBUG) { System.out.println("resourceBlocks: " + resourceBlocks); } Entry resourceBlock = resourceBlocks.getEntryById(PSD.RES_CLIPPING_PATH); if (resourceBlock != null) { return new AdobePathBuilder((byte[]) resourceBlock.getValue()).path(); } return null; } /** * Applies the clipping path to the given image. * All pixels outside the path will be transparent. * * @param clip the clipping path, not {@code null} * @param image the image to clip, not {@code null} * @return the clipped image. * * @throws java.lang.IllegalArgumentException if {@code clip} or {@code image} is {@code null}. */ public static BufferedImage applyClippingPath(final Shape clip, final BufferedImage image) { return applyClippingPath(clip, notNull(image, "image"), new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB)); } /** * Applies the clipping path to the given image. * Client code may decide the type of the {@code destination} image. * The {@code destination} image is assumed to be fully transparent, * and have same dimensions as {@code image}. * All pixels outside the path will be transparent. * * @param clip the clipping path, not {@code null}. * @param image the image to clip, not {@code null}. * @param destination the destination image, may not be {@code null} or same instance as {@code image}. * @return the clipped image. * * @throws java.lang.IllegalArgumentException if {@code clip}, {@code image} or {@code destination} is {@code null}, * or if {@code destination} is the same instance as {@code image}. */ public static BufferedImage applyClippingPath(final Shape clip, final BufferedImage image, final BufferedImage destination) { notNull(clip, "clip"); notNull(image, "image"); isTrue(destination != null && destination != image, "destination may not be null or same instance as image"); Graphics2D g = destination.createGraphics(); try { AffineTransform originalTransform = g.getTransform(); // Fill the clip shape, with antialias, scaled up to the image's size g.scale(image.getWidth(), image.getHeight()); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.fill(clip); // Draw the image inside the clip shape g.setTransform(originalTransform); g.setComposite(AlphaComposite.SrcIn); g.drawImage(image, 0, 0, null); } finally { g.dispose(); } return destination; } /** * Reads the clipping path from the given input stream, if any, * and applies it to the first image in the stream. * If no path was found, the image is returned without any clipping. * Supports PSD, JPEG and TIFF as container formats for Photoshop resources. * * @param stream the stream to read from, not {@code null} * @return the clipped image * * @throws IOException if a general I/O exception occurs during reading. * @throws javax.imageio.IIOException if the input contains a bad image or path data. * @throws java.lang.IllegalArgumentException is {@code stream} is {@code null}. */ public static BufferedImage readClipped(final ImageInputStream stream) throws IOException { Shape clip = readPath(stream); stream.seek(0); BufferedImage image = ImageIO.read(stream); if (clip == null) { return image; } return applyClippingPath(clip, image); } // Test code public static void main(final String[] args) throws IOException, InterruptedException { BufferedImage destination = readClipped(ImageIO.createImageInputStream(new File(args[0]))); File tempFile = File.createTempFile("clipped-", ".png"); tempFile.deleteOnExit(); ImageIO.write(destination, "PNG", tempFile); Desktop.getDesktop().open(tempFile); Thread.sleep(3000l); if (!tempFile.delete()) { System.err.printf("%s not deleted\n", tempFile); } } }
imageio/imageio-clippath/src/main/java/com/twelvemonkeys/imageio/path/Paths.java
/* * Copyright (c) 2014, Harald Kuhr * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name "TwelveMonkeys" nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.twelvemonkeys.imageio.path; import com.twelvemonkeys.imageio.metadata.CompoundDirectory; import com.twelvemonkeys.imageio.metadata.Directory; import com.twelvemonkeys.imageio.metadata.Entry; import com.twelvemonkeys.imageio.metadata.exif.EXIFReader; import com.twelvemonkeys.imageio.metadata.exif.TIFF; import com.twelvemonkeys.imageio.metadata.jpeg.JPEG; import com.twelvemonkeys.imageio.metadata.jpeg.JPEGSegment; import com.twelvemonkeys.imageio.metadata.jpeg.JPEGSegmentUtil; import com.twelvemonkeys.imageio.metadata.psd.PSD; import com.twelvemonkeys.imageio.metadata.psd.PSDReader; import com.twelvemonkeys.imageio.stream.ByteArrayImageInputStream; import com.twelvemonkeys.imageio.stream.SubImageInputStream; import javax.imageio.ImageIO; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.MemoryCacheImageInputStream; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Path2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static com.twelvemonkeys.lang.Validate.isTrue; import static com.twelvemonkeys.lang.Validate.notNull; /** * Support for various Adobe Photoshop Path related operations: * <ul> * <li>Extract a path from an image input stream, {@link #readPath}</li> * <li>Apply a given path to a given {@code BufferedImage} {@link #applyClippingPath}</li> * <li>Read an image with path applied {@link #readClipped}</li> * </ul> * * @see <a href="http://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577409_17587">Adobe Photoshop Path resource format</a> * @author <a href="mailto:[email protected]">Jason Palmer, itemMaster LLC</a> * @author <a href="mailto:[email protected]">Harald Kuhr</a> * @author last modified by $Author: harald.kuhr$ * @version $Id: Paths.java,v 1.0 08/12/14 harald.kuhr Exp$ */ public final class Paths { private Paths() {} /** * Reads the clipping path from the given input stream, if any. * Supports PSD, JPEG and TIFF as container formats for Photoshop resources, * or a "bare" PSD Image Resource Block. * * @param stream the input stream to read from, not {@code null}. * @return the path, or {@code null} if no path is found * @throws IOException if a general I/O exception occurs during reading. * @throws javax.imageio.IIOException if the input contains a bad path data. * @throws java.lang.IllegalArgumentException is {@code stream} is {@code null}. * * @see com.twelvemonkeys.imageio.path.AdobePathBuilder */ public static Path2D readPath(final ImageInputStream stream) throws IOException { notNull(stream, "stream"); int magic = readMagic(stream); if (magic == PSD.RESOURCE_TYPE) { // This is a PSD Image Resource BLock, we can parse directly return buildPathFromPhotoshopResources(stream); } else if (magic == PSD.SIGNATURE_8BPS) { // PSD version // 4 byte magic, 2 byte version, 6 bytes reserved, 2 byte channels, // 4 byte height, 4 byte width, 2 byte bit depth, 2 byte mode stream.skipBytes(26); // 4 byte color mode data length + n byte color mode data long colorModeLen = stream.readUnsignedInt(); stream.skipBytes(colorModeLen); // 4 byte image resources length long imageResourcesLen = stream.readUnsignedInt(); // Image resources return buildPathFromPhotoshopResources(new SubImageInputStream(stream, imageResourcesLen)); } else if (magic >>> 16 == JPEG.SOI && (magic & 0xff00) == 0xff00) { // JPEG version Map<Integer, java.util.List<String>> segmentIdentifiers = new LinkedHashMap<Integer, java.util.List<String>>(); segmentIdentifiers.put(JPEG.APP13, Arrays.asList("Photoshop 3.0")); List<JPEGSegment> photoshop = JPEGSegmentUtil.readSegments(stream, segmentIdentifiers); if (!photoshop.isEmpty()) { return buildPathFromPhotoshopResources(new MemoryCacheImageInputStream(photoshop.get(0).data())); } } else if (magic >>> 16 == TIFF.BYTE_ORDER_MARK_BIG_ENDIAN && (magic & 0xffff) == TIFF.TIFF_MAGIC || magic >>> 16 == TIFF.BYTE_ORDER_MARK_LITTLE_ENDIAN && (magic & 0xffff) == TIFF.TIFF_MAGIC << 8) { // TIFF version CompoundDirectory IFDs = (CompoundDirectory) new EXIFReader().read(stream); Directory directory = IFDs.getDirectory(0); Entry photoshop = directory.getEntryById(TIFF.TAG_PHOTOSHOP); if (photoshop != null) { return buildPathFromPhotoshopResources(new ByteArrayImageInputStream((byte[]) photoshop.getValue())); } } // Unknown file format, or no path found return null; } private static int readMagic(final ImageInputStream stream) throws IOException { stream.mark(); try { return stream.readInt(); } finally { stream.reset(); } } private static Path2D buildPathFromPhotoshopResources(final ImageInputStream stream) throws IOException { Directory resourceBlocks = new PSDReader().read(stream); if (AdobePathBuilder.DEBUG) { System.out.println("resourceBlocks: " + resourceBlocks); } Entry resourceBlock = resourceBlocks.getEntryById(PSD.RES_CLIPPING_PATH); if (resourceBlock != null) { return new AdobePathBuilder((byte[]) resourceBlock.getValue()).path(); } return null; } /** * Applies the clipping path to the given image. * All pixels outside the path will be transparent. * * @param clip the clipping path, not {@code null} * @param image the image to clip, not {@code null} * @return the clipped image. * * @throws java.lang.IllegalArgumentException if {@code clip} or {@code image} is {@code null}. */ public static BufferedImage applyClippingPath(final Shape clip, final BufferedImage image) { return applyClippingPath(clip, notNull(image, "image"), new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB)); } /** * Applies the clipping path to the given image. * Client code may decide the type of the {@code destination} image. * The {@code destination} image is assumed to be fully transparent, * and have same dimensions as {@code image}. * All pixels outside the path will be transparent. * * @param clip the clipping path, not {@code null}. * @param image the image to clip, not {@code null}. * @param destination the destination image, may not be {@code null} or same instance as {@code image}. * @return the clipped image. * * @throws java.lang.IllegalArgumentException if {@code clip}, {@code image} or {@code destination} is {@code null}, * or if {@code destination} is the same instance as {@code image}. */ public static BufferedImage applyClippingPath(final Shape clip, final BufferedImage image, final BufferedImage destination) { notNull(clip, "clip"); notNull(image, "image"); isTrue(destination != null && destination != image, "destination may not be null or same instance as image"); Graphics2D g = destination.createGraphics(); try { AffineTransform originalTransform = g.getTransform(); // Fill the clip shape, with antialias, scaled up to the image's size g.scale(image.getWidth(), image.getHeight()); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.fill(clip); // Draw the image inside the clip shape g.setTransform(originalTransform); g.setComposite(AlphaComposite.SrcIn); g.drawImage(image, 0, 0, null); } finally { g.dispose(); } return destination; } /** * Reads the clipping path from the given input stream, if any, * and applies it to the first image in the stream. * If no path was found, the image is returned without any clipping. * Supports PSD, JPEG and TIFF as container formats for Photoshop resources. * * @param stream the stream to read from, not {@code null} * @return the clipped image * * @throws IOException if a general I/O exception occurs during reading. * @throws javax.imageio.IIOException if the input contains a bad image or path data. * @throws java.lang.IllegalArgumentException is {@code stream} is {@code null}. */ public static BufferedImage readClipped(final ImageInputStream stream) throws IOException { Shape clip = readPath(stream); stream.seek(0); BufferedImage image = ImageIO.read(stream); if (clip == null) { return image; } return applyClippingPath(clip, image); } // Test code public static void main(final String[] args) throws IOException, InterruptedException { BufferedImage destination = readClipped(ImageIO.createImageInputStream(new File(args[0]))); File tempFile = File.createTempFile("clipped-", ".png"); tempFile.deleteOnExit(); ImageIO.write(destination, "PNG", tempFile); Desktop.getDesktop().open(tempFile); Thread.sleep(3000l); if (!tempFile.delete()) { System.err.printf("%s not deleted\n", tempFile); } } }
Paths documentation.
imageio/imageio-clippath/src/main/java/com/twelvemonkeys/imageio/path/Paths.java
Paths documentation.
<ide><path>mageio/imageio-clippath/src/main/java/com/twelvemonkeys/imageio/path/Paths.java <ide> * </ul> <ide> * <ide> * @see <a href="http://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577409_17587">Adobe Photoshop Path resource format</a> <add> * @see com.twelvemonkeys.imageio.path.AdobePathBuilder <ide> * @author <a href="mailto:[email protected]">Jason Palmer, itemMaster LLC</a> <ide> * @author <a href="mailto:[email protected]">Harald Kuhr</a> <ide> * @author last modified by $Author: harald.kuhr$
Java
apache-2.0
4b3f44a5d05a9b583881554afc4818b12919b88e
0
SpineEventEngine/base,SpineEventEngine/base,SpineEventEngine/base
/* * Copyright 2018, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.tools.compiler.field.type; import com.squareup.javapoet.TypeName; /** * The type information of a field for a code-generation. */ public interface FieldType { /** * Obtains the {@link TypeName} for the field. * * @return the type name */ TypeName getTypeName(); /** * Obtains the setter prefix for the field. * * @return the setter prefix */ String getSetterPrefix(); }
tools/model-compiler/src/main/java/io/spine/tools/compiler/field/type/FieldType.java
/* * Copyright 2018, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.tools.compiler.field.type; import com.squareup.javapoet.TypeName; /** * Interface for obtaining type specific information. * * @author Dmytro Grankin */ public interface FieldType { /** * Returns the {@link TypeName} for specific {@link FieldType}. * * @return the type name */ TypeName getTypeName(); /** * Returns the setter prefix for specific {@link FieldType}. * * @return the setter prefix */ String getSetterPrefix(); }
Update `FieldType` Javadocs
tools/model-compiler/src/main/java/io/spine/tools/compiler/field/type/FieldType.java
Update `FieldType` Javadocs
<ide><path>ools/model-compiler/src/main/java/io/spine/tools/compiler/field/type/FieldType.java <ide> import com.squareup.javapoet.TypeName; <ide> <ide> /** <del> * Interface for obtaining type specific information. <del> * <del> * @author Dmytro Grankin <add> * The type information of a field for a code-generation. <ide> */ <ide> public interface FieldType { <ide> <ide> /** <del> * Returns the {@link TypeName} for specific {@link FieldType}. <add> * Obtains the {@link TypeName} for the field. <ide> * <ide> * @return the type name <ide> */ <ide> TypeName getTypeName(); <ide> <ide> /** <del> * Returns the setter prefix for specific {@link FieldType}. <add> * Obtains the setter prefix for the field. <ide> * <ide> * @return the setter prefix <ide> */
Java
mit
32c68b45f2010ee8fc58c48697e2a0a281832140
0
elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin
package com.elmakers.mine.bukkit.wand; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.block.BlockFace; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerExpChangeEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.Vector; import com.elmakers.mine.bukkit.api.effect.ParticleType; import com.elmakers.mine.bukkit.api.spell.CastingCost; import com.elmakers.mine.bukkit.api.spell.CostReducer; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.api.spell.SpellTemplate; import com.elmakers.mine.bukkit.block.MaterialAndData; import com.elmakers.mine.bukkit.block.MaterialBrush; import com.elmakers.mine.bukkit.effect.builtin.EffectRing; import com.elmakers.mine.bukkit.magic.Mage; import com.elmakers.mine.bukkit.magic.MagicController; import com.elmakers.mine.bukkit.spell.BrushSpell; import com.elmakers.mine.bukkit.spell.UndoableSpell; import com.elmakers.mine.bukkit.utility.ColorHD; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; import com.elmakers.mine.bukkit.utility.InventoryUtils; import com.elmakers.mine.bukkit.utility.Messages; public class Wand implements CostReducer, com.elmakers.mine.bukkit.api.wand.Wand { public final static int INVENTORY_SIZE = 27; public final static int HOTBAR_SIZE = 9; public final static float DEFAULT_SPELL_COLOR_MIX_WEIGHT = 0.0001f; public final static float DEFAULT_WAND_COLOR_MIX_WEIGHT = 1.0f; // REMEMBER! Each of these MUST have a corresponding class in .traders, else traders will // destroy the corresponding data. public final static String[] PROPERTY_KEYS = { "active_spell", "active_material", "xp", "xp_regeneration", "xp_max", "bound", "uses", "upgrade", "indestructible", "cost_reduction", "cooldown_reduction", "effect_bubbles", "effect_color", "effect_particle", "effect_particle_count", "effect_particle_data", "effect_particle_interval", "effect_sound", "effect_sound_interval", "effect_sound_pitch", "effect_sound_volume", "haste", "health_regeneration", "hunger_regeneration", "icon", "mode", "keep", "locked", "quiet", "power", "protection", "protection_physical", "protection_projectiles", "protection_falling", "protection_fire", "protection_explosions", "materials", "spells" }; public final static String[] HIDDEN_PROPERTY_KEYS = { "id", "owner", "name", "description", "template", "organize", "fill" }; public final static String[] ALL_PROPERTY_KEYS = (String[])ArrayUtils.addAll(PROPERTY_KEYS, HIDDEN_PROPERTY_KEYS); protected ItemStack item; protected MagicController controller; protected Mage mage; // Cached state private String id = ""; private Inventory hotbar; private List<Inventory> inventories; private String activeSpell = ""; private String activeMaterial = ""; protected String wandName = ""; protected String description = ""; private String owner = ""; private String template = ""; private boolean bound = false; private boolean indestructible = false; private boolean keep = false; private boolean autoOrganize = false; private boolean autoFill = false; private boolean isUpgrade = false; private MaterialAndData icon = null; private float costReduction = 0; private float cooldownReduction = 0; private float damageReduction = 0; private float damageReductionPhysical = 0; private float damageReductionProjectiles = 0; private float damageReductionFalling = 0; private float damageReductionFire = 0; private float damageReductionExplosions = 0; private float power = 0; private boolean hasInventory = false; private boolean locked = false; private int uses = 0; private int xp = 0; private int xpRegeneration = 0; private int xpMax = 0; private float healthRegeneration = 0; private PotionEffect healthRegenEffect = null; private float hungerRegeneration = 0; private PotionEffect hungerRegenEffect = null; private ColorHD effectColor = null; private float effectColorSpellMixWeight = DEFAULT_SPELL_COLOR_MIX_WEIGHT; private float effectColorMixWeight = DEFAULT_WAND_COLOR_MIX_WEIGHT; private ParticleType effectParticle = null; private float effectParticleData = 0; private int effectParticleCount = 0; private int effectParticleInterval = 0; private int effectParticleCounter = 0; private boolean effectBubbles = false; private EffectRing effectPlayer = null; private Sound effectSound = null; private int effectSoundInterval = 0; private int effectSoundCounter = 0; private float effectSoundVolume = 0; private float effectSoundPitch = 0; private float speedIncrease = 0; private PotionEffect hasteEffect = null; private int storedXpLevel = 0; private int storedXp = 0; private float storedXpProgress = 0; private int quietLevel = 0; // Inventory functionality private WandMode mode = null; private int openInventoryPage = 0; private boolean inventoryIsOpen = false; private Inventory displayInventory = null; // Kinda of a hacky initialization optimization :\ private boolean suspendSave = false; // Wand configurations protected static Map<String, ConfigurationSection> wandTemplates = new HashMap<String, ConfigurationSection>(); public static boolean displayManaAsBar = true; public static boolean retainLevelDisplay = true; public static Material DefaultUpgradeMaterial = Material.NETHER_STAR; public static Material DefaultWandMaterial = Material.BLAZE_ROD; public static Material EnchantableWandMaterial = null; public static boolean EnableGlow = true; public Wand(MagicController controller, ItemStack itemStack) { this.controller = controller; hotbar = InventoryUtils.createInventory(null, 9, "Wand"); this.icon = new MaterialAndData(itemStack.getType(), (byte)itemStack.getDurability()); inventories = new ArrayList<Inventory>(); item = itemStack; indestructible = controller.getIndestructibleWands(); loadState(); } public Wand(MagicController controller) { this(controller, DefaultWandMaterial, (short)0); } protected Wand(MagicController controller, String templateName) throws IllegalArgumentException { this(controller); suspendSave = true; String wandName = Messages.get("wand.default_name"); String wandDescription = ""; // Check for default wand if ((templateName == null || templateName.length() == 0) && wandTemplates.containsKey("default")) { templateName = "default"; } // See if there is a template with this key if (templateName != null && templateName.length() > 0) { if ((templateName.equals("random") || templateName.startsWith("random(")) && wandTemplates.containsKey("random")) { int level = 1; if (!templateName.equals("random")) { String randomLevel = templateName.substring(templateName.indexOf('(') + 1, templateName.length() - 1); level = Integer.parseInt(randomLevel); } ConfigurationSection randomTemplate = wandTemplates.get("random"); randomize(level, false); // Random wands take a few properties from the "random" template locked = (boolean)randomTemplate.getBoolean("locked", false); setEffectColor(randomTemplate.getString("effect_color")); suspendSave = false; saveState(); return; } if (!wandTemplates.containsKey(templateName)) { throw new IllegalArgumentException("No template named " + templateName); } ConfigurationSection wandConfig = wandTemplates.get(templateName); // Default to localized names wandName = Messages.get("wands." + templateName + ".name", wandName); wandDescription = Messages.get("wands." + templateName + ".description", wandDescription); // Load all properties loadProperties(wandConfig); } setDescription(wandDescription); setName(wandName); setTemplate(templateName); suspendSave = false; generateId(); saveState(); } public Wand(MagicController controller, Material icon, short iconData) { // This will make the Bukkit ItemStack into a real ItemStack with NBT data. this(controller, InventoryUtils.getCopy(new ItemStack(icon, 1, iconData))); wandName = Messages.get("wand.default_name"); updateName(); if (EnableGlow) { InventoryUtils.addGlow(item); } generateId(); saveState(); } protected void generateId() { id = UUID.randomUUID().toString(); } public void unenchant() { item = new ItemStack(item.getType(), 1, (short)item.getDurability()); } public void setIcon(Material material, byte data) { setIcon(material == null ? null : new MaterialAndData(material, data)); } public void setIcon(MaterialAndData materialData) { icon = materialData; if (icon != null) { item.setType(icon.getMaterial()); item.setDurability(icon.getData()); } } public void makeUpgrade() { isUpgrade = true; wandName = Messages.get("wand.upgrade_name"); description = Messages.get("wand.upgrade_default_description"); setIcon(DefaultUpgradeMaterial, (byte)0); saveState(); updateName(true); updateLore(); } protected void activateBrush(String materialKey) { setActiveBrush(materialKey); if (materialKey != null) { com.elmakers.mine.bukkit.api.block.MaterialBrush brush = mage.getBrush(); if (brush != null) { brush.activate(mage.getLocation(), materialKey); } } } public void activateBrush(ItemStack itemStack) { if (!isBrush(itemStack)) return; activateBrush(getBrush(itemStack)); } public int getXpRegeneration() { return xpRegeneration; } public int getXpMax() { return xpMax; } public int getExperience() { return xp; } public void removeExperience(int amount) { xp = Math.max(0, xp - amount); updateMana(); } public float getHealthRegeneration() { return healthRegeneration; } public float getHungerRegeneration() { return hungerRegeneration; } public boolean isModifiable() { return !locked; } public boolean isIndestructible() { return indestructible; } public boolean isUpgrade() { return isUpgrade; } public boolean usesMana() { return xpMax > 0 && xpRegeneration > 0 && !isCostFree(); } public float getCooldownReduction() { return controller.getCooldownReduction() + cooldownReduction * WandLevel.maxCooldownReduction; } public float getCostReduction() { if (isCostFree()) return 1.0f; return controller.getCostReduction() + costReduction * WandLevel.maxCostReduction; } public void setCooldownReduction(float reduction) { cooldownReduction = reduction; } public boolean getHasInventory() { return hasInventory; } public float getPower() { return power; } public boolean isSuperProtected() { return damageReduction > 1; } public boolean isSuperPowered() { return power > 1; } public boolean isCostFree() { return costReduction > 1; } public boolean isCooldownFree() { return cooldownReduction > 1; } public float getDamageReduction() { return damageReduction * WandLevel.maxDamageReduction; } public float getDamageReductionPhysical() { return damageReductionPhysical * WandLevel.maxDamageReductionPhysical; } public float getDamageReductionProjectiles() { return damageReductionProjectiles * WandLevel.maxDamageReductionProjectiles; } public float getDamageReductionFalling() { return damageReductionFalling * WandLevel.maxDamageReductionFalling; } public float getDamageReductionFire() { return damageReductionFire * WandLevel.maxDamageReductionFire; } public float getDamageReductionExplosions() { return damageReductionExplosions * WandLevel.maxDamageReductionExplosions; } public int getUses() { return uses; } public String getName() { return wandName; } public String getDescription() { return description; } public String getOwner() { return owner; } public void setName(String name) { wandName = ChatColor.stripColor(name); updateName(); } public void setTemplate(String templateName) { this.template = templateName; } public String getTemplate() { return this.template; } public void setDescription(String description) { this.description = description; updateLore(); } public void tryToOwn(Player player) { if (owner == null || owner.length() == 0) { takeOwnership(player); } } protected void takeOwnership(Player player) { owner = player.getName(); if (controller != null && controller.bindWands()) { bound = true; } if (controller != null && controller.keepWands()) { keep = true; } updateLore(); } public ItemStack getItem() { return item; } protected List<Inventory> getAllInventories() { List<Inventory> allInventories = new ArrayList<Inventory>(inventories.size() + 1); allInventories.add(hotbar); allInventories.addAll(inventories); return allInventories; } public Set<String> getSpells() { return getSpells(false); } protected Set<String> getSpells(boolean includePositions) { Set<String> spellNames = new TreeSet<String>(); List<Inventory> allInventories = getAllInventories(); int index = 0; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int i = 0; i < items.length; i++) { if (items[i] != null && !isWand(items[i])) { if (isSpell(items[i])) { String spellName = getSpell(items[i]); if (includePositions) { spellName += "@" + index; } spellNames.add(spellName); } } index++; } } return spellNames; } protected String getSpellString() { return StringUtils.join(getSpells(true), ","); } public Set<String> getBrushes() { return getMaterialKeys(false); } protected Set<String> getMaterialKeys(boolean includePositions) { Set<String> materialNames = new TreeSet<String>(); List<Inventory> allInventories = new ArrayList<Inventory>(inventories.size() + 1); allInventories.add(hotbar); allInventories.addAll(inventories); Integer index = 0; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int i = 0; i < items.length; i++) { String materialKey = getMaterialKey(items[i], includePositions ? index : null); if (materialKey != null) { materialNames.add(materialKey); } index++; } } return materialNames; } protected String getMaterialString() { return StringUtils.join(getMaterialKeys(true), ","); } protected Integer parseSlot(String[] pieces) { Integer slot = null; if (pieces.length > 0) { try { slot = Integer.parseInt(pieces[1]); } catch (Exception ex) { slot = null; } if (slot != null && slot < 0) { slot = null; } } return slot; } protected void addToInventory(ItemStack itemStack) { // Set the wand item WandMode wandMode = getMode(); Integer selectedItem = null; if (wandMode == WandMode.INVENTORY) { if (mage != null && mage.getPlayer() != null) { selectedItem = mage.getPlayer().getInventory().getHeldItemSlot(); hotbar.setItem(selectedItem, item); } } List<Inventory> checkInventories = wandMode == WandMode.INVENTORY ? getAllInventories() : inventories; boolean added = false; for (Inventory inventory : checkInventories) { HashMap<Integer, ItemStack> returned = inventory.addItem(itemStack); if (returned.size() == 0) { added = true; break; } } if (!added) { Inventory newInventory = InventoryUtils.createInventory(null, INVENTORY_SIZE, "Wand"); newInventory.addItem(itemStack); inventories.add(newInventory); } // Restore empty wand slot if (selectedItem != null) { hotbar.setItem(selectedItem, null); } } protected Inventory getDisplayInventory() { if (displayInventory == null) { displayInventory = InventoryUtils.createInventory(null, INVENTORY_SIZE + HOTBAR_SIZE, "Wand"); } return displayInventory; } protected Inventory getInventoryByIndex(int inventoryIndex) { while (inventoryIndex >= inventories.size()) { inventories.add(InventoryUtils.createInventory(null, INVENTORY_SIZE, "Wand")); } return inventories.get(inventoryIndex); } protected Inventory getInventory(Integer slot) { Inventory inventory = hotbar; if (slot >= HOTBAR_SIZE) { int inventoryIndex = (slot - HOTBAR_SIZE) / INVENTORY_SIZE; inventory = getInventoryByIndex(inventoryIndex); } return inventory; } protected int getInventorySlot(Integer slot) { if (slot < HOTBAR_SIZE) { return slot; } return ((slot - HOTBAR_SIZE) % INVENTORY_SIZE); } protected void addToInventory(ItemStack itemStack, Integer slot) { if (slot == null) { addToInventory(itemStack); return; } Inventory inventory = getInventory(slot); slot = getInventorySlot(slot); ItemStack existing = inventory.getItem(slot); inventory.setItem(slot, itemStack); if (existing != null && existing.getType() != Material.AIR) { addToInventory(existing); } } protected void parseInventoryStrings(String spellString, String materialString) { hotbar.clear(); inventories.clear(); // Support YML-List-As-String format and |-delimited format spellString = spellString.replaceAll("[\\]\\[]", ""); String[] spellNames = StringUtils.split(spellString, "|,"); for (String spellName : spellNames) { String[] pieces = spellName.split("@"); Integer slot = parseSlot(pieces); String spellKey = pieces[0].trim(); ItemStack itemStack = createSpellIcon(spellKey); if (itemStack == null) { controller.getPlugin().getLogger().warning("Unable to create spell icon for key " + spellKey); continue; } if (activeSpell == null || activeSpell.length() == 0) activeSpell = spellKey; addToInventory(itemStack, slot); } materialString = materialString.replaceAll("[\\]\\[]", ""); String[] materialNames = StringUtils.split(materialString, "|,"); for (String materialName : materialNames) { String[] pieces = materialName.split("@"); Integer slot = parseSlot(pieces); String materialKey = pieces[0].trim(); ItemStack itemStack = createBrushIcon(materialKey); if (itemStack == null) { controller.getPlugin().getLogger().warning("Unable to create material icon for key " + materialKey); continue; } if (activeMaterial == null || activeMaterial.length() == 0) activeMaterial = materialKey; addToInventory(itemStack, slot); } hasInventory = spellNames.length + materialNames.length > 1; } @SuppressWarnings("deprecation") public static ItemStack createSpellItem(String spellKey, MagicController controller, Wand wand, boolean isItem) { SpellTemplate spell = controller.getSpellTemplate(spellKey); if (spell == null) return null; com.elmakers.mine.bukkit.api.block.MaterialAndData icon = spell.getIcon(); if (icon == null) { controller.getPlugin().getLogger().warning("Unable to create spell icon for " + spell.getName() + ", missing material"); return null; } ItemStack itemStack = null; ItemStack originalItemStack = null; try { originalItemStack = new ItemStack(icon.getMaterial(), 1, (short)0, (byte)icon.getData()); itemStack = InventoryUtils.getCopy(originalItemStack); } catch (Exception ex) { itemStack = null; } if (itemStack == null) { controller.getPlugin().getLogger().warning("Unable to create spell icon for " + spellKey + " with material " + icon.getMaterial().name()); return originalItemStack; } updateSpellItem(itemStack, spell, wand, wand == null ? null : wand.activeMaterial, isItem); return itemStack; } protected ItemStack createSpellIcon(String spellKey) { return createSpellItem(spellKey, controller, this, false); } private String getActiveWandName(String materialKey) { SpellTemplate spell = controller.getSpellTemplate(activeSpell); return getActiveWandName(spell, materialKey); } protected ItemStack createBrushIcon(String materialKey) { return createBrushItem(materialKey, controller, this, false); } @SuppressWarnings("deprecation") public static ItemStack createBrushItem(String materialKey, MagicController controller, Wand wand, boolean isItem) { MaterialAndData brushData = MaterialBrush.parseMaterialKey(materialKey, false); if (brushData == null) return null; Material material = brushData.getMaterial(); if (material == null || material == Material.AIR) { return null; } byte dataId = brushData.getData(); ItemStack originalItemStack = new ItemStack(material, 1, (short)0, (byte)dataId); ItemStack itemStack = InventoryUtils.getCopy(originalItemStack); if (itemStack == null) { controller.getPlugin().getLogger().warning("Unable to create material icon for " + material.name() + ": " + materialKey); return null; } ItemMeta meta = itemStack.getItemMeta(); List<String> lore = new ArrayList<String>(); if (material != null) { lore.add(ChatColor.GRAY + Messages.get("wand.building_material_info").replace("$material", MaterialBrush.getMaterialName(materialKey))); if (material == MaterialBrush.EraseMaterial) { lore.add(Messages.get("wand.erase_material_description")); } else if (material == MaterialBrush.CopyMaterial) { lore.add(Messages.get("wand.copy_material_description")); } else if (material == MaterialBrush.CloneMaterial) { lore.add(Messages.get("wand.clone_material_description")); } else if (material == MaterialBrush.ReplicateMaterial) { lore.add(Messages.get("wand.replicate_material_description")); } else if (material == MaterialBrush.MapMaterial) { lore.add(Messages.get("wand.map_material_description")); } else if (material == MaterialBrush.SchematicMaterial) { lore.add(Messages.get("wand.schematic_material_description").replace("$schematic", brushData.getCustomName())); } else { lore.add(ChatColor.LIGHT_PURPLE + Messages.get("wand.building_material_description")); } } if (isItem) { lore.add(ChatColor.YELLOW + Messages.get("wand.brush_item_description")); } meta.setLore(lore); itemStack.setItemMeta(meta); updateBrushItem(itemStack, materialKey, wand); return itemStack; } protected void saveState() { if (suspendSave || item == null) return; if (id == null || id.length() == 0) { generateId(); } Object wandNode = InventoryUtils.createNode(item, "wand"); if (wandNode == null) { controller.getLogger().warning("Failed to save wand state for wand id " + id + " to : " + item + " of class " + item.getClass()); return; } ConfigurationSection stateNode = new MemoryConfiguration(); saveProperties(stateNode); InventoryUtils.saveTagsToNBT(stateNode, wandNode, ALL_PROPERTY_KEYS); } protected void loadState() { if (item == null) return; Object wandNode = InventoryUtils.getNode(item, "wand"); if (wandNode == null) { return; } ConfigurationSection stateNode = new MemoryConfiguration(); InventoryUtils.loadTagsFromNBT(stateNode, wandNode, ALL_PROPERTY_KEYS); loadProperties(stateNode); } public void saveProperties(ConfigurationSection node) { node.set("id", id); node.set("materials", getMaterialString()); node.set("spells", getSpellString()); node.set("active_spell", activeSpell); node.set("active_material", activeMaterial); node.set("name", wandName); node.set("description", description); node.set("owner", owner); node.set("cost_reduction", costReduction); node.set("cooldown_reduction", cooldownReduction); node.set("power", power); node.set("protection", damageReduction); node.set("protection_physical", damageReductionPhysical); node.set("protection_projectiles", damageReductionProjectiles); node.set("protection_falling", damageReductionFalling); node.set("protection_fire", damageReductionFire); node.set("protection_explosions", damageReductionExplosions); node.set("haste", speedIncrease); node.set("xp", xp); node.set("xp_regeneration", xpRegeneration); node.set("xp_max", xpMax); node.set("health_regeneration", healthRegeneration); node.set("hunger_regeneration", hungerRegeneration); node.set("uses", uses); node.set("locked", locked); node.set("effect_color", effectColor == null ? "none" : effectColor.toString()); node.set("effect_bubbles", effectBubbles); node.set("effect_particle_data", Float.toString(effectParticleData)); node.set("effect_particle_count", effectParticleCount); node.set("effect_particle_interval", effectParticleInterval); node.set("effect_sound_interval", effectSoundInterval); node.set("effect_sound_volume", Float.toString(effectSoundVolume)); node.set("effect_sound_pitch", Float.toString(effectSoundPitch)); node.set("quiet", quietLevel); node.set("keep", keep); node.set("bound", bound); node.set("indestructible", indestructible); node.set("fill", autoFill); node.set("upgrade", isUpgrade); node.set("organize", autoOrganize); if (effectSound != null) { node.set("effect_sound", effectSound.name()); } else { node.set("effectSound", null); } if (effectParticle != null) { node.set("effect_particle", effectParticle.name()); } else { node.set("effect_particle", null); } if (mode != null) { node.set("mode", mode.name()); } else { node.set("mode", null); } if (icon != null) { String iconKey = MaterialBrush.getMaterialKey(icon); if (iconKey != null && iconKey.length() > 0) { node.set("icon", iconKey); } else { node.set("icon", null); } } else { node.set("icon", null); } if (template != null && template.length() > 0) { node.set("template", template); } else { node.set("template", null); } } public void loadProperties(ConfigurationSection wandConfig) { loadProperties(wandConfig, false); } public void setEffectColor(String hexColor) { if (hexColor == null || hexColor.length() == 0 || hexColor.equals("none")) { effectColor = null; return; } effectColor = new ColorHD(hexColor); } public void loadProperties(ConfigurationSection wandConfig, boolean safe) { locked = (boolean)wandConfig.getBoolean("locked", locked); float _costReduction = (float)wandConfig.getDouble("cost_reduction", costReduction); costReduction = safe ? Math.max(_costReduction, costReduction) : _costReduction; float _cooldownReduction = (float)wandConfig.getDouble("cooldown_reduction", cooldownReduction); cooldownReduction = safe ? Math.max(_cooldownReduction, cooldownReduction) : _cooldownReduction; float _power = (float)wandConfig.getDouble("power", power); power = safe ? Math.max(_power, power) : _power; float _damageReduction = (float)wandConfig.getDouble("protection", damageReduction); damageReduction = safe ? Math.max(_damageReduction, damageReduction) : _damageReduction; float _damageReductionPhysical = (float)wandConfig.getDouble("protection_physical", damageReductionPhysical); damageReductionPhysical = safe ? Math.max(_damageReductionPhysical, damageReductionPhysical) : _damageReductionPhysical; float _damageReductionProjectiles = (float)wandConfig.getDouble("protection_projectiles", damageReductionProjectiles); damageReductionProjectiles = safe ? Math.max(_damageReductionProjectiles, damageReductionPhysical) : _damageReductionProjectiles; float _damageReductionFalling = (float)wandConfig.getDouble("protection_falling", damageReductionFalling); damageReductionFalling = safe ? Math.max(_damageReductionFalling, damageReductionFalling) : _damageReductionFalling; float _damageReductionFire = (float)wandConfig.getDouble("protection_fire", damageReductionFire); damageReductionFire = safe ? Math.max(_damageReductionFire, damageReductionFire) : _damageReductionFire; float _damageReductionExplosions = (float)wandConfig.getDouble("protection_explosions", damageReductionExplosions); damageReductionExplosions = safe ? Math.max(_damageReductionExplosions, damageReductionExplosions) : _damageReductionExplosions; int _xpRegeneration = wandConfig.getInt("xp_regeneration", xpRegeneration); xpRegeneration = safe ? Math.max(_xpRegeneration, xpRegeneration) : _xpRegeneration; int _xpMax = wandConfig.getInt("xp_max", xpMax); xpMax = safe ? Math.max(_xpMax, xpMax) : _xpMax; int _xp = wandConfig.getInt("xp", xp); xp = safe ? Math.max(_xp, xp) : _xp; float _healthRegeneration = (float)wandConfig.getDouble("health_regeneration", healthRegeneration); healthRegeneration = safe ? Math.max(_healthRegeneration, healthRegeneration) : _healthRegeneration; float _hungerRegeneration = (float)wandConfig.getDouble("hunger_regeneration", hungerRegeneration); hungerRegeneration = safe ? Math.max(_hungerRegeneration, hungerRegeneration) : _hungerRegeneration; int _uses = wandConfig.getInt("uses", uses); uses = safe ? Math.max(_uses, uses) : _uses; float _speedIncrease = (float)wandConfig.getDouble("haste", speedIncrease); speedIncrease = safe ? Math.max(_speedIncrease, speedIncrease) : _speedIncrease; if (wandConfig.contains("effect_color") && !safe) { setEffectColor(wandConfig.getString("effect_color")); } // Don't change any of this stuff in safe mode if (!safe) { id = wandConfig.getString("id", id); if (id == null) id = ""; quietLevel = wandConfig.getInt("quiet", quietLevel); effectBubbles = wandConfig.getBoolean("effect_bubbles", effectBubbles); keep = wandConfig.getBoolean("keep", keep); indestructible = wandConfig.getBoolean("indestructible", indestructible); bound = wandConfig.getBoolean("bound", bound); autoOrganize = wandConfig.getBoolean("organize", autoOrganize); autoFill = wandConfig.getBoolean("fill", autoFill); isUpgrade = wandConfig.getBoolean("upgrade", isUpgrade); if (wandConfig.contains("effect_particle")) { parseParticleEffect(wandConfig.getString("effect_particle")); effectParticleData = 0; } if (wandConfig.contains("effect_sound")) { parseSoundEffect(wandConfig.getString("effect_sound")); } effectParticleData = (float)wandConfig.getDouble("effect_particle_data", effectParticleData); effectParticleCount = wandConfig.getInt("effect_particle_count", effectParticleCount); effectParticleInterval = wandConfig.getInt("effect_particle_interval", effectParticleInterval); effectSoundInterval = wandConfig.getInt("effect_sound_interval", effectSoundInterval); effectSoundVolume = (float)wandConfig.getDouble("effect_sound_volume", effectSoundVolume); effectSoundPitch = (float)wandConfig.getDouble("effect_sound_pitch", effectSoundPitch); setMode(parseWandMode(wandConfig.getString("mode"), mode)); owner = wandConfig.getString("owner", owner); wandName = wandConfig.getString("name", wandName); description = wandConfig.getString("description", description); template = wandConfig.getString("template", template); activeSpell = wandConfig.getString("active_spell", activeSpell); activeMaterial = wandConfig.getString("active_material", activeMaterial); String wandMaterials = wandConfig.getString("materials", ""); String wandSpells = wandConfig.getString("spells", ""); if (wandMaterials.length() > 0 || wandSpells.length() > 0) { wandMaterials = wandMaterials.length() == 0 ? getMaterialString() : wandMaterials; wandSpells = wandSpells.length() == 0 ? getSpellString() : wandSpells; parseInventoryStrings(wandSpells, wandMaterials); } if (wandConfig.contains("icon")) { setIcon(ConfigurationUtils.getMaterialAndData(wandConfig, "icon")); } } // Some cleanup and sanity checks. In theory we don't need to store any non-zero value (as it is with the traders) // so try to keep defaults as 0/0.0/false. if (effectSound == null) { effectSoundInterval = 0; effectSoundVolume = 0; effectSoundPitch = 0; } else { effectSoundInterval = (effectSoundInterval == 0) ? 5 : effectSoundInterval; effectSoundVolume = (effectSoundVolume < 0.01f) ? 0.8f : effectSoundVolume; effectSoundPitch = (effectSoundPitch < 0.01f) ? 1.1f : effectSoundPitch; } if (effectParticle == null) { effectParticleInterval = 0; } else { effectParticleInterval = (effectParticleInterval == 0) ? 2 : effectParticleInterval; effectParticleCount = (effectParticleCount == 0) ? 1 : effectParticleCount; } if (xpRegeneration <= 0 || xpMax <= 0 || costReduction >= 1) { xpMax = 0; xpRegeneration = 0; xp = 0; } checkActiveMaterial(); saveState(); updateName(); updateLore(); } protected void parseSoundEffect(String effectSoundName) { if (effectSoundName.length() > 0) { String testName = effectSoundName.toUpperCase().replace("_", ""); try { for (Sound testType : Sound.values()) { String testTypeName = testType.name().replace("_", ""); if (testTypeName.equals(testName)) { effectSound = testType; break; } } } catch (Exception ex) { effectSound = null; } } else { effectSound = null; } } protected void parseParticleEffect(String effectParticleName) { if (effectParticleName.length() > 0) { String testName = effectParticleName.toUpperCase().replace("_", ""); try { for (ParticleType testType : ParticleType.values()) { String testTypeName = testType.name().replace("_", ""); if (testTypeName.equals(testName)) { effectParticle = testType; break; } } } catch (Exception ex) { effectParticle = null; } } else { effectParticle = null; } } public void describe(CommandSender sender) { Object wandNode = InventoryUtils.getNode(item, "wand"); if (wandNode == null) { sender.sendMessage("Found a wand with missing NBT data. This may be an old wand, or something may have wiped its data"); return; } ChatColor wandColor = isModifiable() ? ChatColor.AQUA : ChatColor.RED; sender.sendMessage(wandColor + wandName); if (description.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + description); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + "(No Description)"); } if (owner.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + owner); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + "(No Owner)"); } for (String key : PROPERTY_KEYS) { String value = InventoryUtils.getMeta(wandNode, key); if (value != null && value.length() > 0) { sender.sendMessage(key + ": " + value); } } } private static String getSpellDisplayName(SpellTemplate spell, String materialKey) { String name = ""; if (spell != null) { if (materialKey != null && (spell instanceof BrushSpell) && !((BrushSpell)spell).hasBrushOverride()) { String materialName = MaterialBrush.getMaterialName(materialKey); if (materialName == null) { materialName = "none"; } name = ChatColor.GOLD + spell.getName() + ChatColor.GRAY + " " + materialName + ChatColor.WHITE; } else { name = ChatColor.GOLD + spell.getName() + ChatColor.WHITE; } } return name; } private String getActiveWandName(SpellTemplate spell, String materialKey) { // Build wand name ChatColor wandColor = isModifiable() ? (bound ? ChatColor.DARK_AQUA : ChatColor.AQUA) : ChatColor.RED; String name = wandColor + wandName; // Add active spell to description if (spell != null) { name = getSpellDisplayName(spell, materialKey) + " (" + name + ChatColor.WHITE + ")"; } int remaining = getRemainingUses(); if (remaining > 0) { String message = (remaining == 1) ? Messages.get("wand.uses_remaining_singular") : Messages.get("wand.uses_remaining_brief"); name = name + " (" + ChatColor.RED + message.replace("$count", ((Integer)remaining).toString()) + ")"; } return name; } private String getActiveWandName(SpellTemplate spell) { return getActiveWandName(spell, activeMaterial); } private String getActiveWandName() { SpellTemplate spell = null; if (hasInventory && activeSpell != null && activeSpell.length() > 0) { spell = controller.getSpellTemplate(activeSpell); } return getActiveWandName(spell); } public void updateName(boolean isActive) { ItemMeta meta = item.getItemMeta(); meta.setDisplayName(isActive ? getActiveWandName() : wandName); item.setItemMeta(meta); // Reset Enchantment glow if (EnableGlow) { InventoryUtils.addGlow(item); } // The all-important last step of restoring the meta state, something // the Anvil will blow away. saveState(); } private void updateName() { updateName(true); } protected static String convertToHTML(String line) { int tagCount = 1; line = "<span style=\"color:white\">" + line; for (ChatColor c : ChatColor.values()) { tagCount += StringUtils.countMatches(line, c.toString()); String replaceStyle = ""; if (c == ChatColor.ITALIC) { replaceStyle = "font-style: italic"; } else if (c == ChatColor.BOLD) { replaceStyle = "font-weight: bold"; } else if (c == ChatColor.UNDERLINE) { replaceStyle = "text-decoration: underline"; } else { String color = c.name().toLowerCase().replace("_", ""); if (c == ChatColor.LIGHT_PURPLE) { color = "mediumpurple"; } replaceStyle = "color:" + color; } line = line.replace(c.toString(), "<span style=\"" + replaceStyle + "\">"); } for (int i = 0; i < tagCount; i++) { line += "</span>"; } return line; } public String getHTMLDescription() { Collection<String> rawLore = getLore(); Collection<String> lore = new ArrayList<String>(); lore.add("<h2>" + convertToHTML(getActiveWandName()) + "</h2>"); for (String line : rawLore) { lore.add(convertToHTML(line)); } return "<div style=\"background-color: black; margin: 8px; padding: 8px\">" + StringUtils.join(lore, "<br/>") + "</div>"; } protected List<String> getLore() { return getLore(getSpells().size(), getBrushes().size()); } protected void addPropertyLore(List<String> lore) { if (usesMana()) { lore.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + getLevelString("wand.mana_amount", xpMax, WandLevel.maxMaxXp)); lore.add(ChatColor.RESET + "" + ChatColor.LIGHT_PURPLE + getLevelString("wand.mana_regeneration", xpRegeneration, WandLevel.maxXpRegeneration)); } if (costReduction > 0) lore.add(ChatColor.AQUA + getLevelString("wand.cost_reduction", costReduction)); if (cooldownReduction > 0) lore.add(ChatColor.AQUA + getLevelString("wand.cooldown_reduction", cooldownReduction)); if (power > 0) lore.add(ChatColor.AQUA + getLevelString("wand.power", power)); if (speedIncrease > 0) lore.add(ChatColor.AQUA + getLevelString("wand.haste", speedIncrease)); if (damageReduction > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection", damageReduction, WandLevel.maxDamageReduction)); if (damageReduction < 1) { if (damageReductionPhysical > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_physical", damageReductionPhysical, WandLevel.maxDamageReductionPhysical)); if (damageReductionProjectiles > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_projectile", damageReductionProjectiles, WandLevel.maxDamageReductionProjectiles)); if (damageReductionFalling > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_fall", damageReductionFalling, WandLevel.maxDamageReductionFalling)); if (damageReductionFire > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_fire", damageReductionFire, WandLevel.maxDamageReductionFire)); if (damageReductionExplosions > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_blast", damageReductionExplosions, WandLevel.maxDamageReductionExplosions)); } if (healthRegeneration > 0) lore.add(ChatColor.AQUA + getLevelString("wand.health_regeneration", healthRegeneration)); if (hungerRegeneration > 0) lore.add(ChatColor.AQUA + getLevelString("wand.hunger_regeneration", hungerRegeneration)); } private String getLevelString(String templateName, float amount) { return getLevelString(templateName, amount, 1); } private static String getLevelString(String templateName, float amount, float max) { String templateString = Messages.get(templateName); if (templateString.contains("$roman")) { templateString = templateString.replace("$roman", getRomanString(amount)); } return templateString.replace("$amount", Integer.toString((int)amount)); } private static String getRomanString(float amount) { String roman = ""; if (amount > 1) { roman = Messages.get("wand.enchantment_level_max"); } else if (amount > 0.8) { roman = Messages.get("wand.enchantment_level_5"); } else if (amount > 0.6) { roman = Messages.get("wand.enchantment_level_4"); } else if (amount > 0.4) { roman = Messages.get("wand.enchantment_level_3"); } else if (amount > 0.2) { roman = Messages.get("wand.enchantment_level_2"); } else { roman = Messages.get("wand.enchantment_level_1"); } return roman; } protected List<String> getLore(int spellCount, int materialCount) { List<String> lore = new ArrayList<String>(); SpellTemplate spell = controller.getSpellTemplate(activeSpell); if (spell != null && spellCount == 1 && materialCount <= 1 && !isUpgrade) { addSpellLore(spell, lore, this); } else { if (description.length() > 0) { lore.add(ChatColor.ITALIC + "" + ChatColor.GREEN + description); } if (!isUpgrade) { if (owner.length() > 0) { if (bound) { String ownerDescription = Messages.get("wand.bound_description", "$name").replace("$name", owner); lore.add(ChatColor.ITALIC + "" + ChatColor.DARK_AQUA + ownerDescription); } else { String ownerDescription = Messages.get("wand.owner_description", "$name").replace("$name", owner); lore.add(ChatColor.ITALIC + "" + ChatColor.DARK_GREEN + ownerDescription); } } } if (spellCount > 0) { if (isUpgrade) { lore.add(Messages.get("wand.upgrade_spell_count").replace("$count", ((Integer)spellCount).toString())); } else { lore.add(Messages.get("wand.spell_count").replace("$count", ((Integer)spellCount).toString())); } } if (materialCount > 0) { if (isUpgrade) { lore.add(Messages.get("wand.material_count").replace("$count", ((Integer)materialCount).toString())); } else { lore.add(Messages.get("wand.upgrade_material_count").replace("$count", ((Integer)materialCount).toString())); } } } int remaining = getRemainingUses(); if (remaining > 0) { if (isUpgrade) { String message = (remaining == 1) ? Messages.get("wand.upgrade_uses_singular") : Messages.get("wand.upgrade_uses"); lore.add(ChatColor.RED + message.replace("$count", ((Integer)remaining).toString())); } else { String message = (remaining == 1) ? Messages.get("wand.uses_remaining_singular") : Messages.get("wand.uses_remaining_brief"); lore.add(ChatColor.RED + message.replace("$count", ((Integer)remaining).toString())); } } addPropertyLore(lore); if (isUpgrade) { lore.add(ChatColor.YELLOW + Messages.get("wand.upgrade_item_description")); } return lore; } protected void updateLore() { ItemMeta meta = item.getItemMeta(); List<String> lore = getLore(); meta.setLore(lore); item.setItemMeta(meta); if (EnableGlow) { InventoryUtils.addGlow(item); } // Setting lore will reset wand data saveState(); } public int getRemainingUses() { return uses; } public void makeEnchantable(boolean enchantable) { if (EnchantableWandMaterial == null) return; if (!enchantable) { item.setType(icon.getMaterial()); item.setDurability(icon.getData()); } else { Set<Material> enchantableMaterials = controller.getMaterialSet("enchantable"); if (!enchantableMaterials.contains(item.getType())) { item.setType(EnchantableWandMaterial); item.setDurability((short)0); } } updateName(); } public static boolean hasActiveWand(Player player) { if (player == null) return false; ItemStack activeItem = player.getInventory().getItemInHand(); return isWand(activeItem); } public static Wand getActiveWand(MagicController spells, Player player) { ItemStack activeItem = player.getInventory().getItemInHand(); if (isWand(activeItem)) { return new Wand(spells, activeItem); } return null; } public static boolean isWand(ItemStack item) { // Note that WandUpgrades also show up here! return item != null && InventoryUtils.hasMeta(item, "wand"); } public static boolean isWandUpgrade(ItemStack item) { if (item == null) return false; Object wandNode = InventoryUtils.getNode(item, "wand"); if (wandNode == null) return false; String upgradeData = InventoryUtils.getMeta(wandNode, "upgrade"); return upgradeData != null && upgradeData.equals("true"); } public static boolean isSpell(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "spell"); } public static boolean isBrush(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "brush"); } public static String getSpell(ItemStack item) { if (!isSpell(item)) return null; Object spellNode = InventoryUtils.getNode(item, "spell"); return InventoryUtils.getMeta(spellNode, "key"); } public static String getBrush(ItemStack item) { if (!isBrush(item)) return null; Object brushNode = InventoryUtils.getNode(item, "brush"); return InventoryUtils.getMeta(brushNode, "key"); } protected static String getMaterialKey(ItemStack itemStack, Integer index) { String materialKey = getBrush(itemStack); if (materialKey == null) return null; if (index != null) { materialKey += "@" + index; } return materialKey; } protected void updateInventoryName(ItemStack item, boolean activeName) { if (isSpell(item)) { Spell spell = mage.getSpell(getSpell(item)); if (spell != null) { updateSpellItem(item, spell, activeName ? this : null, activeMaterial, false); } } else if (isBrush(item)) { updateBrushItem(item, getBrush(item), activeName ? this : null); } } public static void updateSpellItem(ItemStack itemStack, SpellTemplate spell, Wand wand, String activeMaterial, boolean isItem) { ItemMeta meta = itemStack.getItemMeta(); String displayName = null; if (wand != null) { displayName = wand.getActiveWandName(spell); } else { displayName = getSpellDisplayName(spell, activeMaterial); } meta.setDisplayName(displayName); List<String> lore = new ArrayList<String>(); addSpellLore(spell, lore, wand); if (isItem) { lore.add(ChatColor.YELLOW + Messages.get("wand.spell_item_description")); } meta.setLore(lore); itemStack.setItemMeta(meta); InventoryUtils.addGlow(itemStack); Object spellNode = InventoryUtils.createNode(itemStack, "spell"); InventoryUtils.setMeta(spellNode, "key", spell.getKey()); } public static void updateBrushItem(ItemStack itemStack, String materialKey, Wand wand) { ItemMeta meta = itemStack.getItemMeta(); String displayName = null; if (wand != null) { displayName = wand.getActiveWandName(materialKey); } else { displayName = MaterialBrush.getMaterialName(materialKey); } meta.setDisplayName(displayName); itemStack.setItemMeta(meta); Object brushNode = InventoryUtils.createNode(itemStack, "brush"); InventoryUtils.setMeta(brushNode, "key", materialKey); } @SuppressWarnings("deprecation") private void updateInventory() { if (mage == null) return; if (!isInventoryOpen()) return; Player player = mage.getPlayer(); if (player == null) return; WandMode wandMode = getMode(); if (wandMode == WandMode.INVENTORY) { if (!mage.hasStoredInventory()) return; PlayerInventory inventory = player.getInventory(); inventory.clear(); updateHotbar(inventory); updateInventory(inventory, HOTBAR_SIZE, false); updateName(); player.updateInventory(); } else if (wandMode == WandMode.CHEST) { Inventory inventory = getDisplayInventory(); inventory.clear(); updateInventory(inventory, 0, true); player.updateInventory(); } } private void updateHotbar(PlayerInventory playerInventory) { // Check for an item already in the player's held slot, which // we are about to replace with the wand. int currentSlot = playerInventory.getHeldItemSlot(); ItemStack existingHotbar = hotbar.getItem(currentSlot); if (existingHotbar != null && existingHotbar.getType() != Material.AIR && !isWand(existingHotbar)) { // Toss the item back into the wand inventory, it'll find a home somewhere. addToInventory(existingHotbar); hotbar.setItem(currentSlot, null); } // Put the wand in the player's active slot. playerInventory.setItem(currentSlot, item); // Set hotbar items from remaining list for (int hotbarSlot = 0; hotbarSlot < HOTBAR_SIZE; hotbarSlot++) { if (hotbarSlot != currentSlot) { ItemStack hotbarItem = hotbar.getItem(hotbarSlot); updateInventoryName(hotbarItem, true); playerInventory.setItem(hotbarSlot, hotbarItem); } } } private void updateInventory(Inventory targetInventory, int startOffset, boolean addHotbar) { // Set inventory from current page int currentOffset = startOffset; if (openInventoryPage < inventories.size()) { Inventory inventory = inventories.get(openInventoryPage); ItemStack[] contents = inventory.getContents(); for (int i = 0; i < contents.length; i++) { ItemStack inventoryItem = contents[i]; updateInventoryName(inventoryItem, false); targetInventory.setItem(currentOffset, inventoryItem); currentOffset++; } } if (addHotbar) { for (int i = 0; i < HOTBAR_SIZE; i++) { ItemStack inventoryItem = hotbar.getItem(i); updateInventoryName(inventoryItem, false); targetInventory.setItem(currentOffset++, inventoryItem); } } } protected static void addSpellLore(SpellTemplate spell, List<String> lore, CostReducer reducer) { String description = spell.getDescription(); String usage = spell.getUsage(); if (description != null && description.length() > 0) { lore.add(description); } if (usage != null && usage.length() > 0) { lore.add(usage); } Collection<CastingCost> costs = spell.getCosts(); if (costs != null) { for (CastingCost cost : costs) { if (cost.hasCosts(reducer)) { lore.add(ChatColor.YELLOW + Messages.get("wand.costs_description").replace("$description", cost.getFullDescription(reducer))); } } } Collection<CastingCost> activeCosts = spell.getActiveCosts(); if (activeCosts != null) { for (CastingCost cost : activeCosts) { if (cost.hasCosts(reducer)) { lore.add(ChatColor.YELLOW + Messages.get("wand.active_costs_description").replace("$description", cost.getFullDescription(reducer))); } } } long duration = spell.getDuration(); if (duration > 0) { long seconds = duration / 1000; if (seconds > 60 * 60 ) { long hours = seconds / (60 * 60); lore.add(Messages.get("duration.lasts_hours").replace("$hours", ((Long)hours).toString())); } else if (seconds > 60) { long minutes = seconds / 60; lore.add(Messages.get("duration.lasts_minutes").replace("$minutes", ((Long)minutes).toString())); } else { lore.add(Messages.get("duration.lasts_seconds").replace("$seconds", ((Long)seconds).toString())); } } if ((spell instanceof BrushSpell) && !((BrushSpell)spell).hasBrushOverride()) { lore.add(ChatColor.GOLD + Messages.get("spell.brush")); } if (spell instanceof UndoableSpell && ((UndoableSpell)spell).isUndoable()) { lore.add(ChatColor.GRAY + Messages.get("spell.undoable")); } } protected Inventory getOpenInventory() { while (openInventoryPage >= inventories.size()) { inventories.add(InventoryUtils.createInventory(null, INVENTORY_SIZE, "Wand")); } return inventories.get(openInventoryPage); } public void saveInventory() { if (mage == null) return; if (!isInventoryOpen()) return; if (mage.getPlayer() == null) return; if (getMode() != WandMode.INVENTORY) return; if (!mage.hasStoredInventory()) return; // Fill in the hotbar Player player = mage.getPlayer(); PlayerInventory playerInventory = player.getInventory(); for (int i = 0; i < HOTBAR_SIZE; i++) { ItemStack playerItem = playerInventory.getItem(i); if (isWand(playerItem)) { playerItem = null; } hotbar.setItem(i, playerItem); } // Fill in the active inventory page Inventory openInventory = getOpenInventory(); for (int i = 0; i < openInventory.getSize(); i++) { openInventory.setItem(i, playerInventory.getItem(i + HOTBAR_SIZE)); } saveState(); } public static boolean isActive(Player player) { ItemStack activeItem = player.getInventory().getItemInHand(); return isWand(activeItem); } protected void randomize(int totalLevels, boolean additive) { if (!wandTemplates.containsKey("random")) return; if (!additive) { wandName = Messages.get("wands.random.name", wandName); } int maxLevel = WandLevel.getMaxLevel(); int addLevels = Math.min(totalLevels, maxLevel); while (addLevels > 0) { WandLevel.randomizeWand(this, additive, addLevels); totalLevels -= maxLevel; addLevels = Math.min(totalLevels, maxLevel); additive = true; } } public static Wand createWand(MagicController controller, String templateName) { if (controller == null) return null; Wand wand = null; try { wand = new Wand(controller, templateName); } catch (Exception ex) { ex.printStackTrace(); } return wand; } protected void sendAddMessage(String messageKey, String nameParam) { if (mage == null) return; String message = Messages.get(messageKey).replace("$name", nameParam); mage.sendMessage(message); } public boolean add(Wand other) { if (!isModifiable() || !other.isModifiable()) return false; boolean modified = false; if (other.costReduction > costReduction) { costReduction = other.costReduction; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.cost_reduction", costReduction)); } if (other.power > power) { power = other.power; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.power", power)); } if (other.damageReduction > damageReduction) { damageReduction = other.damageReduction; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.protection", damageReduction)); } if (other.damageReductionPhysical > damageReductionPhysical) { damageReductionPhysical = other.damageReductionPhysical; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_physical", damageReductionPhysical)); } if (other.damageReductionProjectiles > damageReductionProjectiles) { damageReductionProjectiles = other.damageReductionProjectiles; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_projectile", damageReductionProjectiles)); } if (other.damageReductionFalling > damageReductionFalling) { damageReductionFalling = other.damageReductionFalling; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_falling", damageReductionFalling)); } if (other.damageReductionFire > damageReductionFire) { damageReductionFire = other.damageReductionFire; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_fire", damageReductionFire)); } if (other.damageReductionExplosions > damageReductionExplosions) { damageReductionExplosions = other.damageReductionExplosions; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_explosions", damageReductionExplosions)); } if (other.healthRegeneration > healthRegeneration) { healthRegeneration = other.healthRegeneration; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.health_regeneration", healthRegeneration)); } if (other.hungerRegeneration > hungerRegeneration) { hungerRegeneration = other.hungerRegeneration; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.hunger_regeneration", hungerRegeneration)); } if (other.speedIncrease > speedIncrease) { speedIncrease = other.speedIncrease; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.haste", speedIncrease)); } // Mix colors if (other.effectColor != null) { if (this.effectColor == null) { this.effectColor = other.effectColor; } else { this.effectColor = this.effectColor.mixColor(other.effectColor, other.effectColorMixWeight); } modified = true; } modified = modified | (!keep && other.keep); modified = modified | (!bound && other.bound); modified = modified | (!effectBubbles && other.effectBubbles); keep = keep || other.keep; bound = bound || other.bound; effectBubbles = effectBubbles || other.effectBubbles; if (other.effectParticle != null && (other.isUpgrade || effectParticle == null)) { modified = modified | (effectParticle != other.effectParticle); effectParticle = other.effectParticle; modified = modified | (effectParticleData != other.effectParticleData); effectParticleData = other.effectParticleData; modified = modified | (effectParticleCount != other.effectParticleCount); effectParticleCount = other.effectParticleCount; modified = modified | (effectParticleInterval != other.effectParticleInterval); effectParticleInterval = other.effectParticleInterval; } if (other.effectSound != null && (other.isUpgrade || effectSound == null)) { modified = modified | (effectSound != other.effectSound); effectSound = other.effectSound; modified = modified | (effectSoundInterval != other.effectSoundInterval); effectSoundInterval = other.effectSoundInterval; modified = modified | (effectSoundVolume != other.effectSoundVolume); effectSoundVolume = other.effectSoundVolume; modified = modified | (effectSoundPitch != other.effectSoundPitch); effectSoundPitch = other.effectSoundPitch; } if (other.template != null && other.template.length() > 0) { modified = modified | (!template.equals(other.template)); template = other.template; } if (other.isUpgrade && other.mode != null) { modified = modified | (mode != other.mode); setMode(other.mode); } // Don't need mana if cost-free if (costReduction >= 1) { xpRegeneration = 0; xpMax = 0; xp = 0; } else { if (other.xpRegeneration > xpRegeneration) { xpRegeneration = other.xpRegeneration; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.mana_regeneration", xpRegeneration, WandLevel.maxXpRegeneration)); } if (other.xpMax > xpMax) { xpMax = other.xpMax; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.mana_amount", xpMax, WandLevel.maxMaxXp)); } if (other.xp > xp) { xp = other.xp; modified = true; } } // Eliminate limited-use wands if (uses == 0 || other.uses == 0) { modified = modified | (uses != 0); uses = 0; } else { // Otherwise add them modified = modified | (other.uses != 0); uses = uses + other.uses; } // Add spells Set<String> spells = other.getSpells(); for (String spellKey : spells) { if (addSpell(spellKey)) { modified = true; String spellName = spellKey; SpellTemplate spell = controller.getSpellTemplate(spellKey); if (spell != null) spellName = spell.getName(); if (mage != null) mage.sendMessage(Messages.get("wand.spell_added").replace("$name", spellName)); } } // Add materials Set<String> materials = other.getBrushes(); for (String materialKey : materials) { if (addBrush(materialKey)) { modified = true; if (mage != null) mage.sendMessage(Messages.get("wand.brush_added").replace("$name", MaterialBrush.getMaterialName(materialKey))); } } Player player = (mage == null) ? null : mage.getPlayer(); if (other.autoFill && player != null) { this.fill(player); modified = true; if (mage != null) mage.sendMessage(Messages.get("wand.filled")); } if (other.autoOrganize && mage != null) { this.organizeInventory(mage); modified = true; if (mage != null) mage.sendMessage(Messages.get("wand.reorganized")); } saveState(); updateName(); updateLore(); return modified; } public boolean keepOnDeath() { return keep; } public static void loadTemplates(ConfigurationSection properties) { wandTemplates.clear(); Set<String> wandKeys = properties.getKeys(false); for (String key : wandKeys) { ConfigurationSection wandNode = properties.getConfigurationSection(key); wandNode.set("key", key); ConfigurationSection existing = wandTemplates.get(key); if (existing != null) { Set<String> overrideKeys = existing.getKeys(false); for (String propertyKey : overrideKeys) { existing.set(propertyKey, existing.get(key)); } } else { wandTemplates.put(key, wandNode); } if (!wandNode.getBoolean("enabled", true)) { wandTemplates.remove(key); } if (key.equals("random")) { WandLevel.mapLevels(wandNode); } } } public static Collection<String> getWandKeys() { return wandTemplates.keySet(); } public static Collection<ConfigurationSection> getWandTemplates() { return wandTemplates.values(); } public static WandMode parseWandMode(String modeString, WandMode defaultValue) { for (WandMode testMode : WandMode.values()) { if (testMode.name().equalsIgnoreCase(modeString)) { return testMode; } } return defaultValue; } private void updateActiveMaterial() { if (mage == null) return; if (activeMaterial == null) { mage.clearBuildingMaterial(); } else { com.elmakers.mine.bukkit.api.block.MaterialBrush brush = mage.getBrush(); brush.update(activeMaterial); } } public void toggleInventory() { if (!hasInventory) { if (activeSpell == null || activeSpell.length() == 0) { Set<String> spells = getSpells(); // Sanity check, so it'll switch to inventory next time if (spells.size() > 1) hasInventory = true; if (spells.size() > 0) { activeSpell = spells.iterator().next(); } } updateName(); return; } if (!isInventoryOpen()) { openInventory(); } else { closeInventory(); } } @SuppressWarnings("deprecation") public void cycleInventory() { if (!hasInventory) { return; } if (isInventoryOpen()) { saveInventory(); int inventoryCount = inventories.size(); openInventoryPage = inventoryCount == 0 ? 0 : (openInventoryPage + 1) % inventoryCount; updateInventory(); if (mage != null && inventories.size() > 1) { mage.playSound(Sound.CHEST_OPEN, 0.3f, 1.5f); mage.getPlayer().updateInventory(); } } } @SuppressWarnings("deprecation") private void openInventory() { if (mage == null) return; WandMode wandMode = getMode(); if (wandMode == WandMode.CHEST) { inventoryIsOpen = true; mage.playSound(Sound.CHEST_OPEN, 0.4f, 0.2f); updateInventory(); mage.getPlayer().openInventory(getDisplayInventory()); } else if (wandMode == WandMode.INVENTORY) { if (mage.hasStoredInventory()) return; if (mage.storeInventory()) { inventoryIsOpen = true; mage.playSound(Sound.CHEST_OPEN, 0.4f, 0.2f); updateInventory(); mage.getPlayer().updateInventory(); } } } @SuppressWarnings("deprecation") public void closeInventory() { if (!isInventoryOpen()) return; saveInventory(); inventoryIsOpen = false; if (mage != null) { mage.playSound(Sound.CHEST_CLOSE, 0.4f, 0.2f); if (getMode() == WandMode.INVENTORY) { mage.restoreInventory(); Player player = mage.getPlayer(); player.setItemInHand(item); player.updateInventory(); } else { mage.getPlayer().closeInventory(); } } saveState(); } public boolean fill(Player player) { Collection<SpellTemplate> allSpells = controller.getPlugin().getSpellTemplates(); for (SpellTemplate spell : allSpells) { if (spell.hasCastPermission(player) && spell.getIcon().getMaterial() != Material.AIR) { addSpell(spell.getKey()); } } autoFill = false; saveState(); // TODO: Detect changes return true; } public boolean hasId() { return id != null && id.length() > 0; } public void activate(Mage mage, ItemStack wandItem) { if (mage == null || wandItem == null) return; // Update held item, it may have been copied since this wand was created. this.item = wandItem; this.mage = mage; // Check for spell or other special icons in the player's inventory Player player = mage.getPlayer(); boolean modified = false; ItemStack[] items = player.getInventory().getContents(); for (int i = 0; i < items.length; i++) { ItemStack item = items[i]; if (addItem(item)) { modified = true; items[i] = null; } } if (modified) { player.getInventory().setContents(items); } // Check for an empty wand and auto-fill if (!isUpgrade && (controller.fillWands() || autoFill)) { if (getSpells().size() == 0) { fill(mage.getPlayer()); } } // Check for auto-organize if (autoOrganize && !isUpgrade) { organizeInventory(mage); } // Check for auto-bind if (bound && (owner == null || owner.length() == 0)) { takeOwnership(mage.getPlayer()); } checkActiveMaterial(); saveState(); mage.setActiveWand(this); if (usesMana()) { storedXpLevel = player.getLevel(); storedXpProgress = player.getExp(); storedXp = 0; updateMana(); } updateActiveMaterial(); updateName(); updateLore(); updateEffects(); } protected void checkActiveMaterial() { if (activeMaterial == null || activeMaterial.length() == 0) { Set<String> materials = getBrushes(); if (materials.size() > 0) { activeMaterial = materials.iterator().next(); } } } public boolean addItem(ItemStack item) { if (isUpgrade) return false; if (isSpell(item)) { String spellKey = getSpell(item); Set<String> spells = getSpells(); if (!spells.contains(spellKey) && addSpell(spellKey)) { SpellTemplate spell = controller.getSpellTemplate(spellKey); if (spell != null) { mage.sendMessage(Messages.get("wand.spell_added").replace("$name", spell.getName())); return true; } } } else if (isBrush(item)) { String materialKey = getBrush(item); Set<String> materials = getBrushes(); if (!materials.contains(materialKey) && addBrush(materialKey)) { mage.sendMessage(Messages.get("wand.brush_added").replace("$name", MaterialBrush.getMaterialName(materialKey))); return true; } } else if (isWandUpgrade(item)) { Wand wand = new Wand(controller, item); return this.add(wand); } return false; } protected void updateEffects() { if (mage == null) return; Player player = mage.getPlayer(); if (player == null) return; // Update Bubble effects effects if (effectBubbles) { InventoryUtils.addPotionEffect(player, effectColor.getColor()); } Location location = mage.getLocation(); if (effectParticle != null && location != null) { if ((effectParticleCounter++ % effectParticleInterval) == 0) { if (effectPlayer == null) { effectPlayer = new EffectRing(controller.getPlugin()); effectPlayer.setParticleCount(2); effectPlayer.setIterations(2); effectPlayer.setRadius(2); effectPlayer.setSize(5); effectPlayer.setMaterial(location.getBlock().getRelative(BlockFace.DOWN)); } effectPlayer.setParticleType(effectParticle); effectPlayer.setParticleData(effectParticleData); effectPlayer.setParticleCount(effectParticleCount); effectPlayer.start(player.getEyeLocation(), null); } } if (effectSound != null && location != null && controller.soundsEnabled()) { if ((effectSoundCounter++ % effectSoundInterval) == 0) { mage.getLocation().getWorld().playSound(location, effectSound, effectSoundVolume, effectSoundPitch); } } } protected void updateMana() { if (mage != null && xpMax > 0 && xpRegeneration > 0) { Player player = mage.getPlayer(); if (displayManaAsBar) { if (!retainLevelDisplay) { player.setLevel(0); } player.setExp((float)xp / (float)xpMax); } else { player.setLevel(xp); player.setExp(0); } } } public boolean isInventoryOpen() { return mage != null && inventoryIsOpen; } public void deactivate() { if (mage == null) return; saveState(); if (effectBubbles) { InventoryUtils.removePotionEffect(mage.getPlayer()); } // This is a tying wands together with other spells, potentially // But with the way the mana system works, this seems like the safest route. mage.deactivateAllSpells(); if (isInventoryOpen()) { closeInventory(); } // Extra just-in-case mage.restoreInventory(); if (usesMana()) { mage.getPlayer().setExp(storedXpProgress); mage.getPlayer().setLevel(storedXpLevel); mage.getPlayer().giveExp(storedXp); storedXp = 0; storedXpProgress = 0; storedXpLevel = 0; } mage.setActiveWand(null); mage = null; } public Spell getActiveSpell() { if (mage == null || activeSpell == null || activeSpell.length() == 0) return null; return mage.getSpell(activeSpell); } public boolean cast() { Spell spell = getActiveSpell(); if (spell != null) { if (spell.cast()) { Color spellColor = spell.getColor(); if (spellColor != null && this.effectColor != null) { this.effectColor = this.effectColor.mixColor(spellColor, effectColorSpellMixWeight); // Note that we don't save this change. // The hope is that the wand will get saved at some point later // And we don't want to trigger NBT writes every spell cast. // And the effect color morphing isn't all that important if a few // casts get lost. } use(); return true; } } return false; } @SuppressWarnings("deprecation") protected void use() { if (mage == null) return; if (uses > 0) { uses--; if (uses <= 0) { Player player = mage.getPlayer(); mage.playSound(Sound.ITEM_BREAK, 1.0f, 0.8f); PlayerInventory playerInventory = player.getInventory(); playerInventory.setItemInHand(new ItemStack(Material.AIR, 1)); player.updateInventory(); deactivate(); } else { updateName(); updateLore(); saveState(); } } } public void onPlayerExpChange(PlayerExpChangeEvent event) { if (mage == null) return; if (usesMana()) { storedXp += event.getAmount(); event.setAmount(0); } } public void tick() { if (mage == null) return; Player player = mage.getPlayer(); if (player == null) return; if (speedIncrease > 0) { int hasteLevel = (int)(speedIncrease * WandLevel.maxHasteLevel); if (hasteEffect == null || hasteEffect.getAmplifier() != hasteLevel) { hasteEffect = new PotionEffect(PotionEffectType.SPEED, 80, hasteLevel, true); } CompatibilityUtils.applyPotionEffect(player, hasteEffect); } if (healthRegeneration > 0) { int regenLevel = (int)(healthRegeneration * WandLevel.maxHealthRegeneration); if (healthRegenEffect == null || healthRegenEffect.getAmplifier() != regenLevel) { healthRegenEffect = new PotionEffect(PotionEffectType.REGENERATION, 80, regenLevel, true); } CompatibilityUtils.applyPotionEffect(player, healthRegenEffect); } if (hungerRegeneration > 0) { int regenLevel = (int)(hungerRegeneration * WandLevel.maxHungerRegeneration); if (hungerRegenEffect == null || hungerRegenEffect.getAmplifier() != regenLevel) { hungerRegenEffect = new PotionEffect(PotionEffectType.SATURATION, 80, regenLevel, true); } CompatibilityUtils.applyPotionEffect(player, hungerRegenEffect); } if (usesMana()) { xp = Math.min(xpMax, xp + xpRegeneration); updateMana(); } if (damageReductionFire > 0 && player.getFireTicks() > 0) { player.setFireTicks(0); } updateEffects(); } @Override public boolean equals(Object other) { if (other == null) return false; if (!(other instanceof Wand)) return false; Wand otherWand = ((Wand)other); if (this.id.length() == 0 || otherWand.id.length() == 0) return false; return otherWand.id.equals(this.id); } public MagicController getMaster() { return controller; } public void cycleSpells(ItemStack newItem) { if (isWand(newItem)) item = newItem; Set<String> spellsSet = getSpells(); ArrayList<String> spells = new ArrayList<String>(spellsSet); if (spells.size() == 0) return; if (activeSpell == null) { activeSpell = spells.get(0).split("@")[0]; return; } int spellIndex = 0; for (int i = 0; i < spells.size(); i++) { if (spells.get(i).split("@")[0].equals(activeSpell)) { spellIndex = i; break; } } spellIndex = (spellIndex + 1) % spells.size(); setActiveSpell(spells.get(spellIndex).split("@")[0]); } public void cycleMaterials(ItemStack newItem) { if (isWand(newItem)) item = newItem; Set<String> materialsSet = getBrushes(); ArrayList<String> materials = new ArrayList<String>(materialsSet); if (materials.size() == 0) return; if (activeMaterial == null) { activeMaterial = materials.get(0).split("@")[0]; return; } int materialIndex = 0; for (int i = 0; i < materials.size(); i++) { if (materials.get(i).split("@")[0].equals(activeMaterial)) { materialIndex = i; break; } } materialIndex = (materialIndex + 1) % materials.size(); activateBrush(materials.get(materialIndex).split("@")[0]); } public boolean hasExperience() { return xpRegeneration > 0; } public Mage getActivePlayer() { return mage; } protected void clearInventories() { inventories.clear(); hotbar.clear(); } public Color getEffectColor() { return effectColor == null ? null : effectColor.getColor(); } public Inventory getHotbar() { return hotbar; } public WandMode getMode() { return mode != null ? mode : controller.getDefaultWandMode(); } public void setMode(WandMode mode) { this.mode = mode; } public boolean showCastMessages() { return quietLevel == 0; } public boolean showMessages() { return quietLevel < 2; } /* * Public API Implementation */ public String getId() { return this.id; } @Override public void activate(com.elmakers.mine.bukkit.api.magic.Mage mage) { Player player = mage.getPlayer(); if (!Wand.hasActiveWand(player)) { controller.getLogger().warning("Wand activated without holding a wand!"); try { throw new Exception("Wand activated without holding a wand!"); } catch (Exception ex) { ex.printStackTrace(); } return; } if (!canUse(player)) { mage.sendMessage(Messages.get("wand.bound").replace("$name", owner)); player.setItemInHand(null); Location location = player.getLocation(); location.setY(location.getY() + 1); Item droppedItem = player.getWorld().dropItemNaturally(location, item); Vector velocity = droppedItem.getVelocity(); velocity.setY(velocity.getY() * 2 + 1); droppedItem.setVelocity(velocity); return; } if (mage instanceof Mage) { activate((Mage)mage, player.getItemInHand()); } } @Override public void organizeInventory(com.elmakers.mine.bukkit.api.magic.Mage mage) { WandOrganizer organizer = new WandOrganizer(this, mage); organizer.organize(); openInventoryPage = 0; autoOrganize = false; saveState(); } @Override public com.elmakers.mine.bukkit.api.wand.Wand duplicate() { ItemStack newItem = InventoryUtils.getCopy(item); Wand newWand = new Wand(controller, newItem); newWand.generateId(); newWand.saveState(); return newWand; } @Override public boolean configure(Map<String, Object> properties) { Map<Object, Object> convertedProperties = new HashMap<Object, Object>(properties); loadProperties(ConfigurationUtils.toNodeList(convertedProperties), false); // TODO: Detect changes return true; } @Override public boolean upgrade(Map<String, Object> properties) { Map<Object, Object> convertedProperties = new HashMap<Object, Object>(properties); loadProperties(ConfigurationUtils.toNodeList(convertedProperties), true); // TODO: Detect changes return true; } @Override public boolean isLocked() { return this.locked; } @Override public boolean canUse(Player player) { if (!bound || owner == null || owner.length() == 0) return true; if (controller.hasPermission(player, "Magic.wand.override_bind", false)) return true; return owner.equalsIgnoreCase(player.getName()); } public boolean addSpell(String spellName) { if (!isModifiable()) return false; if (hasSpell(spellName)) return false; if (isInventoryOpen()) { saveInventory(); } ItemStack spellItem = createSpellIcon(spellName); if (spellItem == null) { controller.getPlugin().getLogger().info("Unknown spell: " + spellName); return false; } addToInventory(spellItem); updateInventory(); hasInventory = getSpells().size() + getBrushes().size() > 1; updateLore(); saveState(); return true; } @Override public boolean add(com.elmakers.mine.bukkit.api.wand.Wand other) { if (other instanceof Wand) { return add((Wand)other); } return false; } @Override public boolean hasBrush(String materialKey) { return getBrushes().contains(materialKey); } @Override public boolean hasSpell(String spellName) { return getSpells().contains(spellName); } @Override public boolean addBrush(String materialKey) { if (!isModifiable()) return false; if (hasBrush(materialKey)) return false; ItemStack itemStack = createBrushIcon(materialKey); if (itemStack == null) return false; addToInventory(itemStack); if (activeMaterial == null || activeMaterial.length() == 0) { setActiveBrush(materialKey); } else { updateInventory(); } updateLore(); saveState(); hasInventory = getSpells().size() + getBrushes().size() > 1; return true; } @Override public void setActiveBrush(String materialKey) { this.activeMaterial = materialKey; updateName(); updateActiveMaterial(); updateInventory(); saveState(); } @Override public void setActiveSpell(String activeSpell) { this.activeSpell = activeSpell; updateName(); updateInventory(); saveState(); } @Override public boolean removeBrush(String materialKey) { if (!isModifiable() || materialKey == null) return false; if (isInventoryOpen()) { saveInventory(); } if (materialKey.equals(activeMaterial)) { activeMaterial = null; } List<Inventory> allInventories = getAllInventories(); boolean found = false; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int index = 0; index < items.length; index++) { ItemStack itemStack = items[index]; if (itemStack != null && isBrush(itemStack)) { String itemKey = getBrush(itemStack); if (itemKey.equals(materialKey)) { found = true; inventory.setItem(index, null); } else if (activeMaterial == null) { activeMaterial = materialKey; } if (found && activeMaterial != null) { break; } } } } updateActiveMaterial(); updateInventory(); updateName(); updateLore(); saveState(); if (isInventoryOpen()) { updateInventory(); } return found; } @Override public boolean removeSpell(String spellName) { if (!isModifiable()) return false; if (isInventoryOpen()) { saveInventory(); } if (spellName.equals(activeSpell)) { activeSpell = null; } List<Inventory> allInventories = getAllInventories(); boolean found = false; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int index = 0; index < items.length; index++) { ItemStack itemStack = items[index]; if (itemStack != null && itemStack.getType() != Material.AIR && !isWand(itemStack) && isSpell(itemStack)) { if (getSpell(itemStack).equals(spellName)) { found = true; inventory.setItem(index, null); } else if (activeSpell == null) { activeSpell = getSpell(itemStack); } if (found && activeSpell != null) { break; } } } } updateName(); updateLore(); saveState(); updateInventory(); return found; } }
src/main/java/com/elmakers/mine/bukkit/wand/Wand.java
package com.elmakers.mine.bukkit.wand; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.block.BlockFace; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerExpChangeEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.Vector; import com.elmakers.mine.bukkit.api.effect.ParticleType; import com.elmakers.mine.bukkit.api.spell.CastingCost; import com.elmakers.mine.bukkit.api.spell.CostReducer; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.api.spell.SpellCategory; import com.elmakers.mine.bukkit.api.spell.SpellTemplate; import com.elmakers.mine.bukkit.block.MaterialAndData; import com.elmakers.mine.bukkit.block.MaterialBrush; import com.elmakers.mine.bukkit.effect.builtin.EffectRing; import com.elmakers.mine.bukkit.magic.Mage; import com.elmakers.mine.bukkit.magic.MagicController; import com.elmakers.mine.bukkit.spell.BrushSpell; import com.elmakers.mine.bukkit.spell.UndoableSpell; import com.elmakers.mine.bukkit.utility.ColorHD; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; import com.elmakers.mine.bukkit.utility.InventoryUtils; import com.elmakers.mine.bukkit.utility.Messages; public class Wand implements CostReducer, com.elmakers.mine.bukkit.api.wand.Wand { public final static int INVENTORY_SIZE = 27; public final static int HOTBAR_SIZE = 9; public final static float DEFAULT_SPELL_COLOR_MIX_WEIGHT = 0.0001f; public final static float DEFAULT_WAND_COLOR_MIX_WEIGHT = 1.0f; // REMEMBER! Each of these MUST have a corresponding class in .traders, else traders will // destroy the corresponding data. public final static String[] PROPERTY_KEYS = { "active_spell", "active_material", "xp", "xp_regeneration", "xp_max", "bound", "uses", "upgrade", "indestructible", "cost_reduction", "cooldown_reduction", "effect_bubbles", "effect_color", "effect_particle", "effect_particle_count", "effect_particle_data", "effect_particle_interval", "effect_sound", "effect_sound_interval", "effect_sound_pitch", "effect_sound_volume", "haste", "health_regeneration", "hunger_regeneration", "icon", "mode", "keep", "locked", "quiet", "power", "protection", "protection_physical", "protection_projectiles", "protection_falling", "protection_fire", "protection_explosions", "materials", "spells" }; public final static String[] HIDDEN_PROPERTY_KEYS = { "id", "owner", "name", "description", "template", "organize", "fill" }; public final static String[] ALL_PROPERTY_KEYS = (String[])ArrayUtils.addAll(PROPERTY_KEYS, HIDDEN_PROPERTY_KEYS); protected ItemStack item; protected MagicController controller; protected Mage mage; // Cached state private String id = ""; private Inventory hotbar; private List<Inventory> inventories; private String activeSpell = ""; private String activeMaterial = ""; protected String wandName = ""; protected String description = ""; private String owner = ""; private String template = ""; private boolean bound = false; private boolean indestructible = false; private boolean keep = false; private boolean autoOrganize = false; private boolean autoFill = false; private boolean isUpgrade = false; private MaterialAndData icon = null; private float costReduction = 0; private float cooldownReduction = 0; private float damageReduction = 0; private float damageReductionPhysical = 0; private float damageReductionProjectiles = 0; private float damageReductionFalling = 0; private float damageReductionFire = 0; private float damageReductionExplosions = 0; private float power = 0; private boolean hasInventory = false; private boolean locked = false; private int uses = 0; private int xp = 0; private int xpRegeneration = 0; private int xpMax = 0; private float healthRegeneration = 0; private PotionEffect healthRegenEffect = null; private float hungerRegeneration = 0; private PotionEffect hungerRegenEffect = null; private ColorHD effectColor = null; private float effectColorSpellMixWeight = DEFAULT_SPELL_COLOR_MIX_WEIGHT; private float effectColorMixWeight = DEFAULT_WAND_COLOR_MIX_WEIGHT; private ParticleType effectParticle = null; private float effectParticleData = 0; private int effectParticleCount = 0; private int effectParticleInterval = 0; private int effectParticleCounter = 0; private boolean effectBubbles = false; private EffectRing effectPlayer = null; private Sound effectSound = null; private int effectSoundInterval = 0; private int effectSoundCounter = 0; private float effectSoundVolume = 0; private float effectSoundPitch = 0; private float speedIncrease = 0; private PotionEffect hasteEffect = null; private int storedXpLevel = 0; private int storedXp = 0; private float storedXpProgress = 0; private int quietLevel = 0; // Inventory functionality private WandMode mode = null; private int openInventoryPage = 0; private boolean inventoryIsOpen = false; private Inventory displayInventory = null; // Kinda of a hacky initialization optimization :\ private boolean suspendSave = false; // Wand configurations protected static Map<String, ConfigurationSection> wandTemplates = new HashMap<String, ConfigurationSection>(); public static boolean displayManaAsBar = true; public static boolean retainLevelDisplay = true; public static Material DefaultUpgradeMaterial = Material.NETHER_STAR; public static Material DefaultWandMaterial = Material.BLAZE_ROD; public static Material EnchantableWandMaterial = null; public static boolean EnableGlow = true; public Wand(MagicController controller, ItemStack itemStack) { this.controller = controller; hotbar = InventoryUtils.createInventory(null, 9, "Wand"); this.icon = new MaterialAndData(itemStack.getType(), (byte)itemStack.getDurability()); inventories = new ArrayList<Inventory>(); item = itemStack; indestructible = controller.getIndestructibleWands(); loadState(); } public Wand(MagicController controller) { this(controller, DefaultWandMaterial, (short)0); } protected Wand(MagicController controller, String templateName) throws IllegalArgumentException { this(controller); suspendSave = true; String wandName = Messages.get("wand.default_name"); String wandDescription = ""; // Check for default wand if ((templateName == null || templateName.length() == 0) && wandTemplates.containsKey("default")) { templateName = "default"; } // See if there is a template with this key if (templateName != null && templateName.length() > 0) { if ((templateName.equals("random") || templateName.startsWith("random(")) && wandTemplates.containsKey("random")) { int level = 1; if (!templateName.equals("random")) { String randomLevel = templateName.substring(templateName.indexOf('(') + 1, templateName.length() - 1); level = Integer.parseInt(randomLevel); } ConfigurationSection randomTemplate = wandTemplates.get("random"); randomize(level, false); // Random wands take a few properties from the "random" template locked = (boolean)randomTemplate.getBoolean("locked", false); setEffectColor(randomTemplate.getString("effect_color")); suspendSave = false; saveState(); return; } if (!wandTemplates.containsKey(templateName)) { throw new IllegalArgumentException("No template named " + templateName); } ConfigurationSection wandConfig = wandTemplates.get(templateName); // Default to localized names wandName = Messages.get("wands." + templateName + ".name", wandName); wandDescription = Messages.get("wands." + templateName + ".description", wandDescription); // Load all properties loadProperties(wandConfig); } setDescription(wandDescription); setName(wandName); setTemplate(templateName); suspendSave = false; generateId(); saveState(); } public Wand(MagicController controller, Material icon, short iconData) { // This will make the Bukkit ItemStack into a real ItemStack with NBT data. this(controller, InventoryUtils.getCopy(new ItemStack(icon, 1, iconData))); wandName = Messages.get("wand.default_name"); updateName(); if (EnableGlow) { InventoryUtils.addGlow(item); } generateId(); saveState(); } protected void generateId() { id = UUID.randomUUID().toString(); } public void unenchant() { item = new ItemStack(item.getType(), 1, (short)item.getDurability()); } public void setIcon(Material material, byte data) { setIcon(material == null ? null : new MaterialAndData(material, data)); } public void setIcon(MaterialAndData materialData) { icon = materialData; if (icon != null) { item.setType(icon.getMaterial()); item.setDurability(icon.getData()); } } public void makeUpgrade() { isUpgrade = true; wandName = Messages.get("wand.upgrade_name"); description = Messages.get("wand.upgrade_default_description"); setIcon(DefaultUpgradeMaterial, (byte)0); saveState(); updateName(true); updateLore(); } protected void activateBrush(String materialKey) { setActiveBrush(materialKey); if (materialKey != null) { com.elmakers.mine.bukkit.api.block.MaterialBrush brush = mage.getBrush(); if (brush != null) { brush.activate(mage.getLocation(), materialKey); } } } public void activateBrush(ItemStack itemStack) { if (!isBrush(itemStack)) return; activateBrush(getBrush(itemStack)); } public int getXpRegeneration() { return xpRegeneration; } public int getXpMax() { return xpMax; } public int getExperience() { return xp; } public void removeExperience(int amount) { xp = Math.max(0, xp - amount); updateMana(); } public float getHealthRegeneration() { return healthRegeneration; } public float getHungerRegeneration() { return hungerRegeneration; } public boolean isModifiable() { return !locked; } public boolean isIndestructible() { return indestructible; } public boolean isUpgrade() { return isUpgrade; } public boolean usesMana() { return xpMax > 0 && xpRegeneration > 0 && !isCostFree(); } public float getCooldownReduction() { return controller.getCooldownReduction() + cooldownReduction * WandLevel.maxCooldownReduction; } public float getCostReduction() { if (isCostFree()) return 1.0f; return controller.getCostReduction() + costReduction * WandLevel.maxCostReduction; } public void setCooldownReduction(float reduction) { cooldownReduction = reduction; } public boolean getHasInventory() { return hasInventory; } public float getPower() { return power; } public boolean isSuperProtected() { return damageReduction > 1; } public boolean isSuperPowered() { return power > 1; } public boolean isCostFree() { return costReduction > 1; } public boolean isCooldownFree() { return cooldownReduction > 1; } public float getDamageReduction() { return damageReduction * WandLevel.maxDamageReduction; } public float getDamageReductionPhysical() { return damageReductionPhysical * WandLevel.maxDamageReductionPhysical; } public float getDamageReductionProjectiles() { return damageReductionProjectiles * WandLevel.maxDamageReductionProjectiles; } public float getDamageReductionFalling() { return damageReductionFalling * WandLevel.maxDamageReductionFalling; } public float getDamageReductionFire() { return damageReductionFire * WandLevel.maxDamageReductionFire; } public float getDamageReductionExplosions() { return damageReductionExplosions * WandLevel.maxDamageReductionExplosions; } public int getUses() { return uses; } public String getName() { return wandName; } public String getDescription() { return description; } public String getOwner() { return owner; } public void setName(String name) { wandName = ChatColor.stripColor(name); updateName(); } public void setTemplate(String templateName) { this.template = templateName; } public String getTemplate() { return this.template; } public void setDescription(String description) { this.description = description; updateLore(); } public void tryToOwn(Player player) { if (owner == null || owner.length() == 0) { takeOwnership(player); } } protected void takeOwnership(Player player) { owner = player.getName(); if (controller != null && controller.bindWands()) { bound = true; } if (controller != null && controller.keepWands()) { keep = true; } updateLore(); } public ItemStack getItem() { return item; } protected List<Inventory> getAllInventories() { List<Inventory> allInventories = new ArrayList<Inventory>(inventories.size() + 1); allInventories.add(hotbar); allInventories.addAll(inventories); return allInventories; } public Set<String> getSpells() { return getSpells(false); } protected Set<String> getSpells(boolean includePositions) { Set<String> spellNames = new TreeSet<String>(); List<Inventory> allInventories = getAllInventories(); int index = 0; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int i = 0; i < items.length; i++) { if (items[i] != null && !isWand(items[i])) { if (isSpell(items[i])) { String spellName = getSpell(items[i]); if (includePositions) { spellName += "@" + index; } spellNames.add(spellName); } } index++; } } return spellNames; } protected String getSpellString() { return StringUtils.join(getSpells(true), ","); } public Set<String> getBrushes() { return getMaterialKeys(false); } protected Set<String> getMaterialKeys(boolean includePositions) { Set<String> materialNames = new TreeSet<String>(); List<Inventory> allInventories = new ArrayList<Inventory>(inventories.size() + 1); allInventories.add(hotbar); allInventories.addAll(inventories); Integer index = 0; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int i = 0; i < items.length; i++) { String materialKey = getMaterialKey(items[i], includePositions ? index : null); if (materialKey != null) { materialNames.add(materialKey); } index++; } } return materialNames; } protected String getMaterialString() { return StringUtils.join(getMaterialKeys(true), ","); } protected Integer parseSlot(String[] pieces) { Integer slot = null; if (pieces.length > 0) { try { slot = Integer.parseInt(pieces[1]); } catch (Exception ex) { slot = null; } if (slot != null && slot < 0) { slot = null; } } return slot; } protected void addToInventory(ItemStack itemStack) { // Set the wand item WandMode wandMode = getMode(); Integer selectedItem = null; if (wandMode == WandMode.INVENTORY) { if (mage != null && mage.getPlayer() != null) { selectedItem = mage.getPlayer().getInventory().getHeldItemSlot(); hotbar.setItem(selectedItem, item); } } List<Inventory> checkInventories = wandMode == WandMode.INVENTORY ? getAllInventories() : inventories; boolean added = false; for (Inventory inventory : checkInventories) { HashMap<Integer, ItemStack> returned = inventory.addItem(itemStack); if (returned.size() == 0) { added = true; break; } } if (!added) { Inventory newInventory = InventoryUtils.createInventory(null, INVENTORY_SIZE, "Wand"); newInventory.addItem(itemStack); inventories.add(newInventory); } // Restore empty wand slot if (selectedItem != null) { hotbar.setItem(selectedItem, null); } } protected Inventory getDisplayInventory() { if (displayInventory == null) { displayInventory = InventoryUtils.createInventory(null, INVENTORY_SIZE + HOTBAR_SIZE, "Wand"); } return displayInventory; } protected Inventory getInventoryByIndex(int inventoryIndex) { while (inventoryIndex >= inventories.size()) { inventories.add(InventoryUtils.createInventory(null, INVENTORY_SIZE, "Wand")); } return inventories.get(inventoryIndex); } protected Inventory getInventory(Integer slot) { Inventory inventory = hotbar; if (slot >= HOTBAR_SIZE) { int inventoryIndex = (slot - HOTBAR_SIZE) / INVENTORY_SIZE; inventory = getInventoryByIndex(inventoryIndex); } return inventory; } protected int getInventorySlot(Integer slot) { if (slot < HOTBAR_SIZE) { return slot; } return ((slot - HOTBAR_SIZE) % INVENTORY_SIZE); } protected void addToInventory(ItemStack itemStack, Integer slot) { if (slot == null) { addToInventory(itemStack); return; } Inventory inventory = getInventory(slot); slot = getInventorySlot(slot); ItemStack existing = inventory.getItem(slot); inventory.setItem(slot, itemStack); if (existing != null && existing.getType() != Material.AIR) { addToInventory(existing); } } protected void parseInventoryStrings(String spellString, String materialString) { hotbar.clear(); inventories.clear(); // Support YML-List-As-String format and |-delimited format spellString = spellString.replaceAll("[\\]\\[]", ""); String[] spellNames = StringUtils.split(spellString, "|,"); for (String spellName : spellNames) { String[] pieces = spellName.split("@"); Integer slot = parseSlot(pieces); String spellKey = pieces[0].trim(); ItemStack itemStack = createSpellIcon(spellKey); if (itemStack == null) { controller.getPlugin().getLogger().warning("Unable to create spell icon for key " + spellKey); continue; } if (activeSpell == null || activeSpell.length() == 0) activeSpell = spellKey; addToInventory(itemStack, slot); } materialString = materialString.replaceAll("[\\]\\[]", ""); String[] materialNames = StringUtils.split(materialString, "|,"); for (String materialName : materialNames) { String[] pieces = materialName.split("@"); Integer slot = parseSlot(pieces); String materialKey = pieces[0].trim(); ItemStack itemStack = createBrushIcon(materialKey); if (itemStack == null) { controller.getPlugin().getLogger().warning("Unable to create material icon for key " + materialKey); continue; } if (activeMaterial == null || activeMaterial.length() == 0) activeMaterial = materialKey; addToInventory(itemStack, slot); } hasInventory = spellNames.length + materialNames.length > 1; } @SuppressWarnings("deprecation") public static ItemStack createSpellItem(String spellKey, MagicController controller, Wand wand, boolean isItem) { SpellTemplate spell = controller.getSpellTemplate(spellKey); if (spell == null) return null; com.elmakers.mine.bukkit.api.block.MaterialAndData icon = spell.getIcon(); if (icon == null) { controller.getPlugin().getLogger().warning("Unable to create spell icon for " + spell.getName() + ", missing material"); return null; } ItemStack itemStack = null; ItemStack originalItemStack = null; try { originalItemStack = new ItemStack(icon.getMaterial(), 1, (short)0, (byte)icon.getData()); itemStack = InventoryUtils.getCopy(originalItemStack); } catch (Exception ex) { itemStack = null; } if (itemStack == null) { controller.getPlugin().getLogger().warning("Unable to create spell icon for " + spellKey + " with material " + icon.getMaterial().name()); return originalItemStack; } updateSpellItem(itemStack, spell, wand, wand == null ? null : wand.activeMaterial, isItem); return itemStack; } protected ItemStack createSpellIcon(String spellKey) { return createSpellItem(spellKey, controller, this, false); } private String getActiveWandName(String materialKey) { SpellTemplate spell = controller.getSpellTemplate(activeSpell); return getActiveWandName(spell, materialKey); } protected ItemStack createBrushIcon(String materialKey) { return createBrushItem(materialKey, controller, this, false); } @SuppressWarnings("deprecation") public static ItemStack createBrushItem(String materialKey, MagicController controller, Wand wand, boolean isItem) { MaterialAndData brushData = MaterialBrush.parseMaterialKey(materialKey, false); if (brushData == null) return null; Material material = brushData.getMaterial(); if (material == null || material == Material.AIR) { return null; } byte dataId = brushData.getData(); ItemStack originalItemStack = new ItemStack(material, 1, (short)0, (byte)dataId); ItemStack itemStack = InventoryUtils.getCopy(originalItemStack); if (itemStack == null) { controller.getPlugin().getLogger().warning("Unable to create material icon for " + material.name() + ": " + materialKey); return null; } ItemMeta meta = itemStack.getItemMeta(); List<String> lore = new ArrayList<String>(); if (material != null) { lore.add(ChatColor.GRAY + Messages.get("wand.building_material_info").replace("$material", MaterialBrush.getMaterialName(materialKey))); if (material == MaterialBrush.EraseMaterial) { lore.add(Messages.get("wand.erase_material_description")); } else if (material == MaterialBrush.CopyMaterial) { lore.add(Messages.get("wand.copy_material_description")); } else if (material == MaterialBrush.CloneMaterial) { lore.add(Messages.get("wand.clone_material_description")); } else if (material == MaterialBrush.ReplicateMaterial) { lore.add(Messages.get("wand.replicate_material_description")); } else if (material == MaterialBrush.MapMaterial) { lore.add(Messages.get("wand.map_material_description")); } else if (material == MaterialBrush.SchematicMaterial) { lore.add(Messages.get("wand.schematic_material_description").replace("$schematic", brushData.getCustomName())); } else { lore.add(ChatColor.LIGHT_PURPLE + Messages.get("wand.building_material_description")); } } if (isItem) { lore.add(ChatColor.YELLOW + Messages.get("wand.brush_item_description")); } meta.setLore(lore); itemStack.setItemMeta(meta); updateBrushItem(itemStack, materialKey, wand); return itemStack; } protected void saveState() { if (suspendSave || item == null) return; if (id == null || id.length() == 0) { generateId(); } Object wandNode = InventoryUtils.createNode(item, "wand"); if (wandNode == null) { controller.getLogger().warning("Failed to save wand state for wand id " + id + " to : " + item + " of class " + item.getClass()); return; } ConfigurationSection stateNode = new MemoryConfiguration(); saveProperties(stateNode); InventoryUtils.saveTagsToNBT(stateNode, wandNode, ALL_PROPERTY_KEYS); } protected void loadState() { if (item == null) return; Object wandNode = InventoryUtils.getNode(item, "wand"); if (wandNode == null) { return; } ConfigurationSection stateNode = new MemoryConfiguration(); InventoryUtils.loadTagsFromNBT(stateNode, wandNode, ALL_PROPERTY_KEYS); loadProperties(stateNode); } public void saveProperties(ConfigurationSection node) { node.set("id", id); node.set("materials", getMaterialString()); node.set("spells", getSpellString()); node.set("active_spell", activeSpell); node.set("active_material", activeMaterial); node.set("name", wandName); node.set("description", description); node.set("owner", owner); node.set("cost_reduction", costReduction); node.set("cooldown_reduction", cooldownReduction); node.set("power", power); node.set("protection", damageReduction); node.set("protection_physical", damageReductionPhysical); node.set("protection_projectiles", damageReductionProjectiles); node.set("protection_falling", damageReductionFalling); node.set("protection_fire", damageReductionFire); node.set("protection_explosions", damageReductionExplosions); node.set("haste", speedIncrease); node.set("xp", xp); node.set("xp_regeneration", xpRegeneration); node.set("xp_max", xpMax); node.set("health_regeneration", healthRegeneration); node.set("hunger_regeneration", hungerRegeneration); node.set("uses", uses); node.set("locked", locked); node.set("effect_color", effectColor == null ? "none" : effectColor.toString()); node.set("effect_bubbles", effectBubbles); node.set("effect_particle_data", Float.toString(effectParticleData)); node.set("effect_particle_count", effectParticleCount); node.set("effect_particle_interval", effectParticleInterval); node.set("effect_sound_interval", effectSoundInterval); node.set("effect_sound_volume", Float.toString(effectSoundVolume)); node.set("effect_sound_pitch", Float.toString(effectSoundPitch)); node.set("quiet", quietLevel); node.set("keep", keep); node.set("bound", bound); node.set("indestructible", indestructible); node.set("fill", autoFill); node.set("upgrade", isUpgrade); node.set("organize", autoOrganize); if (effectSound != null) { node.set("effect_sound", effectSound.name()); } else { node.set("effectSound", null); } if (effectParticle != null) { node.set("effect_particle", effectParticle.name()); } else { node.set("effect_particle", null); } if (mode != null) { node.set("mode", mode.name()); } else { node.set("mode", null); } if (icon != null) { String iconKey = MaterialBrush.getMaterialKey(icon); if (iconKey != null && iconKey.length() > 0) { node.set("icon", iconKey); } else { node.set("icon", null); } } else { node.set("icon", null); } if (template != null && template.length() > 0) { node.set("template", template); } else { node.set("template", null); } } public void loadProperties(ConfigurationSection wandConfig) { loadProperties(wandConfig, false); } public void setEffectColor(String hexColor) { if (hexColor == null || hexColor.length() == 0 || hexColor.equals("none")) { effectColor = null; return; } effectColor = new ColorHD(hexColor); } public void loadProperties(ConfigurationSection wandConfig, boolean safe) { locked = (boolean)wandConfig.getBoolean("locked", locked); float _costReduction = (float)wandConfig.getDouble("cost_reduction", costReduction); costReduction = safe ? Math.max(_costReduction, costReduction) : _costReduction; float _cooldownReduction = (float)wandConfig.getDouble("cooldown_reduction", cooldownReduction); cooldownReduction = safe ? Math.max(_cooldownReduction, cooldownReduction) : _cooldownReduction; float _power = (float)wandConfig.getDouble("power", power); power = safe ? Math.max(_power, power) : _power; float _damageReduction = (float)wandConfig.getDouble("protection", damageReduction); damageReduction = safe ? Math.max(_damageReduction, damageReduction) : _damageReduction; float _damageReductionPhysical = (float)wandConfig.getDouble("protection_physical", damageReductionPhysical); damageReductionPhysical = safe ? Math.max(_damageReductionPhysical, damageReductionPhysical) : _damageReductionPhysical; float _damageReductionProjectiles = (float)wandConfig.getDouble("protection_projectiles", damageReductionProjectiles); damageReductionProjectiles = safe ? Math.max(_damageReductionProjectiles, damageReductionPhysical) : _damageReductionProjectiles; float _damageReductionFalling = (float)wandConfig.getDouble("protection_falling", damageReductionFalling); damageReductionFalling = safe ? Math.max(_damageReductionFalling, damageReductionFalling) : _damageReductionFalling; float _damageReductionFire = (float)wandConfig.getDouble("protection_fire", damageReductionFire); damageReductionFire = safe ? Math.max(_damageReductionFire, damageReductionFire) : _damageReductionFire; float _damageReductionExplosions = (float)wandConfig.getDouble("protection_explosions", damageReductionExplosions); damageReductionExplosions = safe ? Math.max(_damageReductionExplosions, damageReductionExplosions) : _damageReductionExplosions; int _xpRegeneration = wandConfig.getInt("xp_regeneration", xpRegeneration); xpRegeneration = safe ? Math.max(_xpRegeneration, xpRegeneration) : _xpRegeneration; int _xpMax = wandConfig.getInt("xp_max", xpMax); xpMax = safe ? Math.max(_xpMax, xpMax) : _xpMax; int _xp = wandConfig.getInt("xp", xp); xp = safe ? Math.max(_xp, xp) : _xp; float _healthRegeneration = (float)wandConfig.getDouble("health_regeneration", healthRegeneration); healthRegeneration = safe ? Math.max(_healthRegeneration, healthRegeneration) : _healthRegeneration; float _hungerRegeneration = (float)wandConfig.getDouble("hunger_regeneration", hungerRegeneration); hungerRegeneration = safe ? Math.max(_hungerRegeneration, hungerRegeneration) : _hungerRegeneration; int _uses = wandConfig.getInt("uses", uses); uses = safe ? Math.max(_uses, uses) : _uses; float _speedIncrease = (float)wandConfig.getDouble("haste", speedIncrease); speedIncrease = safe ? Math.max(_speedIncrease, speedIncrease) : _speedIncrease; if (wandConfig.contains("effect_color") && !safe) { setEffectColor(wandConfig.getString("effect_color")); } // Don't change any of this stuff in safe mode if (!safe) { id = wandConfig.getString("id", id); if (id == null) id = ""; quietLevel = wandConfig.getInt("quiet", quietLevel); effectBubbles = wandConfig.getBoolean("effect_bubbles", effectBubbles); keep = wandConfig.getBoolean("keep", keep); indestructible = wandConfig.getBoolean("indestructible", indestructible); bound = wandConfig.getBoolean("bound", bound); autoOrganize = wandConfig.getBoolean("organize", autoOrganize); autoFill = wandConfig.getBoolean("fill", autoFill); isUpgrade = wandConfig.getBoolean("upgrade", isUpgrade); if (wandConfig.contains("effect_particle")) { parseParticleEffect(wandConfig.getString("effect_particle")); effectParticleData = 0; } if (wandConfig.contains("effect_sound")) { parseSoundEffect(wandConfig.getString("effect_sound")); } effectParticleData = (float)wandConfig.getDouble("effect_particle_data", effectParticleData); effectParticleCount = wandConfig.getInt("effect_particle_count", effectParticleCount); effectParticleInterval = wandConfig.getInt("effect_particle_interval", effectParticleInterval); effectSoundInterval = wandConfig.getInt("effect_sound_interval", effectSoundInterval); effectSoundVolume = (float)wandConfig.getDouble("effect_sound_volume", effectSoundVolume); effectSoundPitch = (float)wandConfig.getDouble("effect_sound_pitch", effectSoundPitch); setMode(parseWandMode(wandConfig.getString("mode"), mode)); owner = wandConfig.getString("owner", owner); wandName = wandConfig.getString("name", wandName); description = wandConfig.getString("description", description); template = wandConfig.getString("template", template); activeSpell = wandConfig.getString("active_spell", activeSpell); activeMaterial = wandConfig.getString("active_material", activeMaterial); String wandMaterials = wandConfig.getString("materials", ""); String wandSpells = wandConfig.getString("spells", ""); if (wandMaterials.length() > 0 || wandSpells.length() > 0) { wandMaterials = wandMaterials.length() == 0 ? getMaterialString() : wandMaterials; wandSpells = wandSpells.length() == 0 ? getSpellString() : wandSpells; parseInventoryStrings(wandSpells, wandMaterials); } if (wandConfig.contains("icon")) { setIcon(ConfigurationUtils.getMaterialAndData(wandConfig, "icon")); } } // Some cleanup and sanity checks. In theory we don't need to store any non-zero value (as it is with the traders) // so try to keep defaults as 0/0.0/false. if (effectSound == null) { effectSoundInterval = 0; effectSoundVolume = 0; effectSoundPitch = 0; } else { effectSoundInterval = (effectSoundInterval == 0) ? 5 : effectSoundInterval; effectSoundVolume = (effectSoundVolume < 0.01f) ? 0.8f : effectSoundVolume; effectSoundPitch = (effectSoundPitch < 0.01f) ? 1.1f : effectSoundPitch; } if (effectParticle == null) { effectParticleInterval = 0; } else { effectParticleInterval = (effectParticleInterval == 0) ? 2 : effectParticleInterval; effectParticleCount = (effectParticleCount == 0) ? 1 : effectParticleCount; } if (xpRegeneration <= 0 || xpMax <= 0 || costReduction >= 1) { xpMax = 0; xpRegeneration = 0; xp = 0; } checkActiveMaterial(); saveState(); updateName(); updateLore(); } protected void parseSoundEffect(String effectSoundName) { if (effectSoundName.length() > 0) { String testName = effectSoundName.toUpperCase().replace("_", ""); try { for (Sound testType : Sound.values()) { String testTypeName = testType.name().replace("_", ""); if (testTypeName.equals(testName)) { effectSound = testType; break; } } } catch (Exception ex) { effectSound = null; } } else { effectSound = null; } } protected void parseParticleEffect(String effectParticleName) { if (effectParticleName.length() > 0) { String testName = effectParticleName.toUpperCase().replace("_", ""); try { for (ParticleType testType : ParticleType.values()) { String testTypeName = testType.name().replace("_", ""); if (testTypeName.equals(testName)) { effectParticle = testType; break; } } } catch (Exception ex) { effectParticle = null; } } else { effectParticle = null; } } public void describe(CommandSender sender) { Object wandNode = InventoryUtils.getNode(item, "wand"); if (wandNode == null) { sender.sendMessage("Found a wand with missing NBT data. This may be an old wand, or something may have wiped its data"); return; } ChatColor wandColor = isModifiable() ? ChatColor.AQUA : ChatColor.RED; sender.sendMessage(wandColor + wandName); if (description.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + description); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + "(No Description)"); } if (owner.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + owner); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + "(No Owner)"); } for (String key : PROPERTY_KEYS) { String value = InventoryUtils.getMeta(wandNode, key); if (value != null && value.length() > 0) { sender.sendMessage(key + ": " + value); } } } private static String getSpellDisplayName(SpellTemplate spell, String materialKey) { String name = ""; if (spell != null) { if (materialKey != null && (spell instanceof BrushSpell) && !((BrushSpell)spell).hasBrushOverride()) { String materialName = MaterialBrush.getMaterialName(materialKey); if (materialName == null) { materialName = "none"; } name = ChatColor.GOLD + spell.getName() + ChatColor.GRAY + " " + materialName + ChatColor.WHITE; } else { name = ChatColor.GOLD + spell.getName() + ChatColor.WHITE; } } return name; } private String getActiveWandName(SpellTemplate spell, String materialKey) { // Build wand name ChatColor wandColor = isModifiable() ? (bound ? ChatColor.DARK_AQUA : ChatColor.AQUA) : ChatColor.RED; String name = wandColor + wandName; // Add active spell to description if (spell != null) { name = getSpellDisplayName(spell, materialKey) + " (" + name + ChatColor.WHITE + ")"; } int remaining = getRemainingUses(); if (remaining > 0) { String message = (remaining == 1) ? Messages.get("wand.uses_remaining_singular") : Messages.get("wand.uses_remaining_brief"); name = name + " (" + ChatColor.RED + message.replace("$count", ((Integer)remaining).toString()) + ")"; } return name; } private String getActiveWandName(SpellTemplate spell) { return getActiveWandName(spell, activeMaterial); } private String getActiveWandName() { SpellTemplate spell = null; if (hasInventory && activeSpell != null && activeSpell.length() > 0) { spell = controller.getSpellTemplate(activeSpell); } return getActiveWandName(spell); } public void updateName(boolean isActive) { ItemMeta meta = item.getItemMeta(); meta.setDisplayName(isActive ? getActiveWandName() : wandName); item.setItemMeta(meta); // Reset Enchantment glow if (EnableGlow) { InventoryUtils.addGlow(item); } // The all-important last step of restoring the meta state, something // the Anvil will blow away. saveState(); } private void updateName() { updateName(true); } protected static String convertToHTML(String line) { int tagCount = 1; line = "<span style=\"color:white\">" + line; for (ChatColor c : ChatColor.values()) { tagCount += StringUtils.countMatches(line, c.toString()); String replaceStyle = ""; if (c == ChatColor.ITALIC) { replaceStyle = "font-style: italic"; } else if (c == ChatColor.BOLD) { replaceStyle = "font-weight: bold"; } else if (c == ChatColor.UNDERLINE) { replaceStyle = "text-decoration: underline"; } else { String color = c.name().toLowerCase().replace("_", ""); if (c == ChatColor.LIGHT_PURPLE) { color = "mediumpurple"; } replaceStyle = "color:" + color; } line = line.replace(c.toString(), "<span style=\"" + replaceStyle + "\">"); } for (int i = 0; i < tagCount; i++) { line += "</span>"; } return line; } public String getHTMLDescription() { Collection<String> rawLore = getLore(); Collection<String> lore = new ArrayList<String>(); lore.add("<h2>" + convertToHTML(getActiveWandName()) + "</h2>"); for (String line : rawLore) { lore.add(convertToHTML(line)); } return "<div style=\"background-color: black; margin: 8px; padding: 8px\">" + StringUtils.join(lore, "<br/>") + "</div>"; } protected List<String> getLore() { return getLore(getSpells().size(), getBrushes().size()); } protected void addPropertyLore(List<String> lore) { if (usesMana()) { lore.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + getLevelString("wand.mana_amount", xpMax, WandLevel.maxMaxXp)); lore.add(ChatColor.RESET + "" + ChatColor.LIGHT_PURPLE + getLevelString("wand.mana_regeneration", xpRegeneration, WandLevel.maxXpRegeneration)); } if (costReduction > 0) lore.add(ChatColor.AQUA + getLevelString("wand.cost_reduction", costReduction)); if (cooldownReduction > 0) lore.add(ChatColor.AQUA + getLevelString("wand.cooldown_reduction", cooldownReduction)); if (power > 0) lore.add(ChatColor.AQUA + getLevelString("wand.power", power)); if (speedIncrease > 0) lore.add(ChatColor.AQUA + getLevelString("wand.haste", speedIncrease)); if (damageReduction > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection", damageReduction, WandLevel.maxDamageReduction)); if (damageReduction < 1) { if (damageReductionPhysical > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_physical", damageReductionPhysical, WandLevel.maxDamageReductionPhysical)); if (damageReductionProjectiles > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_projectile", damageReductionProjectiles, WandLevel.maxDamageReductionProjectiles)); if (damageReductionFalling > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_fall", damageReductionFalling, WandLevel.maxDamageReductionFalling)); if (damageReductionFire > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_fire", damageReductionFire, WandLevel.maxDamageReductionFire)); if (damageReductionExplosions > 0) lore.add(ChatColor.AQUA + getLevelString("wand.protection_blast", damageReductionExplosions, WandLevel.maxDamageReductionExplosions)); } if (healthRegeneration > 0) lore.add(ChatColor.AQUA + getLevelString("wand.health_regeneration", healthRegeneration)); if (hungerRegeneration > 0) lore.add(ChatColor.AQUA + getLevelString("wand.hunger_regeneration", hungerRegeneration)); } private String getLevelString(String templateName, float amount) { return getLevelString(templateName, amount, 1); } private static String getLevelString(String templateName, float amount, float max) { String templateString = Messages.get(templateName); if (templateString.contains("$roman")) { templateString = templateString.replace("$roman", getRomanString(amount)); } return templateString.replace("$amount", Integer.toString((int)amount)); } private static String getRomanString(float amount) { String roman = ""; if (amount > 1) { roman = Messages.get("wand.enchantment_level_max"); } else if (amount > 0.8) { roman = Messages.get("wand.enchantment_level_5"); } else if (amount > 0.6) { roman = Messages.get("wand.enchantment_level_4"); } else if (amount > 0.4) { roman = Messages.get("wand.enchantment_level_3"); } else if (amount > 0.2) { roman = Messages.get("wand.enchantment_level_2"); } else { roman = Messages.get("wand.enchantment_level_1"); } return roman; } protected List<String> getLore(int spellCount, int materialCount) { List<String> lore = new ArrayList<String>(); SpellTemplate spell = controller.getSpellTemplate(activeSpell); if (spell != null && spellCount == 1 && materialCount <= 1 && !isUpgrade) { addSpellLore(spell, lore, this); } else { if (description.length() > 0) { lore.add(ChatColor.ITALIC + "" + ChatColor.GREEN + description); } if (!isUpgrade) { if (owner.length() > 0) { if (bound) { String ownerDescription = Messages.get("wand.bound_description", "$name").replace("$name", owner); lore.add(ChatColor.ITALIC + "" + ChatColor.DARK_AQUA + ownerDescription); } else { String ownerDescription = Messages.get("wand.owner_description", "$name").replace("$name", owner); lore.add(ChatColor.ITALIC + "" + ChatColor.DARK_GREEN + ownerDescription); } } } if (spellCount > 0) { if (isUpgrade) { lore.add(Messages.get("wand.upgrade_spell_count").replace("$count", ((Integer)spellCount).toString())); } else { lore.add(Messages.get("wand.spell_count").replace("$count", ((Integer)spellCount).toString())); } } if (materialCount > 0) { if (isUpgrade) { lore.add(Messages.get("wand.material_count").replace("$count", ((Integer)materialCount).toString())); } else { lore.add(Messages.get("wand.upgrade_material_count").replace("$count", ((Integer)materialCount).toString())); } } } int remaining = getRemainingUses(); if (remaining > 0) { if (isUpgrade) { String message = (remaining == 1) ? Messages.get("wand.upgrade_uses_singular") : Messages.get("wand.upgrade_uses"); lore.add(ChatColor.RED + message.replace("$count", ((Integer)remaining).toString())); } else { String message = (remaining == 1) ? Messages.get("wand.uses_remaining_singular") : Messages.get("wand.uses_remaining_brief"); lore.add(ChatColor.RED + message.replace("$count", ((Integer)remaining).toString())); } } addPropertyLore(lore); if (isUpgrade) { lore.add(ChatColor.YELLOW + Messages.get("wand.upgrade_item_description")); } return lore; } protected void updateLore() { ItemMeta meta = item.getItemMeta(); List<String> lore = getLore(); meta.setLore(lore); item.setItemMeta(meta); if (EnableGlow) { InventoryUtils.addGlow(item); } // Setting lore will reset wand data saveState(); } public int getRemainingUses() { return uses; } public void makeEnchantable(boolean enchantable) { if (EnchantableWandMaterial == null) return; if (!enchantable) { item.setType(icon.getMaterial()); item.setDurability(icon.getData()); } else { Set<Material> enchantableMaterials = controller.getMaterialSet("enchantable"); if (!enchantableMaterials.contains(item.getType())) { item.setType(EnchantableWandMaterial); item.setDurability((short)0); } } updateName(); } public static boolean hasActiveWand(Player player) { if (player == null) return false; ItemStack activeItem = player.getInventory().getItemInHand(); return isWand(activeItem); } public static Wand getActiveWand(MagicController spells, Player player) { ItemStack activeItem = player.getInventory().getItemInHand(); if (isWand(activeItem)) { return new Wand(spells, activeItem); } return null; } public static boolean isWand(ItemStack item) { // Note that WandUpgrades also show up here! return item != null && InventoryUtils.hasMeta(item, "wand"); } public static boolean isWandUpgrade(ItemStack item) { if (item == null) return false; Object wandNode = InventoryUtils.getNode(item, "wand"); if (wandNode == null) return false; String upgradeData = InventoryUtils.getMeta(wandNode, "upgrade"); return upgradeData != null && upgradeData.equals("true"); } public static boolean isSpell(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "spell"); } public static boolean isBrush(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "brush"); } public static String getSpell(ItemStack item) { if (!isSpell(item)) return null; Object spellNode = InventoryUtils.getNode(item, "spell"); return InventoryUtils.getMeta(spellNode, "key"); } public static String getBrush(ItemStack item) { if (!isBrush(item)) return null; Object brushNode = InventoryUtils.getNode(item, "brush"); return InventoryUtils.getMeta(brushNode, "key"); } protected static String getMaterialKey(ItemStack itemStack, Integer index) { String materialKey = getBrush(itemStack); if (materialKey == null) return null; if (index != null) { materialKey += "@" + index; } return materialKey; } protected void updateInventoryName(ItemStack item, boolean activeName) { if (isSpell(item)) { Spell spell = mage.getSpell(getSpell(item)); if (spell != null) { updateSpellItem(item, spell, activeName ? this : null, activeMaterial, false); } } else if (isBrush(item)) { updateBrushItem(item, getBrush(item), activeName ? this : null); } } public static void updateSpellItem(ItemStack itemStack, SpellTemplate spell, Wand wand, String activeMaterial, boolean isItem) { ItemMeta meta = itemStack.getItemMeta(); String displayName = null; if (wand != null) { displayName = wand.getActiveWandName(spell); } else { displayName = getSpellDisplayName(spell, activeMaterial); } meta.setDisplayName(displayName); List<String> lore = new ArrayList<String>(); addSpellLore(spell, lore, wand); if (isItem) { lore.add(ChatColor.YELLOW + Messages.get("wand.spell_item_description")); } meta.setLore(lore); itemStack.setItemMeta(meta); InventoryUtils.addGlow(itemStack); Object spellNode = InventoryUtils.createNode(itemStack, "spell"); InventoryUtils.setMeta(spellNode, "key", spell.getKey()); } public static void updateBrushItem(ItemStack itemStack, String materialKey, Wand wand) { ItemMeta meta = itemStack.getItemMeta(); String displayName = null; if (wand != null) { displayName = wand.getActiveWandName(materialKey); } else { displayName = MaterialBrush.getMaterialName(materialKey); } meta.setDisplayName(displayName); itemStack.setItemMeta(meta); Object brushNode = InventoryUtils.createNode(itemStack, "brush"); InventoryUtils.setMeta(brushNode, "key", materialKey); } @SuppressWarnings("deprecation") private void updateInventory() { if (mage == null) return; if (!isInventoryOpen()) return; Player player = mage.getPlayer(); if (player == null) return; WandMode wandMode = getMode(); if (wandMode == WandMode.INVENTORY) { if (!mage.hasStoredInventory()) return; PlayerInventory inventory = player.getInventory(); inventory.clear(); updateHotbar(inventory); updateInventory(inventory, HOTBAR_SIZE, false); updateName(); player.updateInventory(); } else if (wandMode == WandMode.CHEST) { Inventory inventory = getDisplayInventory(); inventory.clear(); updateInventory(inventory, 0, true); player.updateInventory(); } } private void updateHotbar(PlayerInventory playerInventory) { // Check for an item already in the player's held slot, which // we are about to replace with the wand. int currentSlot = playerInventory.getHeldItemSlot(); ItemStack existingHotbar = hotbar.getItem(currentSlot); if (existingHotbar != null && existingHotbar.getType() != Material.AIR && !isWand(existingHotbar)) { // Toss the item back into the wand inventory, it'll find a home somewhere. addToInventory(existingHotbar); hotbar.setItem(currentSlot, null); } // Put the wand in the player's active slot. playerInventory.setItem(currentSlot, item); // Set hotbar items from remaining list for (int hotbarSlot = 0; hotbarSlot < HOTBAR_SIZE; hotbarSlot++) { if (hotbarSlot != currentSlot) { ItemStack hotbarItem = hotbar.getItem(hotbarSlot); updateInventoryName(hotbarItem, true); playerInventory.setItem(hotbarSlot, hotbarItem); } } } private void updateInventory(Inventory targetInventory, int startOffset, boolean addHotbar) { // Set inventory from current page int currentOffset = startOffset; if (openInventoryPage < inventories.size()) { Inventory inventory = inventories.get(openInventoryPage); ItemStack[] contents = inventory.getContents(); for (int i = 0; i < contents.length; i++) { ItemStack inventoryItem = contents[i]; updateInventoryName(inventoryItem, false); targetInventory.setItem(currentOffset, inventoryItem); currentOffset++; } } if (addHotbar) { for (int i = 0; i < HOTBAR_SIZE; i++) { ItemStack inventoryItem = hotbar.getItem(i); updateInventoryName(inventoryItem, false); targetInventory.setItem(currentOffset++, inventoryItem); } } } protected static void addSpellLore(SpellTemplate spell, List<String> lore, CostReducer reducer) { String description = spell.getDescription(); String usage = spell.getUsage(); if (description != null && description.length() > 0) { lore.add(description); } if (usage != null && usage.length() > 0) { lore.add(usage); } Collection<CastingCost> costs = spell.getCosts(); if (costs != null) { for (CastingCost cost : costs) { if (cost.hasCosts(reducer)) { lore.add(ChatColor.YELLOW + Messages.get("wand.costs_description").replace("$description", cost.getFullDescription(reducer))); } } } Collection<CastingCost> activeCosts = spell.getActiveCosts(); if (activeCosts != null) { for (CastingCost cost : activeCosts) { if (cost.hasCosts(reducer)) { lore.add(ChatColor.YELLOW + Messages.get("wand.active_costs_description").replace("$description", cost.getFullDescription(reducer))); } } } long duration = spell.getDuration(); if (duration > 0) { long seconds = duration / 1000; if (seconds > 60 * 60 ) { long hours = seconds / (60 * 60); lore.add(Messages.get("duration.lasts_hours").replace("$hours", ((Long)hours).toString())); } else if (seconds > 60) { long minutes = seconds / 60; lore.add(Messages.get("duration.lasts_minutes").replace("$minutes", ((Long)minutes).toString())); } else { lore.add(Messages.get("duration.lasts_seconds").replace("$seconds", ((Long)seconds).toString())); } } if ((spell instanceof BrushSpell) && !((BrushSpell)spell).hasBrushOverride()) { lore.add(ChatColor.GOLD + Messages.get("spell.brush")); } if (spell instanceof UndoableSpell && ((UndoableSpell)spell).isUndoable()) { lore.add(ChatColor.GRAY + Messages.get("spell.undoable")); } } protected Inventory getOpenInventory() { while (openInventoryPage >= inventories.size()) { inventories.add(InventoryUtils.createInventory(null, INVENTORY_SIZE, "Wand")); } return inventories.get(openInventoryPage); } public void saveInventory() { if (mage == null) return; if (!isInventoryOpen()) return; if (mage.getPlayer() == null) return; if (getMode() != WandMode.INVENTORY) return; if (!mage.hasStoredInventory()) return; // Fill in the hotbar Player player = mage.getPlayer(); PlayerInventory playerInventory = player.getInventory(); for (int i = 0; i < HOTBAR_SIZE; i++) { ItemStack playerItem = playerInventory.getItem(i); if (isWand(playerItem)) { playerItem = null; } hotbar.setItem(i, playerItem); } // Fill in the active inventory page Inventory openInventory = getOpenInventory(); for (int i = 0; i < openInventory.getSize(); i++) { openInventory.setItem(i, playerInventory.getItem(i + HOTBAR_SIZE)); } saveState(); } public static boolean isActive(Player player) { ItemStack activeItem = player.getInventory().getItemInHand(); return isWand(activeItem); } protected void randomize(int totalLevels, boolean additive) { if (!wandTemplates.containsKey("random")) return; if (!additive) { wandName = Messages.get("wands.random.name", wandName); } int maxLevel = WandLevel.getMaxLevel(); int addLevels = Math.min(totalLevels, maxLevel); while (addLevels > 0) { WandLevel.randomizeWand(this, additive, addLevels); totalLevels -= maxLevel; addLevels = Math.min(totalLevels, maxLevel); additive = true; } } public static Wand createWand(MagicController controller, String templateName) { if (controller == null) return null; Wand wand = null; try { wand = new Wand(controller, templateName); } catch (Exception ex) { ex.printStackTrace(); } return wand; } protected void sendAddMessage(String messageKey, String nameParam) { if (mage == null) return; String message = Messages.get(messageKey).replace("$name", nameParam); mage.sendMessage(message); } public boolean add(Wand other) { if (!isModifiable() || !other.isModifiable()) return false; boolean modified = false; if (other.costReduction > costReduction) { costReduction = other.costReduction; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.cost_reduction", costReduction)); } if (other.power > power) { power = other.power; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.power", power)); } if (other.damageReduction > damageReduction) { damageReduction = other.damageReduction; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.protection", damageReduction)); } if (other.damageReductionPhysical > damageReductionPhysical) { damageReductionPhysical = other.damageReductionPhysical; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_physical", damageReductionPhysical)); } if (other.damageReductionProjectiles > damageReductionProjectiles) { damageReductionProjectiles = other.damageReductionProjectiles; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_projectile", damageReductionProjectiles)); } if (other.damageReductionFalling > damageReductionFalling) { damageReductionFalling = other.damageReductionFalling; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_falling", damageReductionFalling)); } if (other.damageReductionFire > damageReductionFire) { damageReductionFire = other.damageReductionFire; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_fire", damageReductionFire)); } if (other.damageReductionExplosions > damageReductionExplosions) { damageReductionExplosions = other.damageReductionExplosions; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.protection_explosions", damageReductionExplosions)); } if (other.healthRegeneration > healthRegeneration) { healthRegeneration = other.healthRegeneration; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.health_regeneration", healthRegeneration)); } if (other.hungerRegeneration > hungerRegeneration) { hungerRegeneration = other.hungerRegeneration; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.hunger_regeneration", hungerRegeneration)); } if (other.speedIncrease > speedIncrease) { speedIncrease = other.speedIncrease; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.haste", speedIncrease)); } // Mix colors if (other.effectColor != null) { if (this.effectColor == null) { this.effectColor = other.effectColor; } else { this.effectColor = this.effectColor.mixColor(other.effectColor, other.effectColorMixWeight); } modified = true; } modified = modified | (!keep && other.keep); modified = modified | (!bound && other.bound); modified = modified | (!effectBubbles && other.effectBubbles); keep = keep || other.keep; bound = bound || other.bound; effectBubbles = effectBubbles || other.effectBubbles; if (other.effectParticle != null && (other.isUpgrade || effectParticle == null)) { modified = modified | (effectParticle != other.effectParticle); effectParticle = other.effectParticle; modified = modified | (effectParticleData != other.effectParticleData); effectParticleData = other.effectParticleData; modified = modified | (effectParticleCount != other.effectParticleCount); effectParticleCount = other.effectParticleCount; modified = modified | (effectParticleInterval != other.effectParticleInterval); effectParticleInterval = other.effectParticleInterval; } if (other.effectSound != null && (other.isUpgrade || effectSound == null)) { modified = modified | (effectSound != other.effectSound); effectSound = other.effectSound; modified = modified | (effectSoundInterval != other.effectSoundInterval); effectSoundInterval = other.effectSoundInterval; modified = modified | (effectSoundVolume != other.effectSoundVolume); effectSoundVolume = other.effectSoundVolume; modified = modified | (effectSoundPitch != other.effectSoundPitch); effectSoundPitch = other.effectSoundPitch; } if (other.template != null && other.template.length() > 0) { modified = modified | (!template.equals(other.template)); template = other.template; } if (other.isUpgrade && other.mode != null) { modified = modified | (mode != other.mode); setMode(other.mode); } // Don't need mana if cost-free if (costReduction >= 1) { xpRegeneration = 0; xpMax = 0; xp = 0; } else { if (other.xpRegeneration > xpRegeneration) { xpRegeneration = other.xpRegeneration; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.mana_regeneration", xpRegeneration, WandLevel.maxXpRegeneration)); } if (other.xpMax > xpMax) { xpMax = other.xpMax; modified = true; sendAddMessage("wand.upgraded_property", getLevelString("wand.mana_amount", xpMax, WandLevel.maxMaxXp)); } if (other.xp > xp) { xp = other.xp; modified = true; } } // Eliminate limited-use wands if (uses == 0 || other.uses == 0) { modified = modified | (uses != 0); uses = 0; } else { // Otherwise add them modified = modified | (other.uses != 0); uses = uses + other.uses; } // Add spells Set<String> spells = other.getSpells(); for (String spellKey : spells) { if (addSpell(spellKey)) { modified = true; String spellName = spellKey; SpellTemplate spell = controller.getSpellTemplate(spellKey); if (spell != null) spellName = spell.getName(); if (mage != null) mage.sendMessage(Messages.get("wand.spell_added").replace("$name", spellName)); } } // Add materials Set<String> materials = other.getBrushes(); for (String materialKey : materials) { if (addBrush(materialKey)) { modified = true; if (mage != null) mage.sendMessage(Messages.get("wand.brush_added").replace("$name", MaterialBrush.getMaterialName(materialKey))); } } Player player = (mage == null) ? null : mage.getPlayer(); if (other.autoFill && player != null) { this.fill(player); modified = true; if (mage != null) mage.sendMessage(Messages.get("wand.filled")); } if (other.autoOrganize && mage != null) { this.organizeInventory(mage); modified = true; if (mage != null) mage.sendMessage(Messages.get("wand.reorganized")); } saveState(); updateName(); updateLore(); return modified; } public boolean keepOnDeath() { return keep; } public static void loadTemplates(ConfigurationSection properties) { wandTemplates.clear(); Set<String> wandKeys = properties.getKeys(false); for (String key : wandKeys) { ConfigurationSection wandNode = properties.getConfigurationSection(key); wandNode.set("key", key); ConfigurationSection existing = wandTemplates.get(key); if (existing != null) { Set<String> overrideKeys = existing.getKeys(false); for (String propertyKey : overrideKeys) { existing.set(propertyKey, existing.get(key)); } } else { wandTemplates.put(key, wandNode); } if (!wandNode.getBoolean("enabled", true)) { wandTemplates.remove(key); } if (key.equals("random")) { WandLevel.mapLevels(wandNode); } } } public static Collection<String> getWandKeys() { return wandTemplates.keySet(); } public static Collection<ConfigurationSection> getWandTemplates() { return wandTemplates.values(); } public static WandMode parseWandMode(String modeString, WandMode defaultValue) { for (WandMode testMode : WandMode.values()) { if (testMode.name().equalsIgnoreCase(modeString)) { return testMode; } } return defaultValue; } private void updateActiveMaterial() { if (mage == null) return; if (activeMaterial == null) { mage.clearBuildingMaterial(); } else { com.elmakers.mine.bukkit.api.block.MaterialBrush brush = mage.getBrush(); brush.update(activeMaterial); } } public void toggleInventory() { if (!hasInventory) { if (activeSpell == null || activeSpell.length() == 0) { Set<String> spells = getSpells(); // Sanity check, so it'll switch to inventory next time if (spells.size() > 1) hasInventory = true; if (spells.size() > 0) { activeSpell = spells.iterator().next(); } } updateName(); return; } if (!isInventoryOpen()) { openInventory(); } else { closeInventory(); } } @SuppressWarnings("deprecation") public void cycleInventory() { if (!hasInventory) { return; } if (isInventoryOpen()) { saveInventory(); int inventoryCount = inventories.size(); openInventoryPage = inventoryCount == 0 ? 0 : (openInventoryPage + 1) % inventoryCount; updateInventory(); if (mage != null && inventories.size() > 1) { mage.playSound(Sound.CHEST_OPEN, 0.3f, 1.5f); mage.getPlayer().updateInventory(); } } } @SuppressWarnings("deprecation") private void openInventory() { if (mage == null) return; WandMode wandMode = getMode(); if (wandMode == WandMode.CHEST) { inventoryIsOpen = true; mage.playSound(Sound.CHEST_OPEN, 0.4f, 0.2f); updateInventory(); mage.getPlayer().openInventory(getDisplayInventory()); } else if (wandMode == WandMode.INVENTORY) { if (mage.hasStoredInventory()) return; if (mage.storeInventory()) { inventoryIsOpen = true; mage.playSound(Sound.CHEST_OPEN, 0.4f, 0.2f); updateInventory(); mage.getPlayer().updateInventory(); } } } @SuppressWarnings("deprecation") public void closeInventory() { if (!isInventoryOpen()) return; saveInventory(); inventoryIsOpen = false; if (mage != null) { mage.playSound(Sound.CHEST_CLOSE, 0.4f, 0.2f); if (getMode() == WandMode.INVENTORY) { mage.restoreInventory(); Player player = mage.getPlayer(); player.setItemInHand(item); player.updateInventory(); } else { mage.getPlayer().closeInventory(); } } saveState(); } public boolean fill(Player player) { Collection<SpellTemplate> allSpells = controller.getPlugin().getSpellTemplates(); for (SpellTemplate spell : allSpells) { if (spell.hasCastPermission(player) && spell.getIcon().getMaterial() != Material.AIR) { addSpell(spell.getKey()); } } autoFill = false; saveState(); // TODO: Detect changes return true; } public boolean hasId() { return id != null && id.length() > 0; } public void activate(Mage mage, ItemStack wandItem) { if (mage == null || wandItem == null) return; // Update held item, it may have been copied since this wand was created. this.item = wandItem; this.mage = mage; // Check for spell or other special icons in the player's inventory Player player = mage.getPlayer(); boolean modified = false; ItemStack[] items = player.getInventory().getContents(); for (int i = 0; i < items.length; i++) { ItemStack item = items[i]; if (addItem(item)) { modified = true; items[i] = null; } } if (modified) { player.getInventory().setContents(items); } // Check for an empty wand and auto-fill if (!isUpgrade && (controller.fillWands() || autoFill)) { if (getSpells().size() == 0) { fill(mage.getPlayer()); } } // Check for auto-organize if (autoOrganize && !isUpgrade) { organizeInventory(mage); } // Check for auto-bind if (bound && (owner == null || owner.length() == 0)) { takeOwnership(mage.getPlayer()); } checkActiveMaterial(); saveState(); mage.setActiveWand(this); if (usesMana()) { storedXpLevel = player.getLevel(); storedXpProgress = player.getExp(); storedXp = 0; updateMana(); } updateActiveMaterial(); updateName(); updateLore(); updateEffects(); } protected void checkActiveMaterial() { if (activeMaterial == null || activeMaterial.length() == 0) { Set<String> materials = getBrushes(); if (materials.size() > 0) { activeMaterial = materials.iterator().next(); } } } public boolean addItem(ItemStack item) { if (isUpgrade) return false; if (isSpell(item)) { String spellKey = getSpell(item); Set<String> spells = getSpells(); if (!spells.contains(spellKey) && addSpell(spellKey)) { SpellTemplate spell = controller.getSpellTemplate(spellKey); if (spell != null) { mage.sendMessage(Messages.get("wand.spell_added").replace("$name", spell.getName())); return true; } } } else if (isBrush(item)) { String materialKey = getBrush(item); Set<String> materials = getBrushes(); if (!materials.contains(materialKey) && addBrush(materialKey)) { mage.sendMessage(Messages.get("wand.brush_added").replace("$name", MaterialBrush.getMaterialName(materialKey))); return true; } } else if (isWandUpgrade(item)) { Wand wand = new Wand(controller, item); return this.add(wand); } return false; } protected void updateEffects() { if (mage == null) return; Player player = mage.getPlayer(); if (player == null) return; // Update Bubble effects effects if (effectBubbles) { InventoryUtils.addPotionEffect(player, effectColor.getColor()); } Location location = mage.getLocation(); if (effectParticle != null && location != null) { if ((effectParticleCounter++ % effectParticleInterval) == 0) { if (effectPlayer == null) { effectPlayer = new EffectRing(controller.getPlugin()); effectPlayer.setParticleCount(2); effectPlayer.setIterations(2); effectPlayer.setRadius(2); effectPlayer.setSize(5); effectPlayer.setMaterial(location.getBlock().getRelative(BlockFace.DOWN)); } effectPlayer.setParticleType(effectParticle); effectPlayer.setParticleData(effectParticleData); effectPlayer.setParticleCount(effectParticleCount); effectPlayer.start(player.getEyeLocation(), null); } } if (effectSound != null && location != null && controller.soundsEnabled()) { if ((effectSoundCounter++ % effectSoundInterval) == 0) { mage.getLocation().getWorld().playSound(location, effectSound, effectSoundVolume, effectSoundPitch); } } } protected void updateMana() { if (mage != null && xpMax > 0 && xpRegeneration > 0) { Player player = mage.getPlayer(); if (displayManaAsBar) { if (!retainLevelDisplay) { player.setLevel(0); } player.setExp((float)xp / (float)xpMax); } else { player.setLevel(xp); player.setExp(0); } } } public boolean isInventoryOpen() { return mage != null && inventoryIsOpen; } public void deactivate() { if (mage == null) return; saveState(); if (effectBubbles) { InventoryUtils.removePotionEffect(mage.getPlayer()); } // This is a tying wands together with other spells, potentially // But with the way the mana system works, this seems like the safest route. mage.deactivateAllSpells(); if (isInventoryOpen()) { closeInventory(); } // Extra just-in-case mage.restoreInventory(); if (usesMana()) { mage.getPlayer().setExp(storedXpProgress); mage.getPlayer().setLevel(storedXpLevel); mage.getPlayer().giveExp(storedXp); storedXp = 0; storedXpProgress = 0; storedXpLevel = 0; } mage.setActiveWand(null); mage = null; } public Spell getActiveSpell() { if (mage == null || activeSpell == null || activeSpell.length() == 0) return null; return mage.getSpell(activeSpell); } public boolean cast() { Spell spell = getActiveSpell(); if (spell != null) { if (spell.cast()) { SpellCategory spellCategory = spell.getCategory(); Color categoryColor = spellCategory == null ? null : spellCategory.getColor(); if (categoryColor != null && this.effectColor != null) { this.effectColor = this.effectColor.mixColor(categoryColor, effectColorSpellMixWeight); // Note that we don't save this change. // The hope is that the wand will get saved at some point later // And we don't want to trigger NBT writes every spell cast. // And the effect color morphing isn't all that important if a few // casts get lost. } use(); return true; } } return false; } @SuppressWarnings("deprecation") protected void use() { if (mage == null) return; if (uses > 0) { uses--; if (uses <= 0) { Player player = mage.getPlayer(); mage.playSound(Sound.ITEM_BREAK, 1.0f, 0.8f); PlayerInventory playerInventory = player.getInventory(); playerInventory.setItemInHand(new ItemStack(Material.AIR, 1)); player.updateInventory(); deactivate(); } else { updateName(); updateLore(); saveState(); } } } public void onPlayerExpChange(PlayerExpChangeEvent event) { if (mage == null) return; if (usesMana()) { storedXp += event.getAmount(); event.setAmount(0); } } public void tick() { if (mage == null) return; Player player = mage.getPlayer(); if (player == null) return; if (speedIncrease > 0) { int hasteLevel = (int)(speedIncrease * WandLevel.maxHasteLevel); if (hasteEffect == null || hasteEffect.getAmplifier() != hasteLevel) { hasteEffect = new PotionEffect(PotionEffectType.SPEED, 80, hasteLevel, true); } CompatibilityUtils.applyPotionEffect(player, hasteEffect); } if (healthRegeneration > 0) { int regenLevel = (int)(healthRegeneration * WandLevel.maxHealthRegeneration); if (healthRegenEffect == null || healthRegenEffect.getAmplifier() != regenLevel) { healthRegenEffect = new PotionEffect(PotionEffectType.REGENERATION, 80, regenLevel, true); } CompatibilityUtils.applyPotionEffect(player, healthRegenEffect); } if (hungerRegeneration > 0) { int regenLevel = (int)(hungerRegeneration * WandLevel.maxHungerRegeneration); if (hungerRegenEffect == null || hungerRegenEffect.getAmplifier() != regenLevel) { hungerRegenEffect = new PotionEffect(PotionEffectType.SATURATION, 80, regenLevel, true); } CompatibilityUtils.applyPotionEffect(player, hungerRegenEffect); } if (usesMana()) { xp = Math.min(xpMax, xp + xpRegeneration); updateMana(); } if (damageReductionFire > 0 && player.getFireTicks() > 0) { player.setFireTicks(0); } updateEffects(); } @Override public boolean equals(Object other) { if (other == null) return false; if (!(other instanceof Wand)) return false; Wand otherWand = ((Wand)other); if (this.id.length() == 0 || otherWand.id.length() == 0) return false; return otherWand.id.equals(this.id); } public MagicController getMaster() { return controller; } public void cycleSpells(ItemStack newItem) { if (isWand(newItem)) item = newItem; Set<String> spellsSet = getSpells(); ArrayList<String> spells = new ArrayList<String>(spellsSet); if (spells.size() == 0) return; if (activeSpell == null) { activeSpell = spells.get(0).split("@")[0]; return; } int spellIndex = 0; for (int i = 0; i < spells.size(); i++) { if (spells.get(i).split("@")[0].equals(activeSpell)) { spellIndex = i; break; } } spellIndex = (spellIndex + 1) % spells.size(); setActiveSpell(spells.get(spellIndex).split("@")[0]); } public void cycleMaterials(ItemStack newItem) { if (isWand(newItem)) item = newItem; Set<String> materialsSet = getBrushes(); ArrayList<String> materials = new ArrayList<String>(materialsSet); if (materials.size() == 0) return; if (activeMaterial == null) { activeMaterial = materials.get(0).split("@")[0]; return; } int materialIndex = 0; for (int i = 0; i < materials.size(); i++) { if (materials.get(i).split("@")[0].equals(activeMaterial)) { materialIndex = i; break; } } materialIndex = (materialIndex + 1) % materials.size(); activateBrush(materials.get(materialIndex).split("@")[0]); } public boolean hasExperience() { return xpRegeneration > 0; } public Mage getActivePlayer() { return mage; } protected void clearInventories() { inventories.clear(); hotbar.clear(); } public Color getEffectColor() { return effectColor == null ? null : effectColor.getColor(); } public Inventory getHotbar() { return hotbar; } public WandMode getMode() { return mode != null ? mode : controller.getDefaultWandMode(); } public void setMode(WandMode mode) { this.mode = mode; } public boolean showCastMessages() { return quietLevel == 0; } public boolean showMessages() { return quietLevel < 2; } /* * Public API Implementation */ public String getId() { return this.id; } @Override public void activate(com.elmakers.mine.bukkit.api.magic.Mage mage) { Player player = mage.getPlayer(); if (!Wand.hasActiveWand(player)) { controller.getLogger().warning("Wand activated without holding a wand!"); try { throw new Exception("Wand activated without holding a wand!"); } catch (Exception ex) { ex.printStackTrace(); } return; } if (!canUse(player)) { mage.sendMessage(Messages.get("wand.bound").replace("$name", owner)); player.setItemInHand(null); Location location = player.getLocation(); location.setY(location.getY() + 1); Item droppedItem = player.getWorld().dropItemNaturally(location, item); Vector velocity = droppedItem.getVelocity(); velocity.setY(velocity.getY() * 2 + 1); droppedItem.setVelocity(velocity); return; } if (mage instanceof Mage) { activate((Mage)mage, player.getItemInHand()); } } @Override public void organizeInventory(com.elmakers.mine.bukkit.api.magic.Mage mage) { WandOrganizer organizer = new WandOrganizer(this, mage); organizer.organize(); openInventoryPage = 0; autoOrganize = false; saveState(); } @Override public com.elmakers.mine.bukkit.api.wand.Wand duplicate() { ItemStack newItem = InventoryUtils.getCopy(item); Wand newWand = new Wand(controller, newItem); newWand.generateId(); newWand.saveState(); return newWand; } @Override public boolean configure(Map<String, Object> properties) { Map<Object, Object> convertedProperties = new HashMap<Object, Object>(properties); loadProperties(ConfigurationUtils.toNodeList(convertedProperties), false); // TODO: Detect changes return true; } @Override public boolean upgrade(Map<String, Object> properties) { Map<Object, Object> convertedProperties = new HashMap<Object, Object>(properties); loadProperties(ConfigurationUtils.toNodeList(convertedProperties), true); // TODO: Detect changes return true; } @Override public boolean isLocked() { return this.locked; } @Override public boolean canUse(Player player) { if (!bound || owner == null || owner.length() == 0) return true; if (controller.hasPermission(player, "Magic.wand.override_bind", false)) return true; return owner.equalsIgnoreCase(player.getName()); } public boolean addSpell(String spellName) { if (!isModifiable()) return false; if (hasSpell(spellName)) return false; if (isInventoryOpen()) { saveInventory(); } ItemStack spellItem = createSpellIcon(spellName); if (spellItem == null) { controller.getPlugin().getLogger().info("Unknown spell: " + spellName); return false; } addToInventory(spellItem); updateInventory(); hasInventory = getSpells().size() + getBrushes().size() > 1; updateLore(); saveState(); return true; } @Override public boolean add(com.elmakers.mine.bukkit.api.wand.Wand other) { if (other instanceof Wand) { return add((Wand)other); } return false; } @Override public boolean hasBrush(String materialKey) { return getBrushes().contains(materialKey); } @Override public boolean hasSpell(String spellName) { return getSpells().contains(spellName); } @Override public boolean addBrush(String materialKey) { if (!isModifiable()) return false; if (hasBrush(materialKey)) return false; ItemStack itemStack = createBrushIcon(materialKey); if (itemStack == null) return false; addToInventory(itemStack); if (activeMaterial == null || activeMaterial.length() == 0) { setActiveBrush(materialKey); } else { updateInventory(); } updateLore(); saveState(); hasInventory = getSpells().size() + getBrushes().size() > 1; return true; } @Override public void setActiveBrush(String materialKey) { this.activeMaterial = materialKey; updateName(); updateActiveMaterial(); updateInventory(); saveState(); } @Override public void setActiveSpell(String activeSpell) { this.activeSpell = activeSpell; updateName(); updateInventory(); saveState(); } @Override public boolean removeBrush(String materialKey) { if (!isModifiable() || materialKey == null) return false; if (isInventoryOpen()) { saveInventory(); } if (materialKey.equals(activeMaterial)) { activeMaterial = null; } List<Inventory> allInventories = getAllInventories(); boolean found = false; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int index = 0; index < items.length; index++) { ItemStack itemStack = items[index]; if (itemStack != null && isBrush(itemStack)) { String itemKey = getBrush(itemStack); if (itemKey.equals(materialKey)) { found = true; inventory.setItem(index, null); } else if (activeMaterial == null) { activeMaterial = materialKey; } if (found && activeMaterial != null) { break; } } } } updateActiveMaterial(); updateInventory(); updateName(); updateLore(); saveState(); if (isInventoryOpen()) { updateInventory(); } return found; } @Override public boolean removeSpell(String spellName) { if (!isModifiable()) return false; if (isInventoryOpen()) { saveInventory(); } if (spellName.equals(activeSpell)) { activeSpell = null; } List<Inventory> allInventories = getAllInventories(); boolean found = false; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int index = 0; index < items.length; index++) { ItemStack itemStack = items[index]; if (itemStack != null && itemStack.getType() != Material.AIR && !isWand(itemStack) && isSpell(itemStack)) { if (getSpell(itemStack).equals(spellName)) { found = true; inventory.setItem(index, null); } else if (activeSpell == null) { activeSpell = getSpell(itemStack); } if (found && activeSpell != null) { break; } } } } updateName(); updateLore(); saveState(); updateInventory(); return found; } }
Blend Spell color with Wand color
src/main/java/com/elmakers/mine/bukkit/wand/Wand.java
Blend Spell color with Wand color
<ide><path>rc/main/java/com/elmakers/mine/bukkit/wand/Wand.java <ide> import com.elmakers.mine.bukkit.api.spell.CastingCost; <ide> import com.elmakers.mine.bukkit.api.spell.CostReducer; <ide> import com.elmakers.mine.bukkit.api.spell.Spell; <del>import com.elmakers.mine.bukkit.api.spell.SpellCategory; <ide> import com.elmakers.mine.bukkit.api.spell.SpellTemplate; <ide> import com.elmakers.mine.bukkit.block.MaterialAndData; <ide> import com.elmakers.mine.bukkit.block.MaterialBrush; <ide> Spell spell = getActiveSpell(); <ide> if (spell != null) { <ide> if (spell.cast()) { <del> SpellCategory spellCategory = spell.getCategory(); <del> Color categoryColor = spellCategory == null ? null : spellCategory.getColor(); <del> if (categoryColor != null && this.effectColor != null) { <del> this.effectColor = this.effectColor.mixColor(categoryColor, effectColorSpellMixWeight); <add> Color spellColor = spell.getColor(); <add> if (spellColor != null && this.effectColor != null) { <add> this.effectColor = this.effectColor.mixColor(spellColor, effectColorSpellMixWeight); <ide> // Note that we don't save this change. <ide> // The hope is that the wand will get saved at some point later <ide> // And we don't want to trigger NBT writes every spell cast.
Java
apache-2.0
ad551be6c8859a3a45596baaf27ad2c2b1e430ba
0
mccalv/ginema,mccalv/ginema
/******************************************************************************* * Copyright Mirko Calvaresi [email protected] 2015 * * 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.ginema.api.serialization; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.InputStream; import java.util.Date; import java.util.HashMap; import java.util.UUID; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.DataFileWriter; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DatumWriter; import org.apache.avro.specific.SpecificDatumReader; import org.apache.avro.specific.SpecificDatumWriter; import org.junit.Test; import com.ginema.api.avro.DateEntry; import com.ginema.api.avro.SensitiveDataHolder; import com.ginema.api.avro.util.SchemaHelper; /** * A base test for serialization in Avro * * @author mccalv * */ public class SerializationTest { private final static File AVRO_SERIALIZED_FILE = new File("sensitiveDataHolder.avro"); private final static Date DATE = new Date(); private final static String ID_GENERATED = UUID.randomUUID().toString(); private final static String ID_HOLDER = UUID.randomUUID().toString(); private final static String DOMAIN = "domain"; @Test public void testSchemaBuilderAndJsonShouldBeEqual() throws Exception { InputStream resourceAsStream = ClassLoader.getSystemResourceAsStream("avro/sensitivedataHolder.avsc"); Schema parse = new Schema.Parser() .parse(resourceAsStream); assertEquals(parse, SchemaHelper.getGinemaSchema()); } /** Test the serialization and serialization using Apache Avro */ @Test public void testSerialization() throws Exception { // Deserialize users from disk SensitiveDataHolder sensitiveDataHolder = new SensitiveDataHolder(); sensitiveDataHolder.setId(ID_HOLDER); sensitiveDataHolder.setDomain(DOMAIN); sensitiveDataHolder.setDates(new HashMap<String, DateEntry>()); sensitiveDataHolder.getDates().put(ID_GENERATED, new DateEntry(ID_GENERATED, DATE.getTime())); DatumWriter<SensitiveDataHolder> userDatumWriter = new SpecificDatumWriter<SensitiveDataHolder>(SensitiveDataHolder.class); DataFileWriter<SensitiveDataHolder> dataFileWriter = new DataFileWriter<SensitiveDataHolder>(userDatumWriter); dataFileWriter.create(sensitiveDataHolder.getSchema(), AVRO_SERIALIZED_FILE); dataFileWriter.append(sensitiveDataHolder); dataFileWriter.close(); DatumReader<SensitiveDataHolder> userDatumReader = new SpecificDatumReader<SensitiveDataHolder>(SensitiveDataHolder.class); DataFileReader<SensitiveDataHolder> dataFileReader = new DataFileReader<SensitiveDataHolder>(AVRO_SERIALIZED_FILE, userDatumReader); SensitiveDataHolder sensitideDataHolder = null; while (dataFileReader.hasNext()) { // Reuse user object by passing it to next(). This saves us from // allocating and garbage collecting many objects for files with // many items. sensitideDataHolder = dataFileReader.next(); assertEquals(ID_HOLDER, sensitideDataHolder.getId().toString()); assertEquals(DOMAIN, sensitideDataHolder.getDomain().toString()); assertEquals(DATE, new Date(sensitideDataHolder.getDates().get(ID_GENERATED).getValue())); System.out.println(sensitideDataHolder); } AVRO_SERIALIZED_FILE.delete(); dataFileReader.close(); } }
ginema-api/src/test/java/com/ginema/api/serialization/SerializationTest.java
/******************************************************************************* * Copyright Mirko Calvaresi [email protected] 2015 * * 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.ginema.api.serialization; import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Date; import java.util.HashMap; import java.util.UUID; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.DataFileWriter; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DatumWriter; import org.apache.avro.specific.SpecificDatumReader; import org.apache.avro.specific.SpecificDatumWriter; import org.junit.Test; import com.ginema.api.avro.DateEntry; import com.ginema.api.avro.SensitiveDataHolder; import com.ginema.api.avro.util.SchemaHelper; /** * A base test for serialization in Avro * * @author mccalv * */ public class SerializationTest { private final static File AVRO_SERIALIZED_FILE = new File("sensitiveDataHolder.avro"); private final static Date DATE = new Date(); private final static String ID_GENERATED = UUID.randomUUID().toString(); private final static String ID_HOLDER = UUID.randomUUID().toString(); private final static String DOMAIN = "domain"; @Test public void testSchemaBuilderAndJsonShouldBeEqual() throws Exception { Schema parse = new Schema.Parser() .parse(this.getClass().getClassLoader().getResourceAsStream("avro/sensitivedataHolder.avsc")); assertEquals(parse, SchemaHelper.getGinemaSchema()); } /** Test the serialization and serialization using Apache Avro */ @Test public void testSerialization() throws Exception { // Deserialize users from disk SensitiveDataHolder sensitiveDataHolder = new SensitiveDataHolder(); sensitiveDataHolder.setId(ID_HOLDER); sensitiveDataHolder.setDomain(DOMAIN); sensitiveDataHolder.setDates(new HashMap<String, DateEntry>()); sensitiveDataHolder.getDates().put(ID_GENERATED, new DateEntry(ID_GENERATED, DATE.getTime())); DatumWriter<SensitiveDataHolder> userDatumWriter = new SpecificDatumWriter<SensitiveDataHolder>(SensitiveDataHolder.class); DataFileWriter<SensitiveDataHolder> dataFileWriter = new DataFileWriter<SensitiveDataHolder>(userDatumWriter); dataFileWriter.create(sensitiveDataHolder.getSchema(), AVRO_SERIALIZED_FILE); dataFileWriter.append(sensitiveDataHolder); dataFileWriter.close(); DatumReader<SensitiveDataHolder> userDatumReader = new SpecificDatumReader<SensitiveDataHolder>(SensitiveDataHolder.class); DataFileReader<SensitiveDataHolder> dataFileReader = new DataFileReader<SensitiveDataHolder>(AVRO_SERIALIZED_FILE, userDatumReader); SensitiveDataHolder sensitideDataHolder = null; while (dataFileReader.hasNext()) { // Reuse user object by passing it to next(). This saves us from // allocating and garbage collecting many objects for files with // many items. sensitideDataHolder = dataFileReader.next(); assertEquals(ID_HOLDER, sensitideDataHolder.getId().toString()); assertEquals(DOMAIN, sensitideDataHolder.getDomain().toString()); assertEquals(DATE, new Date(sensitideDataHolder.getDates().get(ID_GENERATED).getValue())); System.out.println(sensitideDataHolder); } AVRO_SERIALIZED_FILE.delete(); dataFileReader.close(); } }
Added Schema Helper used to produce the JSON schema
ginema-api/src/test/java/com/ginema/api/serialization/SerializationTest.java
Added Schema Helper used to produce the JSON schema
<ide><path>inema-api/src/test/java/com/ginema/api/serialization/SerializationTest.java <ide> import static org.junit.Assert.assertEquals; <ide> <ide> import java.io.File; <add>import java.io.InputStream; <ide> import java.util.Date; <ide> import java.util.HashMap; <ide> import java.util.UUID; <ide> <ide> @Test <ide> public void testSchemaBuilderAndJsonShouldBeEqual() throws Exception { <add> <add> InputStream resourceAsStream = ClassLoader.getSystemResourceAsStream("avro/sensitivedataHolder.avsc"); <ide> Schema parse = new Schema.Parser() <del> .parse(this.getClass().getClassLoader().getResourceAsStream("avro/sensitivedataHolder.avsc")); <add> .parse(resourceAsStream); <ide> assertEquals(parse, SchemaHelper.getGinemaSchema()); <ide> <ide> }
Java
apache-2.0
716808950ab722663d69c511f37e40acf4f5f849
0
apache/batik,Uni-Sol/batik,Uni-Sol/batik,apache/batik,Uni-Sol/batik,Uni-Sol/batik,apache/batik,apache/batik,Uni-Sol/batik
/***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * * ------------------------------------------------------------------------- * * This software is published under the terms of the Apache Software License * * version 1.1, a copy of which has been included with this distribution in * * the LICENSE file. * *****************************************************************************/ package org.apache.batik.svggen; import org.w3c.dom.Document; /** * This class contains all non graphical contextual information that * are needed by the {@link org.apache.batik.svggen.SVGGraphics2D} to * generate SVG from Java 2D primitives. * You can subclass it to change the defaults. * * @see org.apache.batik.svggen.SVGGraphics2D#SVGGraphics2D(SVGGeneratorContext,boolean) * @author <a href="mailto:[email protected]>Christophe Jolif</a> * @version $Id$ */ public class SVGGeneratorContext implements ErrorConstants { // this fields are package access for read-only purpose /** * Factory used by this Graphics2D to create Elements * that make the SVG DOM Tree */ Document domFactory; /** * Handler that defines how images are referenced in the * generated SVG fragment. This allows different strategies * to be used to handle images. * @see org.apache.batik.svggen.ImageHandler * @see org.apache.batik.svggen.ImageHandlerBase64Encoder * @see org.apache.batik.svggen.ImageHandlerPNGEncoder * @see org.apache.batik.svggen.ImageHandlerJPEGEncoder */ ImageHandler imageHandler; /** * To deal with Java 2D extension (custom java.awt.Paint for example). */ ExtensionHandler extensionHandler; /** * To generate consitent ids. */ SVGIDGenerator idGenerator; /** * To set style. */ StyleHandler styleHandler; /** * The comment to insert at generation time. */ String generatorComment; /** * The error handler. */ ErrorHandler errorHandler; /** * Builds an instance of <code>SVGGeneratorContext</code> with the given * <code>domFactory</code> but let the user set later the other contextual * information. * @see #setIDGenerator * @see #setExtensionHandler * @see #setImageHandler */ protected SVGGeneratorContext(Document domFactory) { setDOMFactory(domFactory); } /** * Creates an instance of <code>SVGGeneratorContext</code> with the * given <code>domFactory</code> and with the default values for the * other information. * @see org.apache.batik.svggen.SVGIDGenerator * @see org.apache.batik.svggen.DefaultExtensionHandler * @see org.apache.batik.svggen.ImageHandlerBase64Encoder */ public static SVGGeneratorContext createDefault(Document domFactory) { SVGGeneratorContext ctx = new SVGGeneratorContext(domFactory); ctx.setIDGenerator(new SVGIDGenerator()); ctx.setExtensionHandler(new DefaultExtensionHandler()); ctx.setImageHandler(new ImageHandlerBase64Encoder()); ctx.setStyleHandler(new DefaultStyleHandler()); ctx.setComment("Generated by the Batik Graphics2D SVG Generator"); ctx.setErrorHandler(new DefaultErrorHandler()); return ctx; } /** * Returns the {@link org.apache.batik.svggen.SVGIDGenerator} that * has been set. */ final public SVGIDGenerator getIDGenerator() { return idGenerator; } /** * Sets the {@link org.apache.batik.svggen.SVGIDGenerator} * to be used. It should not be <code>null</code>. */ final public void setIDGenerator(SVGIDGenerator idGenerator) { if (idGenerator == null) throw new SVGGraphics2DRuntimeException(ERR_ID_GENERATOR_NULL); this.idGenerator = idGenerator; } /** * Returns the DOM Factory that * has been set. */ final public Document getDOMFactory() { return domFactory; } /** * Sets the DOM Factory * to be used. It should not be <code>null</code>. */ final public void setDOMFactory(Document domFactory) { if (domFactory == null) throw new SVGGraphics2DRuntimeException(ERR_DOM_FACTORY_NULL); this.domFactory = domFactory; } /** * Returns the {@link org.apache.batik.svggen.ExtensionHandler} that * has been set. */ final public ExtensionHandler getExtensionHandler() { return extensionHandler; } /** * Sets the {@link org.apache.batik.svggen.ExtensionHandler} * to be used. It should not be <code>null</code>. */ final public void setExtensionHandler(ExtensionHandler extensionHandler) { if (extensionHandler == null) throw new SVGGraphics2DRuntimeException(ERR_EXTENSION_HANDLER_NULL); this.extensionHandler = extensionHandler; } /** * Returns the {@link org.apache.batik.svggen.ImageHandler} that * has been set. */ final public ImageHandler getImageHandler() { return imageHandler; } /** * Sets the {@link org.apache.batik.svggen.ImageHandler} * to be used. It should not be <code>null</code>. */ final public void setImageHandler(ImageHandler imageHandler) { if (imageHandler == null) throw new SVGGraphics2DRuntimeException(ERR_IMAGE_HANDLER_NULL); this.imageHandler = imageHandler; } /** * Returns the {@link org.apache.batik.svggen.StyleHandler} that * has been set. */ final public StyleHandler getStyleHandler() { return styleHandler; } /** * Sets the {@link org.apache.batik.svggen.Stylehandler} * to be used. It should not be <code>null</code>. */ final public void setStyleHandler(StyleHandler styleHandler) { if (styleHandler == null) throw new SVGGraphics2DRuntimeException(ERR_STYLE_HANDLER_NULL); this.styleHandler = styleHandler; } /** * Returns the comment to be generated in the SVG file. */ final public String getComment() { return generatorComment; } /** * Sets the comment to be used. It can be <code>null</code> if you * want to disable it. */ final public void setComment(String generatorComment) { this.generatorComment = generatorComment; } /** * Returns the {@link org.apache.batik.svggen.ErrorHandler} that * has been set. */ final public ErrorHandler getErrorHandler() { return errorHandler; } /** * Sets the {@link org.apache.batik.svggen.Errorhandler} * to be used. It should not be <code>null</code>. */ final public void setErrorHandler(ErrorHandler errorHandler) { if (errorHandler == null) throw new SVGGraphics2DRuntimeException(ERR_ERROR_HANDLER_NULL); this.errorHandler = errorHandler; } }
sources/org/apache/batik/svggen/SVGGeneratorContext.java
/***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * * ------------------------------------------------------------------------- * * This software is published under the terms of the Apache Software License * * version 1.1, a copy of which has been included with this distribution in * * the LICENSE file. * *****************************************************************************/ package org.apache.batik.svggen; import org.w3c.dom.Document; /** * This class contains all non graphical contextual information that * are needed by the {@link org.apache.batik.svggen.SVGGraphics2D} to * generate SVG from Java 2D primitives. * You can subclass it to change the defaults. * * @see org.apache.batik.svggen.SVGGraphics2D#SVGGraphics2D(SVGGeneratorContext,boolean) * @author <a href="mailto:[email protected]>Christophe Jolif</a> * @version $Id$ */ public class SVGGeneratorContext implements ErrorConstants { // this fields are package access for read-only purpose /** * Factory used by this Graphics2D to create Elements * that make the SVG DOM Tree */ Document domFactory; /** * Handler that defines how images are referenced in the * generated SVG fragment. This allows different strategies * to be used to handle images. * @see org.apache.batik.svggen.ImageHandler * @see org.apache.batik.svggen.ImageHandlerBase64Encoder * @see org.apache.batik.svggen.ImageHandlerPNGEncoder * @see org.apache.batik.svggen.ImageHandlerJPEGEncoder */ ImageHandler imageHandler; /** * To deal with Java 2D extension (custom java.awt.Paint for example). */ ExtensionHandler extensionHandler; /** * To generate consitent ids. */ SVGIDGenerator idGenerator; /** * To set style. */ StyleHandler styleHandler; /** * The comment to insert at generation time. */ String generatorComment; /** * The error handler. */ ErrorHandler errorHandler; /** * Builds an instance of <code>SVGGeneratorContext</code> with the given * <code>domFactory</code> but let the user set later the other contextual * information. * @see #setIDGenerator * @see #setExtensionHandler * @see #setImageHandler */ protected SVGGeneratorContext(Document domFactory) { setDOMFactory(domFactory); } /** * Creates an instance of <code>SVGGeneratorContext</code> with the * given <code>domFactory</code> and with the default values for the * other information. * @see org.apache.batik.svggen.SVGIDGenerator * @see org.apache.batik.svggen.DefaultExtensionHandler * @see org.apache.batik.svggen.ImageHandlerBase64Encoder */ public static SVGGeneratorContext createDefault(Document domFactory) { SVGGeneratorContext ctx = new SVGGeneratorContext(domFactory); ctx.setIDGenerator(new SVGIDGenerator()); ctx.setExtensionHandler(new DefaultExtensionHandler()); ctx.setImageHandler(new ImageHandlerBase64Encoder()); ctx.setStyleHandler(new DefaultStyleHandler()); ctx.setComment("Generated by the Batik Graphics2D SVG Generator"); ctx.setErrorHandler(new DefaultErrorHandler()); return ctx; } /** * Returns the {@link org.apache.batik.svggen.SVGIDGenerator} that * has been set. */ final public SVGIDGenerator getIDGenerator() { return idGenerator; } /** * Sets the {@link org.apache.batik.svggen.SVGIDGenerator} * to be used. It should not be <code>null</code>. */ final protected void setIDGenerator(SVGIDGenerator idGenerator) { if (idGenerator == null) throw new SVGGraphics2DRuntimeException(ERR_ID_GENERATOR_NULL); this.idGenerator = idGenerator; } /** * Returns the DOM Factory that * has been set. */ final public Document getDOMFactory() { return domFactory; } /** * Sets the DOM Factory * to be used. It should not be <code>null</code>. */ final protected void setDOMFactory(Document domFactory) { if (domFactory == null) throw new SVGGraphics2DRuntimeException(ERR_DOM_FACTORY_NULL); this.domFactory = domFactory; } /** * Returns the {@link org.apache.batik.svggen.ExtensionHandler} that * has been set. */ final public ExtensionHandler getExtensionHandler() { return extensionHandler; } /** * Sets the {@link org.apache.batik.svggen.ExtensionHandler} * to be used. It should not be <code>null</code>. */ final protected void setExtensionHandler(ExtensionHandler extensionHandler) { if (extensionHandler == null) throw new SVGGraphics2DRuntimeException(ERR_EXTENSION_HANDLER_NULL); this.extensionHandler = extensionHandler; } /** * Returns the {@link org.apache.batik.svggen.ImageHandler} that * has been set. */ final public ImageHandler getImageHandler() { return imageHandler; } /** * Sets the {@link org.apache.batik.svggen.ImageHandler} * to be used. It should not be <code>null</code>. */ final protected void setImageHandler(ImageHandler imageHandler) { if (imageHandler == null) throw new SVGGraphics2DRuntimeException(ERR_IMAGE_HANDLER_NULL); this.imageHandler = imageHandler; } /** * Returns the {@link org.apache.batik.svggen.StyleHandler} that * has been set. */ final public StyleHandler getStyleHandler() { return styleHandler; } /** * Sets the {@link org.apache.batik.svggen.Stylehandler} * to be used. It should not be <code>null</code>. */ final protected void setStyleHandler(StyleHandler styleHandler) { if (styleHandler == null) throw new SVGGraphics2DRuntimeException(ERR_STYLE_HANDLER_NULL); this.styleHandler = styleHandler; } /** * Returns the comment to be generated in the SVG file. */ final public String getComment() { return generatorComment; } /** * Sets the comment to be used. It can be <code>null</code> if you * want to disable it. */ final protected void setComment(String generatorComment) { this.generatorComment = generatorComment; } /** * Returns the {@link org.apache.batik.svggen.ErrorHandler} that * has been set. */ final public ErrorHandler getErrorHandler() { return errorHandler; } /** * Sets the {@link org.apache.batik.svggen.Errorhandler} * to be used. It should not be <code>null</code>. */ final protected void setErrorHandler(ErrorHandler errorHandler) { if (errorHandler == null) throw new SVGGraphics2DRuntimeException(ERR_ERROR_HANDLER_NULL); this.errorHandler = errorHandler; } }
simplify user work by moving some protected -> public git-svn-id: e944db0f7b5c8f0ae3e1ad43ca99b026751ef0c2@199828 13f79535-47bb-0310-9956-ffa450edef68
sources/org/apache/batik/svggen/SVGGeneratorContext.java
simplify user work by moving some protected -> public
<ide><path>ources/org/apache/batik/svggen/SVGGeneratorContext.java <ide> * Sets the {@link org.apache.batik.svggen.SVGIDGenerator} <ide> * to be used. It should not be <code>null</code>. <ide> */ <del> final protected void setIDGenerator(SVGIDGenerator idGenerator) { <add> final public void setIDGenerator(SVGIDGenerator idGenerator) { <ide> if (idGenerator == null) <ide> throw new SVGGraphics2DRuntimeException(ERR_ID_GENERATOR_NULL); <ide> this.idGenerator = idGenerator; <ide> * Sets the DOM Factory <ide> * to be used. It should not be <code>null</code>. <ide> */ <del> final protected void setDOMFactory(Document domFactory) { <add> final public void setDOMFactory(Document domFactory) { <ide> if (domFactory == null) <ide> throw new SVGGraphics2DRuntimeException(ERR_DOM_FACTORY_NULL); <ide> this.domFactory = domFactory; <ide> * Sets the {@link org.apache.batik.svggen.ExtensionHandler} <ide> * to be used. It should not be <code>null</code>. <ide> */ <del> final protected void setExtensionHandler(ExtensionHandler extensionHandler) { <add> final public void setExtensionHandler(ExtensionHandler extensionHandler) { <ide> if (extensionHandler == null) <ide> throw new SVGGraphics2DRuntimeException(ERR_EXTENSION_HANDLER_NULL); <ide> this.extensionHandler = extensionHandler; <ide> * Sets the {@link org.apache.batik.svggen.ImageHandler} <ide> * to be used. It should not be <code>null</code>. <ide> */ <del> final protected void setImageHandler(ImageHandler imageHandler) { <add> final public void setImageHandler(ImageHandler imageHandler) { <ide> if (imageHandler == null) <ide> throw new SVGGraphics2DRuntimeException(ERR_IMAGE_HANDLER_NULL); <ide> this.imageHandler = imageHandler; <ide> * Sets the {@link org.apache.batik.svggen.Stylehandler} <ide> * to be used. It should not be <code>null</code>. <ide> */ <del> final protected void setStyleHandler(StyleHandler styleHandler) { <add> final public void setStyleHandler(StyleHandler styleHandler) { <ide> if (styleHandler == null) <ide> throw new SVGGraphics2DRuntimeException(ERR_STYLE_HANDLER_NULL); <ide> this.styleHandler = styleHandler; <ide> * Sets the comment to be used. It can be <code>null</code> if you <ide> * want to disable it. <ide> */ <del> final protected void setComment(String generatorComment) { <add> final public void setComment(String generatorComment) { <ide> this.generatorComment = generatorComment; <ide> } <ide> <ide> * Sets the {@link org.apache.batik.svggen.Errorhandler} <ide> * to be used. It should not be <code>null</code>. <ide> */ <del> final protected void setErrorHandler(ErrorHandler errorHandler) { <add> final public void setErrorHandler(ErrorHandler errorHandler) { <ide> if (errorHandler == null) <ide> throw new SVGGraphics2DRuntimeException(ERR_ERROR_HANDLER_NULL); <ide> this.errorHandler = errorHandler;
Java
epl-1.0
017111b53c437763458a6724faa726e26bd63e74
0
rohitmohan96/ceylon-ide-eclipse,rohitmohan96/ceylon-ide-eclipse
package com.redhat.ceylon.eclipse.code.propose; import static com.redhat.ceylon.compiler.loader.AbstractModelLoader.JDK_MODULE_VERSION; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.AIDENTIFIER; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.ASTRING_LITERAL; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.AVERBATIM_STRING; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.CHAR_LITERAL; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.EOF; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.FLOAT_LITERAL; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.LBRACE; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.LIDENTIFIER; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.LINE_COMMENT; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.MULTI_COMMENT; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.NATURAL_LITERAL; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.PIDENTIFIER; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.RBRACE; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.SEMICOLON; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.STRING_END; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.STRING_LITERAL; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.STRING_MID; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.STRING_START; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.UIDENTIFIER; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.VERBATIM_STRING; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.WS; import static com.redhat.ceylon.eclipse.code.editor.CeylonAutoEditStrategy.getDefaultIndent; import static com.redhat.ceylon.eclipse.code.hover.DocHover.getDocumentationFor; import static com.redhat.ceylon.eclipse.code.hover.DocHover.getDocumentationForModule; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.ANN_STYLER; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.ARCHIVE; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.ID_STYLER; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.KW_STYLER; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.PACKAGE; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.TYPE_STYLER; import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.findNode; import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.getTokenIndexAtCharacter; import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.keywords; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.CLASS_ALIAS; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.EXPRESSION; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.EXTENDS; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.IMPORT; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.OF; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.PARAMETER_LIST; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.SATISFIES; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.TYPE_ALIAS; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.TYPE_ARGUMENT_LIST; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.TYPE_PARAMETER_LIST; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.UPPER_BOUND; import static com.redhat.ceylon.eclipse.code.quickfix.CeylonQuickFixAssistant.getIndent; import static java.lang.Character.isJavaIdentifierPart; import static java.lang.Character.isLowerCase; import static java.lang.Character.isUpperCase; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.viewers.StyledString; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import com.redhat.ceylon.cmr.api.JDKUtils; import com.redhat.ceylon.cmr.api.ModuleQuery; import com.redhat.ceylon.cmr.api.ModuleSearchResult; import com.redhat.ceylon.cmr.api.ModuleSearchResult.ModuleDetails; import com.redhat.ceylon.compiler.loader.AbstractModelLoader; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.DeclarationWithProximity; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.Generic; import com.redhat.ceylon.compiler.typechecker.model.ImportList; import com.redhat.ceylon.compiler.typechecker.model.Interface; import com.redhat.ceylon.compiler.typechecker.model.IntersectionType; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.NothingType; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ParameterList; import com.redhat.ceylon.compiler.typechecker.model.ProducedReference; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.ProducedTypedReference; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.TypeAlias; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.model.UnknownType; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.MemberLiteral; import com.redhat.ceylon.compiler.typechecker.tree.Util; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; import com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider; import com.redhat.ceylon.eclipse.code.parse.CeylonParseController; import com.redhat.ceylon.eclipse.core.builder.CeylonBuilder; import com.redhat.ceylon.eclipse.ui.CeylonPlugin; import com.redhat.ceylon.eclipse.ui.CeylonResources; public class CeylonContentProposer { public static Image DEFAULT_REFINEMENT = CeylonPlugin.getInstance() .getImageRegistry().get(CeylonResources.CEYLON_DEFAULT_REFINEMENT); public static Image FORMAL_REFINEMENT = CeylonPlugin.getInstance() .getImageRegistry().get(CeylonResources.CEYLON_FORMAL_REFINEMENT); /** * Returns an array of content proposals applicable relative to the AST of the given * parse controller at the given position. * * (The provided ITextViewer is not used in the default implementation provided here * but but is stipulated by the IContentProposer interface for purposes such as accessing * the IDocument for which content proposals are sought.) * * @param controller A parse controller from which the AST of the document being edited * can be obtained * @param int The offset for which content proposals are sought * @param viewer The viewer in which the document represented by the AST in the given * parse controller is being displayed (may be null for some implementations) * @return An array of completion proposals applicable relative to the AST of the given * parse controller at the given position */ public ICompletionProposal[] getContentProposals(CeylonParseController cpc, final int offset, ITextViewer viewer, boolean filter) { if (cpc==null || viewer==null || cpc.getRootNode()==null || cpc.getTokens()==null) { return null; } cpc.parse(viewer.getDocument(), new NullProgressMonitor(), null); cpc.getHandler().updateAnnotations(); List<CommonToken> tokens = cpc.getTokens(); Tree.CompilationUnit rn = cpc.getRootNode(); //compensate for the fact that we get sent an old //tree that doesn't contain the characters the user //just typed PositionedPrefix result = compensateForMissingCharacter(offset, viewer, tokens); if (result==null) { return null; } //adjust the token to account for unclosed blocks //we search for the first non-whitespace/non-comment //token to the left of the caret int tokenIndex = getTokenIndexAtCharacter(tokens, result.start); if (tokenIndex<0) tokenIndex = -tokenIndex; CommonToken adjustedToken = adjust(tokenIndex, offset, tokens); int tt = adjustedToken.getType(); if (offset<=adjustedToken.getStopIndex() && offset>=adjustedToken.getStartIndex()) { if (tt==MULTI_COMMENT||tt==LINE_COMMENT) { return null; } if (tt==STRING_LITERAL || tt==STRING_END || tt==STRING_MID || tt==STRING_START || tt==VERBATIM_STRING || tt==AVERBATIM_STRING || tt==CHAR_LITERAL || tt==FLOAT_LITERAL || tt==NATURAL_LITERAL) { return null; } } int line=-1; try { line = viewer.getDocument().getLineOfOffset(offset); } catch (BadLocationException e) { e.printStackTrace(); } if (tt==LINE_COMMENT && offset>=adjustedToken.getStartIndex() && adjustedToken.getLine()==line+1) { return null; } // overrrides above. TODO separate block for all non-typechecker proposals boolean inDoc = false; if ((tt==ASTRING_LITERAL || tt==AVERBATIM_STRING) && offset>adjustedToken.getStartIndex() && offset<adjustedToken.getStopIndex()) { result = getDocReferencePosition(offset, viewer, tokens); if (result == null) { return null; } inDoc = true; } //find the node at the token Node node = getTokenNode(adjustedToken.getStartIndex(), adjustedToken.getStopIndex()+1, tt, rn); //find the type that is expected in the current //location so we can prioritize proposals of that //type //TODO: this breaks as soon as the user starts typing // an expression, since RequiredTypeVisitor // doesn't know how to search up the tree for // the containing InvocationExpression RequiredTypeVisitor rtv = new RequiredTypeVisitor(node); rtv.visit(rn); ProducedType requiredType = rtv.getType(); //construct completions when outside ordinary code ICompletionProposal[] completions = constructCompletions(offset, result.prefix, cpc, node, adjustedToken); if (completions==null) { //finally, construct and sort proposals Map<String, DeclarationWithProximity> proposals = getProposals(node, result.prefix, result.isMemberOp, rn); filterProposals(filter, rn, requiredType, proposals); Set<DeclarationWithProximity> sortedProposals = sortProposals(result.prefix, requiredType, proposals); completions = constructCompletions(offset, result.prefix, sortedProposals, cpc, node, adjustedToken, result.isMemberOp, viewer.getDocument(), filter, inDoc); } return completions; } private void filterProposals(boolean filter, Tree.CompilationUnit rn, ProducedType requiredType, Map<String, DeclarationWithProximity> proposals) { if (filter) { Iterator<Map.Entry<String, DeclarationWithProximity>> iter = proposals.entrySet().iterator(); while (iter.hasNext()) { Declaration d = iter.next().getValue().getDeclaration(); ProducedType type = type(d); ProducedType fullType = fullType(d); if (requiredType!=null && (type==null || (!type.isSubtypeOf(requiredType) && !fullType.isSubtypeOf(requiredType)) || type.isSubtypeOf(rn.getUnit().getNullDeclaration().getType()))) { iter.remove(); } } } } public static OccurrenceLocation getOccurrenceLocation(Tree.CompilationUnit cu, Node node) { if (node.getToken()==null) return null; FindOccurrenceLocationVisitor visitor = new FindOccurrenceLocationVisitor(node); cu.visit(visitor); return visitor.getOccurrenceLocation(); } private static PositionedPrefix getDocReferencePosition(final int offset, ITextViewer viewer, List<CommonToken> tokens) { CommonToken token = getTokenAtCaret(offset, viewer, tokens); String text = viewer.getDocument().get().substring( token.getStartIndex(), token.getStopIndex() + 1); Matcher wikiRef = Pattern.compile("\\[\\[(.*?)\\]\\]").matcher(text); if (token==null || offset==0 || !wikiRef.find()) { return null; } int offsetInToken = offset-token.getStartIndex(); String prefix = null; wikiRef.reset(); while (wikiRef.find()) { for (int i = 1; i <= wikiRef.groupCount(); i++) { // loop for safety if (offsetInToken >= wikiRef.start(i) && offsetInToken <= wikiRef.end(i)) { prefix = wikiRef.group(i).substring(0, offsetInToken - wikiRef.start(i)); break; } } } if (prefix == null) { // it will be empty string if we are in a wiki ref return null; } return new PositionedPrefix(prefix, token.getStartIndex()); } private static PositionedPrefix compensateForMissingCharacter(final int offset, ITextViewer viewer, List<CommonToken> tokens) { //What is going on here is that when I have a list of proposals open //and then I type a character, IMP sends us the old syntax tree and //doesn't bother to even send us the character I just typed, except //in the ITextViewer. So we need to do some guessing to figure out //that there is a missing character in the token stream and take //corrective action. This should be fixed in IMP! return getPositionedPrefix(offset, viewer, getTokenAtCaret(offset, viewer, tokens)); } private static PositionedPrefix getPositionedPrefix(final int offset, ITextViewer viewer, CommonToken token) { String text = viewer.getDocument().get(); if (token==null || offset==0) { //no earlier token, so we're typing at the //start of an empty file return new PositionedPrefix(text.substring(0, offset), 0); } //try to guess the character the user just typed //(it would be the character immediately behind //the caret, i.e. at offset-1) char charAtOffset = text.charAt(offset-1); int offsetInToken = offset-1-token.getStartIndex(); boolean inToken = offsetInToken>=0 && offsetInToken<token.getText().length(); //int end = offset; if (inToken && charAtOffset==token.getText().charAt(offsetInToken)) { //then we're not missing the typed character //from the tree we were passed by IMP if (isIdentifierOrKeyword(token)) { return new PositionedPrefix( token.getText().substring(0, offsetInToken+1), token.getStartIndex()); } else { return new PositionedPrefix(offset, isMemberOperator(token)); } } else { //then we are missing the typed character from //the tree, along with possibly some other //previously typed characters boolean isIdentifierChar = isJavaIdentifierPart(charAtOffset); if (isIdentifierChar) { if (token.getType()==CeylonLexer.WS) { //we are typing in or after whitespace String prefix = text.substring(token.getStartIndex(), offset).trim(); return new PositionedPrefix(prefix, offset-prefix.length()-1); } else if (isIdentifierOrKeyword(token)) { //we are typing in or after within an //identifier or keyword String prefix = text.substring(token.getStartIndex(), offset); return new PositionedPrefix(prefix, token.getStartIndex()); } else if (offset<=token.getStopIndex()+1) { //we are typing in or after a comment //block or strings, etc - not much //useful compensation we can do here return new PositionedPrefix( Character.toString(charAtOffset), offset-1); } else { //after a member dereference and other //misc cases of punctuation, etc return new PositionedPrefix( text.substring(token.getStopIndex()+1, offset), token.getStopIndex()); } } //disable this for now cos it causes problem in //import statements /*else if (charAtOffset=='.') { return new PositionedPrefix(offset-2, true); } else {*/ return new PositionedPrefix(offset-1, false); //} } } private static CommonToken getTokenAtCaret(final int offset, ITextViewer viewer, List<CommonToken> tokens) { //find the token behind the caret, adjusting to an //earlier token if the token we find is not at the //same position in the current text (in which case //it is probably a token that actually comes after //what we are currently typing) if (offset==0) { return null; } int index = getTokenIndexAtCharacter(tokens, offset-1); if (index<0) index = -index; while (index>=0) { CommonToken token = (CommonToken) tokens.get(index); String text = viewer.getDocument().get(); boolean tokenHasMoved = text.charAt(token.getStartIndex())!= token.getText().charAt(0); if (!tokenHasMoved) { return token; } index--; } return null; } private static class PositionedPrefix { String prefix; int start; boolean isMemberOp; PositionedPrefix(String prefix, int start) { this.prefix=prefix; this.start=start; this.isMemberOp=false; } PositionedPrefix(int start, boolean isMemberOp) { this.prefix=""; this.isMemberOp=isMemberOp; this.start=start; } } private static CommonToken adjust(int tokenIndex, int offset, List<CommonToken> tokens) { CommonToken adjustedToken = tokens.get(tokenIndex); while (--tokenIndex>=0 && (adjustedToken.getType()==WS //ignore whitespace || adjustedToken.getType()==EOF || adjustedToken.getStartIndex()==offset)) { //don't consider the token to the right of the caret adjustedToken = tokens.get(tokenIndex); if (adjustedToken.getType()!=WS && adjustedToken.getType()!=EOF && adjustedToken.getChannel()!=CommonToken.HIDDEN_CHANNEL) { //don't adjust to a ws token break; } } return adjustedToken; } private static Boolean isDirectlyInsideBlock(Node node, CommonToken token, List<CommonToken> tokens) { Scope scope = node.getScope(); if (scope instanceof Interface || scope instanceof Package) { return false; } else { //TODO: check that it is not the opening/closing // brace of a named argument list! return !(node instanceof Tree.SequenceEnumeration) && occursAfterBraceOrSemicolon(token, tokens); } } private static Boolean occursAfterBraceOrSemicolon(CommonToken token, List<CommonToken> tokens) { if (token.getTokenIndex()==0) { return false; } else { int tokenType = token.getType(); if (tokenType==LBRACE || tokenType==RBRACE || tokenType==SEMICOLON) { return true; } int previousTokenType = adjust(token.getTokenIndex()-1, token.getStartIndex(), tokens).getType(); return previousTokenType==LBRACE || previousTokenType==RBRACE || previousTokenType==SEMICOLON; } } private static Node getTokenNode(int adjustedStart, int adjustedEnd, int tokenType, Tree.CompilationUnit rn) { Node node = findNode(rn, adjustedStart, adjustedEnd); if (tokenType==RBRACE || tokenType==SEMICOLON) { //We are to the right of a } or ; //so the returned node is the previous //statement/declaration. Look for the //containing body. class BodyVisitor extends Visitor { Node node, currentBody, result; BodyVisitor(Node node, Node root) { this.node = node; currentBody = root; } @Override public void visitAny(Node that) { if (that==node) { result = currentBody; } else { Node cb = currentBody; if (that instanceof Tree.Body) { currentBody = that; } if (that instanceof Tree.NamedArgumentList) { currentBody = that; } super.visitAny(that); currentBody = cb; } } } BodyVisitor mv = new BodyVisitor(node, rn); mv.visit(rn); node = mv.result; } if (node==null) node = rn; //we're in whitespace at the start of the file return node; } private static void addPackageCompletions(CeylonParseController cpc, int offset, String prefix, Tree.ImportPath path, Node node, List<ICompletionProposal> result) { String fullPath = fullPath(offset, prefix, path); addPackageCompletions(offset, prefix, node, result, fullPath.length(), fullPath+prefix, cpc); } private static void addModuleCompletions(CeylonParseController cpc, int offset, String prefix, Tree.ImportPath path, Node node, List<ICompletionProposal> result) { String fullPath = fullPath(offset, prefix, path); addModuleCompletions(offset, prefix, node, result, fullPath.length(), fullPath+prefix, cpc); } private static String fullPath(int offset, String prefix, Tree.ImportPath path) { StringBuilder fullPath = new StringBuilder(); if (path!=null) { fullPath.append(Util.formatPath(path.getIdentifiers())); fullPath.append('.'); fullPath.setLength(offset-path.getStartIndex()-prefix.length()); } return fullPath.toString(); } private static void addPackageCompletions(final int offset, final String prefix, Node node, List<ICompletionProposal> result, final int len, String pfp, final CeylonParseController cpc) { //TODO: someday it would be nice to propose from all packages // and auto-add the module dependency! /*TypeChecker tc = CeylonBuilder.getProjectTypeChecker(cpc.getProject().getRawProject()); if (tc!=null) { for (Module m: tc.getContext().getModules().getListOfModules()) {*/ //Set<Package> packages = new HashSet<Package>(); Unit unit = node.getUnit(); if (unit!=null) { //a null unit can occur if we have not finished parsing the file Module module = unit.getPackage().getModule(); for (final Package p: module.getAllPackages()) { //if (!packages.contains(p)) { //packages.add(p); //if ( p.getModule().equals(module) || p.isShared() ) { final String pkg = p.getQualifiedNameString(); if (!pkg.isEmpty() && pkg.startsWith(pfp)) { boolean already = false; if (!pfp.equals(pkg)) { //don't add already imported packages, unless //it is an exact match to the typed path for (ImportList il: node.getUnit().getImportLists()) { if (il.getImportedScope()==p) { already = true; break; } } } if (!already) { result.add(new CompletionProposal(offset, prefix, PACKAGE, pkg, pkg.substring(len) + " { ... }", false) { @Override public Point getSelection(IDocument document) { return new Point(offset+pkg.length()-prefix.length()-len+3, 3); } @Override public String getAdditionalProposalInfo() { return getDocumentationFor(cpc, p); } }); } } //} } } } private static final SortedSet<String> JDK_MODULE_VERSION_SET = new TreeSet<String>(); { JDK_MODULE_VERSION_SET.add(AbstractModelLoader.JDK_MODULE_VERSION); } private static void addModuleCompletions(int offset, String prefix, Node node, List<ICompletionProposal> result, int len, String pfp, final CeylonParseController cpc) { if (pfp.startsWith("java.")) { for (final String mod: JDKUtils.getJDKModuleNames()) { if (mod.startsWith(pfp)) { String versioned = getModuleString(mod, JDK_MODULE_VERSION); result.add(new CompletionProposal(offset, prefix, ARCHIVE, versioned, versioned.substring(len) + ";", false) { @Override public String getAdditionalProposalInfo() { return getDocumentationForModule(mod, JDK_MODULE_VERSION, "This module forms part of the Java SDK."); } }); } } } else { final TypeChecker tc = cpc.getTypeChecker(); if (tc!=null) { ModuleSearchResult results = tc.getContext().getRepositoryManager() .completeModules(new ModuleQuery(pfp, ModuleQuery.Type.JVM)); for (final ModuleDetails module: results.getResults()) { final String name = module.getName(); if (!name.equals(Module.DEFAULT_MODULE_NAME)) { for (final String version : module.getVersions().descendingSet()) { String versioned = getModuleString(name, version); result.add(new CompletionProposal(offset, prefix, ARCHIVE, versioned, versioned.substring(len) + ";", false) { @Override public String getAdditionalProposalInfo() { return JDKUtils.isJDKModule(name) ? "This module forms part of the Java SDK." : getDocumentationFor(module, version); } }); } } } } } } private static String getModuleString(final String name, final String version) { return name + " \"" + version + "\""; } private static boolean isIdentifierOrKeyword(Token token) { int type = token.getType(); return type==LIDENTIFIER || type==UIDENTIFIER || type==AIDENTIFIER || type==PIDENTIFIER || keywords.contains(token.getText()); } private static ICompletionProposal[] constructCompletions(final int offset, final String prefix, final CeylonParseController cpc, final Node node, CommonToken token) { final List<ICompletionProposal> result = new ArrayList<ICompletionProposal>(); if (node instanceof Tree.Import && offset>token.getStopIndex()+1) { addPackageCompletions(cpc, offset, prefix, null, node, result); } else if (node instanceof Tree.ImportModule && offset>token.getStopIndex()+1) { addModuleCompletions(cpc, offset, prefix, null, node, result); } else if (node instanceof Tree.ImportPath) { new Visitor() { @Override public void visit(Tree.Import that) { super.visit(that); if (that.getImportPath()==node) { addPackageCompletions(cpc, offset, prefix, (Tree.ImportPath) node, node, result); } } @Override public void visit(Tree.ImportModule that) { super.visit(that); if (that.getImportPath()==node) { addModuleCompletions(cpc, offset, prefix, (Tree.ImportPath) node, node, result); } } }.visit(cpc.getRootNode()); } else if (isEmptyModuleDescriptor(cpc)) { addModuleDescriptorCompletion(cpc, offset, prefix, result); addKeywordProposals(cpc, offset, prefix, result, node); } else if (isEmptyPackageDescriptor(cpc)) { addPackageDescriptorCompletion(cpc, offset, prefix, result); addKeywordProposals(cpc, offset, prefix, result, node); } else { return null; } return result.toArray(new ICompletionProposal[result.size()]); } private static ICompletionProposal[] constructCompletions(final int offset, final String prefix, Set<DeclarationWithProximity> set, final CeylonParseController cpc, final Node node, CommonToken token, boolean memberOp, IDocument doc, boolean filter, boolean inDoc) { final List<ICompletionProposal> result = new ArrayList<ICompletionProposal>(); if (node instanceof Tree.TypeConstraint) { for (DeclarationWithProximity dwp: set) { Declaration dec = dwp.getDeclaration(); if (isTypeParameterOfCurrentDeclaration(node, dec)) { addBasicProposal(offset, prefix, cpc, result, dwp, dec, null); } } } else { if ((node instanceof Tree.SimpleType || node instanceof Tree.BaseTypeExpression || node instanceof Tree.QualifiedTypeExpression) && prefix.isEmpty() && !memberOp) { addMemberNameProposal(offset, node, result); } else if (node instanceof Tree.TypedDeclaration && !(node instanceof Tree.Variable && ((Tree.Variable)node).getType() instanceof Tree.SyntheticVariable) && !(node instanceof Tree.InitializerParameter)) { addMemberNameProposal(offset, node, result); } else { OccurrenceLocation ol = getOccurrenceLocation(cpc.getRootNode(), node); if (!filter && !inDoc && !(node instanceof Tree.QualifiedMemberOrTypeExpression)) { addKeywordProposals(cpc, offset, prefix, result, node); //addTemplateProposal(offset, prefix, result); } boolean isPackageOrModuleDescriptor = isModuleDescriptor(cpc) || isPackageDescriptor(cpc); for (DeclarationWithProximity dwp: set) { Declaration dec = dwp.getDeclaration(); if (isPackageOrModuleDescriptor && !inDoc) { if (!dec.isAnnotation()||!(dec instanceof Method)) continue; } if (isParameterOfNamedArgInvocation(node, dwp)) { if (isDirectlyInsideNamedArgumentList(cpc, node, token)) { addNamedArgumentProposal(offset, prefix, cpc, result, dwp, dec, ol); addInlineFunctionProposal(offset, prefix, cpc, node, result, dec, doc); } } CommonToken nextToken = getNextToken(cpc, token); boolean noParamsFollow = noParametersFollow(nextToken); if (isInvocationProposable(dwp, ol) && !isQualifiedType(node) && !inDoc && noParamsFollow) { for (Declaration d: overloads(dec)) { ProducedReference pr = node instanceof Tree.QualifiedMemberOrTypeExpression ? getQualifiedProducedReference(node, d) : getRefinedProducedReference(node, d); addInvocationProposals(offset, prefix, cpc, result, new DeclarationWithProximity(d, dwp), pr, ol); } } if (isProposable(dwp, ol, node.getScope()) && (definitelyRequiresType(ol) || noParamsFollow || dwp.getDeclaration() instanceof Functional)) { addBasicProposal(offset, prefix, cpc, result, dwp, dec, ol); } if (isProposable(dwp, ol, node.getScope()) && isDirectlyInsideBlock(node, token, cpc.getTokens()) && !memberOp && !filter) { addForProposal(offset, prefix, cpc, result, dwp, dec, ol); addIfExistsProposal(offset, prefix, cpc, result, dwp, dec, ol); addSwitchProposal(offset, prefix, cpc, result, dwp, dec, ol, node, doc); } if (isRefinementProposable(dec, ol) && !memberOp && !filter) { for (Declaration d: overloads(dec)) { addRefinementProposal(offset, prefix, cpc, node, result, d, doc); } } } } } return result.toArray(new ICompletionProposal[result.size()]); } private static boolean isQualifiedType(Node node) { return (node instanceof Tree.QualifiedType) || (node instanceof Tree.QualifiedMemberOrTypeExpression && ((Tree.QualifiedMemberOrTypeExpression) node).getStaticMethodReference()); } private static boolean isPackageDescriptor(CeylonParseController cpc) { return cpc.getRootNode() != null && cpc.getRootNode().getUnit() != null && cpc.getRootNode().getUnit().getFilename().equals("package.ceylon"); } private static boolean isModuleDescriptor(CeylonParseController cpc) { return cpc.getRootNode() != null && cpc.getRootNode().getUnit() != null && cpc.getRootNode().getUnit().getFilename().equals("module.ceylon"); } private static boolean isEmptyModuleDescriptor(CeylonParseController cpc) { return isModuleDescriptor(cpc) && cpc.getRootNode() != null && cpc.getRootNode().getModuleDescriptor() == null; } private static void addModuleDescriptorCompletion(CeylonParseController cpc, int offset, String prefix, List<ICompletionProposal> result) { if (!"module".startsWith(prefix)) return; IFile file = cpc.getProject().getFile(cpc.getPath()); String moduleName = CeylonBuilder.getPackageName(file); String moduleDesc = "module " + moduleName; String moduleText = "module " + moduleName + " \"1.0.0\" {}"; final int selectionStart = offset - prefix.length() + moduleName.length() + 9; final int selectionLength = 5; result.add(new CompletionProposal(offset, prefix, ARCHIVE, moduleDesc, moduleText, false) { @Override public Point getSelection(IDocument document) { return new Point(selectionStart, selectionLength); }}); } private static boolean isEmptyPackageDescriptor(CeylonParseController cpc) { return cpc.getRootNode() != null && cpc.getRootNode().getUnit() != null && cpc.getRootNode().getUnit().getFilename().equals("package.ceylon") && cpc.getRootNode().getPackageDescriptor() == null; } private static void addPackageDescriptorCompletion(CeylonParseController cpc, int offset, String prefix, List<ICompletionProposal> result) { if (!"package".startsWith(prefix)) return; IFile file = cpc.getProject().getFile(cpc.getPath()); String packageName = CeylonBuilder.getPackageName(file); String packageDesc = "package " + packageName; String packageText = "package " + packageName + ";"; result.add(new CompletionProposal(offset, prefix, PACKAGE, packageDesc, packageText, false)); } private static boolean noParametersFollow(CommonToken nextToken) { return nextToken==null || //should we disable this, since a statement //can in fact begin with an LPAREN?? nextToken.getType()!=CeylonLexer.LPAREN //disabled now because a declaration can //begin with an LBRACE (an Iterable type) /*&& nextToken.getType()!=CeylonLexer.LBRACE*/; } private static boolean definitelyRequiresType(OccurrenceLocation ol) { return ol==SATISFIES || ol==OF || ol==UPPER_BOUND || ol==TYPE_ALIAS; } private static CommonToken getNextToken(final CeylonParseController cpc, CommonToken token) { int i = token.getTokenIndex(); CommonToken nextToken=null; List<CommonToken> tokens = cpc.getTokens(); do { if (++i<tokens.size()) { nextToken = tokens.get(i); } else { break; } } while (nextToken.getChannel()==CommonToken.HIDDEN_CHANNEL); return nextToken; } private static boolean isDirectlyInsideNamedArgumentList( CeylonParseController cpc, Node node, CommonToken token) { return node instanceof Tree.NamedArgumentList || (!(node instanceof Tree.SequenceEnumeration) && occursAfterBraceOrSemicolon(token, cpc.getTokens())); } private static boolean isMemberOperator(Token token) { int type = token.getType(); return type==CeylonLexer.MEMBER_OP || type==CeylonLexer.SPREAD_OP || type==CeylonLexer.SAFE_MEMBER_OP; } public static List<Declaration> overloads(Declaration dec) { if (dec instanceof Functional && ((Functional)dec).isAbstraction()) { return ((Functional)dec).getOverloads(); } else { return Collections.singletonList(dec); } } /*private static boolean isKeywordProposable(OccurrenceLocation ol) { return ol==null || ol==EXPRESSION; }*/ private static boolean isRefinementProposable(Declaration dec, OccurrenceLocation ol) { return ol==null && (dec instanceof MethodOrValue || dec instanceof Class); } private static boolean isInvocationProposable(DeclarationWithProximity dwp, OccurrenceLocation ol) { Declaration dec = dwp.getDeclaration(); return dec instanceof Functional && //!((Functional) dec).getParameterLists().isEmpty() && (ol==null || ol==EXPRESSION && ( !(dec instanceof Class) || !((Class)dec).isAbstract()) || ol==EXTENDS && dec instanceof Class && !((Class)dec).isFinal() || ol==CLASS_ALIAS && dec instanceof Class || ol==PARAMETER_LIST && dec instanceof Method && dec.isAnnotation()) && dwp.getNamedArgumentList()==null && (!dec.isAnnotation() || !(dec instanceof Method) || !((Method)dec).getParameterLists().isEmpty() && !((Method)dec).getParameterLists().get(0).getParameters().isEmpty()); } private static boolean isProposable(DeclarationWithProximity dwp, OccurrenceLocation ol, Scope scope) { Declaration dec = dwp.getDeclaration(); return (ol!=EXTENDS || dec instanceof Class && !((Class)dec).isFinal()) && (ol!=CLASS_ALIAS || dec instanceof Class) && (ol!=SATISFIES || dec instanceof Interface) && (ol!=OF || dec instanceof Class || (dec instanceof Value && ((Value) dec).getTypeDeclaration()!=null && ((Value) dec).getTypeDeclaration().isAnonymous())) && ((ol!=TYPE_ARGUMENT_LIST && ol!=UPPER_BOUND && ol!=TYPE_ALIAS) || dec instanceof TypeDeclaration) && (ol!=PARAMETER_LIST || dec instanceof TypeDeclaration || dec instanceof Method && dec.isAnnotation() || //i.e. an annotation dec instanceof Value && dec.getContainer().equals(scope)) && //a parameter ref (ol!=IMPORT || !dwp.isUnimported()) && ol!=TYPE_PARAMETER_LIST && dwp.getNamedArgumentList()==null; } private static boolean isTypeParameterOfCurrentDeclaration(Node node, Declaration d) { //TODO: this is a total mess and totally error-prone - figure out something better! return d instanceof TypeParameter && (((TypeParameter) d).getContainer()==node.getScope() || ((Tree.TypeConstraint) node).getDeclarationModel()!=null && ((TypeParameter) d).getContainer()==((Tree.TypeConstraint) node).getDeclarationModel().getContainer()); } private static void addInlineFunctionProposal(int offset, String prefix, CeylonParseController cpc, Node node, List<ICompletionProposal> result, Declaration d, IDocument doc) { //TODO: type argument substitution using the ProducedReference of the primary node if (d.isParameter()) { Parameter p = ((MethodOrValue) d).getInitializerParameter(); result.add(new RefinementCompletionProposal(offset, prefix, getInlineFunctionDescriptionFor(p, null), getInlineFunctionTextFor(p, null, "\n" + getIndent(node, doc)), cpc, d)); } } /*private static boolean isParameterOfNamedArgInvocation(Node node, Declaration d) { if (node instanceof Tree.NamedArgumentList) { ParameterList pl = ((Tree.NamedArgumentList) node).getNamedArgumentList() .getParameterList(); return d instanceof Parameter && pl!=null && pl.getParameters().contains(d); } else if (node.getScope() instanceof NamedArgumentList) { ParameterList pl = ((NamedArgumentList) node.getScope()).getParameterList(); return d instanceof Parameter && pl!=null && pl.getParameters().contains(d); } else { return false; } }*/ private static boolean isParameterOfNamedArgInvocation(Node node, DeclarationWithProximity d) { return node.getScope()==d.getNamedArgumentList(); } private static void addRefinementProposal(int offset, String prefix, final CeylonParseController cpc, Node node, List<ICompletionProposal> result, final Declaration d, IDocument doc) { if ((d.isDefault() || d.isFormal()) && node.getScope() instanceof ClassOrInterface && ((ClassOrInterface) node.getScope()).isInheritedFromSupertype(d)) { boolean isInterface = node.getScope() instanceof Interface; ProducedReference pr = getRefinedProducedReference(node, d); //TODO: if it is equals() or hash, fill in the implementation result.add(new RefinementCompletionProposal(offset, prefix, getRefinementDescriptionFor(d, pr), getRefinementTextFor(d, pr, isInterface, "\n" + getIndent(node, doc)), cpc, d)); } } public static ProducedReference getQualifiedProducedReference(Node node, Declaration d) { ProducedType pt = ((Tree.QualifiedMemberOrTypeExpression) node) .getPrimary().getTypeModel(); if (pt!=null && d.isClassOrInterfaceMember()) { pt = pt.getSupertype((TypeDeclaration)d.getContainer()); } return d.getProducedReference(pt, Collections.<ProducedType>emptyList()); } public static ProducedReference getRefinedProducedReference(Node node, Declaration d) { return refinedProducedReference(node.getScope().getDeclaringType(d), d); } public static ProducedReference getRefinedProducedReference(ProducedType superType, Declaration d) { if (superType.getDeclaration() instanceof IntersectionType) { for (ProducedType pt: superType.getDeclaration().getSatisfiedTypes()) { ProducedReference result = getRefinedProducedReference(pt, d); if (result!=null) return result; } return null; //never happens? } else { ProducedType declaringType = superType.getDeclaration().getDeclaringType(d); if (declaringType==null) return null; ProducedType outerType = superType.getSupertype(declaringType.getDeclaration()); return refinedProducedReference(outerType, d); } } private static ProducedReference refinedProducedReference(ProducedType outerType, Declaration d) { List<ProducedType> params = new ArrayList<ProducedType>(); if (d instanceof Generic) { for (TypeParameter tp: ((Generic)d).getTypeParameters()) { params.add(tp.getType()); } } return d.getProducedReference(outerType, params); } private static void addBasicProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d, OccurrenceLocation ol) { result.add(new DeclarationCompletionProposal(offset, prefix, getDescriptionFor(dwp, ol), getTextFor(dwp, ol), true, cpc, d, dwp.isUnimported())); } private static void addForProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d, OccurrenceLocation ol) { if (d instanceof Value) { TypedDeclaration td = (TypedDeclaration) d; if (td.getType()!=null && d.getUnit().isIterableType(td.getType())) { String elemName; if (d.getName().length()==1) { elemName = "element"; } else if (d.getName().endsWith("s")) { elemName = d.getName().substring(0, d.getName().length()-1); } else { elemName = d.getName().substring(0, 1); } result.add(new DeclarationCompletionProposal(offset, prefix, "for (" + elemName + " in " + getDescriptionFor(dwp, ol) + ")", "for (" + elemName + " in " + getTextFor(dwp, ol) + ") {}", true, cpc, d)); } } } private static void addIfExistsProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d, OccurrenceLocation ol) { if (!dwp.isUnimported()) { if (d instanceof Value) { TypedDeclaration v = (TypedDeclaration) d; if (v.getType()!=null && d.getUnit().isOptionalType(v.getType()) && !v.isVariable()) { result.add(new DeclarationCompletionProposal(offset, prefix, "if (exists " + getDescriptionFor(dwp, ol) + ")", "if (exists " + getTextFor(dwp, ol) + ") {}", true, cpc, d)); } } } } private static void addSwitchProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d, OccurrenceLocation ol, Node node, IDocument doc) { if (!dwp.isUnimported()) { if (d instanceof Value) { TypedDeclaration v = (TypedDeclaration) d; if (v.getType()!=null && v.getType().getCaseTypes()!=null && !v.isVariable()) { StringBuilder body = new StringBuilder(); String indent = getIndent(node, doc); for (ProducedType pt: v.getType().getCaseTypes()) { body.append(indent).append("case ("); if (!pt.getDeclaration().isAnonymous()) { body.append("is "); } body.append(pt.getProducedTypeName()); body.append(") {}\n"); } body.append(indent); result.add(new DeclarationCompletionProposal(offset, prefix, "switch (" + getDescriptionFor(dwp, ol) + ")", "switch (" + getTextFor(dwp, ol) + ")\n" + body, true, cpc, d)); } } } } private static void addNamedArgumentProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d, OccurrenceLocation ol) { result.add(new DeclarationCompletionProposal(offset, prefix, getDescriptionFor(dwp, ol), getTextFor(dwp, ol) + " = nothing;", true, cpc, d)); } private static void addInvocationProposals(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, ProducedReference pr, OccurrenceLocation ol) { Declaration d = pr.getDeclaration(); if (!(d instanceof Functional)) return; boolean isAbstractClass = d instanceof Class && ((Class) d).isAbstract(); Functional fd = (Functional) d; List<ParameterList> pls = fd.getParameterLists(); if (!pls.isEmpty()) { List<Parameter> ps = pls.get(0).getParameters(); int defaulted = 0; for (Parameter p: ps) { if (p.isDefaulted()) { defaulted ++; } } if (!isAbstractClass || ol==EXTENDS) { if (defaulted>0) { result.add(new DeclarationCompletionProposal(offset, prefix, getPositionalInvocationDescriptionFor(dwp, ol, pr, false), getPositionalInvocationTextFor(dwp, ol, pr, false), true, cpc, d, dwp.isUnimported())); } result.add(new DeclarationCompletionProposal(offset, prefix, getPositionalInvocationDescriptionFor(dwp, ol, pr, true), getPositionalInvocationTextFor(dwp, ol, pr, true), true, cpc, d, dwp.isUnimported())); } if (!isAbstractClass && ol!=EXTENDS && !fd.isOverloaded()) { //if there is at least one parameter, //suggest a named argument invocation if (defaulted>0 && ps.size()>defaulted) { result.add(new DeclarationCompletionProposal(offset, prefix, getNamedInvocationDescriptionFor(dwp, pr, false), getNamedInvocationTextFor(dwp, pr, false), true, cpc, d, dwp.isUnimported())); } if (!ps.isEmpty()) { result.add(new DeclarationCompletionProposal(offset, prefix, getNamedInvocationDescriptionFor(dwp, pr, true), getNamedInvocationTextFor(dwp, pr, true), true, cpc, d, dwp.isUnimported())); } } } } protected static void addMemberNameProposal(int offset, Node node, List<ICompletionProposal> result) { String suggestedName = null; String prefix = ""; if (node instanceof Tree.TypeDeclaration) { /*Tree.TypeDeclaration td = (Tree.TypeDeclaration) node; prefix = td.getIdentifier()==null ? "" : td.getIdentifier().getText(); suggestedName = prefix;*/ //TODO: dictionary completions? return; } else if (node instanceof Tree.TypedDeclaration) { Tree.TypedDeclaration td = (Tree.TypedDeclaration) node; prefix = td.getIdentifier()==null ? "" : td.getIdentifier().getText(); suggestedName = prefix; if (td.getType() instanceof Tree.SimpleType) { String type = ((Tree.SimpleType) td.getType()).getIdentifier().getText(); if (lower(type).startsWith(prefix)) { result.add(new CompletionProposal(offset, prefix, null, lower(type), escape(lower(type)), false)); } if (!suggestedName.endsWith(type)) { suggestedName += type; } result.add(new CompletionProposal(offset, prefix, null, lower(suggestedName), escape(lower(suggestedName)), false)); } return; } else if (node instanceof Tree.SimpleType) { suggestedName = ((Tree.SimpleType) node).getIdentifier().getText(); } else if (node instanceof Tree.BaseTypeExpression) { suggestedName = ((Tree.BaseTypeExpression) node).getIdentifier().getText(); } else if (node instanceof Tree.QualifiedTypeExpression) { suggestedName = ((Tree.QualifiedTypeExpression) node).getIdentifier().getText(); } if (suggestedName!=null) { result.add(new CompletionProposal(offset, "", null, lower(suggestedName), escape(lower(suggestedName)), false)); } } private static String lower(String suggestedName) { return Character.toLowerCase(suggestedName.charAt(0)) + suggestedName.substring(1); } private static String escape(String suggestedName) { if (keywords.contains(suggestedName)) { return "\\i" + suggestedName; } else { return suggestedName; } } private static void addKeywordProposals(CeylonParseController cpc, int offset, String prefix, List<ICompletionProposal> result, Node node) { if( isModuleDescriptor(cpc) ) { if( prefix.isEmpty() || "import".startsWith(prefix) ) { if (node instanceof Tree.CompilationUnit) { Tree.ModuleDescriptor moduleDescriptor = ((Tree.CompilationUnit) node).getModuleDescriptor(); if (moduleDescriptor != null && moduleDescriptor.getImportModuleList() != null && moduleDescriptor.getImportModuleList().getStartIndex() < offset ) { addKeywordProposal(offset, prefix, result, "import"); } } else if (node instanceof Tree.ImportModuleList || node instanceof Tree.BaseMemberExpression) { addKeywordProposal(offset, prefix, result, "import"); } } } else if (!prefix.isEmpty()) { for (String keyword: keywords) { if (keyword.startsWith(prefix)) { addKeywordProposal(offset, prefix, result, keyword); } } } } private static void addKeywordProposal(int offset, String prefix, List<ICompletionProposal> result, final String keyword) { result.add(new CompletionProposal(offset, prefix, null, keyword, keyword, true) { @Override public StyledString getStyledDisplayString() { return new StyledString(keyword, CeylonLabelProvider.KW_STYLER); } }); } /*private static void addTemplateProposal(int offset, String prefix, List<ICompletionProposal> result) { if (!prefix.isEmpty()) { if ("class".startsWith(prefix)) { String prop = "class Class() {}"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } if ("interface".startsWith(prefix)) { String prop = "interface Interface {}"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } if ("void".startsWith(prefix)) { String prop = "void method() {}"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } if ("function".startsWith(prefix)) { String prop = "function method() { return nothing; }"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } if ("value".startsWith(prefix)) { String prop = "value attribute = nothing;"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); prop = "value attribute { return nothing; }"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } if ("object".startsWith(prefix)) { String prop = "object instance {}"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } } }*/ /*private static String getDocumentationFor(CeylonParseController cpc, Declaration d) { return getDocumentation(getReferencedNode(d, getCompilationUnit(cpc, d))); }*/ private static Set<DeclarationWithProximity> sortProposals(final String prefix, final ProducedType type, Map<String, DeclarationWithProximity> proposals) { Set<DeclarationWithProximity> set = new TreeSet<DeclarationWithProximity>( new Comparator<DeclarationWithProximity>() { public int compare(DeclarationWithProximity x, DeclarationWithProximity y) { boolean xbt = x.getDeclaration() instanceof NothingType; boolean ybt = y.getDeclaration() instanceof NothingType; if (xbt&&ybt) { return 0; } if (xbt&&!ybt) { return 1; } if (ybt&&!xbt) { return -1; } ProducedType xtype = type(x.getDeclaration()); ProducedType ytype = type(y.getDeclaration()); boolean xbottom = xtype!=null && xtype.getDeclaration() instanceof NothingType; boolean ybottom = ytype!=null && ytype.getDeclaration() instanceof NothingType; if (xbottom && !ybottom) { return 1; } if (ybottom && !xbottom) { return -1; } String xName = x.getName(); String yName = y.getName(); if (!prefix.isEmpty() && isUpperCase(prefix.charAt(0))) { if (isLowerCase(xName.charAt(0)) && isUpperCase(yName.charAt(0))) { return 1; } else if (isUpperCase(xName.charAt(0)) && isLowerCase(yName.charAt(0))) { return -1; } } if (type!=null) { boolean xassigns = xtype!=null && xtype.isSubtypeOf(type); boolean yassigns = ytype!=null && ytype.isSubtypeOf(type); if (xassigns && !yassigns) { return -1; } if (yassigns && !xassigns) { return 1; } if (xassigns && yassigns) { boolean xtd = x.getDeclaration() instanceof TypedDeclaration; boolean ytd = y.getDeclaration() instanceof TypedDeclaration; if (xtd && !ytd) { return -1; } if (ytd && !xtd) { return 1; } } } if (x.getProximity()!=y.getProximity()) { return new Integer(x.getProximity()).compareTo(y.getProximity()); } //if (!prefix.isEmpty() && isLowerCase(prefix.charAt(0))) { if (isLowerCase(xName.charAt(0)) && isUpperCase(yName.charAt(0))) { return -1; } else if (isUpperCase(xName.charAt(0)) && isLowerCase(yName.charAt(0))) { return 1; } int nc = xName.compareTo(yName); if (nc==0) { String xqn = x.getDeclaration().getQualifiedNameString(); String yqn = y.getDeclaration().getQualifiedNameString(); return xqn.compareTo(yqn); } else { return nc; } } }); set.addAll(proposals.values()); return set; } static ProducedType type(Declaration d) { if (d instanceof TypeDeclaration) { if (d instanceof Class) { if (!((Class) d).isAbstract()) { return ((TypeDeclaration) d).getType(); } } return null; } else if (d instanceof TypedDeclaration) { return ((TypedDeclaration) d).getType(); } else { return null;//impossible } } static ProducedType fullType(Declaration d) { //TODO: substitute type args from surrounding scope return d.getProducedReference(null, Collections.<ProducedType>emptyList()).getFullType(); } public static Map<String, DeclarationWithProximity> getProposals(Node node, Tree.CompilationUnit cu) { return getProposals(node, "", false, cu); } private static Map<String, DeclarationWithProximity> getProposals(Node node, String prefix, boolean memberOp, Tree.CompilationUnit cu) { if (node instanceof MemberLiteral) { //this case is rather ugly! Tree.StaticType mlt = ((Tree.MemberLiteral) node).getType(); if (mlt!=null) { ProducedType type = mlt.getTypeModel(); if (type!=null) { return type.resolveAliases().getDeclaration() .getMatchingMemberDeclarations(node.getScope(), prefix, 0); } else { return Collections.emptyMap(); } } } if (node instanceof Tree.QualifiedMemberOrTypeExpression) { Tree.QualifiedMemberOrTypeExpression qmte = (Tree.QualifiedMemberOrTypeExpression) node; ProducedType type = getPrimaryType((Tree.QualifiedMemberOrTypeExpression) node); if (qmte.getStaticMethodReference()) { type = node.getUnit().getCallableReturnType(type); } if (type!=null) { return type.resolveAliases().getDeclaration() .getMatchingMemberDeclarations(node.getScope(), prefix, 0); } else if (qmte.getPrimary() instanceof Tree.MemberOrTypeExpression) { //it might be a qualified type or even a static method reference Declaration pmte = ((Tree.MemberOrTypeExpression) qmte.getPrimary()).getDeclaration(); if (pmte instanceof TypeDeclaration) { type = ((TypeDeclaration) pmte).getType(); if (type!=null) { return type.resolveAliases().getDeclaration() .getMatchingMemberDeclarations(node.getScope(), prefix, 0); } } } return Collections.emptyMap(); } else if (node instanceof Tree.QualifiedType) { ProducedType type = ((Tree.QualifiedType) node).getOuterType().getTypeModel(); if (type!=null) { return type.resolveAliases().getDeclaration() .getMatchingMemberDeclarations(node.getScope(), prefix, 0); } else { return Collections.emptyMap(); } } else if (memberOp && node instanceof Tree.Term) { ProducedType type = ((Tree.Term)node).getTypeModel(); if (type!=null) { return type.resolveAliases().getDeclaration() .getMatchingMemberDeclarations(node.getScope(), prefix, 0); } else { return Collections.emptyMap(); } } else { Scope scope = node.getScope(); if (scope instanceof ImportList) { return ((ImportList) scope).getMatchingDeclarations(null, prefix, 0); } else { return scope==null ? //a null scope occurs when we have not finished parsing the file getUnparsedProposals(cu, prefix) : scope.getMatchingDeclarations(node.getUnit(), prefix, 0); } } } private static ProducedType getPrimaryType(Tree.QualifiedMemberOrTypeExpression qme) { ProducedType type = qme.getPrimary().getTypeModel(); if (type==null) return null; if (qme.getMemberOperator() instanceof Tree.SafeMemberOp) { return qme.getUnit().getDefiniteType(type); } else if (qme.getMemberOperator() instanceof Tree.SpreadOp) { return qme.getUnit().getIteratedType(type); } else { return type; } } private static Map<String, DeclarationWithProximity> getUnparsedProposals(Node node, String prefix) { if (node == null) { return new TreeMap<String, DeclarationWithProximity>(); } Unit unit = node.getUnit(); if (unit == null) { return new TreeMap<String, DeclarationWithProximity>(); } Package pkg = unit.getPackage(); if (pkg == null) { return new TreeMap<String, DeclarationWithProximity>(); } return pkg.getModule().getAvailableDeclarations(prefix); } private static boolean forceExplicitTypeArgs(Declaration d, OccurrenceLocation ol) { if (ol==EXTENDS) { return true; } else { //TODO: this is a pretty limited implementation // for now, but eventually we could do // something much more sophisticated to // guess is explicit type args will be // necessary (variance, etc) if (d instanceof Functional) { List<ParameterList> pls = ((Functional) d).getParameterLists(); return pls.isEmpty() || pls.get(0).getParameters().isEmpty(); } else { return false; } } } private static String name(DeclarationWithProximity d) { return name(d.getDeclaration(), d.getName()); } private static String name(Declaration d) { return name(d, d.getName()); } private static String name(Declaration d, String alias) { char c = alias.charAt(0); if (d instanceof TypedDeclaration && (isUpperCase(c)||"object".equals(alias))) { return "\\i" + alias; } else if (d instanceof TypeDeclaration && !(d instanceof Class && d.isAnonymous()) && isLowerCase(c)) { return "\\I" + alias; } else { return alias; } } private static String getTextFor(DeclarationWithProximity d, OccurrenceLocation ol) { StringBuilder result = new StringBuilder(name(d)); if (ol!=IMPORT) appendTypeParameters(d.getDeclaration(), result); return result.toString(); } private static String getPositionalInvocationTextFor(DeclarationWithProximity d, OccurrenceLocation ol, ProducedReference pr, boolean includeDefaulted) { StringBuilder result = new StringBuilder(name(d)); Declaration dd = d.getDeclaration(); if (forceExplicitTypeArgs(dd, ol)) appendTypeParameters(dd, result); appendPositionalArgs(dd, pr, result, includeDefaulted); appendSemiToVoidInvocation(result, dd); return result.toString(); } private static String getNamedInvocationTextFor(DeclarationWithProximity d, ProducedReference pr, boolean includeDefaulted) { StringBuilder result = new StringBuilder(name(d)); Declaration dd = d.getDeclaration(); if (forceExplicitTypeArgs(dd, null)) appendTypeParameters(dd, result); appendNamedArgs(dd, pr, result, includeDefaulted, false); appendSemiToVoidInvocation(result, dd); return result.toString(); } private static void appendSemiToVoidInvocation(StringBuilder result, Declaration dd) { if ((dd instanceof Method) && ((Method) dd).isDeclaredVoid() && ((Method) dd).getParameterLists().size()==1) { result.append(';'); } } private static String getDescriptionFor(DeclarationWithProximity d, OccurrenceLocation ol) { StringBuilder result = new StringBuilder(d.getName()); if (ol!=IMPORT) appendTypeParameters(d.getDeclaration(), result); return result.toString(); } private static String getPositionalInvocationDescriptionFor(DeclarationWithProximity d, OccurrenceLocation ol, ProducedReference pr, boolean includeDefaulted) { StringBuilder result = new StringBuilder(d.getName()); if (forceExplicitTypeArgs(d.getDeclaration(), ol)) appendTypeParameters(d.getDeclaration(), result); appendPositionalArgs(d.getDeclaration(), pr, result, includeDefaulted); return result.toString(); } private static String getNamedInvocationDescriptionFor(DeclarationWithProximity d, ProducedReference pr, boolean includeDefaulted) { StringBuilder result = new StringBuilder(d.getName()); if (forceExplicitTypeArgs(d.getDeclaration(), null)) appendTypeParameters(d.getDeclaration(), result); appendNamedArgs(d.getDeclaration(), pr, result, includeDefaulted, true); return result.toString(); } public static String getRefinementTextFor(Declaration d, ProducedReference pr, boolean isInterface, String indent) { StringBuilder result = new StringBuilder("shared actual "); if (isVariable(d) && !isInterface) { result.append("variable "); } appendDeclarationText(d, pr, result); appendTypeParameters(d, result); appendParameters(d, pr, result); if (d instanceof Class) { result.append(extraIndent(extraIndent(indent))) .append(" extends super.").append(d.getName()); appendPositionalArgs(d, pr, result, true); } appendConstraints(d, pr, indent, result); appendImpl(d, isInterface, indent, result); return result.toString(); } private static void appendConstraints(Declaration d, ProducedReference pr, String indent, StringBuilder result) { if (d instanceof Functional) { for (TypeParameter tp: ((Functional) d).getTypeParameters()) { List<ProducedType> sts = tp.getSatisfiedTypes(); if (!sts.isEmpty()) { result.append(extraIndent(extraIndent(indent))) .append("given ").append(tp.getName()) .append(" satisfies "); boolean first = true; for (ProducedType st: sts) { if (first) { first = false; } else { result.append("&"); } result.append(st.substitute(pr.getTypeArguments()).getProducedTypeName()); } } } } } private static String getInlineFunctionTextFor(Parameter p, ProducedReference pr, String indent) { StringBuilder result = new StringBuilder(); appendNamedArgumentText(p, pr, result); appendTypeParameters(p.getModel(), result); appendParameters(p.getModel(), pr, result); appendImpl(p.getModel(), false, indent, result); return result.toString(); } private static boolean isVariable(Declaration d) { return d instanceof TypedDeclaration && ((TypedDeclaration) d).isVariable(); } /*private static String getAttributeRefinementTextFor(Declaration d) { StringBuilder result = new StringBuilder(); result.append("super.").append(d.getName()) .append(" = ").append(d.getName()).append(";"); return result.toString(); }*/ private static String getRefinementDescriptionFor(Declaration d, ProducedReference pr) { StringBuilder result = new StringBuilder("shared actual "); if (isVariable(d)) { result.append("variable "); } appendDeclarationText(d, pr, result); appendTypeParameters(d, result); appendParameters(d, pr, result); /*result.append(" - refine declaration in ") .append(((Declaration) d.getContainer()).getName());*/ return result.toString(); } private static String getInlineFunctionDescriptionFor(Parameter p, ProducedReference pr) { StringBuilder result = new StringBuilder(); appendNamedArgumentText(p, pr, result); appendTypeParameters(p.getModel(), result); appendParameters(p.getModel(), pr, result); /*result.append(" - refine declaration in ") .append(((Declaration) d.getContainer()).getName());*/ return result.toString(); } public static String getDescriptionFor(Declaration d) { StringBuilder result = new StringBuilder(); if (d!=null) { if (d.isFormal()) result.append("formal "); if (d.isDefault()) result.append("default "); appendDeclarationText(d, result); appendTypeParameters(d, result); appendParameters(d, result); /*result.append(" - refine declaration in ") .append(((Declaration) d.getContainer()).getName());*/ } return result.toString(); } public static StyledString getStyledDescriptionFor(Declaration d) { StyledString result = new StyledString(); if (d!=null) { if (d.isFormal()) result.append("formal ", ANN_STYLER); if (d.isDefault()) result.append("default ", ANN_STYLER); appendDeclarationText(d, result); appendTypeParameters(d, result); appendParameters(d, result); /*result.append(" - refine declaration in ") .append(((Declaration) d.getContainer()).getName());*/ } return result; } private static void appendPositionalArgs(Declaration d, ProducedReference pr, StringBuilder result, boolean includeDefaulted) { if (d instanceof Functional) { List<Parameter> params = getParameters((Functional) d, includeDefaulted); if (params.isEmpty()) { result.append("()"); } else { result.append("("); for (Parameter p: params) { appendParameters(p.getModel(), pr.getTypedParameter(p), result); if (p.getModel() instanceof Functional) { result.append(" => "); } result.append(p.getName()).append(", "); } result.setLength(result.length()-2); result.append(")"); } } } private static List<Parameter> getParameters(Functional fd, boolean includeDefaults) { List<ParameterList> plists = fd.getParameterLists(); if (plists==null || plists.isEmpty()) { return Collections.<Parameter>emptyList(); } List<Parameter> pl = plists.get(0).getParameters(); if (includeDefaults) { return pl; } else { List<Parameter> list = new ArrayList<Parameter>(); for (Parameter p: pl) { if (!p.isDefaulted()) list.add(p); } return list; } } private static void appendNamedArgs(Declaration d, ProducedReference pr, StringBuilder result, boolean includeDefaulted, boolean descriptionOnly) { if (d instanceof Functional) { List<Parameter> params = getParameters((Functional) d, includeDefaulted); if (params.isEmpty()) { result.append(" {}"); } else { result.append(" { "); for (Parameter p: params) { if (!p.isSequenced()) { if (p.getModel() instanceof Functional) { result.append("function ").append(p.getName()); appendParameters(p.getModel(), pr.getTypedParameter(p), result); if (descriptionOnly) { result.append("; "); } else { result.append(" => ") //.append(CeylonQuickFixAssistant.defaultValue(p.getUnit(), p.getType())) .append("nothing") .append("; "); } } else { result.append(p.getName()).append(" = ") //.append(CeylonQuickFixAssistant.defaultValue(p.getUnit(), p.getType())) .append("nothing") .append("; "); } } } result.append("}"); } } } private static void appendTypeParameters(Declaration d, StringBuilder result) { if (d instanceof Generic) { List<TypeParameter> types = ((Generic) d).getTypeParameters(); if (!types.isEmpty()) { result.append("<"); for (TypeParameter p: types) { result.append(p.getName()).append(", "); } result.setLength(result.length()-2); result.append(">"); } } } private static void appendTypeParameters(Declaration d, StyledString result) { if (d instanceof Generic) { List<TypeParameter> types = ((Generic) d).getTypeParameters(); if (!types.isEmpty()) { result.append("<"); int len = types.size(), i = 0; for (TypeParameter p: types) { result.append(p.getName(), TYPE_STYLER); if (++i<len) result.append(", "); } result.append(">"); } } } private static void appendDeclarationText(Declaration d, StringBuilder result) { appendDeclarationText(d, null, result); } private static void appendDeclarationText(Declaration d, ProducedReference pr, StringBuilder result) { if (d instanceof Class) { if (d.isAnonymous()) { result.append("object"); } else { result.append("class"); } } else if (d instanceof Interface) { result.append("interface"); } else if (d instanceof TypeAlias) { result.append("alias"); } else if (d instanceof TypedDeclaration) { TypedDeclaration td = (TypedDeclaration) d; ProducedType type = td.getType(); if (type==null) type = new UnknownType(d.getUnit()).getType(); boolean isSequenced = d.isParameter() && ((MethodOrValue) d).getInitializerParameter().isSequenced(); if (pr!=null) { type = type.substitute(pr.getTypeArguments()); } if (isSequenced) { type = d.getUnit().getIteratedType(type); } String typeName = type.getProducedTypeName(); if (td.isDynamicallyTyped()) { result.append("dynamic"); } else if (td instanceof Value && type.getDeclaration().isAnonymous()) { result.append("object"); } else if (d instanceof Method) { if (((Functional) d).isDeclaredVoid()) { result.append("void"); } else { result.append(typeName); } } else { result.append(typeName); } if (isSequenced) { if (((MethodOrValue) d).getInitializerParameter().isAtLeastOne()) { result.append("+"); } else { result.append("*"); } } } result.append(" ").append(name(d)); } private static void appendNamedArgumentText(Parameter p, ProducedReference pr, StringBuilder result) { if (p.getModel() instanceof Functional) { Functional fp = (Functional) p.getModel(); result.append(fp.isDeclaredVoid() ? "void" : "function"); } else { result.append("value"); } result.append(" ").append(p.getName()); } private static void appendDeclarationText(Declaration d, StyledString result) { if (d instanceof Class) { if (d.isAnonymous()) { result.append("object", KW_STYLER); } else { result.append("class", KW_STYLER); } } else if (d instanceof Interface) { result.append("interface", KW_STYLER); } else if (d instanceof TypeAlias) { result.append("alias", KW_STYLER); } else if (d instanceof TypedDeclaration) { TypedDeclaration td = (TypedDeclaration) d; ProducedType type = td.getType(); if (td.isDynamicallyTyped()) { result.append("dynamic", KW_STYLER); } else if (type!=null) { boolean isSequenced = d.isParameter() && ((MethodOrValue) d).getInitializerParameter().isSequenced(); if (isSequenced) { type = d.getUnit().getIteratedType(type); } String typeName = type.getProducedTypeName(); if (td instanceof Value && td.getTypeDeclaration().isAnonymous()) { result.append("object", KW_STYLER); } else if (d instanceof Method) { if (((Functional)d).isDeclaredVoid()) { result.append("void", KW_STYLER); } else { result.append(typeName, TYPE_STYLER); } } else { result.append(typeName, TYPE_STYLER); } if (isSequenced) { result.append("*"); } } } result.append(" "); if (d instanceof TypeDeclaration) { result.append(d.getName(), TYPE_STYLER); } else { result.append(d.getName(), ID_STYLER); } } /*private static void appendPackage(Declaration d, StringBuilder result) { if (d.isToplevel()) { result.append(" - ").append(getPackageLabel(d)); } if (d.isClassOrInterfaceMember()) { result.append(" - "); ClassOrInterface td = (ClassOrInterface) d.getContainer(); result.append( td.getName() ); appendPackage(td, result); } }*/ private static void appendImpl(Declaration d, boolean isInterface, String indent, StringBuilder result) { if (d instanceof Method) { result.append(((Functional) d).isDeclaredVoid() ? " {}" : " => nothing; /*TODO: Implement*/"); } else if (d.isParameter()) { result.append(" => nothing; /*TODO: Implement*/"); } else if (d instanceof MethodOrValue) { if (isInterface) { result.append(" => nothing; /*TODO: Implement*/"); if (isVariable(d)) { result.append(indent + "assign " + d.getName() + " {} /*TODO: Implement*/"); } } else { result.append(" = nothing; /*TODO: Implement*/"); } } else { //TODO: in the case of a class, formal member refinements! result.append(" {}"); } } private static String extraIndent(String indent) { return indent.contains("\n") ? indent + getDefaultIndent() : indent; } private static void appendParameters(Declaration d, StringBuilder result) { appendParameters(d, null, result); } public static void appendParameters(Declaration d, ProducedReference pr, StringBuilder result) { if (d instanceof Functional) { List<ParameterList> plists = ((Functional) d).getParameterLists(); if (plists!=null) { for (ParameterList params: plists) { if (params.getParameters().isEmpty()) { result.append("()"); } else { result.append("("); for (Parameter p: params.getParameters()) { ProducedTypedReference ppr = pr==null ? null : pr.getTypedParameter(p); if (p.getModel() == null) { result.append(p.getName()); } else { appendDeclarationText(p.getModel(), ppr, result); appendParameters(p.getModel(), ppr, result); } /*ProducedType type = p.getType(); if (pr!=null) { type = type.substitute(pr.getTypeArguments()); } result.append(type.getProducedTypeName()).append(" ") .append(p.getName()); if (p instanceof FunctionalParameter) { result.append("("); FunctionalParameter fp = (FunctionalParameter) p; for (Parameter pp: fp.getParameterLists().get(0).getParameters()) { result.append(pp.getType().substitute(pr.getTypeArguments()) .getProducedTypeName()) .append(" ").append(pp.getName()).append(", "); } result.setLength(result.length()-2); result.append(")"); }*/ if (p.isDefaulted()) result.append("="); result.append(", "); } result.setLength(result.length()-2); result.append(")"); } } } } } private static void appendParameters(Declaration d, StyledString result) { if (d instanceof Functional) { List<ParameterList> plists = ((Functional) d).getParameterLists(); if (plists!=null) { for (ParameterList params: plists) { if (params.getParameters().isEmpty()) { result.append("()"); } else { result.append("("); int len = params.getParameters().size(), i=0; for (Parameter p: params.getParameters()) { if (p.getModel()==null) { result.append(p.getName()); } else { appendDeclarationText(p.getModel(), result); appendParameters(p.getModel(), result); /*result.append(p.getType().getProducedTypeName(), TYPE_STYLER) .append(" ").append(p.getName(), ID_STYLER); if (p instanceof FunctionalParameter) { result.append("("); FunctionalParameter fp = (FunctionalParameter) p; List<Parameter> fpl = fp.getParameterLists().get(0).getParameters(); int len2 = fpl.size(), j=0; for (Parameter pp: fpl) { result.append(pp.getType().getProducedTypeName(), TYPE_STYLER) .append(" ").append(pp.getName(), ID_STYLER); if (++j<len2) result.append(", "); } result.append(")"); }*/ } if (++i<len) result.append(", "); } result.append(")"); } } } } } }
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/propose/CeylonContentProposer.java
package com.redhat.ceylon.eclipse.code.propose; import static com.redhat.ceylon.compiler.loader.AbstractModelLoader.JDK_MODULE_VERSION; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.AIDENTIFIER; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.ASTRING_LITERAL; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.AVERBATIM_STRING; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.CHAR_LITERAL; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.EOF; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.FLOAT_LITERAL; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.LBRACE; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.LIDENTIFIER; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.LINE_COMMENT; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.MULTI_COMMENT; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.NATURAL_LITERAL; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.PIDENTIFIER; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.RBRACE; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.SEMICOLON; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.STRING_END; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.STRING_LITERAL; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.STRING_MID; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.STRING_START; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.UIDENTIFIER; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.VERBATIM_STRING; import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.WS; import static com.redhat.ceylon.eclipse.code.editor.CeylonAutoEditStrategy.getDefaultIndent; import static com.redhat.ceylon.eclipse.code.hover.DocHover.getDocumentationFor; import static com.redhat.ceylon.eclipse.code.hover.DocHover.getDocumentationForModule; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.ANN_STYLER; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.ARCHIVE; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.ID_STYLER; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.KW_STYLER; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.PACKAGE; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.TYPE_STYLER; import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.findNode; import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.getTokenIndexAtCharacter; import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.keywords; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.CLASS_ALIAS; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.EXPRESSION; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.EXTENDS; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.IMPORT; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.OF; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.PARAMETER_LIST; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.SATISFIES; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.TYPE_ALIAS; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.TYPE_ARGUMENT_LIST; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.TYPE_PARAMETER_LIST; import static com.redhat.ceylon.eclipse.code.propose.OccurrenceLocation.UPPER_BOUND; import static com.redhat.ceylon.eclipse.code.quickfix.CeylonQuickFixAssistant.getIndent; import static java.lang.Character.isJavaIdentifierPart; import static java.lang.Character.isLowerCase; import static java.lang.Character.isUpperCase; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.viewers.StyledString; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import com.redhat.ceylon.cmr.api.JDKUtils; import com.redhat.ceylon.cmr.api.ModuleQuery; import com.redhat.ceylon.cmr.api.ModuleSearchResult; import com.redhat.ceylon.cmr.api.ModuleSearchResult.ModuleDetails; import com.redhat.ceylon.compiler.loader.AbstractModelLoader; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.DeclarationWithProximity; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.Generic; import com.redhat.ceylon.compiler.typechecker.model.ImportList; import com.redhat.ceylon.compiler.typechecker.model.Interface; import com.redhat.ceylon.compiler.typechecker.model.IntersectionType; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.NothingType; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ParameterList; import com.redhat.ceylon.compiler.typechecker.model.ProducedReference; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.ProducedTypedReference; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.TypeAlias; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.model.UnknownType; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.MemberLiteral; import com.redhat.ceylon.compiler.typechecker.tree.Util; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; import com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider; import com.redhat.ceylon.eclipse.code.parse.CeylonParseController; import com.redhat.ceylon.eclipse.core.builder.CeylonBuilder; import com.redhat.ceylon.eclipse.ui.CeylonPlugin; import com.redhat.ceylon.eclipse.ui.CeylonResources; public class CeylonContentProposer { public static Image DEFAULT_REFINEMENT = CeylonPlugin.getInstance() .getImageRegistry().get(CeylonResources.CEYLON_DEFAULT_REFINEMENT); public static Image FORMAL_REFINEMENT = CeylonPlugin.getInstance() .getImageRegistry().get(CeylonResources.CEYLON_FORMAL_REFINEMENT); /** * Returns an array of content proposals applicable relative to the AST of the given * parse controller at the given position. * * (The provided ITextViewer is not used in the default implementation provided here * but but is stipulated by the IContentProposer interface for purposes such as accessing * the IDocument for which content proposals are sought.) * * @param controller A parse controller from which the AST of the document being edited * can be obtained * @param int The offset for which content proposals are sought * @param viewer The viewer in which the document represented by the AST in the given * parse controller is being displayed (may be null for some implementations) * @return An array of completion proposals applicable relative to the AST of the given * parse controller at the given position */ public ICompletionProposal[] getContentProposals(CeylonParseController cpc, final int offset, ITextViewer viewer, boolean filter) { if (cpc==null || viewer==null || cpc.getRootNode()==null || cpc.getTokens()==null) { return null; } cpc.parse(viewer.getDocument(), new NullProgressMonitor(), null); cpc.getHandler().updateAnnotations(); List<CommonToken> tokens = cpc.getTokens(); Tree.CompilationUnit rn = cpc.getRootNode(); //compensate for the fact that we get sent an old //tree that doesn't contain the characters the user //just typed PositionedPrefix result = compensateForMissingCharacter(offset, viewer, tokens); if (result==null) { return null; } //adjust the token to account for unclosed blocks //we search for the first non-whitespace/non-comment //token to the left of the caret int tokenIndex = getTokenIndexAtCharacter(tokens, result.start); if (tokenIndex<0) tokenIndex = -tokenIndex; CommonToken adjustedToken = adjust(tokenIndex, offset, tokens); int tt = adjustedToken.getType(); if (offset<=adjustedToken.getStopIndex() && offset>=adjustedToken.getStartIndex()) { if (tt==MULTI_COMMENT||tt==LINE_COMMENT) { return null; } if (tt==STRING_LITERAL || tt==STRING_END || tt==STRING_MID || tt==STRING_START || tt==VERBATIM_STRING || tt==AVERBATIM_STRING || tt==CHAR_LITERAL || tt==FLOAT_LITERAL || tt==NATURAL_LITERAL) { return null; } } int line=-1; try { line = viewer.getDocument().getLineOfOffset(offset); } catch (BadLocationException e) { e.printStackTrace(); } if (tt==LINE_COMMENT && offset>=adjustedToken.getStartIndex() && adjustedToken.getLine()==line+1) { return null; } // overrrides above. TODO separate block for all non-typechecker proposals boolean inDoc = false; if ((tt==ASTRING_LITERAL || tt==AVERBATIM_STRING) && offset>adjustedToken.getStartIndex() && offset<adjustedToken.getStopIndex()) { result = getDocReferencePosition(offset, viewer, tokens); if (result == null) { return null; } inDoc = true; } //find the node at the token Node node = getTokenNode(adjustedToken.getStartIndex(), adjustedToken.getStopIndex()+1, tt, rn); //find the type that is expected in the current //location so we can prioritize proposals of that //type //TODO: this breaks as soon as the user starts typing // an expression, since RequiredTypeVisitor // doesn't know how to search up the tree for // the containing InvocationExpression RequiredTypeVisitor rtv = new RequiredTypeVisitor(node); rtv.visit(rn); ProducedType requiredType = rtv.getType(); //construct completions when outside ordinary code ICompletionProposal[] completions = constructCompletions(offset, result.prefix, cpc, node, adjustedToken); if (completions==null) { //finally, construct and sort proposals Map<String, DeclarationWithProximity> proposals = getProposals(node, result.prefix, result.isMemberOp, rn); filterProposals(filter, rn, requiredType, proposals); Set<DeclarationWithProximity> sortedProposals = sortProposals(result.prefix, requiredType, proposals); completions = constructCompletions(offset, result.prefix, sortedProposals, cpc, node, adjustedToken, result.isMemberOp, viewer.getDocument(), filter, inDoc); } return completions; } private void filterProposals(boolean filter, Tree.CompilationUnit rn, ProducedType requiredType, Map<String, DeclarationWithProximity> proposals) { if (filter) { Iterator<Map.Entry<String, DeclarationWithProximity>> iter = proposals.entrySet().iterator(); while (iter.hasNext()) { Declaration d = iter.next().getValue().getDeclaration(); ProducedType type = type(d); ProducedType fullType = fullType(d); if (requiredType!=null && (type==null || (!type.isSubtypeOf(requiredType) && !fullType.isSubtypeOf(requiredType)) || type.isSubtypeOf(rn.getUnit().getNullDeclaration().getType()))) { iter.remove(); } } } } public static OccurrenceLocation getOccurrenceLocation(Tree.CompilationUnit cu, Node node) { if (node.getToken()==null) return null; FindOccurrenceLocationVisitor visitor = new FindOccurrenceLocationVisitor(node); cu.visit(visitor); return visitor.getOccurrenceLocation(); } private static PositionedPrefix getDocReferencePosition(final int offset, ITextViewer viewer, List<CommonToken> tokens) { CommonToken token = getTokenAtCaret(offset, viewer, tokens); String text = viewer.getDocument().get().substring( token.getStartIndex(), token.getStopIndex() + 1); Matcher wikiRef = Pattern.compile("\\[\\[(.*?)\\]\\]").matcher(text); if (token==null || offset==0 || !wikiRef.find()) { return null; } int offsetInToken = offset-token.getStartIndex(); String prefix = null; wikiRef.reset(); while (wikiRef.find()) { for (int i = 1; i <= wikiRef.groupCount(); i++) { // loop for safety if (offsetInToken >= wikiRef.start(i) && offsetInToken <= wikiRef.end(i)) { prefix = wikiRef.group(i).substring(0, offsetInToken - wikiRef.start(i)); break; } } } if (prefix == null) { // it will be empty string if we are in a wiki ref return null; } return new PositionedPrefix(prefix, token.getStartIndex()); } private static PositionedPrefix compensateForMissingCharacter(final int offset, ITextViewer viewer, List<CommonToken> tokens) { //What is going on here is that when I have a list of proposals open //and then I type a character, IMP sends us the old syntax tree and //doesn't bother to even send us the character I just typed, except //in the ITextViewer. So we need to do some guessing to figure out //that there is a missing character in the token stream and take //corrective action. This should be fixed in IMP! return getPositionedPrefix(offset, viewer, getTokenAtCaret(offset, viewer, tokens)); } private static PositionedPrefix getPositionedPrefix(final int offset, ITextViewer viewer, CommonToken token) { String text = viewer.getDocument().get(); if (token==null || offset==0) { //no earlier token, so we're typing at the //start of an empty file return new PositionedPrefix(text.substring(0, offset), 0); } //try to guess the character the user just typed //(it would be the character immediately behind //the caret, i.e. at offset-1) char charAtOffset = text.charAt(offset-1); int offsetInToken = offset-1-token.getStartIndex(); boolean inToken = offsetInToken>=0 && offsetInToken<token.getText().length(); //int end = offset; if (inToken && charAtOffset==token.getText().charAt(offsetInToken)) { //then we're not missing the typed character //from the tree we were passed by IMP if (isIdentifierOrKeyword(token)) { return new PositionedPrefix( token.getText().substring(0, offsetInToken+1), token.getStartIndex()); } else { return new PositionedPrefix(offset, isMemberOperator(token)); } } else { //then we are missing the typed character from //the tree, along with possibly some other //previously typed characters boolean isIdentifierChar = isJavaIdentifierPart(charAtOffset); if (isIdentifierChar) { if (token.getType()==CeylonLexer.WS) { //we are typing in or after whitespace String prefix = text.substring(token.getStartIndex(), offset).trim(); return new PositionedPrefix(prefix, offset-prefix.length()-1); } else if (isIdentifierOrKeyword(token)) { //we are typing in or after within an //identifier or keyword String prefix = text.substring(token.getStartIndex(), offset); return new PositionedPrefix(prefix, token.getStartIndex()); } else if (offset<=token.getStopIndex()+1) { //we are typing in or after a comment //block or strings, etc - not much //useful compensation we can do here return new PositionedPrefix( Character.toString(charAtOffset), offset-1); } else { //after a member dereference and other //misc cases of punctuation, etc return new PositionedPrefix( text.substring(token.getStopIndex()+1, offset), token.getStopIndex()); } } //disable this for now cos it causes problem in //import statements /*else if (charAtOffset=='.') { return new PositionedPrefix(offset-2, true); } else {*/ return new PositionedPrefix(offset-1, false); //} } } private static CommonToken getTokenAtCaret(final int offset, ITextViewer viewer, List<CommonToken> tokens) { //find the token behind the caret, adjusting to an //earlier token if the token we find is not at the //same position in the current text (in which case //it is probably a token that actually comes after //what we are currently typing) if (offset==0) { return null; } int index = getTokenIndexAtCharacter(tokens, offset-1); if (index<0) index = -index; while (index>=0) { CommonToken token = (CommonToken) tokens.get(index); String text = viewer.getDocument().get(); boolean tokenHasMoved = text.charAt(token.getStartIndex())!= token.getText().charAt(0); if (!tokenHasMoved) { return token; } index--; } return null; } private static class PositionedPrefix { String prefix; int start; boolean isMemberOp; PositionedPrefix(String prefix, int start) { this.prefix=prefix; this.start=start; this.isMemberOp=false; } PositionedPrefix(int start, boolean isMemberOp) { this.prefix=""; this.isMemberOp=isMemberOp; this.start=start; } } private static CommonToken adjust(int tokenIndex, int offset, List<CommonToken> tokens) { CommonToken adjustedToken = tokens.get(tokenIndex); while (--tokenIndex>=0 && (adjustedToken.getType()==WS //ignore whitespace || adjustedToken.getType()==EOF || adjustedToken.getStartIndex()==offset)) { //don't consider the token to the right of the caret adjustedToken = tokens.get(tokenIndex); if (adjustedToken.getType()!=WS && adjustedToken.getType()!=EOF && adjustedToken.getChannel()!=CommonToken.HIDDEN_CHANNEL) { //don't adjust to a ws token break; } } return adjustedToken; } private static Boolean isDirectlyInsideBlock(Node node, CommonToken token, List<CommonToken> tokens) { Scope scope = node.getScope(); if (scope instanceof Interface || scope instanceof Package) { return false; } else { //TODO: check that it is not the opening/closing // brace of a named argument list! return !(node instanceof Tree.SequenceEnumeration) && occursAfterBraceOrSemicolon(token, tokens); } } private static Boolean occursAfterBraceOrSemicolon(CommonToken token, List<CommonToken> tokens) { if (token.getTokenIndex()==0) { return false; } else { int tokenType = token.getType(); if (tokenType==LBRACE || tokenType==RBRACE || tokenType==SEMICOLON) { return true; } int previousTokenType = adjust(token.getTokenIndex()-1, token.getStartIndex(), tokens).getType(); return previousTokenType==LBRACE || previousTokenType==RBRACE || previousTokenType==SEMICOLON; } } private static Node getTokenNode(int adjustedStart, int adjustedEnd, int tokenType, Tree.CompilationUnit rn) { Node node = findNode(rn, adjustedStart, adjustedEnd); if (tokenType==RBRACE || tokenType==SEMICOLON) { //We are to the right of a } or ; //so the returned node is the previous //statement/declaration. Look for the //containing body. class BodyVisitor extends Visitor { Node node, currentBody, result; BodyVisitor(Node node, Node root) { this.node = node; currentBody = root; } @Override public void visitAny(Node that) { if (that==node) { result = currentBody; } else { Node cb = currentBody; if (that instanceof Tree.Body) { currentBody = that; } if (that instanceof Tree.NamedArgumentList) { currentBody = that; } super.visitAny(that); currentBody = cb; } } } BodyVisitor mv = new BodyVisitor(node, rn); mv.visit(rn); node = mv.result; } if (node==null) node = rn; //we're in whitespace at the start of the file return node; } private static void addPackageCompletions(CeylonParseController cpc, int offset, String prefix, Tree.ImportPath path, Node node, List<ICompletionProposal> result) { String fullPath = fullPath(offset, prefix, path); addPackageCompletions(offset, prefix, node, result, fullPath.length(), fullPath+prefix, cpc); } private static void addModuleCompletions(CeylonParseController cpc, int offset, String prefix, Tree.ImportPath path, Node node, List<ICompletionProposal> result) { String fullPath = fullPath(offset, prefix, path); addModuleCompletions(offset, prefix, node, result, fullPath.length(), fullPath+prefix, cpc); } private static String fullPath(int offset, String prefix, Tree.ImportPath path) { StringBuilder fullPath = new StringBuilder(); if (path!=null) { fullPath.append(Util.formatPath(path.getIdentifiers())); fullPath.append('.'); fullPath.setLength(offset-path.getStartIndex()-prefix.length()); } return fullPath.toString(); } private static void addPackageCompletions(final int offset, final String prefix, Node node, List<ICompletionProposal> result, final int len, String pfp, final CeylonParseController cpc) { //TODO: someday it would be nice to propose from all packages // and auto-add the module dependency! /*TypeChecker tc = CeylonBuilder.getProjectTypeChecker(cpc.getProject().getRawProject()); if (tc!=null) { for (Module m: tc.getContext().getModules().getListOfModules()) {*/ //Set<Package> packages = new HashSet<Package>(); Unit unit = node.getUnit(); if (unit!=null) { //a null unit can occur if we have not finished parsing the file Module module = unit.getPackage().getModule(); for (final Package p: module.getAllPackages()) { //if (!packages.contains(p)) { //packages.add(p); //if ( p.getModule().equals(module) || p.isShared() ) { final String pkg = p.getQualifiedNameString(); if (!pkg.isEmpty() && pkg.startsWith(pfp)) { boolean already = false; if (!pfp.equals(pkg)) { //don't add already imported packages, unless //it is an exact match to the typed path for (ImportList il: node.getUnit().getImportLists()) { if (il.getImportedScope()==p) { already = true; break; } } } if (!already) { result.add(new CompletionProposal(offset, prefix, PACKAGE, pkg, pkg.substring(len) + " { ... }", false) { @Override public Point getSelection(IDocument document) { return new Point(offset+pkg.length()-prefix.length()-len+3, 3); } @Override public String getAdditionalProposalInfo() { return getDocumentationFor(cpc, p); } }); } } //} } } } private static final SortedSet<String> JDK_MODULE_VERSION_SET = new TreeSet<String>(); { JDK_MODULE_VERSION_SET.add(AbstractModelLoader.JDK_MODULE_VERSION); } private static void addModuleCompletions(int offset, String prefix, Node node, List<ICompletionProposal> result, int len, String pfp, final CeylonParseController cpc) { if (pfp.startsWith("java.")) { for (final String mod: JDKUtils.getJDKModuleNames()) { if (mod.startsWith(pfp)) { String versioned = getModuleString(mod, JDK_MODULE_VERSION); result.add(new CompletionProposal(offset, prefix, ARCHIVE, versioned, versioned.substring(len) + ";", false) { @Override public String getAdditionalProposalInfo() { return getDocumentationForModule(mod, JDK_MODULE_VERSION, "This module forms part of the Java SDK."); } }); } } } else { final TypeChecker tc = cpc.getTypeChecker(); if (tc!=null) { ModuleSearchResult results = tc.getContext().getRepositoryManager() .completeModules(new ModuleQuery(pfp, ModuleQuery.Type.JVM)); for (final ModuleDetails module: results.getResults()) { final String name = module.getName(); if (!name.equals(Module.DEFAULT_MODULE_NAME)) { for (final String version : module.getVersions().descendingSet()) { String versioned = getModuleString(name, version); result.add(new CompletionProposal(offset, prefix, ARCHIVE, versioned, versioned.substring(len) + ";", false) { @Override public String getAdditionalProposalInfo() { return JDKUtils.isJDKModule(name) ? "This module forms part of the Java SDK." : getDocumentationFor(module, version); } }); } } } } } } private static String getModuleString(final String name, final String version) { return name + " \"" + version + "\""; } private static boolean isIdentifierOrKeyword(Token token) { int type = token.getType(); return type==LIDENTIFIER || type==UIDENTIFIER || type==AIDENTIFIER || type==PIDENTIFIER || keywords.contains(token.getText()); } private static ICompletionProposal[] constructCompletions(final int offset, final String prefix, final CeylonParseController cpc, final Node node, CommonToken token) { final List<ICompletionProposal> result = new ArrayList<ICompletionProposal>(); if (node instanceof Tree.Import && offset>token.getStopIndex()+1) { addPackageCompletions(cpc, offset, prefix, null, node, result); } else if (node instanceof Tree.ImportModule && offset>token.getStopIndex()+1) { addModuleCompletions(cpc, offset, prefix, null, node, result); } else if (node instanceof Tree.ImportPath) { new Visitor() { @Override public void visit(Tree.Import that) { super.visit(that); if (that.getImportPath()==node) { addPackageCompletions(cpc, offset, prefix, (Tree.ImportPath) node, node, result); } } @Override public void visit(Tree.ImportModule that) { super.visit(that); if (that.getImportPath()==node) { addModuleCompletions(cpc, offset, prefix, (Tree.ImportPath) node, node, result); } } }.visit(cpc.getRootNode()); } else if (isEmptyModuleDescriptor(cpc)) { addModuleDescriptorCompletion(cpc, offset, prefix, result); addKeywordProposals(cpc, offset, prefix, result, node); } else if (isEmptyPackageDescriptor(cpc)) { addPackageDescriptorCompletion(cpc, offset, prefix, result); addKeywordProposals(cpc, offset, prefix, result, node); } else { return null; } return result.toArray(new ICompletionProposal[result.size()]); } private static ICompletionProposal[] constructCompletions(final int offset, final String prefix, Set<DeclarationWithProximity> set, final CeylonParseController cpc, final Node node, CommonToken token, boolean memberOp, IDocument doc, boolean filter, boolean inDoc) { final List<ICompletionProposal> result = new ArrayList<ICompletionProposal>(); if (node instanceof Tree.TypeConstraint) { for (DeclarationWithProximity dwp: set) { Declaration dec = dwp.getDeclaration(); if (isTypeParameterOfCurrentDeclaration(node, dec)) { addBasicProposal(offset, prefix, cpc, result, dwp, dec, null); } } } else { if ((node instanceof Tree.SimpleType || node instanceof Tree.BaseTypeExpression || node instanceof Tree.QualifiedTypeExpression) && prefix.isEmpty() && !memberOp) { addMemberNameProposal(offset, node, result); } else if (node instanceof Tree.TypedDeclaration && !(node instanceof Tree.Variable && ((Tree.Variable)node).getType() instanceof Tree.SyntheticVariable) && !(node instanceof Tree.InitializerParameter)) { addMemberNameProposal(offset, node, result); } else { OccurrenceLocation ol = getOccurrenceLocation(cpc.getRootNode(), node); if (!filter && !inDoc && !(node instanceof Tree.QualifiedMemberOrTypeExpression)) { addKeywordProposals(cpc, offset, prefix, result, node); //addTemplateProposal(offset, prefix, result); } boolean isPackageOrModuleDescriptor = isModuleDescriptor(cpc) || isPackageDescriptor(cpc); for (DeclarationWithProximity dwp: set) { Declaration dec = dwp.getDeclaration(); if (isPackageOrModuleDescriptor && !inDoc) { if (!dec.isAnnotation()||!(dec instanceof Method)) continue; } if (isParameterOfNamedArgInvocation(node, dwp)) { if (isDirectlyInsideNamedArgumentList(cpc, node, token)) { addNamedArgumentProposal(offset, prefix, cpc, result, dwp, dec, ol); addInlineFunctionProposal(offset, prefix, cpc, node, result, dec, doc); } } CommonToken nextToken = getNextToken(cpc, token); boolean noParamsFollow = noParametersFollow(nextToken); if (isInvocationProposable(dwp, ol) && !isQualifiedType(node) && !inDoc && noParamsFollow) { for (Declaration d: overloads(dec)) { ProducedReference pr = node instanceof Tree.QualifiedMemberOrTypeExpression ? getQualifiedProducedReference(node, d) : getRefinedProducedReference(node, d); addInvocationProposals(offset, prefix, cpc, result, new DeclarationWithProximity(d, dwp), pr, ol); } } if (isProposable(dwp, ol, node.getScope()) && (definitelyRequiresType(ol) || noParamsFollow || dwp.getDeclaration() instanceof Functional)) { addBasicProposal(offset, prefix, cpc, result, dwp, dec, ol); } if (isProposable(dwp, ol, node.getScope()) && isDirectlyInsideBlock(node, token, cpc.getTokens()) && !memberOp && !filter) { addForProposal(offset, prefix, cpc, result, dwp, dec, ol); addIfExistsProposal(offset, prefix, cpc, result, dwp, dec, ol); addSwitchProposal(offset, prefix, cpc, result, dwp, dec, ol, node, doc); } if (isRefinementProposable(dec, ol) && !memberOp && !filter) { for (Declaration d: overloads(dec)) { addRefinementProposal(offset, prefix, cpc, node, result, d, doc); } } } } } return result.toArray(new ICompletionProposal[result.size()]); } private static boolean isQualifiedType(Node node) { return (node instanceof Tree.QualifiedType) || (node instanceof Tree.QualifiedMemberOrTypeExpression && ((Tree.QualifiedMemberOrTypeExpression) node).getStaticMethodReference()); } private static boolean isPackageDescriptor(CeylonParseController cpc) { return cpc.getRootNode() != null && cpc.getRootNode().getUnit() != null && cpc.getRootNode().getUnit().getFilename().equals("package.ceylon"); } private static boolean isModuleDescriptor(CeylonParseController cpc) { return cpc.getRootNode() != null && cpc.getRootNode().getUnit() != null && cpc.getRootNode().getUnit().getFilename().equals("module.ceylon"); } private static boolean isEmptyModuleDescriptor(CeylonParseController cpc) { return isModuleDescriptor(cpc) && cpc.getRootNode() != null && cpc.getRootNode().getModuleDescriptor() == null; } private static void addModuleDescriptorCompletion(CeylonParseController cpc, int offset, String prefix, List<ICompletionProposal> result) { if (!"module".startsWith(prefix)) return; IFile file = cpc.getProject().getFile(cpc.getPath()); String moduleName = CeylonBuilder.getPackageName(file); String moduleDesc = "module " + moduleName; String moduleText = "module " + moduleName + " \"1.0.0\" {}"; final int selectionStart = offset - prefix.length() + moduleName.length() + 9; final int selectionLength = 5; result.add(new CompletionProposal(offset, prefix, ARCHIVE, moduleDesc, moduleText, false) { @Override public Point getSelection(IDocument document) { return new Point(selectionStart, selectionLength); }}); } private static boolean isEmptyPackageDescriptor(CeylonParseController cpc) { return cpc.getRootNode() != null && cpc.getRootNode().getUnit() != null && cpc.getRootNode().getUnit().getFilename().equals("package.ceylon") && cpc.getRootNode().getPackageDescriptor() == null; } private static void addPackageDescriptorCompletion(CeylonParseController cpc, int offset, String prefix, List<ICompletionProposal> result) { if (!"package".startsWith(prefix)) return; IFile file = cpc.getProject().getFile(cpc.getPath()); String packageName = CeylonBuilder.getPackageName(file); String packageDesc = "package " + packageName; String packageText = "package " + packageName + ";"; result.add(new CompletionProposal(offset, prefix, PACKAGE, packageDesc, packageText, false)); } private static boolean noParametersFollow(CommonToken nextToken) { return nextToken==null || //should we disable this, since a statement //can in fact begin with an LPAREN?? nextToken.getType()!=CeylonLexer.LPAREN //disabled now because a declaration can //begin with an LBRACE (an Iterable type) /*&& nextToken.getType()!=CeylonLexer.LBRACE*/; } private static boolean definitelyRequiresType(OccurrenceLocation ol) { return ol==SATISFIES || ol==OF || ol==UPPER_BOUND || ol==TYPE_ALIAS; } private static CommonToken getNextToken(final CeylonParseController cpc, CommonToken token) { int i = token.getTokenIndex(); CommonToken nextToken=null; List<CommonToken> tokens = cpc.getTokens(); do { if (++i<tokens.size()) { nextToken = tokens.get(i); } else { break; } } while (nextToken.getChannel()==CommonToken.HIDDEN_CHANNEL); return nextToken; } private static boolean isDirectlyInsideNamedArgumentList( CeylonParseController cpc, Node node, CommonToken token) { return node instanceof Tree.NamedArgumentList || (!(node instanceof Tree.SequenceEnumeration) && occursAfterBraceOrSemicolon(token, cpc.getTokens())); } private static boolean isMemberOperator(Token token) { int type = token.getType(); return type==CeylonLexer.MEMBER_OP || type==CeylonLexer.SPREAD_OP || type==CeylonLexer.SAFE_MEMBER_OP; } public static List<Declaration> overloads(Declaration dec) { if (dec instanceof Functional && ((Functional)dec).isAbstraction()) { return ((Functional)dec).getOverloads(); } else { return Collections.singletonList(dec); } } /*private static boolean isKeywordProposable(OccurrenceLocation ol) { return ol==null || ol==EXPRESSION; }*/ private static boolean isRefinementProposable(Declaration dec, OccurrenceLocation ol) { return ol==null && (dec instanceof MethodOrValue || dec instanceof Class); } private static boolean isInvocationProposable(DeclarationWithProximity dwp, OccurrenceLocation ol) { Declaration dec = dwp.getDeclaration(); return dec instanceof Functional && //!((Functional) dec).getParameterLists().isEmpty() && (ol==null || ol==EXPRESSION && ( !(dec instanceof Class) || !((Class)dec).isAbstract()) || ol==EXTENDS && dec instanceof Class && !((Class)dec).isFinal() || ol==CLASS_ALIAS && dec instanceof Class || ol==PARAMETER_LIST && dec instanceof Method && dec.isAnnotation()) && dwp.getNamedArgumentList()==null && (!dec.isAnnotation() || !(dec instanceof Method) || !((Method)dec).getParameterLists().isEmpty() && !((Method)dec).getParameterLists().get(0).getParameters().isEmpty()); } private static boolean isProposable(DeclarationWithProximity dwp, OccurrenceLocation ol, Scope scope) { Declaration dec = dwp.getDeclaration(); return (ol!=EXTENDS || dec instanceof Class && !((Class)dec).isFinal()) && (ol!=CLASS_ALIAS || dec instanceof Class) && (ol!=SATISFIES || dec instanceof Interface) && (ol!=OF || dec instanceof Class || (dec instanceof Value && ((Value) dec).getTypeDeclaration()!=null && ((Value) dec).getTypeDeclaration().isAnonymous())) && ((ol!=TYPE_ARGUMENT_LIST && ol!=UPPER_BOUND && ol!=TYPE_ALIAS) || dec instanceof TypeDeclaration) && (ol!=PARAMETER_LIST || dec instanceof TypeDeclaration || dec instanceof Method && dec.isAnnotation() || //i.e. an annotation dec instanceof Value && dec.getContainer().equals(scope)) && //a parameter ref (ol!=IMPORT || !dwp.isUnimported()) && ol!=TYPE_PARAMETER_LIST && dwp.getNamedArgumentList()==null; } private static boolean isTypeParameterOfCurrentDeclaration(Node node, Declaration d) { //TODO: this is a total mess and totally error-prone - figure out something better! return d instanceof TypeParameter && (((TypeParameter) d).getContainer()==node.getScope() || ((Tree.TypeConstraint) node).getDeclarationModel()!=null && ((TypeParameter) d).getContainer()==((Tree.TypeConstraint) node).getDeclarationModel().getContainer()); } private static void addInlineFunctionProposal(int offset, String prefix, CeylonParseController cpc, Node node, List<ICompletionProposal> result, Declaration d, IDocument doc) { //TODO: type argument substitution using the ProducedReference of the primary node if (d.isParameter()) { Parameter p = ((MethodOrValue) d).getInitializerParameter(); result.add(new RefinementCompletionProposal(offset, prefix, getInlineFunctionDescriptionFor(p, null), getInlineFunctionTextFor(p, null, "\n" + getIndent(node, doc)), cpc, d)); } } /*private static boolean isParameterOfNamedArgInvocation(Node node, Declaration d) { if (node instanceof Tree.NamedArgumentList) { ParameterList pl = ((Tree.NamedArgumentList) node).getNamedArgumentList() .getParameterList(); return d instanceof Parameter && pl!=null && pl.getParameters().contains(d); } else if (node.getScope() instanceof NamedArgumentList) { ParameterList pl = ((NamedArgumentList) node.getScope()).getParameterList(); return d instanceof Parameter && pl!=null && pl.getParameters().contains(d); } else { return false; } }*/ private static boolean isParameterOfNamedArgInvocation(Node node, DeclarationWithProximity d) { return node.getScope()==d.getNamedArgumentList(); } private static void addRefinementProposal(int offset, String prefix, final CeylonParseController cpc, Node node, List<ICompletionProposal> result, final Declaration d, IDocument doc) { if ((d.isDefault() || d.isFormal()) && node.getScope() instanceof ClassOrInterface && ((ClassOrInterface) node.getScope()).isInheritedFromSupertype(d)) { boolean isInterface = node.getScope() instanceof Interface; ProducedReference pr = getRefinedProducedReference(node, d); //TODO: if it is equals() or hash, fill in the implementation result.add(new RefinementCompletionProposal(offset, prefix, getRefinementDescriptionFor(d, pr), getRefinementTextFor(d, pr, isInterface, "\n" + getIndent(node, doc)), cpc, d)); } } public static ProducedReference getQualifiedProducedReference(Node node, Declaration d) { ProducedType pt = ((Tree.QualifiedMemberOrTypeExpression) node) .getPrimary().getTypeModel(); if (pt!=null && d.isClassOrInterfaceMember()) { pt = pt.getSupertype((TypeDeclaration)d.getContainer()); } return d.getProducedReference(pt, Collections.<ProducedType>emptyList()); } public static ProducedReference getRefinedProducedReference(Node node, Declaration d) { return refinedProducedReference(node.getScope().getDeclaringType(d), d); } public static ProducedReference getRefinedProducedReference(ProducedType superType, Declaration d) { if (superType.getDeclaration() instanceof IntersectionType) { for (ProducedType pt: superType.getDeclaration().getSatisfiedTypes()) { ProducedReference result = getRefinedProducedReference(pt, d); if (result!=null) return result; } return null; //never happens? } else { ProducedType declaringType = superType.getDeclaration().getDeclaringType(d); if (declaringType==null) return null; ProducedType outerType = superType.getSupertype(declaringType.getDeclaration()); return refinedProducedReference(outerType, d); } } private static ProducedReference refinedProducedReference(ProducedType outerType, Declaration d) { List<ProducedType> params = new ArrayList<ProducedType>(); if (d instanceof Generic) { for (TypeParameter tp: ((Generic)d).getTypeParameters()) { params.add(tp.getType()); } } return d.getProducedReference(outerType, params); } private static void addBasicProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d, OccurrenceLocation ol) { result.add(new DeclarationCompletionProposal(offset, prefix, getDescriptionFor(dwp, ol), getTextFor(dwp, ol), true, cpc, d, dwp.isUnimported())); } private static void addForProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d, OccurrenceLocation ol) { if (d instanceof Value) { TypedDeclaration td = (TypedDeclaration) d; if (td.getType()!=null && d.getUnit().isIterableType(td.getType())) { String elemName; if (d.getName().length()==1) { elemName = "element"; } else if (d.getName().endsWith("s")) { elemName = d.getName().substring(0, d.getName().length()-1); } else { elemName = d.getName().substring(0, 1); } result.add(new DeclarationCompletionProposal(offset, prefix, "for (" + elemName + " in " + getDescriptionFor(dwp, ol) + ")", "for (" + elemName + " in " + getTextFor(dwp, ol) + ") {}", true, cpc, d)); } } } private static void addIfExistsProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d, OccurrenceLocation ol) { if (!dwp.isUnimported()) { if (d instanceof Value) { TypedDeclaration v = (TypedDeclaration) d; if (v.getType()!=null && d.getUnit().isOptionalType(v.getType()) && !v.isVariable()) { result.add(new DeclarationCompletionProposal(offset, prefix, "if (exists " + getDescriptionFor(dwp, ol) + ")", "if (exists " + getTextFor(dwp, ol) + ") {}", true, cpc, d)); } } } } private static void addSwitchProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d, OccurrenceLocation ol, Node node, IDocument doc) { if (!dwp.isUnimported()) { if (d instanceof Value) { TypedDeclaration v = (TypedDeclaration) d; if (v.getType()!=null && v.getType().getCaseTypes()!=null && !v.isVariable()) { StringBuilder body = new StringBuilder(); String indent = getIndent(node, doc); for (ProducedType pt: v.getType().getCaseTypes()) { body.append(indent).append("case ("); if (!pt.getDeclaration().isAnonymous()) { body.append("is "); } body.append(pt.getProducedTypeName()); body.append(") {}\n"); } body.append(indent); result.add(new DeclarationCompletionProposal(offset, prefix, "switch (" + getDescriptionFor(dwp, ol) + ")", "switch (" + getTextFor(dwp, ol) + ")\n" + body, true, cpc, d)); } } } } private static void addNamedArgumentProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d, OccurrenceLocation ol) { result.add(new DeclarationCompletionProposal(offset, prefix, getDescriptionFor(dwp, ol), getTextFor(dwp, ol) + " = nothing;", true, cpc, d)); } private static void addInvocationProposals(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, ProducedReference pr, OccurrenceLocation ol) { Declaration d = pr.getDeclaration(); if (!(d instanceof Functional)) return; boolean isAbstractClass = d instanceof Class && ((Class) d).isAbstract(); Functional fd = (Functional) d; List<ParameterList> pls = fd.getParameterLists(); if (!pls.isEmpty()) { List<Parameter> ps = pls.get(0).getParameters(); int defaulted = 0; for (Parameter p: ps) { if (p.isDefaulted()) { defaulted ++; } } if (!isAbstractClass || ol==EXTENDS) { if (defaulted>0) { result.add(new DeclarationCompletionProposal(offset, prefix, getPositionalInvocationDescriptionFor(dwp, ol, pr, false), getPositionalInvocationTextFor(dwp, ol, pr, false), true, cpc, d, dwp.isUnimported())); } result.add(new DeclarationCompletionProposal(offset, prefix, getPositionalInvocationDescriptionFor(dwp, ol, pr, true), getPositionalInvocationTextFor(dwp, ol, pr, true), true, cpc, d, dwp.isUnimported())); } if (!isAbstractClass && ol!=EXTENDS && !fd.isOverloaded()) { //if there is at least one parameter, //suggest a named argument invocation if (defaulted>0 && ps.size()>defaulted) { result.add(new DeclarationCompletionProposal(offset, prefix, getNamedInvocationDescriptionFor(dwp, pr, false), getNamedInvocationTextFor(dwp, pr, false), true, cpc, d, dwp.isUnimported())); } if (!ps.isEmpty()) { result.add(new DeclarationCompletionProposal(offset, prefix, getNamedInvocationDescriptionFor(dwp, pr, true), getNamedInvocationTextFor(dwp, pr, true), true, cpc, d, dwp.isUnimported())); } } } } protected static void addMemberNameProposal(int offset, Node node, List<ICompletionProposal> result) { String suggestedName = null; String prefix = ""; if (node instanceof Tree.TypeDeclaration) { /*Tree.TypeDeclaration td = (Tree.TypeDeclaration) node; prefix = td.getIdentifier()==null ? "" : td.getIdentifier().getText(); suggestedName = prefix;*/ //TODO: dictionary completions? return; } else if (node instanceof Tree.TypedDeclaration) { Tree.TypedDeclaration td = (Tree.TypedDeclaration) node; prefix = td.getIdentifier()==null ? "" : td.getIdentifier().getText(); suggestedName = prefix; if (td.getType() instanceof Tree.SimpleType) { String type = ((Tree.SimpleType) td.getType()).getIdentifier().getText(); if (lower(type).startsWith(prefix)) { result.add(new CompletionProposal(offset, prefix, null, lower(type), escape(lower(type)), false)); } if (!suggestedName.endsWith(type)) { suggestedName += type; } result.add(new CompletionProposal(offset, prefix, null, lower(suggestedName), escape(lower(suggestedName)), false)); } return; } else if (node instanceof Tree.SimpleType) { suggestedName = ((Tree.SimpleType) node).getIdentifier().getText(); } else if (node instanceof Tree.BaseTypeExpression) { suggestedName = ((Tree.BaseTypeExpression) node).getIdentifier().getText(); } else if (node instanceof Tree.QualifiedTypeExpression) { suggestedName = ((Tree.QualifiedTypeExpression) node).getIdentifier().getText(); } if (suggestedName!=null) { result.add(new CompletionProposal(offset, "", null, lower(suggestedName), escape(lower(suggestedName)), false)); } } private static String lower(String suggestedName) { return Character.toLowerCase(suggestedName.charAt(0)) + suggestedName.substring(1); } private static String escape(String suggestedName) { if (keywords.contains(suggestedName)) { return "\\i" + suggestedName; } else { return suggestedName; } } private static void addKeywordProposals(CeylonParseController cpc, int offset, String prefix, List<ICompletionProposal> result, Node node) { if( isModuleDescriptor(cpc) ) { if( prefix.isEmpty() || "import".startsWith(prefix) ) { if (node instanceof Tree.CompilationUnit) { Tree.ModuleDescriptor moduleDescriptor = ((Tree.CompilationUnit) node).getModuleDescriptor(); if (moduleDescriptor != null && moduleDescriptor.getImportModuleList() != null && moduleDescriptor.getImportModuleList().getStartIndex() < offset ) { addKeywordProposal(offset, prefix, result, "import"); } } else if (node instanceof Tree.ImportModuleList || node instanceof Tree.BaseMemberExpression) { addKeywordProposal(offset, prefix, result, "import"); } } } else if (!prefix.isEmpty()) { for (String keyword: keywords) { if (keyword.startsWith(prefix)) { addKeywordProposal(offset, prefix, result, keyword); } } } } private static void addKeywordProposal(int offset, String prefix, List<ICompletionProposal> result, final String keyword) { result.add(new CompletionProposal(offset, prefix, null, keyword, keyword, true) { @Override public StyledString getStyledDisplayString() { return new StyledString(keyword, CeylonLabelProvider.KW_STYLER); } }); } /*private static void addTemplateProposal(int offset, String prefix, List<ICompletionProposal> result) { if (!prefix.isEmpty()) { if ("class".startsWith(prefix)) { String prop = "class Class() {}"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } if ("interface".startsWith(prefix)) { String prop = "interface Interface {}"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } if ("void".startsWith(prefix)) { String prop = "void method() {}"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } if ("function".startsWith(prefix)) { String prop = "function method() { return nothing; }"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } if ("value".startsWith(prefix)) { String prop = "value attribute = nothing;"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); prop = "value attribute { return nothing; }"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } if ("object".startsWith(prefix)) { String prop = "object instance {}"; result.add(sourceProposal(offset, prefix, null, null, prop, prop, true)); } } }*/ /*private static String getDocumentationFor(CeylonParseController cpc, Declaration d) { return getDocumentation(getReferencedNode(d, getCompilationUnit(cpc, d))); }*/ private static Set<DeclarationWithProximity> sortProposals(final String prefix, final ProducedType type, Map<String, DeclarationWithProximity> proposals) { Set<DeclarationWithProximity> set = new TreeSet<DeclarationWithProximity>( new Comparator<DeclarationWithProximity>() { public int compare(DeclarationWithProximity x, DeclarationWithProximity y) { boolean xbt = x.getDeclaration() instanceof NothingType; boolean ybt = y.getDeclaration() instanceof NothingType; if (xbt&&ybt) { return 0; } if (xbt&&!ybt) { return 1; } if (ybt&&!xbt) { return -1; } ProducedType xtype = type(x.getDeclaration()); ProducedType ytype = type(y.getDeclaration()); boolean xbottom = xtype!=null && xtype.getDeclaration() instanceof NothingType; boolean ybottom = ytype!=null && ytype.getDeclaration() instanceof NothingType; if (xbottom && !ybottom) { return 1; } if (ybottom && !xbottom) { return -1; } String xName = x.getName(); String yName = y.getName(); if (!prefix.isEmpty() && isUpperCase(prefix.charAt(0))) { if (isLowerCase(xName.charAt(0)) && isUpperCase(yName.charAt(0))) { return 1; } else if (isUpperCase(xName.charAt(0)) && isLowerCase(yName.charAt(0))) { return -1; } } if (type!=null) { boolean xassigns = xtype!=null && xtype.isSubtypeOf(type); boolean yassigns = ytype!=null && ytype.isSubtypeOf(type); if (xassigns && !yassigns) { return -1; } if (yassigns && !xassigns) { return 1; } if (xassigns && yassigns) { boolean xtd = x.getDeclaration() instanceof TypedDeclaration; boolean ytd = y.getDeclaration() instanceof TypedDeclaration; if (xtd && !ytd) { return -1; } if (ytd && !xtd) { return 1; } } } if (x.getProximity()!=y.getProximity()) { return new Integer(x.getProximity()).compareTo(y.getProximity()); } //if (!prefix.isEmpty() && isLowerCase(prefix.charAt(0))) { if (isLowerCase(xName.charAt(0)) && isUpperCase(yName.charAt(0))) { return -1; } else if (isUpperCase(xName.charAt(0)) && isLowerCase(yName.charAt(0))) { return 1; } int nc = xName.compareTo(yName); if (nc==0) { String xqn = x.getDeclaration().getQualifiedNameString(); String yqn = y.getDeclaration().getQualifiedNameString(); return xqn.compareTo(yqn); } else { return nc; } } }); set.addAll(proposals.values()); return set; } static ProducedType type(Declaration d) { if (d instanceof TypeDeclaration) { if (d instanceof Class) { if (!((Class) d).isAbstract()) { return ((TypeDeclaration) d).getType(); } } return null; } else if (d instanceof TypedDeclaration) { return ((TypedDeclaration) d).getType(); } else { return null;//impossible } } static ProducedType fullType(Declaration d) { //TODO: substitute type args from surrounding scope return d.getProducedReference(null, Collections.<ProducedType>emptyList()).getFullType(); } public static Map<String, DeclarationWithProximity> getProposals(Node node, Tree.CompilationUnit cu) { return getProposals(node, "", false, cu); } private static Map<String, DeclarationWithProximity> getProposals(Node node, String prefix, boolean memberOp, Tree.CompilationUnit cu) { if (node instanceof MemberLiteral) { //this case is rather ugly! Tree.StaticType mlt = ((Tree.MemberLiteral) node).getType(); if (mlt!=null) { ProducedType type = mlt.getTypeModel(); if (type!=null) { return type.resolveAliases().getDeclaration() .getMatchingMemberDeclarations(node.getScope(), prefix, 0); } else { return Collections.emptyMap(); } } } if (node instanceof Tree.QualifiedMemberOrTypeExpression) { Tree.QualifiedMemberOrTypeExpression qmte = (Tree.QualifiedMemberOrTypeExpression) node; ProducedType type = getPrimaryType((Tree.QualifiedMemberOrTypeExpression) node); if (qmte.getStaticMethodReference()) { type = node.getUnit().getCallableReturnType(type); } if (type!=null) { return type.resolveAliases().getDeclaration() .getMatchingMemberDeclarations(node.getScope(), prefix, 0); } else if (qmte.getPrimary() instanceof Tree.MemberOrTypeExpression) { //it might be a qualified type or even a static method reference Declaration pmte = ((Tree.MemberOrTypeExpression) qmte.getPrimary()).getDeclaration(); if (pmte instanceof TypeDeclaration) { type = ((TypeDeclaration) pmte).getType(); if (type!=null) { return type.resolveAliases().getDeclaration() .getMatchingMemberDeclarations(node.getScope(), prefix, 0); } } } return Collections.emptyMap(); } else if (node instanceof Tree.QualifiedType) { ProducedType type = ((Tree.QualifiedType) node).getOuterType().getTypeModel(); if (type!=null) { return type.resolveAliases().getDeclaration() .getMatchingMemberDeclarations(node.getScope(), prefix, 0); } else { return Collections.emptyMap(); } } else if (memberOp && node instanceof Tree.Term) { ProducedType type = ((Tree.Term)node).getTypeModel(); if (type!=null) { return type.resolveAliases().getDeclaration() .getMatchingMemberDeclarations(node.getScope(), prefix, 0); } else { return Collections.emptyMap(); } } else { Scope scope = node.getScope(); if (scope instanceof ImportList) { return ((ImportList) scope).getMatchingDeclarations(null, prefix, 0); } else { return scope==null ? //a null scope occurs when we have not finished parsing the file getUnparsedProposals(cu, prefix) : scope.getMatchingDeclarations(node.getUnit(), prefix, 0); } } } private static ProducedType getPrimaryType(Tree.QualifiedMemberOrTypeExpression qme) { ProducedType type = qme.getPrimary().getTypeModel(); if (type==null) return null; if (qme.getMemberOperator() instanceof Tree.SafeMemberOp) { return qme.getUnit().getDefiniteType(type); } else if (qme.getMemberOperator() instanceof Tree.SpreadOp) { return qme.getUnit().getIteratedType(type); } else { return type; } } private static Map<String, DeclarationWithProximity> getUnparsedProposals(Node node, String prefix) { if (node == null) { return new TreeMap<String, DeclarationWithProximity>(); } Unit unit = node.getUnit(); if (unit == null) { return new TreeMap<String, DeclarationWithProximity>(); } Package pkg = unit.getPackage(); if (pkg == null) { return new TreeMap<String, DeclarationWithProximity>(); } return pkg.getModule().getAvailableDeclarations(prefix); } private static boolean forceExplicitTypeArgs(Declaration d, OccurrenceLocation ol) { if (ol==EXTENDS) { return true; } else { //TODO: this is a pretty limited implementation // for now, but eventually we could do // something much more sophisticated to // guess is explicit type args will be // necessary (variance, etc) if (d instanceof Functional) { List<ParameterList> pls = ((Functional) d).getParameterLists(); return pls.isEmpty() || pls.get(0).getParameters().isEmpty(); } else { return false; } } } private static String name(DeclarationWithProximity d) { return name(d.getDeclaration(), d.getName()); } private static String name(Declaration d) { return name(d, d.getName()); } private static String name(Declaration d, String alias) { char c = alias.charAt(0); if (d instanceof TypedDeclaration && (isUpperCase(c)||"object".equals(alias))) { return "\\i" + alias; } else if (d instanceof TypeDeclaration && !(d instanceof Class && d.isAnonymous()) && isLowerCase(c)) { return "\\I" + alias; } else { return alias; } } private static String getTextFor(DeclarationWithProximity d, OccurrenceLocation ol) { StringBuilder result = new StringBuilder(name(d)); if (ol!=IMPORT) appendTypeParameters(d.getDeclaration(), result); return result.toString(); } private static String getPositionalInvocationTextFor(DeclarationWithProximity d, OccurrenceLocation ol, ProducedReference pr, boolean includeDefaulted) { StringBuilder result = new StringBuilder(name(d)); Declaration dd = d.getDeclaration(); if (forceExplicitTypeArgs(dd, ol)) appendTypeParameters(dd, result); appendPositionalArgs(dd, pr, result, includeDefaulted); appendSemiToVoidInvocation(result, dd); return result.toString(); } private static String getNamedInvocationTextFor(DeclarationWithProximity d, ProducedReference pr, boolean includeDefaulted) { StringBuilder result = new StringBuilder(name(d)); Declaration dd = d.getDeclaration(); if (forceExplicitTypeArgs(dd, null)) appendTypeParameters(dd, result); appendNamedArgs(dd, pr, result, includeDefaulted, false); appendSemiToVoidInvocation(result, dd); return result.toString(); } private static void appendSemiToVoidInvocation(StringBuilder result, Declaration dd) { if ((dd instanceof Method) && ((Method) dd).isDeclaredVoid() && ((Method) dd).getParameterLists().size()==1) { result.append(';'); } } private static String getDescriptionFor(DeclarationWithProximity d, OccurrenceLocation ol) { StringBuilder result = new StringBuilder(d.getName()); if (ol!=IMPORT) appendTypeParameters(d.getDeclaration(), result); return result.toString(); } private static String getPositionalInvocationDescriptionFor(DeclarationWithProximity d, OccurrenceLocation ol, ProducedReference pr, boolean includeDefaulted) { StringBuilder result = new StringBuilder(d.getName()); if (forceExplicitTypeArgs(d.getDeclaration(), ol)) appendTypeParameters(d.getDeclaration(), result); appendPositionalArgs(d.getDeclaration(), pr, result, includeDefaulted); return result.toString(); } private static String getNamedInvocationDescriptionFor(DeclarationWithProximity d, ProducedReference pr, boolean includeDefaulted) { StringBuilder result = new StringBuilder(d.getName()); if (forceExplicitTypeArgs(d.getDeclaration(), null)) appendTypeParameters(d.getDeclaration(), result); appendNamedArgs(d.getDeclaration(), pr, result, includeDefaulted, true); return result.toString(); } public static String getRefinementTextFor(Declaration d, ProducedReference pr, boolean isInterface, String indent) { StringBuilder result = new StringBuilder("shared actual "); if (isVariable(d) && !isInterface) { result.append("variable "); } appendDeclarationText(d, pr, result); appendTypeParameters(d, result); appendParameters(d, pr, result); if (d instanceof Class) { result.append(extraIndent(extraIndent(indent))) .append(" extends super.").append(d.getName()); appendPositionalArgs(d, pr, result, true); } appendConstraints(d, pr, indent, result); appendImpl(d, isInterface, indent, result); return result.toString(); } private static void appendConstraints(Declaration d, ProducedReference pr, String indent, StringBuilder result) { if (d instanceof Functional) { for (TypeParameter tp: ((Functional) d).getTypeParameters()) { List<ProducedType> sts = tp.getSatisfiedTypes(); if (!sts.isEmpty()) { result.append(extraIndent(extraIndent(indent))) .append("given ").append(tp.getName()) .append(" satisfies "); boolean first = true; for (ProducedType st: sts) { if (first) { first = false; } else { result.append("&"); } result.append(st.substitute(pr.getTypeArguments()).getProducedTypeName()); } } } } } private static String getInlineFunctionTextFor(Parameter p, ProducedReference pr, String indent) { StringBuilder result = new StringBuilder(); appendNamedArgumentText(p, pr, result); appendTypeParameters(p.getModel(), result); appendParameters(p.getModel(), pr, result); appendImpl(p.getModel(), false, indent, result); return result.toString(); } private static boolean isVariable(Declaration d) { return d instanceof TypedDeclaration && ((TypedDeclaration) d).isVariable(); } /*private static String getAttributeRefinementTextFor(Declaration d) { StringBuilder result = new StringBuilder(); result.append("super.").append(d.getName()) .append(" = ").append(d.getName()).append(";"); return result.toString(); }*/ private static String getRefinementDescriptionFor(Declaration d, ProducedReference pr) { StringBuilder result = new StringBuilder("shared actual "); if (isVariable(d)) { result.append("variable "); } appendDeclarationText(d, pr, result); appendTypeParameters(d, result); appendParameters(d, pr, result); /*result.append(" - refine declaration in ") .append(((Declaration) d.getContainer()).getName());*/ return result.toString(); } private static String getInlineFunctionDescriptionFor(Parameter p, ProducedReference pr) { StringBuilder result = new StringBuilder(); appendNamedArgumentText(p, pr, result); appendTypeParameters(p.getModel(), result); appendParameters(p.getModel(), pr, result); /*result.append(" - refine declaration in ") .append(((Declaration) d.getContainer()).getName());*/ return result.toString(); } public static String getDescriptionFor(Declaration d) { StringBuilder result = new StringBuilder(); if (d!=null) { if (d.isFormal()) result.append("formal "); if (d.isDefault()) result.append("default "); appendDeclarationText(d, result); appendTypeParameters(d, result); appendParameters(d, result); /*result.append(" - refine declaration in ") .append(((Declaration) d.getContainer()).getName());*/ } return result.toString(); } public static StyledString getStyledDescriptionFor(Declaration d) { StyledString result = new StyledString(); if (d!=null) { if (d.isFormal()) result.append("formal ", ANN_STYLER); if (d.isDefault()) result.append("default ", ANN_STYLER); appendDeclarationText(d, result); appendTypeParameters(d, result); appendParameters(d, result); /*result.append(" - refine declaration in ") .append(((Declaration) d.getContainer()).getName());*/ } return result; } private static void appendPositionalArgs(Declaration d, ProducedReference pr, StringBuilder result, boolean includeDefaulted) { if (d instanceof Functional) { List<Parameter> params = getParameters((Functional) d, includeDefaulted); if (params.isEmpty()) { result.append("()"); } else { result.append("("); for (Parameter p: params) { appendParameters(p.getModel(), pr.getTypedParameter(p), result); if (p.getModel() instanceof Functional) { result.append(" => "); } result.append(p.getName()).append(", "); } result.setLength(result.length()-2); result.append(")"); } } } private static List<Parameter> getParameters(Functional fd, boolean includeDefaults) { List<ParameterList> plists = fd.getParameterLists(); if (plists==null || plists.isEmpty()) { return Collections.<Parameter>emptyList(); } List<Parameter> pl = plists.get(0).getParameters(); if (includeDefaults) { return pl; } else { List<Parameter> list = new ArrayList<Parameter>(); for (Parameter p: pl) { if (!p.isDefaulted()) list.add(p); } return list; } } private static void appendNamedArgs(Declaration d, ProducedReference pr, StringBuilder result, boolean includeDefaulted, boolean descriptionOnly) { if (d instanceof Functional) { List<Parameter> params = getParameters((Functional) d, includeDefaulted); if (params.isEmpty()) { result.append(" {}"); } else { result.append(" { "); for (Parameter p: params) { if (!p.isSequenced()) { if (p.getModel() instanceof Functional) { result.append("function ").append(p.getName()); appendParameters(p.getModel(), pr.getTypedParameter(p), result); if (descriptionOnly) { result.append("; "); } else { result.append(" => ") //.append(CeylonQuickFixAssistant.defaultValue(p.getUnit(), p.getType())) .append("nothing") .append("; "); } } else { result.append(p.getName()).append(" = ") //.append(CeylonQuickFixAssistant.defaultValue(p.getUnit(), p.getType())) .append("nothing") .append("; "); } } } result.append("}"); } } } private static void appendTypeParameters(Declaration d, StringBuilder result) { if (d instanceof Generic) { List<TypeParameter> types = ((Generic) d).getTypeParameters(); if (!types.isEmpty()) { result.append("<"); for (TypeParameter p: types) { result.append(p.getName()).append(", "); } result.setLength(result.length()-2); result.append(">"); } } } private static void appendTypeParameters(Declaration d, StyledString result) { if (d instanceof Generic) { List<TypeParameter> types = ((Generic) d).getTypeParameters(); if (!types.isEmpty()) { result.append("<"); int len = types.size(), i = 0; for (TypeParameter p: types) { result.append(p.getName(), TYPE_STYLER); if (++i<len) result.append(", "); } result.append(">"); } } } private static void appendDeclarationText(Declaration d, StringBuilder result) { appendDeclarationText(d, null, result); } private static void appendDeclarationText(Declaration d, ProducedReference pr, StringBuilder result) { if (d instanceof Class) { if (d.isAnonymous()) { result.append("object"); } else { result.append("class"); } } else if (d instanceof Interface) { result.append("interface"); } else if (d instanceof TypeAlias) { result.append("alias"); } else if (d instanceof TypedDeclaration) { TypedDeclaration td = (TypedDeclaration) d; ProducedType type = td.getType(); if (type==null) type = new UnknownType(d.getUnit()).getType(); boolean isSequenced = d.isParameter() && ((MethodOrValue) d).getInitializerParameter().isSequenced(); if (pr!=null) { type = type.substitute(pr.getTypeArguments()); } if (isSequenced) { type = d.getUnit().getIteratedType(type); } String typeName = type.getProducedTypeName(); if (td.isDynamicallyTyped()) { result.append("dynamic"); } else if (td instanceof Value && type.getDeclaration().isAnonymous()) { result.append("object"); } else if (d instanceof Method) { if (((Functional) d).isDeclaredVoid()) { result.append("void"); } else { result.append(typeName); } } else { result.append(typeName); } if (isSequenced) { if (((MethodOrValue) d).getInitializerParameter().isAtLeastOne()) { result.append("+"); } else { result.append("*"); } } } result.append(" ").append(name(d)); } private static void appendNamedArgumentText(Parameter p, ProducedReference pr, StringBuilder result) { if (p.getModel() instanceof Functional) { Functional fp = (Functional) p.getModel(); result.append(fp.isDeclaredVoid() ? "void" : "function"); } else { result.append("value"); } result.append(" ").append(p.getName()); } private static void appendDeclarationText(Declaration d, StyledString result) { if (d instanceof Class) { if (d.isAnonymous()) { result.append("object", KW_STYLER); } else { result.append("class", KW_STYLER); } } else if (d instanceof Interface) { result.append("interface", KW_STYLER); } else if (d instanceof TypeAlias) { result.append("alias", KW_STYLER); } else if (d instanceof TypedDeclaration) { TypedDeclaration td = (TypedDeclaration) d; ProducedType type = td.getType(); if (td.isDynamicallyTyped()) { result.append("dynamic", KW_STYLER); } else if (type!=null) { boolean isSequenced = d.isParameter() && ((MethodOrValue) d).getInitializerParameter().isSequenced(); if (isSequenced) { type = d.getUnit().getIteratedType(type); } String typeName = type.getProducedTypeName(); if (td instanceof Value && td.getTypeDeclaration().isAnonymous()) { result.append("object", KW_STYLER); } else if (d instanceof Method) { if (((Functional)d).isDeclaredVoid()) { result.append("void", KW_STYLER); } else { result.append(typeName, TYPE_STYLER); } } else { result.append(typeName, TYPE_STYLER); } if (isSequenced) { result.append("*"); } } } result.append(" "); if (d instanceof TypeDeclaration) { result.append(d.getName(), TYPE_STYLER); } else { result.append(d.getName(), ID_STYLER); } } /*private static void appendPackage(Declaration d, StringBuilder result) { if (d.isToplevel()) { result.append(" - ").append(getPackageLabel(d)); } if (d.isClassOrInterfaceMember()) { result.append(" - "); ClassOrInterface td = (ClassOrInterface) d.getContainer(); result.append( td.getName() ); appendPackage(td, result); } }*/ private static void appendImpl(Declaration d, boolean isInterface, String indent, StringBuilder result) { if (d instanceof Method) { result.append(((Functional) d).isDeclaredVoid() ? " {}" : " => nothing;"); result.append(" /* TODO auto-generated stub */"); } else if (d.isParameter()) { result.append(" => nothing;"); } else if (d instanceof MethodOrValue) { if (isInterface) { result.append(" => nothing; /* TODO auto-generated stub */"); if (isVariable(d)) { result.append(indent + "assign " + d.getName() + " {} /* TODO auto-generated stub */"); } } else { result.append(" = nothing; /* TODO auto-generated stub */"); } } else { //TODO: in the case of a class, formal member refinements! result.append(" {}"); } } private static String extraIndent(String indent) { return indent.contains("\n") ? indent + getDefaultIndent() : indent; } private static void appendParameters(Declaration d, StringBuilder result) { appendParameters(d, null, result); } private static void appendParameters(Declaration d, ProducedReference pr, StringBuilder result) { if (d instanceof Functional) { List<ParameterList> plists = ((Functional) d).getParameterLists(); if (plists!=null) { for (ParameterList params: plists) { if (params.getParameters().isEmpty()) { result.append("()"); } else { result.append("("); for (Parameter p: params.getParameters()) { ProducedTypedReference ppr = pr==null ? null : pr.getTypedParameter(p); if (p.getModel()!=null) { appendDeclarationText(p.getModel(), ppr, result); } else { result.append(p.getName()); } appendParameters(p.getModel(), ppr, result); /*ProducedType type = p.getType(); if (pr!=null) { type = type.substitute(pr.getTypeArguments()); } result.append(type.getProducedTypeName()).append(" ") .append(p.getName()); if (p instanceof FunctionalParameter) { result.append("("); FunctionalParameter fp = (FunctionalParameter) p; for (Parameter pp: fp.getParameterLists().get(0).getParameters()) { result.append(pp.getType().substitute(pr.getTypeArguments()) .getProducedTypeName()) .append(" ").append(pp.getName()).append(", "); } result.setLength(result.length()-2); result.append(")"); }*/ if (p.isDefaulted()) result.append("="); result.append(", "); } result.setLength(result.length()-2); result.append(")"); } } } } } private static void appendParameters(Declaration d, StyledString result) { if (d instanceof Functional) { List<ParameterList> plists = ((Functional) d).getParameterLists(); if (plists!=null) { for (ParameterList params: plists) { if (params.getParameters().isEmpty()) { result.append("()"); } else { result.append("("); int len = params.getParameters().size(), i=0; for (Parameter p: params.getParameters()) { if (p.getModel()==null) { result.append(p.getName()); } else { appendDeclarationText(p.getModel(), result); appendParameters(p.getModel(), result); /*result.append(p.getType().getProducedTypeName(), TYPE_STYLER) .append(" ").append(p.getName(), ID_STYLER); if (p instanceof FunctionalParameter) { result.append("("); FunctionalParameter fp = (FunctionalParameter) p; List<Parameter> fpl = fp.getParameterLists().get(0).getParameters(); int len2 = fpl.size(), j=0; for (Parameter pp: fpl) { result.append(pp.getType().getProducedTypeName(), TYPE_STYLER) .append(" ").append(pp.getName(), ID_STYLER); if (++j<len2) result.append(", "); } result.append(")"); }*/ } if (++i<len) result.append(", "); } result.append(")"); } } } } } }
gen shorter comments
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/propose/CeylonContentProposer.java
gen shorter comments
<ide><path>lugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/propose/CeylonContentProposer.java <ide> private static void appendImpl(Declaration d, boolean isInterface, <ide> String indent, StringBuilder result) { <ide> if (d instanceof Method) { <del> result.append(((Functional) d).isDeclaredVoid() ? " {}" : " => nothing;"); <del> result.append(" /* TODO auto-generated stub */"); <add> result.append(((Functional) d).isDeclaredVoid() ? " {}" : " => nothing; /*TODO: Implement*/"); <ide> } <ide> else if (d.isParameter()) { <del> result.append(" => nothing;"); <add> result.append(" => nothing; /*TODO: Implement*/"); <ide> } <ide> else if (d instanceof MethodOrValue) { <ide> if (isInterface) { <del> result.append(" => nothing; /* TODO auto-generated stub */"); <add> result.append(" => nothing; /*TODO: Implement*/"); <ide> if (isVariable(d)) { <del> result.append(indent + "assign " + d.getName() + " {} /* TODO auto-generated stub */"); <add> result.append(indent + "assign " + d.getName() + " {} /*TODO: Implement*/"); <ide> } <ide> } <ide> else { <del> result.append(" = nothing; /* TODO auto-generated stub */"); <add> result.append(" = nothing; /*TODO: Implement*/"); <ide> } <ide> } <ide> else { <ide> appendParameters(d, null, result); <ide> } <ide> <del> private static void appendParameters(Declaration d, ProducedReference pr, <add> public static void appendParameters(Declaration d, ProducedReference pr, <ide> StringBuilder result) { <ide> if (d instanceof Functional) { <ide> List<ParameterList> plists = ((Functional) d).getParameterLists(); <ide> for (Parameter p: params.getParameters()) { <ide> ProducedTypedReference ppr = pr==null ? <ide> null : pr.getTypedParameter(p); <del> if (p.getModel()!=null) { <del> appendDeclarationText(p.getModel(), ppr, result); <add> if (p.getModel() == null) { <add> result.append(p.getName()); <ide> } <ide> else { <del> result.append(p.getName()); <add> appendDeclarationText(p.getModel(), ppr, result); <add> appendParameters(p.getModel(), ppr, result); <ide> } <del> appendParameters(p.getModel(), ppr, result); <ide> /*ProducedType type = p.getType(); <ide> if (pr!=null) { <ide> type = type.substitute(pr.getTypeArguments());
Java
agpl-3.0
ce0650a495f0cfdc2dd01450c5779090eb32f8cc
0
PoweRGbg/AndroidAPS,Heiner1/AndroidAPS,PoweRGbg/AndroidAPS,Heiner1/AndroidAPS,Heiner1/AndroidAPS,MilosKozak/AndroidAPS,PoweRGbg/AndroidAPS,jotomo/AndroidAPS,jotomo/AndroidAPS,Heiner1/AndroidAPS,jotomo/AndroidAPS,winni67/AndroidAPS,MilosKozak/AndroidAPS,MilosKozak/AndroidAPS,winni67/AndroidAPS
package info.nightscout.androidaps.plugins.PumpInsight.connector; import android.content.Intent; import android.os.PowerManager; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.plugins.PumpInsight.events.EventInsightPumpUpdateGui; import info.nightscout.androidaps.plugins.PumpInsight.history.HistoryReceiver; import info.nightscout.androidaps.plugins.PumpInsight.history.LiveHistory; import info.nightscout.androidaps.plugins.PumpInsight.utils.Helpers; import sugar.free.sightparser.handling.ServiceConnectionCallback; import sugar.free.sightparser.handling.SightServiceConnector; import sugar.free.sightparser.handling.StatusCallback; import sugar.free.sightparser.pipeline.Status; import static sugar.free.sightparser.handling.HistoryBroadcast.ACTION_START_RESYNC; import static sugar.free.sightparser.handling.HistoryBroadcast.ACTION_START_SYNC; import static sugar.free.sightparser.handling.SightService.COMPATIBILITY_VERSION; /** * Created by jamorham on 23/01/2018. * * Connects to SightRemote app service using SightParser library * * SightRemote and SightParser created by Tebbe Ubben * * Original proof of concept SightProxy by jamorham * */ public class Connector { //public static final String ACTION_START_RESYNC = "sugar.free.sightremote.services.HistorySyncService.START_RESYNC"; private static final String TAG = "InsightConnector"; private static final String COMPANION_APP_PACKAGE = "sugar.free.sightremote"; private final static long FRESH_MS = 70000; private static volatile Connector instance; private static volatile HistoryReceiver historyReceiver; private volatile SightServiceConnector serviceConnector; private volatile Status lastStatus = null; private String compatabilityMessage = null; private volatile long lastStatusTime = -1; private boolean companionAppInstalled = false; private int serviceReconnects = 0; private StatusCallback statusCallback = new StatusCallback() { @Override public synchronized void onStatusChange(Status status) { log("Status change: " + status); lastStatus = status; lastStatusTime = Helpers.tsl(); MainApp.bus().post(new EventInsightPumpUpdateGui()); } }; private ServiceConnectionCallback connectionCallback = new ServiceConnectionCallback() { @Override public synchronized void onServiceConnected() { log("On service connected"); try { final String remoteVersion = serviceConnector.getRemoteVersion(); if (remoteVersion.equals(COMPATIBILITY_VERSION)) { serviceConnector.connect(); } else { log("PROTOCOL VERSION MISMATCH! local: " + COMPATIBILITY_VERSION + " remote: " + remoteVersion); statusCallback.onStatusChange(Status.INCOMPATIBLE); compatabilityMessage = "Incompatible companion app, we need version " + getLocalVersion(); serviceConnector.disconnectFromService(); } } catch (NullPointerException e) { log("ERROR: null pointer when trying to connect to pump"); } statusCallback.onStatusChange(safeGetStatus()); } @Override public synchronized void onServiceDisconnected() { log("Disconnected from service"); if (Helpers.ratelimit("insight-automatic-reconnect", 30)) { log("Scheduling automatic service reconnection"); Helpers.runOnUiThreadDelayed(new Runnable() { @Override public void run() { init(); } }, 20000); } } }; private Connector() { initializeHistoryReceiver(); } public static Connector get() { if (instance == null) { init_instance(); } return instance; } private synchronized static void init_instance() { if (instance == null) { instance = new Connector(); } } private static boolean isCompanionAppInstalled() { return Helpers.checkPackageExists(MainApp.instance(), TAG, COMPANION_APP_PACKAGE); } public static void connectToPump() { log("Attempting to connect to pump"); get().getServiceConnector().connect(); } static void log(String msg) { android.util.Log.e("INSIGHTPUMP", msg); } static String getLocalVersion() { return COMPATIBILITY_VERSION; } @SuppressWarnings("AccessStaticViaInstance") private synchronized void initializeHistoryReceiver() { if (historyReceiver == null) { historyReceiver = new HistoryReceiver(); } historyReceiver.registerHistoryReceiver(); } public synchronized void init() { log("Connector::init()"); if (serviceConnector == null) { companionAppInstalled = isCompanionAppInstalled(); if (companionAppInstalled) { serviceConnector = new SightServiceConnector(MainApp.instance()); serviceConnector.removeStatusCallback(statusCallback); serviceConnector.addStatusCallback(statusCallback); serviceConnector.setConnectionCallback(connectionCallback); serviceConnector.connectToService(); log("Trying to connect"); } else { log("Not trying init due to missing companion app"); } } else { if (!serviceConnector.isConnectedToService()) { if (serviceReconnects > 0) { serviceConnector = null; init(); } else { log("Trying to reconnect to service (" + serviceReconnects + ")"); serviceConnector.connectToService(); serviceReconnects++; } } else { serviceReconnects = 0; // everything ok } } } public SightServiceConnector getServiceConnector() { init(); return serviceConnector; } public String getCurrent() { init(); return safeGetStatus().toString(); } public Status safeGetStatus() { try { if (isConnected()) return serviceConnector.getStatus(); return Status.DISCONNECTED; } catch (IllegalArgumentException e) { return Status.INCOMPATIBLE; } } public Status getLastStatus() { return lastStatus; } public boolean isConnected() { return serviceConnector != null && serviceConnector.isConnectedToService(); } public boolean isPumpConnected() { return isConnected() && getLastStatus() == Status.CONNECTED; } public String getLastStatusMessage() { if (!companionAppInstalled) { return "Companion app does not appear to be installed!"; } if (!isConnected()) { log("Not connected to companion"); if (Helpers.ratelimit("insight-app-not-connected", 5)) { init(); } if ((lastStatus == null) || (lastStatus != Status.INCOMPATIBLE)) { if (compatabilityMessage != null) { // if disconnected but previous state was incompatible return compatabilityMessage; } else { return "Not connected to companion app!"; } } } if (lastStatus == null) { return "Unknown"; } switch (lastStatus) { case CONNECTED: if (lastStatusTime < 1) { tryToGetPumpStatusAgain(); } // TODO other refresh? break; case INCOMPATIBLE: return lastStatus.toString() + " needs " + getLocalVersion(); } return lastStatus.toString(); } public String getNiceLastStatusTime() { if (lastStatusTime < 1) { return "STARTUP"; } else { return Helpers.niceTimeScalar(Helpers.msSince(lastStatusTime)) + " ago"; } } public boolean uiFresh() { // todo check other changes if (Helpers.msSince(lastStatusTime) < FRESH_MS) { return true; } if (Helpers.msSince(LiveHistory.getStatusTime()) < FRESH_MS) { return true; } return false; } @SuppressWarnings("AccessStaticViaInstance") public void tryToGetPumpStatusAgain() { if (Helpers.ratelimit("insight-retry-status-request", 5)) { try { MainApp.getConfigBuilder().getCommandQueue().readStatus("Insight. Status missing", null); } catch (NullPointerException e) { // } } } public void requestHistorySync() { requestHistorySync(0); } public void requestHistoryReSync() { requestHistoryReSync(0); } public void requestHistorySync(long delay) { if (Helpers.ratelimit("insight-history-sync-request", 10)) { final Intent intent = new Intent(ACTION_START_SYNC); sendBroadcastToCompanion(intent, delay); } } public void requestHistoryReSync(long delay) { if (Helpers.ratelimit("insight-history-resync-request", 300)) { final Intent intent = new Intent(ACTION_START_RESYNC); sendBroadcastToCompanion(intent, delay); } } private void sendBroadcastToCompanion(final Intent intent, final long delay) { new Thread(new Runnable() { @Override public void run() { final PowerManager.WakeLock wl = Helpers.getWakeLock("insight-companion-delay", 60000); intent.setPackage(COMPANION_APP_PACKAGE); intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); try { if (delay > 0) { Thread.sleep(delay); } } catch (InterruptedException e) { // } finally { Helpers.releaseWakeLock(wl); } MainApp.instance().sendBroadcast(intent); } }).start(); } public boolean lastStatusRecent() { return true; // TODO evaluate whether current } }
app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/Connector.java
package info.nightscout.androidaps.plugins.PumpInsight.connector; import android.content.Intent; import android.os.PowerManager; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.plugins.PumpInsight.events.EventInsightPumpUpdateGui; import info.nightscout.androidaps.plugins.PumpInsight.history.HistoryReceiver; import info.nightscout.androidaps.plugins.PumpInsight.history.LiveHistory; import info.nightscout.androidaps.plugins.PumpInsight.utils.Helpers; import sugar.free.sightparser.handling.ServiceConnectionCallback; import sugar.free.sightparser.handling.SightServiceConnector; import sugar.free.sightparser.handling.StatusCallback; import sugar.free.sightparser.pipeline.Status; import static sugar.free.sightparser.handling.HistoryBroadcast.ACTION_START_RESYNC; import static sugar.free.sightparser.handling.HistoryBroadcast.ACTION_START_SYNC; /** * Created by jamorham on 23/01/2018. * * Connects to SightRemote app service using SightParser library * * SightRemote and SightParser created by Tebbe Ubben * * Original proof of concept SightProxy by jamorham * */ public class Connector { //public static final String ACTION_START_RESYNC = "sugar.free.sightremote.services.HistorySyncService.START_RESYNC"; private static final String TAG = "InsightConnector"; private static final String COMPANION_APP_PACKAGE = "sugar.free.sightremote"; private final static long FRESH_MS = 70000; private static volatile Connector instance; private static volatile HistoryReceiver historyReceiver; private volatile SightServiceConnector serviceConnector; private volatile Status lastStatus = null; private volatile long lastStatusTime = -1; private boolean companionAppInstalled = false; private int serviceReconnects = 0; private StatusCallback statusCallback = new StatusCallback() { @Override public synchronized void onStatusChange(Status status) { log("Status change: " + status); lastStatus = status; lastStatusTime = Helpers.tsl(); MainApp.bus().post(new EventInsightPumpUpdateGui()); } }; private ServiceConnectionCallback connectionCallback = new ServiceConnectionCallback() { @Override public synchronized void onServiceConnected() { log("On service connected"); try { serviceConnector.connect(); } catch (NullPointerException e) { log("ERROR: null pointer when trying to connect to pump"); } statusCallback.onStatusChange(safeGetStatus()); } @Override public synchronized void onServiceDisconnected() { log("Disconnected from service"); if (Helpers.ratelimit("insight-automatic-reconnect", 30)) { log("Scheduling automatic service reconnection"); Helpers.runOnUiThreadDelayed(new Runnable() { @Override public void run() { init(); } }, 20000); } } }; private Connector() { initializeHistoryReceiver(); } public static Connector get() { if (instance == null) { init_instance(); } return instance; } private synchronized static void init_instance() { if (instance == null) { instance = new Connector(); } } private static boolean isCompanionAppInstalled() { return Helpers.checkPackageExists(MainApp.instance(), TAG, COMPANION_APP_PACKAGE); } public static void connectToPump() { log("Attempting to connect to pump"); get().getServiceConnector().connect(); } static void log(String msg) { android.util.Log.e("INSIGHTPUMP", msg); } @SuppressWarnings("AccessStaticViaInstance") private synchronized void initializeHistoryReceiver() { if (historyReceiver == null) { historyReceiver = new HistoryReceiver(); } historyReceiver.registerHistoryReceiver(); } public synchronized void init() { log("Connector::init()"); if (serviceConnector == null) { companionAppInstalled = isCompanionAppInstalled(); if (companionAppInstalled) { serviceConnector = new SightServiceConnector(MainApp.instance()); serviceConnector.removeStatusCallback(statusCallback); serviceConnector.addStatusCallback(statusCallback); serviceConnector.setConnectionCallback(connectionCallback); serviceConnector.connectToService(); log("Trying to connect"); } else { log("Not trying init due to missing companion app"); } } else { if (!serviceConnector.isConnectedToService()) { if (serviceReconnects > 0) { serviceConnector = null; init(); } else { log("Trying to reconnect to service (" + serviceReconnects + ")"); serviceConnector.connectToService(); serviceReconnects++; } } else { serviceReconnects = 0; // everything ok } } } public SightServiceConnector getServiceConnector() { init(); return serviceConnector; } public String getCurrent() { init(); return safeGetStatus().toString(); } public Status safeGetStatus() { if (isConnected()) return serviceConnector.getStatus(); return Status.DISCONNECTED; } public Status getLastStatus() { return lastStatus; } public boolean isConnected() { return serviceConnector != null && serviceConnector.isConnectedToService(); } public boolean isPumpConnected() { return isConnected() && getLastStatus() == Status.CONNECTED; } public String getLastStatusMessage() { if (!companionAppInstalled) { return "Companion app does not appear to be installed!"; } if (!isConnected()) { log("Not connected to companion"); if (Helpers.ratelimit("insight-app-not-connected", 5)) { init(); } return "Not connected to companion app!"; } if (lastStatus == null) { return "Unknown"; } switch (lastStatus) { case CONNECTED: if (lastStatusTime < 1) { tryToGetPumpStatusAgain(); } default: return lastStatus.toString(); } } public String getNiceLastStatusTime() { if (lastStatusTime < 1) { return "STARTUP"; } else { return Helpers.niceTimeScalar(Helpers.msSince(lastStatusTime)) + " ago"; } } public boolean uiFresh() { // todo check other changes if (Helpers.msSince(lastStatusTime) < FRESH_MS) { return true; } if (Helpers.msSince(LiveHistory.getStatusTime()) < FRESH_MS) { return true; } return false; } @SuppressWarnings("AccessStaticViaInstance") public void tryToGetPumpStatusAgain() { if (Helpers.ratelimit("insight-retry-status-request", 5)) { try { MainApp.getConfigBuilder().getCommandQueue().readStatus("Insight. Status missing", null); } catch (NullPointerException e) { // } } } public void requestHistorySync() { requestHistorySync(0); } public void requestHistoryReSync() { requestHistoryReSync(0); } public void requestHistorySync(long delay) { if (Helpers.ratelimit("insight-history-sync-request", 10)) { final Intent intent = new Intent(ACTION_START_SYNC); sendBroadcastToCompanion(intent, delay); } } public void requestHistoryReSync(long delay) { if (Helpers.ratelimit("insight-history-resync-request", 300)) { final Intent intent = new Intent(ACTION_START_RESYNC); sendBroadcastToCompanion(intent, delay); } } private void sendBroadcastToCompanion(final Intent intent, final long delay) { new Thread(new Runnable() { @Override public void run() { final PowerManager.WakeLock wl = Helpers.getWakeLock("insight-companion-delay", 60000); intent.setPackage(COMPANION_APP_PACKAGE); intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); try { if (delay > 0) { Thread.sleep(delay); } } catch (InterruptedException e) { // } finally { Helpers.releaseWakeLock(wl); } MainApp.instance().sendBroadcast(intent); } }).start(); } public boolean lastStatusRecent() { return true; // TODO evaluate whether current } }
Check remote protocol version
app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/Connector.java
Check remote protocol version
<ide><path>pp/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/Connector.java <ide> <ide> import static sugar.free.sightparser.handling.HistoryBroadcast.ACTION_START_RESYNC; <ide> import static sugar.free.sightparser.handling.HistoryBroadcast.ACTION_START_SYNC; <add>import static sugar.free.sightparser.handling.SightService.COMPATIBILITY_VERSION; <ide> <ide> /** <ide> * Created by jamorham on 23/01/2018. <ide> private static volatile HistoryReceiver historyReceiver; <ide> private volatile SightServiceConnector serviceConnector; <ide> private volatile Status lastStatus = null; <add> private String compatabilityMessage = null; <ide> private volatile long lastStatusTime = -1; <ide> private boolean companionAppInstalled = false; <ide> private int serviceReconnects = 0; <ide> public synchronized void onServiceConnected() { <ide> log("On service connected"); <ide> try { <del> serviceConnector.connect(); <add> final String remoteVersion = serviceConnector.getRemoteVersion(); <add> if (remoteVersion.equals(COMPATIBILITY_VERSION)) { <add> serviceConnector.connect(); <add> } else { <add> log("PROTOCOL VERSION MISMATCH! local: " + COMPATIBILITY_VERSION + " remote: " + remoteVersion); <add> statusCallback.onStatusChange(Status.INCOMPATIBLE); <add> compatabilityMessage = "Incompatible companion app, we need version " + getLocalVersion(); <add> serviceConnector.disconnectFromService(); <add> <add> } <ide> } catch (NullPointerException e) { <ide> log("ERROR: null pointer when trying to connect to pump"); <ide> } <ide> <ide> static void log(String msg) { <ide> android.util.Log.e("INSIGHTPUMP", msg); <add> } <add> <add> static String getLocalVersion() { <add> return COMPATIBILITY_VERSION; <ide> } <ide> <ide> @SuppressWarnings("AccessStaticViaInstance") <ide> } <ide> <ide> public Status safeGetStatus() { <del> if (isConnected()) return serviceConnector.getStatus(); <del> return Status.DISCONNECTED; <add> try { <add> if (isConnected()) return serviceConnector.getStatus(); <add> return Status.DISCONNECTED; <add> } catch (IllegalArgumentException e) { <add> return Status.INCOMPATIBLE; <add> } <ide> } <ide> <ide> public Status getLastStatus() { <ide> if (Helpers.ratelimit("insight-app-not-connected", 5)) { <ide> init(); <ide> } <del> return "Not connected to companion app!"; <add> <add> if ((lastStatus == null) || (lastStatus != Status.INCOMPATIBLE)) { <add> if (compatabilityMessage != null) { <add> // if disconnected but previous state was incompatible <add> return compatabilityMessage; <add> } else { <add> return "Not connected to companion app!"; <add> } <add> } <ide> } <ide> <ide> if (lastStatus == null) { <ide> } <ide> <ide> switch (lastStatus) { <del> <ide> case CONNECTED: <ide> if (lastStatusTime < 1) { <ide> tryToGetPumpStatusAgain(); <ide> } <del> <del> default: <del> return lastStatus.toString(); <del> } <add> // TODO other refresh? <add> break; <add> case INCOMPATIBLE: <add> return lastStatus.toString() + " needs " + getLocalVersion(); <add> } <add> return lastStatus.toString(); <ide> } <ide> <ide> public String getNiceLastStatusTime() {
Java
apache-2.0
b11d0a9466d3dfafa450a1e21e7e523de226f37c
0
consulo/consulo-mercurial,consulo/consulo-mercurial,consulo/consulo-mercurial
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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.zmlx.hg4idea.log; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Couple; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.VcsKey; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.CollectConsumer; import com.intellij.util.Consumer; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBusConnection; import com.intellij.vcs.log.*; import com.intellij.vcs.log.impl.LogDataImpl; import com.intellij.vcs.log.util.UserNameRegex; import com.intellij.vcs.log.util.VcsUserUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.zmlx.hg4idea.HgNameWithHashInfo; import org.zmlx.hg4idea.HgUpdater; import org.zmlx.hg4idea.HgVcs; import org.zmlx.hg4idea.execution.HgCommandResult; import org.zmlx.hg4idea.repo.HgConfig; import org.zmlx.hg4idea.repo.HgRepository; import org.zmlx.hg4idea.repo.HgRepositoryManager; import org.zmlx.hg4idea.util.HgChangesetUtil; import org.zmlx.hg4idea.util.HgUtil; import org.zmlx.hg4idea.util.HgVersion; import java.text.SimpleDateFormat; import java.util.*; import static org.zmlx.hg4idea.util.HgUtil.HEAD_REFERENCE; import static org.zmlx.hg4idea.util.HgUtil.TIP_REFERENCE; public class HgLogProvider implements VcsLogProvider { private static final Logger LOG = Logger.getInstance(HgLogProvider.class); @NotNull private final Project myProject; @NotNull private final HgRepositoryManager myRepositoryManager; @NotNull private final VcsLogRefManager myRefSorter; @NotNull private final VcsLogObjectsFactory myVcsObjectsFactory; public HgLogProvider(@NotNull Project project, @NotNull HgRepositoryManager repositoryManager, @NotNull VcsLogObjectsFactory factory) { myProject = project; myRepositoryManager = repositoryManager; myRefSorter = new HgRefManager(); myVcsObjectsFactory = factory; } @NotNull @Override public DetailedLogData readFirstBlock(@NotNull VirtualFile root, @NotNull Requirements requirements) throws VcsException { List<VcsCommitMetadata> commits = HgHistoryUtil.loadMetadata(myProject, root, requirements.getCommitCount(), Collections.<String>emptyList()); return new LogDataImpl(readAllRefs(root), commits); } @Override @NotNull public LogData readAllHashes(@NotNull VirtualFile root, @NotNull final Consumer<TimedVcsCommit> commitConsumer) throws VcsException { Set<VcsUser> userRegistry = ContainerUtil.newHashSet(); List<TimedVcsCommit> commits = HgHistoryUtil.readAllHashes(myProject, root, new CollectConsumer<>(userRegistry), Collections.<String>emptyList()); for (TimedVcsCommit commit : commits) { commitConsumer.consume(commit); } return new LogDataImpl(readAllRefs(root), userRegistry); } @Override public void readAllFullDetails(@NotNull VirtualFile root, @NotNull Consumer<VcsFullCommitDetails> commitConsumer) throws VcsException { readFullDetails(root, ContainerUtil.newArrayList(), commitConsumer); } @Override public void readFullDetails(@NotNull VirtualFile root, @NotNull List<String> hashes, @NotNull Consumer<VcsFullCommitDetails> commitConsumer) throws VcsException { // this method currently is very slow and time consuming // so indexing is not to be used for mercurial for now HgVcs hgvcs = HgVcs.getInstance(myProject); assert hgvcs != null; final HgVersion version = hgvcs.getVersion(); final String[] templates = HgBaseLogParser.constructFullTemplateArgument(true, version); HgCommandResult logResult = HgHistoryUtil.getLogResult(myProject, root, version, -1, HgHistoryUtil.prepareHashes(hashes), HgChangesetUtil.makeTemplate(templates)); if (logResult == null) return; if (!logResult.getErrorLines().isEmpty()) throw new VcsException(logResult.getRawError()); HgHistoryUtil.createFullCommitsFromResult(myProject, root, logResult, version, false).forEach(commitConsumer::consume); } @NotNull @Override public List<? extends VcsShortCommitDetails> readShortDetails(@NotNull VirtualFile root, @NotNull List<String> hashes) throws VcsException { return HgHistoryUtil.readMiniDetails(myProject, root, hashes); } @NotNull @Override public List<? extends VcsFullCommitDetails> readFullDetails(@NotNull VirtualFile root, @NotNull List<String> hashes) throws VcsException { return HgHistoryUtil.history(myProject, root, -1, HgHistoryUtil.prepareHashes(hashes)); } @NotNull private Set<VcsRef> readAllRefs(@NotNull VirtualFile root) throws VcsException { if (myProject.isDisposed()) { return Collections.emptySet(); } HgRepository repository = myRepositoryManager.getRepositoryForRoot(root); if (repository == null) { LOG.error("Repository not found for root " + root); return Collections.emptySet(); } repository.update(); Map<String, LinkedHashSet<Hash>> branches = repository.getBranches(); Set<String> openedBranchNames = repository.getOpenedBranches(); Collection<HgNameWithHashInfo> bookmarks = repository.getBookmarks(); Collection<HgNameWithHashInfo> tags = repository.getTags(); Collection<HgNameWithHashInfo> localTags = repository.getLocalTags(); Collection<HgNameWithHashInfo> mqAppliedPatches = repository.getMQAppliedPatches(); Set<VcsRef> refs = new HashSet<>(branches.size() + bookmarks.size()); for (Map.Entry<String, LinkedHashSet<Hash>> entry : branches.entrySet()) { String branchName = entry.getKey(); boolean opened = openedBranchNames.contains(branchName); for (Hash hash : entry.getValue()) { refs.add(myVcsObjectsFactory.createRef(hash, branchName, opened ? HgRefManager.BRANCH : HgRefManager.CLOSED_BRANCH, root)); } } for (HgNameWithHashInfo bookmarkInfo : bookmarks) { refs.add(myVcsObjectsFactory.createRef(bookmarkInfo.getHash(), bookmarkInfo.getName(), HgRefManager.BOOKMARK, root)); } String currentRevision = repository.getCurrentRevision(); if (currentRevision != null) { // null => fresh repository refs.add(myVcsObjectsFactory.createRef(myVcsObjectsFactory.createHash(currentRevision), HEAD_REFERENCE, HgRefManager.HEAD, root)); } String tipRevision = repository.getTipRevision(); if (tipRevision != null) { // null => fresh repository refs.add(myVcsObjectsFactory.createRef(myVcsObjectsFactory.createHash(tipRevision), TIP_REFERENCE, HgRefManager.TIP, root)); } for (HgNameWithHashInfo tagInfo : tags) { refs.add(myVcsObjectsFactory.createRef(tagInfo.getHash(), tagInfo.getName(), HgRefManager.TAG, root)); } for (HgNameWithHashInfo localTagInfo : localTags) { refs.add(myVcsObjectsFactory.createRef(localTagInfo.getHash(), localTagInfo.getName(), HgRefManager.LOCAL_TAG, root)); } for (HgNameWithHashInfo mqPatchRef : mqAppliedPatches) { refs.add(myVcsObjectsFactory.createRef(mqPatchRef.getHash(), mqPatchRef.getName(), HgRefManager.MQ_APPLIED_TAG, root)); } return refs; } @NotNull @Override public VcsKey getSupportedVcs() { return HgVcs.getKey(); } @NotNull @Override public VcsLogRefManager getReferenceManager() { return myRefSorter; } @NotNull @Override public Disposable subscribeToRootRefreshEvents(@NotNull final Collection<VirtualFile> roots, @NotNull final VcsLogRefresher refresher) { MessageBusConnection connection = myProject.getMessageBus().connect(myProject); connection.subscribe(HgVcs.STATUS_TOPIC, new HgUpdater() { @Override public void update(Project project, @Nullable VirtualFile root) { if (root != null && roots.contains(root)) { refresher.refresh(root); } } }); return connection::disconnect; } @NotNull @Override public List<TimedVcsCommit> getCommitsMatchingFilter(@NotNull final VirtualFile root, @NotNull VcsLogFilterCollection filterCollection, int maxCount) throws VcsException { List<String> filterParameters = ContainerUtil.newArrayList(); // branch filter and user filter may be used several times without delimiter VcsLogBranchFilter branchFilter = filterCollection.getBranchFilter(); if (branchFilter != null) { HgRepository repository = myRepositoryManager.getRepositoryForRoot(root); if (repository == null) { LOG.error("Repository not found for root " + root); return Collections.emptyList(); } Collection<String> branchNames = repository.getBranches().keySet(); Collection<String> bookmarkNames = HgUtil.getNamesWithoutHashes(repository.getBookmarks()); Collection<String> predefinedNames = ContainerUtil.list(TIP_REFERENCE); boolean atLeastOneBranchExists = false; for (String branchName : ContainerUtil.concat(branchNames, bookmarkNames, predefinedNames)) { if (branchFilter.matches(branchName)) { filterParameters.add(HgHistoryUtil.prepareParameter("branch", branchName)); atLeastOneBranchExists = true; } } if (branchFilter.matches(HEAD_REFERENCE)) { filterParameters.add(HgHistoryUtil.prepareParameter("branch", ".")); filterParameters.add("-r"); filterParameters.add("::."); //all ancestors for current revision; atLeastOneBranchExists = true; } if (!atLeastOneBranchExists) { // no such branches => filter matches nothing return Collections.emptyList(); } } if (filterCollection.getUserFilter() != null) { filterParameters.add("-r"); String authorFilter = StringUtil.join(ContainerUtil.map(ContainerUtil.map(filterCollection.getUserFilter().getUsers(root), VcsUserUtil::toExactString), UserNameRegex.EXTENDED_INSTANCE), "|"); filterParameters.add("user('re:" + authorFilter + "')"); } if (filterCollection.getDateFilter() != null) { StringBuilder args = new StringBuilder(); final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); filterParameters.add("-d"); VcsLogDateFilter filter = filterCollection.getDateFilter(); if (filter.getAfter() != null) { if (filter.getBefore() != null) { args.append(dateFormatter.format(filter.getAfter())).append(" to ").append(dateFormatter.format(filter.getBefore())); } else { args.append('>').append(dateFormatter.format(filter.getAfter())); } } else if (filter.getBefore() != null) { args.append('<').append(dateFormatter.format(filter.getBefore())); } filterParameters.add(args.toString()); } if (filterCollection.getTextFilter() != null) { String textFilter = filterCollection.getTextFilter().getText(); if (filterCollection.getTextFilter().isRegex()) { filterParameters.add("-r"); filterParameters.add("grep(r'" + textFilter + "')"); } else if (filterCollection.getTextFilter().matchesCase()) { filterParameters.add("-r"); filterParameters.add("grep(r'" + StringUtil.escapeChars(textFilter, UserNameRegex.EXTENDED_REGEX_CHARS) + "')"); } else { filterParameters.add(HgHistoryUtil.prepareParameter("keyword", textFilter)); } } if (filterCollection.getStructureFilter() != null) { for (FilePath file : filterCollection.getStructureFilter().getFiles()) { filterParameters.add(file.getPath()); } } return HgHistoryUtil.readAllHashes(myProject, root, Consumer.EMPTY_CONSUMER, filterParameters); } @Nullable @Override public VcsUser getCurrentUser(@NotNull VirtualFile root) throws VcsException { String userName = HgConfig.getInstance(myProject, root).getNamedConfig("ui", "username"); //order of variables to identify hg username see at mercurial/ui.py if (userName == null) { userName = System.getenv("HGUSER"); if (userName == null) { userName = System.getenv("USER"); if (userName == null) { userName = System.getenv("LOGNAME"); if (userName == null) { return null; } } } } Couple<String> userArgs = HgUtil.parseUserNameAndEmail(userName); return myVcsObjectsFactory.createUser(userArgs.getFirst(), userArgs.getSecond()); } @NotNull @Override public Collection<String> getContainingBranches(@NotNull VirtualFile root, @NotNull Hash commitHash) throws VcsException { return HgHistoryUtil.getDescendingHeadsOfBranches(myProject, root, commitHash); } @Nullable @Override public String getCurrentBranch(@NotNull VirtualFile root) { HgRepository repository = myRepositoryManager.getRepositoryForRoot(root); if (repository == null) return null; return repository.getCurrentBranchName(); } @Nullable @Override public <T> T getPropertyValue(VcsLogProperties.VcsLogProperty<T> property) { if (property == VcsLogProperties.CASE_INSENSITIVE_REGEX) { return (T)Boolean.FALSE; } return null; } }
src/main/java/org/zmlx/hg4idea/log/HgLogProvider.java
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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.zmlx.hg4idea.log; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Couple; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.VcsKey; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.CollectConsumer; import com.intellij.util.Consumer; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBusConnection; import com.intellij.vcs.log.*; import com.intellij.vcs.log.impl.LogDataImpl; import com.intellij.vcs.log.util.UserNameRegex; import com.intellij.vcs.log.util.VcsUserUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.zmlx.hg4idea.HgNameWithHashInfo; import org.zmlx.hg4idea.HgUpdater; import org.zmlx.hg4idea.HgVcs; import org.zmlx.hg4idea.execution.HgCommandResult; import org.zmlx.hg4idea.repo.HgConfig; import org.zmlx.hg4idea.repo.HgRepository; import org.zmlx.hg4idea.repo.HgRepositoryManager; import org.zmlx.hg4idea.util.HgChangesetUtil; import org.zmlx.hg4idea.util.HgUtil; import org.zmlx.hg4idea.util.HgVersion; import java.text.SimpleDateFormat; import java.util.*; import static org.zmlx.hg4idea.util.HgUtil.HEAD_REFERENCE; import static org.zmlx.hg4idea.util.HgUtil.TIP_REFERENCE; public class HgLogProvider implements VcsLogProvider { private static final Logger LOG = Logger.getInstance(HgLogProvider.class); @NotNull private final Project myProject; @NotNull private final HgRepositoryManager myRepositoryManager; @NotNull private final VcsLogRefManager myRefSorter; @NotNull private final VcsLogObjectsFactory myVcsObjectsFactory; public HgLogProvider(@NotNull Project project, @NotNull HgRepositoryManager repositoryManager, @NotNull VcsLogObjectsFactory factory) { myProject = project; myRepositoryManager = repositoryManager; myRefSorter = new HgRefManager(); myVcsObjectsFactory = factory; } @NotNull @Override public DetailedLogData readFirstBlock(@NotNull VirtualFile root, @NotNull Requirements requirements) throws VcsException { List<VcsCommitMetadata> commits = HgHistoryUtil.loadMetadata(myProject, root, requirements.getCommitCount(), Collections.<String>emptyList()); return new LogDataImpl(readAllRefs(root), commits); } @Override @NotNull public LogData readAllHashes(@NotNull VirtualFile root, @NotNull final Consumer<TimedVcsCommit> commitConsumer) throws VcsException { Set<VcsUser> userRegistry = ContainerUtil.newHashSet(); List<TimedVcsCommit> commits = HgHistoryUtil.readAllHashes(myProject, root, new CollectConsumer<>(userRegistry), Collections.<String>emptyList()); for (TimedVcsCommit commit : commits) { commitConsumer.consume(commit); } return new LogDataImpl(readAllRefs(root), userRegistry); } @Override public void readAllFullDetails(@NotNull VirtualFile root, @NotNull Consumer<VcsFullCommitDetails> commitConsumer) throws VcsException { readFullDetails(root, ContainerUtil.newArrayList(), commitConsumer); } @Override public void readFullDetails(@NotNull VirtualFile root, @NotNull List<String> hashes, @NotNull Consumer<VcsFullCommitDetails> commitConsumer) throws VcsException { // this method currently is very slow and time consuming // so indexing is not to be used for mercurial for now HgVcs hgvcs = HgVcs.getInstance(myProject); assert hgvcs != null; final HgVersion version = hgvcs.getVersion(); final String[] templates = HgBaseLogParser.constructFullTemplateArgument(true, version); HgCommandResult logResult = HgHistoryUtil.getLogResult(myProject, root, version, -1, HgHistoryUtil.prepareHashes(hashes), HgChangesetUtil.makeTemplate(templates)); if (logResult == null) return; if (!logResult.getErrorLines().isEmpty()) throw new VcsException(logResult.getRawError()); HgHistoryUtil.createFullCommitsFromResult(myProject, root, logResult, version, false).forEach(commitConsumer::consume); } @NotNull @Override public List<? extends VcsShortCommitDetails> readShortDetails(@NotNull VirtualFile root, @NotNull List<String> hashes) throws VcsException { return HgHistoryUtil.readMiniDetails(myProject, root, hashes); } @NotNull @Override public List<? extends VcsFullCommitDetails> readFullDetails(@NotNull VirtualFile root, @NotNull List<String> hashes) throws VcsException { return HgHistoryUtil.history(myProject, root, -1, HgHistoryUtil.prepareHashes(hashes)); } @NotNull private Set<VcsRef> readAllRefs(@NotNull VirtualFile root) throws VcsException { if (myProject.isDisposed()) { return Collections.emptySet(); } HgRepository repository = myRepositoryManager.getRepositoryForRoot(root); if (repository == null) { LOG.error("Repository not found for root " + root); return Collections.emptySet(); } repository.update(); Map<String, LinkedHashSet<Hash>> branches = repository.getBranches(); Set<String> openedBranchNames = repository.getOpenedBranches(); Collection<HgNameWithHashInfo> bookmarks = repository.getBookmarks(); Collection<HgNameWithHashInfo> tags = repository.getTags(); Collection<HgNameWithHashInfo> localTags = repository.getLocalTags(); Collection<HgNameWithHashInfo> mqAppliedPatches = repository.getMQAppliedPatches(); Set<VcsRef> refs = new HashSet<>(branches.size() + bookmarks.size()); for (Map.Entry<String, LinkedHashSet<Hash>> entry : branches.entrySet()) { String branchName = entry.getKey(); boolean opened = openedBranchNames.contains(branchName); for (Hash hash : entry.getValue()) { refs.add(myVcsObjectsFactory.createRef(hash, branchName, opened ? HgRefManager.BRANCH : HgRefManager.CLOSED_BRANCH, root)); } } for (HgNameWithHashInfo bookmarkInfo : bookmarks) { refs.add(myVcsObjectsFactory.createRef(bookmarkInfo.getHash(), bookmarkInfo.getName(), HgRefManager.BOOKMARK, root)); } String currentRevision = repository.getCurrentRevision(); if (currentRevision != null) { // null => fresh repository refs.add(myVcsObjectsFactory.createRef(myVcsObjectsFactory.createHash(currentRevision), HEAD_REFERENCE, HgRefManager.HEAD, root)); } String tipRevision = repository.getTipRevision(); if (tipRevision != null) { // null => fresh repository refs.add(myVcsObjectsFactory.createRef(myVcsObjectsFactory.createHash(tipRevision), TIP_REFERENCE, HgRefManager.TIP, root)); } for (HgNameWithHashInfo tagInfo : tags) { refs.add(myVcsObjectsFactory.createRef(tagInfo.getHash(), tagInfo.getName(), HgRefManager.TAG, root)); } for (HgNameWithHashInfo localTagInfo : localTags) { refs.add(myVcsObjectsFactory.createRef(localTagInfo.getHash(), localTagInfo.getName(), HgRefManager.LOCAL_TAG, root)); } for (HgNameWithHashInfo mqPatchRef : mqAppliedPatches) { refs.add(myVcsObjectsFactory.createRef(mqPatchRef.getHash(), mqPatchRef.getName(), HgRefManager.MQ_APPLIED_TAG, root)); } return refs; } @NotNull @Override public VcsKey getSupportedVcs() { return HgVcs.getKey(); } @NotNull @Override public VcsLogRefManager getReferenceManager() { return myRefSorter; } @NotNull @Override public Disposable subscribeToRootRefreshEvents(@NotNull final Collection<VirtualFile> roots, @NotNull final VcsLogRefresher refresher) { MessageBusConnection connection = myProject.getMessageBus().connect(myProject); connection.subscribe(HgVcs.STATUS_TOPIC, new HgUpdater() { @Override public void update(Project project, @Nullable VirtualFile root) { if (root != null && roots.contains(root)) { refresher.refresh(root); } } }); return connection; } @NotNull @Override public List<TimedVcsCommit> getCommitsMatchingFilter(@NotNull final VirtualFile root, @NotNull VcsLogFilterCollection filterCollection, int maxCount) throws VcsException { List<String> filterParameters = ContainerUtil.newArrayList(); // branch filter and user filter may be used several times without delimiter VcsLogBranchFilter branchFilter = filterCollection.getBranchFilter(); if (branchFilter != null) { HgRepository repository = myRepositoryManager.getRepositoryForRoot(root); if (repository == null) { LOG.error("Repository not found for root " + root); return Collections.emptyList(); } Collection<String> branchNames = repository.getBranches().keySet(); Collection<String> bookmarkNames = HgUtil.getNamesWithoutHashes(repository.getBookmarks()); Collection<String> predefinedNames = ContainerUtil.list(TIP_REFERENCE); boolean atLeastOneBranchExists = false; for (String branchName : ContainerUtil.concat(branchNames, bookmarkNames, predefinedNames)) { if (branchFilter.matches(branchName)) { filterParameters.add(HgHistoryUtil.prepareParameter("branch", branchName)); atLeastOneBranchExists = true; } } if (branchFilter.matches(HEAD_REFERENCE)) { filterParameters.add(HgHistoryUtil.prepareParameter("branch", ".")); filterParameters.add("-r"); filterParameters.add("::."); //all ancestors for current revision; atLeastOneBranchExists = true; } if (!atLeastOneBranchExists) { // no such branches => filter matches nothing return Collections.emptyList(); } } if (filterCollection.getUserFilter() != null) { filterParameters.add("-r"); String authorFilter = StringUtil.join(ContainerUtil.map(ContainerUtil.map(filterCollection.getUserFilter().getUsers(root), VcsUserUtil::toExactString), UserNameRegex.EXTENDED_INSTANCE), "|"); filterParameters.add("user('re:" + authorFilter + "')"); } if (filterCollection.getDateFilter() != null) { StringBuilder args = new StringBuilder(); final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); filterParameters.add("-d"); VcsLogDateFilter filter = filterCollection.getDateFilter(); if (filter.getAfter() != null) { if (filter.getBefore() != null) { args.append(dateFormatter.format(filter.getAfter())).append(" to ").append(dateFormatter.format(filter.getBefore())); } else { args.append('>').append(dateFormatter.format(filter.getAfter())); } } else if (filter.getBefore() != null) { args.append('<').append(dateFormatter.format(filter.getBefore())); } filterParameters.add(args.toString()); } if (filterCollection.getTextFilter() != null) { String textFilter = filterCollection.getTextFilter().getText(); if (filterCollection.getTextFilter().isRegex()) { filterParameters.add("-r"); filterParameters.add("grep(r'" + textFilter + "')"); } else if (filterCollection.getTextFilter().matchesCase()) { filterParameters.add("-r"); filterParameters.add("grep(r'" + StringUtil.escapeChars(textFilter, UserNameRegex.EXTENDED_REGEX_CHARS) + "')"); } else { filterParameters.add(HgHistoryUtil.prepareParameter("keyword", textFilter)); } } if (filterCollection.getStructureFilter() != null) { for (FilePath file : filterCollection.getStructureFilter().getFiles()) { filterParameters.add(file.getPath()); } } return HgHistoryUtil.readAllHashes(myProject, root, Consumer.EMPTY_CONSUMER, filterParameters); } @Nullable @Override public VcsUser getCurrentUser(@NotNull VirtualFile root) throws VcsException { String userName = HgConfig.getInstance(myProject, root).getNamedConfig("ui", "username"); //order of variables to identify hg username see at mercurial/ui.py if (userName == null) { userName = System.getenv("HGUSER"); if (userName == null) { userName = System.getenv("USER"); if (userName == null) { userName = System.getenv("LOGNAME"); if (userName == null) { return null; } } } } Couple<String> userArgs = HgUtil.parseUserNameAndEmail(userName); return myVcsObjectsFactory.createUser(userArgs.getFirst(), userArgs.getSecond()); } @NotNull @Override public Collection<String> getContainingBranches(@NotNull VirtualFile root, @NotNull Hash commitHash) throws VcsException { return HgHistoryUtil.getDescendingHeadsOfBranches(myProject, root, commitHash); } @Nullable @Override public String getCurrentBranch(@NotNull VirtualFile root) { HgRepository repository = myRepositoryManager.getRepositoryForRoot(root); if (repository == null) return null; return repository.getCurrentBranchName(); } @Nullable @Override public <T> T getPropertyValue(VcsLogProperties.VcsLogProperty<T> property) { if (property == VcsLogProperties.CASE_INSENSITIVE_REGEX) { return (T)Boolean.FALSE; } return null; } }
compilation
src/main/java/org/zmlx/hg4idea/log/HgLogProvider.java
compilation
<ide><path>rc/main/java/org/zmlx/hg4idea/log/HgLogProvider.java <ide> } <ide> } <ide> }); <del> return connection; <add> return connection::disconnect; <ide> } <ide> <ide> @NotNull
Java
mit
56b5322361488acbd9a057bdd4dd47530a83188c
0
jcgay/send-notification,jcgay/send-notification
package fr.jcgay.notification.notifier.growl; import com.google.code.jgntp.GntpErrorStatus; import com.google.code.jgntp.GntpListener; import com.google.code.jgntp.GntpNotification; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class GntpSlf4jListener implements GntpListener { private static final Logger LOGGER = LoggerFactory.getLogger(GntpSlf4jListener.class); private static final String OSX_URL = "https://github.com/jcgay/send-notification/wiki/Growl-(OS-X)"; private static final String WINDOWS_URL = "https://github.com/jcgay/send-notification/wiki/Growl-(Windows)"; @Override public void onRegistrationSuccess() { LOGGER.debug("Client has been successfully registered by Growl"); } @Override public void onNotificationSuccess(GntpNotification notification) { LOGGER.debug("Notification success: {}", notification); } @Override public void onClickCallback(GntpNotification notification) { } @Override public void onCloseCallback(GntpNotification notification) { } @Override public void onTimeoutCallback(GntpNotification notification) { } @Override public void onRegistrationError(GntpErrorStatus status, String description) { LOGGER.error(error("Growl registration has failed.\n {}: {}"), status, description); } @Override public void onNotificationError(GntpNotification notification, GntpErrorStatus status, String description) { LOGGER.error(error("Growl notification has failed.\n {}: {}\n {}"), status, description, notification); } @Override public void onCommunicationError(Throwable t) { LOGGER.error("Cannot communicate with Growl.", t); } private static String error(String message) { return String.format("%s%n%n For more information about the errors and possible solutions, please read the following article:%n%s", message, wikiUrl()); } private static String wikiUrl() { String os = System.getProperty("os.name").toLowerCase(); if (os.contains("win")) { return WINDOWS_URL; } if (os.contains("mac")) { return OSX_URL; } return "https://github.com/jcgay/send-notification/wiki"; } }
send-notification/src/main/java/fr/jcgay/notification/notifier/growl/GntpSlf4jListener.java
package fr.jcgay.notification.notifier.growl; import com.google.code.jgntp.GntpErrorStatus; import com.google.code.jgntp.GntpListener; import com.google.code.jgntp.GntpNotification; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class GntpSlf4jListener implements GntpListener { private static final Logger LOGGER = LoggerFactory.getLogger(GntpSlf4jListener.class); @Override public void onRegistrationSuccess() { LOGGER.debug("Client has been successfully registered by Growl"); } @Override public void onNotificationSuccess(GntpNotification notification) { LOGGER.debug("Notification success: {}", notification); } @Override public void onClickCallback(GntpNotification notification) { } @Override public void onCloseCallback(GntpNotification notification) { } @Override public void onTimeoutCallback(GntpNotification notification) { } @Override public void onRegistrationError(GntpErrorStatus status, String description) { LOGGER.error("Growl registration has failed.\n {}: {}", status, description); } @Override public void onNotificationError(GntpNotification notification, GntpErrorStatus status, String description) { LOGGER.error("Growl notification has failed.\n {}: {}\n {}", status, description, notification); } @Override public void onCommunicationError(Throwable t) { LOGGER.error("Cannot communicate with Growl.", t); } }
Complete Growl error messages with wiki links These links add informations and possible solution(s) for common misconfiguration problems.
send-notification/src/main/java/fr/jcgay/notification/notifier/growl/GntpSlf4jListener.java
Complete Growl error messages with wiki links
<ide><path>end-notification/src/main/java/fr/jcgay/notification/notifier/growl/GntpSlf4jListener.java <ide> class GntpSlf4jListener implements GntpListener { <ide> <ide> private static final Logger LOGGER = LoggerFactory.getLogger(GntpSlf4jListener.class); <add> <add> private static final String OSX_URL = "https://github.com/jcgay/send-notification/wiki/Growl-(OS-X)"; <add> private static final String WINDOWS_URL = "https://github.com/jcgay/send-notification/wiki/Growl-(Windows)"; <ide> <ide> @Override <ide> public void onRegistrationSuccess() { <ide> <ide> @Override <ide> public void onRegistrationError(GntpErrorStatus status, String description) { <del> LOGGER.error("Growl registration has failed.\n {}: {}", status, description); <add> LOGGER.error(error("Growl registration has failed.\n {}: {}"), status, description); <ide> } <ide> <ide> @Override <ide> public void onNotificationError(GntpNotification notification, GntpErrorStatus status, String description) { <del> LOGGER.error("Growl notification has failed.\n {}: {}\n {}", status, description, notification); <add> LOGGER.error(error("Growl notification has failed.\n {}: {}\n {}"), status, description, notification); <ide> } <ide> <ide> @Override <ide> public void onCommunicationError(Throwable t) { <ide> LOGGER.error("Cannot communicate with Growl.", t); <ide> } <add> <add> private static String error(String message) { <add> return String.format("%s%n%n For more information about the errors and possible solutions, please read the following article:%n%s", <add> message, wikiUrl()); <add> } <add> <add> private static String wikiUrl() { <add> String os = System.getProperty("os.name").toLowerCase(); <add> if (os.contains("win")) { <add> return WINDOWS_URL; <add> } <add> if (os.contains("mac")) { <add> return OSX_URL; <add> } <add> return "https://github.com/jcgay/send-notification/wiki"; <add> } <ide> }
JavaScript
bsd-3-clause
3a3b778d218332ce6bf72af9713bc18f81d87d0c
0
remory08/trailsy,trevorackerman/trailsy,vinh3928/trailsy,trevorackerman/trailsy,JamesGould123/trailsy,mbarrenecheajr/trailsy,JamesGould123/trailsy,CodeForBoulder/trailsy,remory08/trailsy,mgraesser/trailsy,CodeForBoulder/trailsy,mbarrenecheajr/trailsy,vinh3928/trailsy,mgraesser/trailsy
var console = console || { "log": function() {} }; console.log("start"); $(document).ready(startup); /* The Big Nested Function ==========================*/ // Print to ensure file is loaded function startup() { "use strict"; console.log("trailhead.js"); var SMALL; if (Modernizr.mq("only screen and (max-width: 529px)")) { SMALL = true; } else if (Modernizr.mq("only screen and (min-width: 530px)")) { SMALL = false; } var TOUCH = $('html').hasClass('touch'); // Map generated in CfA Account var MAPBOX_MAP_ID = "codeforamerica.map-j35lxf9d"; var AKRON = { lat: 41.1, lng: -81.5 }; // API_HOST: The API server. Here we assign a default server, then // test to check whether we're using the Heroky dev app or the Heroku production app // and reassign API_HOST if necessary // var API_HOST = window.location.hostname; // // var API_HOST = "http://127.0.0.1:3000"; var API_HOST = "http://trailsy-dev.herokuapp.com"; // var API_HOST = "http://trailsyserver-dev.herokuapp.com"; // var API_HOST = "http://trailsyserver-prod.herokuapp.com"; // var API_HOST = "http://10.0.1.102:3000"; // var API_HOST = "http://10.0.2.2:3000" // for virtualbox IE if (window.location.hostname.split(".")[0] == "trailsy-dev") { // API_HOST = "http://trailsyserver-dev.herokuapp.com"; API_HOST = window.location.href; } else if (window.location.hostname.split(".")[0] == "trailsyserver-dev") { API_HOST = window.location.href; } else if (window.location.hostname.split(".")[0] == "trailsy" || window.location.hostname == "www.tothetrails.com") { API_HOST = window.location.href; // API_HOST = "http://trailsyserver-prod.herokuapp.com"; } // Near-Global Variables var METERSTOMILESFACTOR = 0.00062137; var MAX_ZOOM = 17; var MIN_ZOOM = 14; var SECONDARY_TRAIL_ZOOM = 13; var SHORT_MAX_DISTANCE = 2.0; var MEDIUM_MAX_DISTANCE = 5.0; var LONG_MAX_DISTANCE = 10.0; var SHOW_ALL_TRAILS = 1; var USE_LOCAL = SMALL ? false : true; // Set this to a true value to preload/use a local trail segment cache var USE_ALL_SEGMENT_LAYER = SMALL ? false : true; var NORMAL_SEGMENT_COLOR = "#678729"; var NORMAL_SEGMENT_WEIGHT = 3; var HOVER_SEGMENT_COLOR = "#678729"; var HOVER_SEGMENT_WEIGHT = 6; var ACTIVE_TRAIL_COLOR = "#445617"; var ACTIVE_TRAIL_WEIGHT = 9; var NOTRAIL_SEGMENT_COLOR = "#FF0000"; var NOTRAIL_SEGMENT_WEIGHT = 3; var LOCAL_LOCATION_THRESHOLD = 100; // distance in km. less than this, use actual location for map/userLocation var centerOffset = SMALL ? new L.point(0, 0) : new L.Point(450, 0); var MARKER_RADIUS = TOUCH ? 12 : 4; var ALL_SEGMENT_LAYER_SIMPLIFY = 5; var map; var mapDivName = SMALL ? "trailMapSmall" : "trailMapLarge"; var CLOSED = false; var trailData = {}; // all of the trails metadata (from traildata table), with trail ID as key // for yes/no features, check for first letter "y" or "n". // { *id*: { geometry: point(0,0), unused for now // properties: { id: *uniqueID* (same as key), // accessible: *disabled access. yes/no*, // dogs: *dog access. yes/no*, // equestrian: *horse access. yes/no*, // hike: *hiking access. yes/no*, // mtnbike: *mountain bike access. yes/no*, // roadbike: *street bike access. yes/no*, // xcntryski: *cross-country skiing access. yes/no* // conditions: *text field of qualifications to above access/use fields*, // description: *text description of trail*, // length: *length of trail in miles*, // map_url: *URL of trail map*, // name: *name of trail*, // source: *whose data this info came from (abbreviation)*, // source_fullname: *full name of source org*, // source_phone: *phone for source org*, // source_url: *URL of source org*, // status: *trail status. 0=open; 1=notice/warning; 2=closed*, // statustext: *trail status text. only displayed if status != 0 // steward: *org to contact for more information (abbrev)*, // steward_fullname: *full name of steward org*, // steward_phone: *phone for steward org*, // steward_url: *URL of steward org*, // trlsurface: *not currently used* // } // } // } var trailheads = []; // all trailheads (from trailsegments) // for yes/no features, check for first letter "y" or "n". // // [ { marker: *Leaflet marker*, // trails: *[array of matched trail IDs], // popupContent: *HTML of Leaflet popup*, // properties: { id: *uniqueID*, // drinkwater: *water available at this trailhead. yes/no* // distance: *from current location in meters*, // kiosk: *presence of informational kiosk. yes/no*, // name: *name*, // parking: *availability of parking. yes/no*, // restrooms: *availability of restrooms. yes/no*, // source: *whose data this info came from (abbreviation)*, // source_fullname: *full name of source org*, // source_phone: *phone number of source org*, // source_url: *URL of source org*, // steward: *org to contact for more information (abbrev)*, // steward_fullname: *full name of steward org*, // steward_phone: *phone number of steward org*, // steward_url: *URL of steward org*, // trail1: *trail at this trailhead*, // trail2: *trail at this trailhead*, // trail3: *trail at this trailhead*, // trail4: *trail at this trailhead*, // trail5: *trail at this trailhead*, // trail6: *trail at this trailhead*, // updated_at: *update time*, // created_at: *creation time* // }, // }[, ...}] // ] var trailSegments = []; var currentMultiTrailLayer = {}; // We have to know if a trail layer is already being displayed, so we can remove it var currentTrailLayers = []; var currentHighlightedTrailLayer = {}; var currentUserLocation = {}; var anchorLocation = {}; var currentTrailheadLayerGroup; var currentFilters = { lengthFilter: [], activityFilter: [], searchFilter: "" }; var orderedTrails = []; var currentDetailTrail = null; var currentDetailTrailhead = null; var userMarker = null; var allSegmentLayer = null; var closeTimeout = null; var openTimeout = null; var currentWeightedSegment = null; var currentTrailPopup = null; var currentTrailhead = null; var orderedTrailIndex; var geoWatchId = null; var currentTrailheadHover = null; var geoSetupDone = false; var segmentTrailnameCache = {}; var allInvisibleSegmentsArray = []; var allVisibleSegmentsArray = []; // Trailhead Variables // Not sure if these should be global, but hey whatev var trailheadIconOptions = { iconSize: [52 * 0.60, 66 * 0.60], iconAnchor: [13 * 0.60, 33 * 0.60], popupAnchor: [0, -3] }; var trailheadIcon1Options = $.extend(trailheadIconOptions, { iconUrl: 'img/icon_trailhead_active.png' }); var trailheadIcon1 = L.icon(trailheadIcon1Options); var trailheadIcon2Options = $.extend(trailheadIconOptions, { iconUrl: 'img/icon_trailhead_active.png' }); var trailheadIcon2 = L.icon(trailheadIcon2Options); // comment these/uncomment the next set to switch between tables var TRAILHEADS_TABLE = "summit_trailheads"; var TRAILSEGMENTS_TABLE = "summit_trailsegments"; var TRAILDATA_TABLE = "summit_traildata"; // var TRAILHEADS_TABLE = "summit_trailheads_test"; // var TRAILSEGMENTS_TABLE = "summit_trail_segments_test"; // var TRAILDATA_TABLE = "summit_traildata_test"; // =====================================================================// // UI events to react to $("#redoSearch").click(reorderTrailsWithNewLocation); $(document).on('click', '.trailhead-trailname', trailnameClick); // Open the detail panel! $(document).on('click', '.closeDetail', closeDetailPanel); // Close the detail panel! $(document).on('click', '.detailPanelControls', changeDetailPanel); // Shuffle Through Trails Shown in Detail Panel $(document).on('change', '.filter', filterChangeHandler); $(".clearSelection").click(clearSelectionHandler); $(document).on('click', '.trail-popup-line-named', trailPopupLineClick); $(".search-key").keyup(function(e) { // if (e.which == 13) { // console.log($('.search-key').val()); processSearch(e); // } }); $(".offsetZoomControl").click(offsetZoomIn); $(".search-submit").click(processSearch); // Detail Panel Navigation UI events $('.hamburgerLine').click(moveSlideDrawer); // $(document).on('click', closeSlideDrawerOnly); $(document).on('click', '.slider', slideDetailPanel); $(".detailPanel").hover(detailPanelHoverIn, detailPanelHoverOut); $(".aboutLink").click(openAboutPage); $(".closeAbout").click(closeAboutPage); // Shouldn't the UI event of a Map Callout click opening the detail panel go here? // =====================================================================// // Kick things off var overlayHTMLIE = "<h1>Welcome to To The Trails!</h1>" + "<p>We're sorry, but To The Trails is not compatible with Microsoft Internet Explorer 8 or earlier versions of that web browser." + "<p>Please upgrade to the latest version of " + "<a href='http://windows.microsoft.com/en-us/internet-explorer/download-ie'>Internet Explorer</a>, " + "<a href='http://google.com/chrome'>Google Chrome</a>, or " + "<a href='http://getfirefox.com'>Mozilla Firefox</a>." + "<p>If you are currently using Windows XP, you'll need to download and use Chrome or Firefox." + "<img src='/img/Overlay-Image-01.png' alt='trees'>"; var overlayHTML = "<span class='closeOverlay'>x</span>" + "<h1>Welcome To The Trails!</h1>" + "<p>ToTheTrails.com helps you find and navigate the trails of Summit County, Ohio." + "<p>Pick trails, find your way, and keep your bearings as you move between trails and parks in Cuyahoga Valley National Park and Metro Parks, Serving Summit County and beyond." + "<p>For easy access from a mobile device, bookmark ToTheTrails.com." + "<p>ToTheTrails.com is currently in public beta. It's a work in progress! We'd love to hear how this site is working for you." + "<p>Send feedback and report bugs to <a href='mailto:[email protected]?Subject=Feedback' target='_top'>[email protected]</a>. Learn more on our 'About' page."; var closedOverlayHTML = "<h1>Come visit us Nov 13th!</h1>" + "<p>We look forward to seeing you for our public launch." + "<img src='/img/Overlay-Image-01.png' alt='trees'>"; if (window.location.hostname === "www.tothetrails.com" || CLOSED) { console.log("closed"); $(".overlay-panel").html(closedOverlayHTML); $(".overlay").show(); } else { if ($("html").hasClass("lt-ie8")) { $(".overlay-panel").html(overlayHTMLIE); } else { $(".overlay-panel").html(overlayHTML); } $(".overlay-panel").click(function() { $(".overlay").hide(); }); } $(".overlay").show(); initialSetup(); // The next three functions perform trailhead/trail mapping // on a) initial startup, b) requested re-sort of trailheads based on the map, // and c) a change in filter settings // They all call addTrailDataToTrailheads() as their final action // -------------------------------------------------------------- // on startup, get location, display the map, // get and display the trailheads, populate trailData, // add trailData to trailheads function initialSetup() { console.log("initialSetup"); setupGeolocation(function() { if (geoSetupDone) { return; } getOrderedTrailheads(currentUserLocation, function() { getTrailData(function() { if (USE_LOCAL) { getTrailSegments(function() { createSegmentTrailnameCache(); addTrailDataToTrailheads(trailData); // if we haven't added the segment layer yet, add it. if (map.getZoom() >= SECONDARY_TRAIL_ZOOM && !(map.hasLayer(allSegmentLayer))) { map.addLayer(allSegmentLayer); } }); } else { // console.log("no USE_LOCAL"); addTrailDataToTrailheads(trailData); highlightTrailhead(orderedTrails[0].trailheadID, 0); orderedTrailIndex = 0; showTrailDetails(orderedTrails[0].trailhead, orderedTrails[0].trail); } }); }); }); } // set currentUserLocation to the center of the currently viewed map // then get the ordered trailheads and add trailData to trailheads function reorderTrailsWithNewLocation() { setAnchorLocationFromMap(); getOrderedTrailheads(anchorLocation, function() { addTrailDataToTrailheads(trailData); }); } // =====================================================================// // Filter function + helper functions, triggered by UI events declared above. function applyFilterChange(currentFilters, trailData) { var filteredTrailData = $.extend(true, {}, trailData); $.each(trailData, function(trail_id, trail) { if (currentFilters.activityFilter) { for (var i = 0; i < currentFilters.activityFilter.length; i++) { var activity = currentFilters.activityFilter[i]; var trailActivity = trail.properties[activity]; if (!trailActivity || trailActivity.toLowerCase().charAt(0) !== "y") { delete filteredTrailData[trail_id]; } } } if (currentFilters.lengthFilter) { var distInclude = false; if (currentFilters.lengthFilter.length === 0) { distInclude = true; } for (var j = 0; j < currentFilters.lengthFilter.length; j++) { var distance = currentFilters.lengthFilter[j]; var trailDist = trail.properties["length"]; if ((distance.toLowerCase() == "short" && trailDist <= SHORT_MAX_DISTANCE) || (distance.toLowerCase() == "medium" && trailDist > SHORT_MAX_DISTANCE && trailDist <= MEDIUM_MAX_DISTANCE) || (distance.toLowerCase() == "long" && trailDist > MEDIUM_MAX_DISTANCE && trailDist <= LONG_MAX_DISTANCE) || (distance.toLowerCase() == "verylong" && trailDist > LONG_MAX_DISTANCE)) { distInclude = true; break; } } if (!distInclude) { delete filteredTrailData[trail_id]; } } if (currentFilters.searchFilter) { var nameIndex = trail.properties.name.toLowerCase().indexOf(currentFilters.searchFilter.toLowerCase()); var descriptionIndex; if (trail.properties.description === null) { descriptionIndex = -1; } else { descriptionIndex = trail.properties.description.toLowerCase().indexOf(currentFilters.searchFilter.toLowerCase()); } if (nameIndex == -1 && descriptionIndex == -1) { delete filteredTrailData[trail_id]; } } }); addTrailDataToTrailheads(filteredTrailData); } function filterChangeHandler(e) { var $currentTarget = $(e.currentTarget); var filterType = $currentTarget.attr("data-filter"); var currentUIFilterState = $currentTarget.val(); console.log(currentUIFilterState); updateFilterObject(filterType, currentUIFilterState); } function processSearch(e) { var $currentTarget = $(e.currentTarget); var filterType = "searchFilter"; var currentUIFilterState; if (SMALL) { currentUIFilterState = $('#mobile .search-key').val(); } else { currentUIFilterState = $('#desktop .search-key').val(); } if (($currentTarget).hasClass('search-key')) { if (SMALL) { if (e.keyCode === 13) { updateFilterObject(filterType, currentUIFilterState); } } else { updateFilterObject(filterType, currentUIFilterState); } } else if (($currentTarget).hasClass('search-submit')) { updateFilterObject(filterType, currentUIFilterState); } // if the event target has a class search-key // see if it is keycode 13 // if true, call updatefilterobject // with filtertype=searchFilter // contents/value of searchbox which we get via jquery // if the event target has a class search-button // check to see if the value does not equal empty string // if it does not equal empty string, call updatefilterobject with filtertype=search filter & contents of box. } function updateFilterObject(filterType, currentUIFilterState) { console.log(currentUIFilterState); var matched = 0; if (filterType == "activityFilter") { var filterlength = currentFilters.activityFilter.length; for (var i = 0; i < currentFilters.activityFilter.length; i++) { var activity = currentFilters.activityFilter[i]; if (activity === currentUIFilterState) { currentFilters.activityFilter.splice(i, 1); matched = 1; break; } } if (matched === 0) { currentFilters.activityFilter.push(currentUIFilterState); } } if (filterType == "lengthFilter") { console.log("length"); console.log(currentFilters.lengthFilter.length); var filterlength = currentFilters.lengthFilter.length; for (var j = 0; j < filterlength; j++) { console.log("j"); console.log(j); var lengthRange = currentFilters.lengthFilter[j]; if (lengthRange == currentUIFilterState) { // console.log("match"); currentFilters.lengthFilter.splice(j, 1); matched = 1; break; } } if (matched === 0) { currentFilters.lengthFilter.push(currentUIFilterState); } } if (filterType == "searchFilter") { // console.log("searchFilter"); currentFilters.searchFilter = currentUIFilterState; } // currentFilters[filterType] = currentUIFilterState; console.log(currentFilters); applyFilterChange(currentFilters, trailData); } function clearSelectionHandler(e) { console.log("clearSelectionHandler"); $(".visuallyhidden_2 input").attr("checked", false); $(".visuallyhidden_3 input").attr("checked", false); $(".search-key").val(""); currentFilters = { lengthFilter: [], activityFilter: [], searchFilter: "" }; applyFilterChange(currentFilters, trailData); } // ====================================== // map generation & geolocation updates function offsetZoomIn(e) { // get map center lat/lng // convert to pixels // add offset // convert to lat/lng // setZoomAround to there with currentzoom + 1 var centerLatLng = map.getCenter(); var centerPoint = map.latLngToContainerPoint(centerLatLng); var offset = centerOffset; var offsetCenterPoint = centerPoint.add(offset.divideBy(2)); var offsetLatLng = map.containerPointToLatLng(offsetCenterPoint); if ($(e.target).hasClass("offsetZoomIn")) { map.setZoomAround(offsetLatLng, map.getZoom() + 1); } else if ($(e.target).hasClass("offsetZoomOut")) { map.setZoomAround(offsetLatLng, map.getZoom() - 1); } } function setAnchorLocationFromMap() { anchorLocation = map.getCenter(); } function setupGeolocation(callback) { console.log("setupGeolocation"); if (navigator.geolocation) { // setup location monitoring var options = { enableHighAccuracy: true, timeout: 5000, maximumAge: 30000 }; geoWatchId = navigator.geolocation.watchPosition( function(position) { if (trailheads.length === 0) { handleGeoSuccess(position, callback); geoSetupDone = true; } else { handleGeoSuccess(position); } }, function(error) { if (trailheads.length === 0) { handleGeoError(error, callback); geoSetupDone = true; } else { handleGeoError(error); } } ); } else { // for now, just returns Akron // should use browser geolocation, // and only return Akron if we're far from home base currentUserLocation = AKRON; handleGeoError("no geolocation", callback); } } function handleGeoSuccess(position, callback) { currentUserLocation = new L.LatLng(position.coords.latitude, position.coords.longitude); var distanceToAkron = currentUserLocation.distanceTo(AKRON) / 1000; // if no map, set it up if (!map) { var startingMapLocation; var startingMapZoom; // if we're close to Akron, start the map and the trailhead distances from // the current location, otherwise just use AKRON for both if (distanceToAkron < LOCAL_LOCATION_THRESHOLD) { anchorLocation = currentUserLocation; startingMapLocation = currentUserLocation; startingMapZoom = 13; } else { anchorLocation = AKRON; startingMapLocation = AKRON; startingMapZoom = 11; } map = createMap(startingMapLocation, startingMapZoom); } // always update the user marker, create if needed if (!userMarker) { userMarker = L.userMarker(currentUserLocation, { smallIcon: true, pulsing: true, accuracy: 0 }).addTo(map); } console.log(currentUserLocation); userMarker.setLatLng(currentUserLocation); if (typeof callback == "function") { callback(); } } function handleGeoError(error, callback) { console.log("handleGeoError"); currentUserLocation = AKRON; console.log(error); if (!map) { console.log("making map anyway"); map = createMap(AKRON, 11); } if (map && userMarker && error.code === 3) { map.removeLayer(userMarker); userMarker = null; } if (typeof callback == "function") { callback(); } } function createMap(startingMapLocation, startingMapZoom) { console.log("createMap"); console.log(mapDivName); var map = L.map(mapDivName, { zoomControl: false, scrollWheelZoom: false }); L.tileLayer.provider('MapBox.' + MAPBOX_MAP_ID).addTo(map); map.setView(startingMapLocation, startingMapZoom); map.fitBounds(map.getBounds(), { paddingTopLeft: centerOffset }); map.on("zoomend", function(e) { // console.log("zoomend"); if (SHOW_ALL_TRAILS && allSegmentLayer) { if (map.getZoom() >= SECONDARY_TRAIL_ZOOM && !(map.hasLayer(allSegmentLayer))) { // console.log(allSegmentLayer); map.addLayer(allSegmentLayer); allSegmentLayer.bringToBack(); } if (map.getZoom() < SECONDARY_TRAIL_ZOOM && map.hasLayer(allSegmentLayer)) { if (currentTrailPopup) { map.removeLayer(currentTrailPopup); } map.removeLayer(allSegmentLayer); } } }); map.on('popupclose', popupCloseHandler); return map; } // =====================================================================// // Getting trailhead data // get all trailhead info, in order of distance from "location" function getOrderedTrailheads(location, callback) { console.log("getOrderedTrailheads"); var callData = { loc: location.lat + "," + location.lng, type: "GET", path: "/trailheads.json?loc=" + location.lat + "," + location.lng }; makeAPICall(callData, function(response) { populateTrailheadArray(response); if (typeof callback == "function") { callback(); } }); } // given the getOrderedTrailheads response, a geoJSON collection of trailheads ordered by distance, // populate trailheads[] with the each trailhead's stored properties, a Leaflet marker, // and a place to put the trails for that trailhead. function populateTrailheadArray(trailheadsGeoJSON) { console.log("populateTrailheadArray"); console.log(trailheadsGeoJSON); trailheads = []; for (var i = 0; i < trailheadsGeoJSON.features.length; i++) { var currentFeature = trailheadsGeoJSON.features[i]; var currentFeatureLatLng = new L.LatLng(currentFeature.geometry.coordinates[1], currentFeature.geometry.coordinates[0]); // var newMarker = L.marker(currentFeatureLatLng, ({ // icon: trailheadIcon1 // })); var newMarker = new L.CircleMarker(currentFeatureLatLng, { color: "#D86930", fillOpacity: 0.5, opacity: 0.8 }).setRadius(MARKER_RADIUS); var trailhead = { properties: currentFeature.properties, geometry: currentFeature.geometry, marker: newMarker, trails: [], popupContent: "" }; setTrailheadEventHandlers(trailhead); trailheads.push(trailhead); } } function setTrailheadEventHandlers(trailhead) { trailhead.marker.on("click", function(trailheadID) { return function() { trailheadMarkerClick(trailheadID); }; }(trailhead.properties.id)); // placeholders for possible trailhead marker hover behavior // trailhead.marker.on("mouseover", function(trailhead) { // }(trailhead)); // trailhead.marker.on("mouseout", function(trailhead) { // }(trailhead)); } function trailheadMarkerClick(id) { console.log("trailheadMarkerClick"); highlightTrailhead(id, 0); var trailhead = getTrailheadById(id); showTrailDetails(trailData[trailhead.trails[0]], trailhead); } function popupCloseHandler(e) { currentTrailPopup = null; } // get the trailData from the API function getTrailData(callback) { console.log("getTrailData"); var callData = { type: "GET", path: "/trails.json" }; makeAPICall(callData, function(response) { populateTrailData(response); if (typeof callback == "function") { callback(); } }); } function populateTrailData(trailDataGeoJSON) { for (var i = 0; i < trailDataGeoJSON.features.length; i++) { trailData[trailDataGeoJSON.features[i].properties.id] = trailDataGeoJSON.features[i]; } } function getTrailSegments(callback) { console.log("getTrailSegments"); var callData = { type: "GET", path: "/trailsegments.json" }; // if (SMALL) { // callData.path = "/trailsegments.json?simplify=" + ALL_SEGMENT_LAYER_SIMPLIFY; // } makeAPICall(callData, function(response) { trailSegments = response; if (USE_ALL_SEGMENT_LAYER) { allSegmentLayer = makeAllSegmentLayer(response); } if (typeof callback == "function") { callback(); } }); } function createSegmentTrailnameCache() { console.log("createSegmentTrailnameCache"); for (var segmentIndex = 0; segmentIndex < trailSegments.features.length; segmentIndex++) { var segment = $.extend(true, {}, trailSegments.features[segmentIndex]); for (var i = 0; i < 6; i++) { var fieldName = "trail" + i; if (segment.properties[fieldName]) { segmentTrailnameCache[segment.properties[fieldName]] = true; } } } } // returns true if trailname is in trailData function trailnameInListOfTrails(trailname) { // console.log("trailnameInListOfTrails"); var result = false; $.each(trailData, function(key, value) { if (trailData[key].properties.name == trailname) { result = key; return false; } }); return result; } function segmentHasTrailWithMetadata(feature) { for (var i = 0; i <= 6; i++) { var trailFieldname = "trail" + i; if (trailnameInListOfTrails(feature.properties[trailFieldname])) { return true; } } return false; } function makeAllSegmentLayer(response) { if (allSegmentLayer !== undefined) { return allSegmentLayer; } console.log("makeAllSegmentLayer"); // make visible layers allVisibleSegmentsArray = []; allInvisibleSegmentsArray = []; var allSegmentLayer = new L.FeatureGroup(); // console.log("visibleAllTrailLayer start"); // make a normal visible layer for the segments, and add each of those layers to the allVisibleSegmentsArray var visibleAllTrailLayer = L.geoJson(response, { style: function visibleStyle() { return { color: NORMAL_SEGMENT_COLOR, weight: NORMAL_SEGMENT_WEIGHT, opacity: 1, clickable: false // dashArray: "5,5" }; }, onEachFeature: function visibleOnEachFeature(feature, layer) { // console.log("visibleAllTrailLayer onEachFeature"); allVisibleSegmentsArray.push(layer); } }); // make invisible layers // make the special invisible layer for mouse/touch events. much wider paths. // make popup html for each segment var invisibleAllTrailLayer = L.geoJson(response, { style: function invisibleStyle() { return { opacity: 0, weight: 20, clickable: true, smoothFactor: 10 }; }, onEachFeature: function invisibleOnEachFeature(feature, layer) { // console.log("invisibleAllTrailLayer onEachFeature"); allInvisibleSegmentsArray.push(layer); } }); // console.log("invisibleAllTrailLayer end"); var numSegments = allInvisibleSegmentsArray.length; for (var i = 0; i < numSegments; i++) { // console.log("numSegments loop"); var invisLayer = allInvisibleSegmentsArray[i]; // make a FeatureGroup including both visible and invisible components // var newTrailFeatureGroup = new L.FeatureGroup([allVisibleSegmentsArray[i]]); var newTrailFeatureGroup = new L.FeatureGroup([allInvisibleSegmentsArray[i], allVisibleSegmentsArray[i]]); var $popupHTML = $("<div class='trail-popup'>"); for (var j = 1; j <= 6; j++) { var trailField = "trail" + j; if (invisLayer.feature.properties[trailField]) { var $trailPopupLineDiv; if (trailnameInListOfTrails(invisLayer.feature.properties[trailField])) { // NOTE: color should be in the css, not here $trailPopupLineDiv = $("<div class='trail-popup-line trail-popup-line-named'>") .attr("data-steward", invisLayer.feature.properties.steward).attr("data-source", invisLayer.feature.properties.source) .attr("data-trailname", invisLayer.feature.properties[trailField]) .html(invisLayer.feature.properties[trailField]); } else { if (trailnameInListOfTrails(invisLayer.feature.properties[trailField].indexOf("_")) === -1) { $trailPopupLineDiv = $("<div class='trail-popup-line trail-popup-line-unnamed'>").html(invisLayer.feature.properties[trailField]) $trailPopupLineDiv.append("<b>"); } else { // console.log("skipping trail segment name because it has an underscore in it"); } } $popupHTML.append($trailPopupLineDiv); } } invisLayer.feature.properties.popupHTML = $popupHTML.outerHTML(); var eventType; // this should be a test for touch, not small if (TOUCH) { eventType = "click"; } else { eventType = "mouseover"; } newTrailFeatureGroup.addEventListener(eventType, function featureGroupEventListener(invisLayer) { return function newMouseover(e) { // console.log("new mouseover"); if (closeTimeout) { clearTimeout(closeTimeout); closeTimeout = null; } if (openTimeout) { clearTimeout(openTimeout); openTimeout = null; } openTimeout = setTimeout(function openTimeoutFunction(originalEvent, target) { return function() { target.setStyle({ weight: HOVER_SEGMENT_WEIGHT, color: HOVER_SEGMENT_COLOR }); // set currentWeightedSegment back to normal if (target != currentWeightedSegment) { if (currentWeightedSegment) { currentWeightedSegment.setStyle({ weight: NORMAL_SEGMENT_WEIGHT, color: NORMAL_SEGMENT_COLOR }); } } var popupHTML = invisLayer.feature.properties.popupHTML; currentTrailPopup = new L.Popup().setContent(popupHTML).setLatLng(originalEvent.latlng).openOn(map); currentWeightedSegment = target; }; }(e, e.target), 250); }; }(invisLayer)); newTrailFeatureGroup.addEventListener("mouseout", function(e) { if (closeTimeout) { clearTimeout(closeTimeout); closeTimeout = null; } if (openTimeout) { clearTimeout(openTimeout); openTimeout = null; } closeTimeout = setTimeout(function(e) { return function() { e.target.setStyle({ weight: 3 }); //map.closePopup(); }; }(e), 1250); }); allSegmentLayer.addLayer(newTrailFeatureGroup); } // use this to just show the network // allSegmentLayer = visibleAllTrailLayer; allVisibleSegmentsArray = null; allInvisibleSegmentsArray = null; return allSegmentLayer; } // after clicking on a trail name in a trail popup, // find the closest matching trailhead and highlight it function trailPopupLineClick(e) { console.log("trailPopupLineClick"); // get all trailheads that have this trailname and source var trailname = $(e.target).attr("data-trailname"); var source = $(e.target).attr("data-source"); var trailheadMatches = []; for (var i = 0; i < trailheads.length; i++) { var trailhead = trailheads[i]; if (trailhead.properties.source == source) { if (trailhead.properties.trail1 == trailname || trailhead.properties.trail2 == trailname || trailhead.properties.trail3 == trailname || trailhead.properties.trail4 == trailname || trailhead.properties.trail5 == trailname || trailhead.properties.trail6) { trailheadMatches.push(trailhead); } } } // find the closest one // popups have no getLatLng, so we're cheating here. var currentLatLng = currentTrailPopup._latlng; var nearestDistance = Infinity; var nearestTrailhead = null; for (var j = 0; j < trailheadMatches.length; j++) { var matchedTrailhead = trailheadMatches[j]; var trailheadLatLng = matchedTrailhead.marker.getLatLng(); var distance = currentLatLng.distanceTo(trailheadLatLng); if (distance < nearestDistance) { nearestTrailhead = matchedTrailhead; nearestDistance = distance; } } // find the index of the clicked trail var trailIndex = 0; var trail = null; for (var k = 0; k < nearestTrailhead.trails.length; k++) { var trailheadTrailID = nearestTrailhead.trails[k]; if (trailData[trailheadTrailID].properties.name == trailname) { trail = trailData[trailheadTrailID]; trailIndex = k; } } // highlight it highlightTrailhead(nearestTrailhead.properties.id, trailIndex); showTrailDetails(trail, nearestTrailhead); } // given trailData, // populate trailheads[x].trails with all of the trails in trailData // that match each trailhead's named trails from the trailhead table. // Also add links to the trails within each trailhead popup function addTrailDataToTrailheads(myTrailData) { console.log("addTrailDataToTrailheads"); for (var j = 0; j < trailheads.length; j++) { var trailhead = trailheads[j]; trailhead.trails = []; // for each original trailhead trail name for (var trailNum = 1; trailNum <= 6; trailNum++) { var trailWithNum = "trail" + trailNum; if (trailhead.properties[trailWithNum] === "") { continue; } var trailheadTrailName = trailhead.properties[trailWithNum]; // TODO: add a test for the case of duplicate trail names. // Right now this // loop through all of the trailData objects, looking for trail names that match // the trailhead trailname. // this works great, except for things like "Ledges Trail," which get added twice, // one for the CVNP instance and one for the MPSSC instance. // we should test for duplicate names and only use the nearest one. // to do that, we'll need to either query the DB for the trail segment info, // or check distance against the (yet-to-be) pre-loaded trail segment info $.each(myTrailData, function(trailID, trail) { if (trailhead.properties[trailWithNum] == trail.properties.name) { if (checkSegmentsForTrailname(trail.properties.name, trail.properties.source) || !USE_LOCAL) { trailhead.trails.push(trailID); } else { console.log("skipping " + trail.properties.name + "/" + trail.properties.source + ": no segment data"); } } }); } } fixDuplicateTrailNames(trailheads); makeTrailheadPopups(trailheads); mapActiveTrailheads(trailheads); makeTrailDivs(trailheads); if (SMALL && USE_LOCAL) { highlightTrailhead(orderedTrails[0].trailheadID, 0); orderedTrailIndex = 0; showTrailDetails(orderedTrails[0].trailhead, orderedTrails[0].trail); } } // this is so very wrong and terrible and makes me want to never write anything again. // alas, it works for now. // for each trailhead, if two or more of the matched trails from addTrailDataToTrailheads() have the same name, // remove any trails that don't match the trailhead source function fixDuplicateTrailNames(trailheads) { console.log("fixDuplicateTrailNames"); for (var trailheadIndex = 0; trailheadIndex < trailheads.length; trailheadIndex++) { var trailhead = trailheads[trailheadIndex]; var trailheadTrailNames = {}; for (var trailsIndex = 0; trailsIndex < trailhead.trails.length; trailsIndex++) { var trailName = trailData[trailhead.trails[trailsIndex]].properties.name; trailheadTrailNames[trailName] = trailheadTrailNames[trailName] || []; var sourceAndTrailID = { source: trailData[trailhead.trails[trailsIndex]].properties.source, trailID: trailData[trailhead.trails[trailsIndex]].properties.id }; trailheadTrailNames[trailName].push(sourceAndTrailID); } for (var trailheadTrailName in trailheadTrailNames) { if (trailheadTrailNames.hasOwnProperty(trailheadTrailName)) { if (trailheadTrailNames[trailheadTrailName].length > 1) { // remove the ID from the trailhead trails array if the source doesn't match for (var i = 0; i < trailheadTrailNames[trailheadTrailName].length; i++) { var mySourceAndTrailID = trailheadTrailNames[trailheadTrailName][i]; if (mySourceAndTrailID.source != trailhead.properties.source) { var idToRemove = mySourceAndTrailID.trailID; var removeIndex = $.inArray(idToRemove.toString(), trailhead.trails); trailhead.trails.splice(removeIndex, 1); } } } } } } } // given the trailheads, // make the popup menu for each one, including each trail present // and add it to the trailhead object // This is really only used in the desktop version function makeTrailheadPopups(trailheads) { for (var trailheadIndex = 0; trailheadIndex < trailheads.length; trailheadIndex++) { var trailhead = trailheads[trailheadIndex]; var $popupContentMainDiv = $("<div>").addClass("trailhead-popup"); var $popupTrailheadDiv = $("<div>").addClass("trailhead-box").html($("<div class='popupTrailheadNames'>" + trailhead.properties.name + "</div>")).appendTo($popupContentMainDiv); $popupTrailheadDiv.append($("<img>").addClass("calloutTrailheadIcon").attr({ src: "img/icon_trailhead_active.png" })); for (var trailsIndex = 0; trailsIndex < trailhead.trails.length; trailsIndex++) { var trail = trailData[trailhead.trails[trailsIndex]]; var $popupTrailDiv = $("<div>").addClass("trailhead-trailname trail" + (trailsIndex + 1)) .attr("data-trailname", trail.properties.name) .attr("data-trailid", trail.properties.id) .attr("data-trailheadname", trailhead.properties.name) .attr("data-trailheadid", trailhead.properties.id) .attr("data-index", trailsIndex); var status = ""; if (trail.properties.status == 1) { $popupTrailDiv.append($("<img>").addClass("status").attr({ src: "img/icon_alert_yellow.png", title: "alert" })); } if (trail.properties.status == 2) { $popupTrailDiv.append($("<img>").addClass("status").attr({ src: "img/icon_alert_red.png", title: "alert" })); } $popupTrailDiv.append("<div class='popupTrailNames'>" + trail.properties.name + "</div>"); $popupTrailDiv.append("<b>") // .append(trail.properties.name) .appendTo($popupTrailheadDiv); } trailhead.popupContent = $popupContentMainDiv.outerHTML(); // trailhead.marker.bindPopup(trailhead.popupContent); } } // given trailheads, add all of the markers to the map in a single Leaflet layer group // except for trailheads with no matched trails function mapActiveTrailheads(trailheads) { console.log("mapActiveTrailheads"); var currentTrailheadMarkerArray = []; for (var i = 0; i < trailheads.length; i++) { if (trailheads[i].trails.length) { currentTrailheadMarkerArray.push(trailheads[i].marker); } else { // console.log(["trailhead not displayed: ", trailheads[i].properties.name]); } } if (currentTrailheadLayerGroup) { console.log("remove"); map.removeLayer(currentTrailheadLayerGroup); } currentTrailheadLayerGroup = L.layerGroup(currentTrailheadMarkerArray); map.addLayer(currentTrailheadLayerGroup); currentTrailheadLayerGroup.eachLayer(function(layer) { if (typeof layer.bringToBack == "function") { layer.bringToBack(); } }); } // given trailheads, now populated with matching trail names, // fill out the left trail(head) pane, // noting if a particular trailhead has no trails associated with it function makeTrailDivs(trailheads) { console.log("makeTrailDivs"); console.log(trailheads); orderedTrails = []; var divCount = 1; $(".trailList").html(""); for (var j = 0; j < trailheads.length; j++) { var trailhead = trailheads[j]; // $.each(trailheads, function(index, trailhead) { var trailheadName = trailhead.properties.name; var trailheadID = trailhead.properties.id; var parkName = trailhead.properties.park; var trailheadTrailIDs = trailhead.trails; if (trailheadTrailIDs.length === 0) { // return true; // next $.each continue; } var trailheadSource = trailhead.properties.source; var trailheadDistance = metersToMiles(trailhead.properties.distance); var $trailDiv; // Making a new div for text / each trail for (var i = 0; i < trailheadTrailIDs.length; i++) { var trailID = trailheadTrailIDs[i]; var trail = trailData[trailID]; var trailName = trailData[trailID].properties.name; var trailLength = trailData[trailID].properties.length; var trailCurrentIndex = divCount++; // Add park name var when it makes it into the database $trailDiv = $("<div>").addClass('trail-box') .attr("data-source", "list") .attr("data-trailid", trailID) .attr("data-trailname", trailName) .attr("data-trail-length", trailLength) .attr("data-trailheadName", trailheadName) .attr("data-trailheadid", trailheadID) .attr("data-index", i) .appendTo(".trailList") .click(populateTrailsForTrailheadDiv) .click(function(trail, trailhead) { return function(e) { showTrailDetails(trail, trailhead); }; }(trail, trailhead)); var $trailInfo = $("<div>").addClass("trailInfo").appendTo($trailDiv); var $trailheadInfo = $("<div>").addClass("trailheadInfo").appendTo($trailDiv); // Making a new div for Detail Panel $("<div class='trailSource' id='" + trailheadSource + "'>" + trailheadSource + "</div>").appendTo($trailDiv); $("<div class='trailCurrentIndex' >" + trailCurrentIndex + "</div>").appendTo($trailInfo); $("<div class='trail' >" + trailName + "</div>").appendTo($trailInfo); var mileString = trailLength == 1 ? "mile" : "miles"; $("<div class='trailLength' >" + trailLength + " " + mileString + " long" + "</div>").appendTo($trailInfo); if (parkName) { // console.log("has a park name"); $("<div class='parkName' >" + trailhead.properties.park + "</div>").appendTo($trailInfo); } // Here we generate icons for each activity filter that is true..? $("<img class='trailheadIcon' src='img/icon_trailhead_active.png'/>").appendTo($trailheadInfo); $("<div class='trailheadName' >" + trailheadName + " Trailhead" + "</div>").appendTo($trailheadInfo); $("<div class='trailheadDistance' >" + trailheadDistance + " miles away" + "</div>").appendTo($trailheadInfo); var trailInfoObject = { trailID: trailID, trail: trail, trailheadID: trailheadID, trailhead: trailhead, index: i }; orderedTrails.push(trailInfoObject); } // diagnostic div to show trailheads with no trail matches // (These shouldn't happen any more because of the trailheadTrailIDs.length check above.) if (trailheadTrailIDs.length === 0) { $trailDiv = $("<div class='trail-box'>").appendTo("#trailList"); $("<span class='trail' id='list|" + trailheadName + "'>" + trailheadName + " - NO TRAILS (" + [val.properties.trail1, val.properties.trail2, val.properties.trail3].join(", ") + ")</span>").appendTo($trailDiv); $("<span class='trailSource'>" + trailheadSource + "</span>").appendTo($trailDiv); } // }); } $(".trails-count").html(orderedTrails.length + " RESULTS FOUND"); console.log("end makeTrailDivs"); console.log(orderedTrails); } function metersToMiles(i) { return (i * METERSTOMILESFACTOR).toFixed(1); } function showTrailDetails(trail, trailhead) { console.log("showTrailDetails"); if ($('.detailPanel').is(':hidden')) { decorateDetailPanel(trail, trailhead); openDetailPanel(); currentDetailTrail = trail; currentDetailTrailhead = trailhead; } else { if (currentDetailTrail == trail && currentDetailTrailhead == trailhead) { currentDetailTrail = null; currentDetailTrailhead = null; closeDetailPanel(); } else { decorateDetailPanel(trail, trailhead); currentDetailTrail = trail; currentDetailTrailhead = trailhead; } } } // About page functions function openAboutPage() { console.log("openAboutPage"); $(".aboutPage").show(); if (!SMALL) { $('.accordion').hide(); } } function closeAboutPage() { console.log("closeAboutPage"); $('.aboutPage').hide(); $('.accordion').show(); } // Helper functions for ShowTrailDetails function openDetailPanel() { console.log("openDetailPanel"); $('.detailPanel').show(); if (!SMALL) { $('.accordion').hide(); } if (SMALL) { if ($(".slideDrawer").hasClass("openDrawer")) { console.log("slide drawer is open"); $(".slideDrawer").removeClass("openDrawer"); $(".slideDrawer").addClass("closedDrawer"); $(".detailPanel").removeClass("hidden"); $(".detailPanel").addClass("contracted"); } } $('.trailhead-trailname.selected').addClass("detail-open"); $(".detailPanel .detailPanelPicture")[0].scrollIntoView(); // map.invalidateSize(); } function closeDetailPanel() { console.log("closeDetailPanel"); $('.detailPanel').hide(); $('.accordion').show(); $('.trailhead-trailname.selected').removeClass("detail-open"); // map.invalidateSize(); } function detailPanelHoverIn(e) { enableTrailControls(); } function detailPanelHoverOut(e) { $(".controlRight").removeClass("enabled").addClass("disabled"); $(".controlLeft").removeClass("enabled").addClass("disabled"); } function changeDetailPanel(e) { console.log("changeDetailPanel"); var trailheadID = currentDetailTrailhead.properties.id; var trailID = String(currentDetailTrail.properties.id); console.log(trailID); var trailhead; for (var i = 0; i < orderedTrails.length; i++) { if (orderedTrails[i].trailID == trailID && orderedTrails[i].trailheadID == trailheadID) { orderedTrailIndex = i; } } var trailChanged = false; if ($(e.target).hasClass("controlRight")) { orderedTrailIndex = orderedTrailIndex + 1; trailChanged = true; } if ($(e.target).hasClass("controlLeft") && orderedTrailIndex > 0) { orderedTrailIndex = orderedTrailIndex - 1; trailChanged = true; } if (trailChanged) { var orderedTrail = orderedTrails[orderedTrailIndex]; // console.log(orderedTrail); trailheadID = orderedTrail.trailheadID; // console.log(["trailheadID", trailheadID]); var trailIndex = orderedTrail.index; // console.log(["trailIndex", trailIndex]); for (var j = 0; j < trailheads.length; j++) { if (trailheads[j].properties.id == trailheadID) { trailhead = trailheads[j]; } } enableTrailControls(); highlightTrailhead(trailheadID, trailIndex); showTrailDetails(trailData[trailhead.trails[trailIndex]], trailhead); $(".detailPanel .detailPanelPicture")[0].scrollIntoView(); } } function enableTrailControls() { if (orderedTrailIndex === 0) { $(".controlLeft").removeClass("enabled").addClass("disabled"); } else { $(".controlLeft").removeClass("disabled").addClass("enabled"); } if (orderedTrailIndex == orderedTrails.length - 1) { $(".controlRight").removeClass("enabled").addClass("disabled"); } else { $(".controlRight").removeClass("disabled").addClass("enabled"); } return orderedTrailIndex; } function resetDetailPanel() { if (!SMALL) { $('.detailPanel .detailPanelPicture').attr("src", "img/ImagePlaceholder.jpg"); $('.detailPanel .detailPanelPictureCredits').remove(); $('.detailPanel .detailConditionsDescription').html(""); $('.detailPanel .detailTrailSurface').html(""); $('.detailPanel .detailTrailheadName').html(""); $('.detailPanel .detailTrailheadPark').html(""); $('.detailPanel .detailTrailheadAddress').html(""); $('.detailPanel .detailTrailheadCity').html(""); $('.detailPanel .detailTrailheadState').html(""); $('.detailPanel .detailTrailheadZip').html(""); $('.detailPanel .detailPanelPictureContainer .statusMessage').remove(); $('.detailPanel .detailTopRow#right .hike').html(""); $('.detailPanel .detailTopRow#right .cycle').html(""); $('.detailPanel .detailTopRow#right .handicap').html(""); $('.detailPanel .detailTopRow#right .horse').html(""); $('.detailPanel .detailTopRow#right .xcountryski').html("") $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons #drinkwater').html(""); $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons #kiosk').html(""); $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons #restrooms').html(""); $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons #parking').html(""); $('.detailPanel .detailDescription').html(""); $('.detailPanel .detailStewardLogo').attr("src", "/img/logoPlaceholder.jpg"); } else { $('.detailPanel .detailPanelPicture').attr("src", "img/ImagePlaceholder.jpg"); $('.detailPanel .detailPanelPictureCredits').remove(); $('.detailPanel .detailConditionsDescription').html(""); $('.detailPanel .detailTrailSurface').html(""); $('.detailPanel .detailTrailheadName').html(""); $('.detailPanel .detailTrailheadPark').html(""); $('.detailPanel .detailTrailheadAddress').html(""); $('.detailPanel .detailTrailheadCity').html(""); $('.detailPanel .detailTrailheadState').html(""); $('.detailPanel .detailTrailheadZip').html(""); $('.detailPanel .detailPanelPictureContainer .statusMessage').remove(); $('.detailPanel .detailActivityRow .hike').html(""); $('.detailPanel .detailActivityRow .cycle').html(""); $('.detailPanel .detailActivityRow .handicap').html(""); $('.detailPanel .detailActivityRow .horse').html(""); $('.detailPanel .detailActivityRow .xcountryski').html(""); $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons #drinkwater').html(""); $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons #kiosk').html(""); $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons #restrooms').html(""); $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons #parking').html(""); $('.detailPanel .detailDescription').html(""); $('.detailPanel .detailStewardLogo').attr("src", "/img/logoPlaceholder.jpg"); } } function decorateDetailPanel(trail, trailhead) { // console.log(orderedTrailIndex); for (var i = 0; i < orderedTrails.length; i++) { if (orderedTrails[i].trailID == trail.properties.id && orderedTrails[i].trailheadID == trailhead.properties.id) { orderedTrailIndex = i; } } enableTrailControls(); resetDetailPanel(); $('.detailPanel .detailPanelBanner .trailIndex').html((orderedTrailIndex + 1) + " of " + orderedTrails.length); $('.detailPanel .detailPanelBanner .trailName').html(trail.properties.name); $('.detailPanel .trailheadName').html(trailhead.properties.name + " Trailhead"); $('.detailPanel .trailheadDistance').html(metersToMiles(trailhead.properties.distance) + " miles away"); if (trail.properties.conditions) { $('.detailPanel .detailConditionsDescription').html(trail.properties.conditions); $('.detailPanel .detailConditionsDescription').show(); $('.detailPanel .detailConditionsHeader').show(); } else { $('.detailPanel .detailConditionsDescription').hide(); $('.detailPanel .detailConditionsHeader').hide(); } if (trail.properties.trlsurface) { $('.detailPanel .detailTrailSurface').html(trail.properties.trlsurface); $('.detailPanel .detailTrailSurface').show(); $('.detailPanel .detailTrailSurfaceHeader').show(); } else { $('.detailPanel .detailTrailSurface').hide(); $('.detailPanel .detailTrailSurfaceHeader').hide(); } if (trailhead.properties.park) { $('.detailPanel .detailTrailheadPark').html(trailhead.properties.park); } if (trailhead.properties.address) { $('.detailPanel .detailTrailheadAddress').html(trailhead.properties.address); } if (trailhead.properties.city) { if (trailhead.properties.state) { $('.detailPanel .detailTrailheadCity').html(trailhead.properties.city + ", "); } else { $('.detailPanel .detailTrailheadCity').html(trailhead.properties.city); } } if (trailhead.properties.state) { $('.detailPanel .detailTrailheadState').html(trailhead.properties.state); } if (trailhead.properties.zip) { $('.detailPanel .detailTrailheadZip').html(trailhead.properties.zip); } if (trail.properties.medium_photo_url) { $('.detailPanel .detailPanelPicture').attr("src", trail.properties.medium_photo_url); $('.detailPanel .detailPanelPictureContainer').append("<div class='detailPanelPictureCredits'>" + trail.properties.photo_credit + "</div>"); } if (trail.properties.status == 1) { $('.detailPanel .detailPanelPictureContainer').append("<div class='statusMessage' id='yellow'>" + "<img src='img/icon_alert_yellow.png'>" + "<span>" + trail.properties.statustext + "</span>" + "</div>"); } if (trail.properties.status == 2) { $('.detailPanel .detailPanelPictureContainer').append("<div class='statusMessage' id='red'>" + "<img src='img/icon_alert_red.png'>" + "<span>" + trail.properties.statustext + "</span>" + "</div>"); } if (trail.properties.hike && trail.properties.hike.toLowerCase().indexOf('y') === 0) { if (!SMALL) { $('.detailPanel .detailTopRow#right .hike').html("<img class='activity-icons' title='Trail is appropriate for hikers. See below for details.' src='img/icon_hike_green.png'>"); } else { $('.detailPanel .detailActivityRow .hike').html("<img class='activity-icons' title='Trail is appropriate for hikers. See below for details.' src='img/icon_hike_green.png'>"); } } if (trail.properties.roadbike && trail.properties.roadbike.toLowerCase().indexOf('y') === 0) { if (!SMALL ) { $('.detailPanel .detailTopRow#right .cycle').html("<img class='activity-icons' title='Trail is appropriate for bicylists. See below for details.' src='img/icon_cycle_green.png'>"); } else { $('.detailPanel .detailActivityRow .cycle').html("<img class='activity-icons' title='Trail is appropriate for bicylists. See below for details.' src='img/icon_cycle_green.png'>"); } } if (trail.properties.accessible && trail.properties.accessible.toLowerCase().indexOf('y') === 0) { if (!SMALL) { $('.detailPanel .detailTopRow#right .handicap').html("<img class='activity-icons' title='Trail is at least in part wheelchair accessible. See below for details.' src='img/icon_handicap_green.png'>"); } else { $('.detailPanel .detailActivityRow .handicap').html("<img class='activity-icons' title='Trail is at least in part wheelchair accessible. See below for details.' src='img/icon_handicap_green.png'>"); } } if (trail.properties.equestrian && trail.properties.equestrian.toLowerCase().indexOf('y') === 0) { if (!SMALL) { $('.detailPanel .detailTopRow#right .horse').html("<img class='activity-icons' title='Trail is appropriate for equestrian use. See below for details.' src='img/icon_horse_green.png'>"); } else { $('.detailPanel .detailActivityRow .horse').html("<img class='activity-icons' title='Trail is appropriate for equestrian use. See below for details.' src='img/icon_horse_green.png'>"); } } if (trail.properties.xcntryski && trail.properties.xcntryski.toLowerCase().indexOf('y') === 0) { if (!SMALL) { $('.detailPanel .detailTopRow#right .xcountryski').html("<img class='activity-icons' title='Trail is appropriate for cross-country skiing. See below for details.' src='img/icon_xcountryski_green.png'>"); } else { $('.detailPanel .detailActivityRow .xcountryski').html("<img class='activity-icons' title='Trail is appropriate for cross-country skiing. See below for details.' src='img/icon_xcountryski_green.png'>"); } } if (trailhead.properties.parking && trailhead.properties.parking.toLowerCase().indexOf('y') === 0) { $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons .parking').html("<img class='amenity-icons' title='Parking available on site.' src='img/icon_parking_green.png'>"); } if (trailhead.properties.drinkwater && trailhead.properties.drinkwater.toLowerCase().indexOf('y') === 0) { $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons .water').html("<img class='amenity-icons' title='NOTE: Drinking water not available during winter temperatures.' src='img/icon_water_green.png'>"); } if (trailhead.properties.restrooms && trailhead.properties.restrooms.toLowerCase().indexOf('y') === 0) { $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons .restrooms').html("<img class='amenity-icons' title='Restrooms on site.' src='img/icon_restroom_green.png'>"); } if (trailhead.properties.kiosk && trailhead.properties.kiosk.toLowerCase().indexOf('y') === 0) { $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons .kiosk').html("<img class='amenity-icons' title='Information kiosk on site.' src='img/icon_kiosk_green.png'>"); } $('.detailPanel .detailSource').html(trailhead.properties.source); if (trail.properties.length) { var mileString = trail.properties.length == "1" ? "mile" : "miles"; $('.detailPanel .detailLength').html(trail.properties.length + " " + mileString); } else { $('.detailPanel .detailLength').html("--"); } $('.detailPanel .detailDescription').html(trail.properties.description); if (trail.properties.map_url) { $('.detailPanel .detailPrintMap a').attr("href", trail.properties.map_url).attr("target", "_blank"); $('.detailPanel .detailPrintMap').show(); } else { $('.detailPanel .detailPrintMap').hide(); } var directionsUrl = "http://maps.google.com?saddr=" + currentUserLocation.lat + "," + currentUserLocation.lng + "&daddr=" + trailhead.geometry.coordinates[1] + "," + trailhead.geometry.coordinates[0]; $('.detailPanel .detailDirections a').attr("href", directionsUrl).attr("target", "_blank"); // $("#email a").attr("href", "mailto:?subject=Heading to the " + trail.properties.name + "&body=Check out more trails at tothetrails.com!").attr("target", "_blank"); $("#twitter a").attr("href", "http://twitter.com/home?status=Headed%20to%20" + trail.properties.name + ".%20Find%20it%20on%20tothetrails.com!").attr("target", "_blank"); $("#facebook a").attr("href", "http://www.facebook.com/sharer/sharer.php?s=100&p[url]=tothetrails.com&p[images][0]=&p[title]=To%20The%20Trails!&p[summary]=Heading to " + trail.properties.name + "!").attr("target", "_blank"); $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons'); if (trail.properties.steward_fullname) { $('.detailPanel .detailFooter').show(); if (trail.properties.steward_logo_url && trail.properties.steward_logo_url.indexOf("missing.png") == -1) { $('.detailPanel .detailStewardLogo').attr("src", trail.properties.steward_logo_url).show(); } $('.detailPanel .detailFooter .detailSource').html(trail.properties.steward_fullname).attr("href", trail.properties.steward_url).attr("target", "_blank"); $('.detailPanel .detailFooter .detailSourcePhone').html(trail.properties.steward_phone); } else { $('.detailPanel .detailFooter').hide(); } } function slideDetailPanel(e) { console.log("slideDetailPanel"); if ($(e.target).parent().hasClass("expanded")) { $('.detailPanel').addClass('contracted'); $('.detailPanel').removeClass('expanded'); $('.trailListColumn').css({ overflow: 'hidden' }); } else { $('.detailPanel').addClass('expanded'); $('.detailPanel').removeClass('contracted'); $('.trailListColumn').css({ overflow: 'scroll' }); } } // Mobile-only function changing the position of the detailPanel function moveSlideDrawer(e) { console.log("moveSlideDrawer") if ($(".slideDrawer").hasClass("closedDrawer")) { console.log("openSlideDrawer"); $('.slideDrawer').removeClass('closedDrawer'); $('.slideDrawer').addClass("openDrawer"); // and move the Detail Panel all the way down if ($(".detailPanel").hasClass("expanded")) { $(".detailPanel").removeClass("expanded"); $(".detailPanel").addClass("hidden"); } else { $(".detailPanel").removeClass("contracted"); $(".detailPanel").addClass("hidden"); } } else { console.log("closeSlideDrawer"); $('.slideDrawer').removeClass('openDrawer'); $('.slideDrawer').addClass('closedDrawer'); // and restore the Detail Panel to contracted $('.detailPanel').removeClass("hidden"); $('.detailPanel').addClass("contracted"); } } // function closeSlideDrawerOnly(e) { // console.log("closeSlideDrawerOnly") // var container = $(".slideDrawer"); // if (!container.is(e.target) // && container.has(e.target).length == 0 // && container.hasClass('openDrawer') { // container.addClass('closedDrawer'); // container.removeClass('openDrawer'); // } // } // event handler for click of a trail name in a trailhead popup // Going to change the function of this trailnameClick function // But currently, it is not logging trailnameClick. // Current: init populateTrailsforTrailheadName(e) // Future: init showTrailDetails function trailnameClick(e) { console.log("trailnameClick"); populateTrailsForTrailheadTrailName(e); } // given jquery function parseTrailElementData($element) { console.log($element); var trailheadID = $element.data("trailheadid"); var highlightedTrailIndex = $element.data("index") || 0; var trailID = $element.data("trailid"); var results = { trailheadID: trailheadID, highlightedTrailIndex: highlightedTrailIndex, trailID: trailID }; return results; } // two event handlers for click of trailDiv and trail in trailhead popup: // get the trailName and trailHead that they clicked on // highlight the trailhead (showing all of the trails there) and highlight the trail path function populateTrailsForTrailheadDiv(e) { console.log("populateTrailsForTrailheadDiv"); var $myTarget; // this makes trailname click do the same thing as general div click // (almost certainly a better solution exists) if (e.target !== this) { $myTarget = $(this); } else { $myTarget = $(e.target); } var parsed = parseTrailElementData($myTarget); highlightTrailhead(parsed.trailheadID, parsed.highlightedTrailIndex); } function populateTrailsForTrailheadTrailName(e) { console.log($(e.target).data("trailheadid")); var $myTarget; if ($(e.target).data("trailheadid")) { $myTarget = $(e.target); } else { $myTarget = $(e.target.parentNode); } var parsed = parseTrailElementData($myTarget); console.log(parsed); var trailhead = getTrailheadById(parsed.trailheadID); // for (var i = 0; i < trailheads.length; i++) { // if (trailheads[i].properties.id == parsed.trailheadID) { // trailhead = trailheads[i]; // } // } // decorateDetailPanel(trailData[parsed.trailID], trailhead); highlightTrailhead(parsed.trailheadID, parsed.highlightedTrailIndex); var trail = trailData[parsed.trailID]; showTrailDetails(trail, trailhead); } function getTrailheadById(trailheadID) { var trailhead; for (var i = 0; i < trailheads.length; i++) { if (trailheads[i].properties.id == trailheadID) { trailhead = trailheads[i]; break; } } return trailhead; } function highlightTrailInPopup(trailhead, highlightedTrailIndex) { // add selected class to selected trail in trailhead popup, and remove it from others, // unless highlightedTrailIndex == -1, then just remove it everywhere var $trailheadPopupContent = $(trailhead.popupContent); $trailheadPopupContent.find(".trailhead-trailname").removeClass("selected").addClass("not-selected"); if (highlightedTrailIndex != -1) { var trailID = trailhead.trails[highlightedTrailIndex]; var selector = '[data-trailid="' + trailID + '"]'; var $trailnameItem = $trailheadPopupContent.find(selector); $trailnameItem.addClass("selected").removeClass("not-selected"); } trailhead.popupContent = $trailheadPopupContent.outerHTML(); if ($('.detailPanel').is(":visible")) { // console.log("detail is open"); // console.log($('.trailhead-trailname.selected')); $('.trailhead-trailname.selected').addClass("detail-open"); } } // given a trailheadID and a trail index within that trailhead // display the trailhead marker and popup, // then call highlightTrailheadDivs() and getAllTrailPathsForTrailhead() // with the trailhead record var currentTrailheadMarker; function highlightTrailhead(trailheadID, highlightedTrailIndex) { console.log("highlightTrailhead"); highlightedTrailIndex = highlightedTrailIndex || 0; var trailhead = null; trailhead = getTrailheadById(trailheadID); // for (var i = 0; i < trailheads.length; i++) { // if (trailheads[i].properties.id == trailheadID) { // trailhead = trailheads[i]; // break; // } // } if ($('.detailPanel').is(":visible")) { $('.trailhead-trailname.selected').removeClass("detail-open"); } if (currentTrailhead) { map.removeLayer(currentTrailhead.marker); currentTrailhead.marker = new L.CircleMarker(currentTrailhead.marker.getLatLng(), { color: "#D86930", fillOpacity: 0.5, opacity: 0.6, zIndexOffset: 100 }).setRadius(MARKER_RADIUS).addTo(map); setTrailheadEventHandlers(currentTrailhead); } if ($('.detailPanel').is(":visible")) { $('.trailhead-trailname.selected').addClass("detail-open"); } currentTrailhead = trailhead; map.removeLayer(currentTrailhead.marker); currentTrailhead.marker = new L.Marker(currentTrailhead.marker.getLatLng(), { icon: trailheadIcon1 }).addTo(map); setTrailheadEventHandlers(currentTrailhead); getAllTrailPathsForTrailhead(trailhead, highlightedTrailIndex); highlightTrailInPopup(trailhead, highlightedTrailIndex); var popup = new L.Popup({ offset: [0, -12], autoPanPadding: [100, 100] }) .setContent(trailhead.popupContent) .setLatLng(trailhead.marker.getLatLng()) .openOn(map); } function getAllTrailPathsForTrailhead(trailhead, highlightedTrailIndex) { console.log("getAllTrailPathsForTrailhead"); if (trailSegments.type == "FeatureCollection" && USE_LOCAL) { getAllTrailPathsForTrailheadLocal(trailhead, highlightedTrailIndex); } else { getAllTrailPathsForTrailheadRemote(trailhead, highlightedTrailIndex); } } // given a trailhead and a trail index within that trailhead // get the paths for any associated trails, // then call drawMultiTrailLayer() and setCurrentTrail() function getAllTrailPathsForTrailheadRemote(trailhead, highlightedTrailIndex) { console.log("getAllTrailPathsForTrailheadRemote"); var responses = []; var queryTaskArray = []; // got trailhead.trails, now get the segment collection for all of them // get segment collection for each for (var i = 0; i < trailhead.trails.length; i++) { var trailID = trailhead.trails[i]; var trailName = trailData[trailID].properties.name; var trail_query = "select st_collect(the_geom) the_geom, '" + trailName + "' trailname from " + TRAILSEGMENTS_TABLE + " segments where " + "(segments.trail1 = '" + trailName + "' or " + "segments.trail2 = '" + trailName + "' or " + "segments.trail3 = '" + trailName + "' or " + "segments.trail4 = '" + trailName + "' or " + "segments.trail5 = '" + trailName + "' or " + "segments.trail6 = '" + trailName + "' or " + "segments.trail1 = '" + trailName + " Trail' or " + "segments.trail2 = '" + trailName + " Trail' or " + "segments.trail3 = '" + trailName + " Trail' or " + "segments.trail4 = '" + trailName + " Trail' or " + "segments.trail5 = '" + trailName + " Trail' or " + "segments.trail6 = '" + trailName + " Trail') and " + "(source = '" + trailData[trailID].properties.source + "' or " + (trailName == "Ohio & Erie Canal Towpath Trail") + ")"; var queryTask = function(trail_query, index) { return function(callback) { var callData = { type: "GET", path: "/trailsegments.json" }; makeAPICall(callData, function(response) { responses[index] = response; callback(null, trailID); }); }; }(trail_query, i); queryTaskArray.push(queryTask); } async.parallel(queryTaskArray, function(err, results) { responses = mergeResponses(responses); drawMultiTrailLayer(responses); setCurrentTrail(highlightedTrailIndex); }); } // LOCAL EDITION: // given a trailhead and a trail index within that trailhead // get the paths for any associated trails, // then call drawMultiTrailLayer() and setCurrentTrail() // (it's a little convoluted because it's trying to return identical GeoJSON to what // CartoDB would return) function getAllTrailPathsForTrailheadLocal(trailhead, highlightedTrailIndex) { console.log("getAllTrailPathsForTrailheadLocal"); var responses = []; var trailFeatureArray = []; // got trailhead.trails, now get the segment collection for all of them // get segment collection for each for (var i = 0; i < trailhead.trails.length; i++) { var trailID = trailhead.trails[i]; var trail = trailData[trailID]; var trailSource = trail.properties.source; var trailName = trail.properties.name; var trailFeatureCollection = { type: "FeatureCollection", features: [{ geometry: { geometries: [], type: "GeometryCollection" }, type: "Feature" }] }; var valid = 0; for (var segmentIndex = 0; segmentIndex < trailSegments.features.length; segmentIndex++) { var segment = $.extend(true, {}, trailSegments.features[segmentIndex]); if ((segment.properties.trail1 == trailName || segment.properties.trail1 + " Trail" == trailName || segment.properties.trail2 == trailName || segment.properties.trail2 + " Trail" == trailName || segment.properties.trail3 == trailName || segment.properties.trail3 + " Trail" == trailName || segment.properties.trail4 == trailName || segment.properties.trail4 + " Trail" == trailName || segment.properties.trail5 == trailName || segment.properties.trail5 + " Trail" == trailName || segment.properties.trail6 == trailName || segment.properties.trail6 + " Trail" == trailName) && (segment.properties.source == trailSource || trailName == "Ohio & Erie Canal Towpath Trail")) { // 1) { trailFeatureCollection.features[0].properties = { trailname: trailName }; valid = 1; // console.log("match"); trailFeatureCollection.features[0].geometry.geometries.push(segment.geometry); } else { // console.log("invalid!"); } } console.log(valid); if (valid) { trailFeatureArray.push(trailFeatureCollection); } } console.log(trailFeatureArray); responses = mergeResponses(trailFeatureArray); drawMultiTrailLayer(responses); setCurrentTrail(highlightedTrailIndex); } // merge multiple geoJSON trail features into one geoJSON FeatureCollection function mergeResponses(responses) { console.log("mergeResponses"); // console.log(responses); // var combined = { type: "FeatureCollection", features: [] }; // for (var i = 0; i < responses.length; i++) { // console.log("xxxx"); // console.log(responses[i]); // // responses[i].properties.order = i; // combined.features.push(responses[i]); // } var combined = $.extend(true, {}, responses[0]); if (combined.features) { combined.features[0].properties.order = 0; for (var i = 1; i < responses.length; i++) { combined.features = combined.features.concat(responses[i].features); combined.features[i].properties.order = i; } } else { console.log("ERROR: missing segment data for trail."); } // console.log("----"); // console.log(combined); return combined; } function checkSegmentsForTrailname(trailName, trailSource) { var segmentsExist = false; segmentsExist = trailName in segmentTrailnameCache || 'trailname + " Trail"' in segmentTrailnameCache; return segmentsExist; } // given a geoJSON set of linestring features, // draw them all on the map (in a single layer we can remove later) function drawMultiTrailLayer(response) { console.log("drawMultiTrailLayer"); if (currentMultiTrailLayer) { map.removeLayer(currentMultiTrailLayer); currentTrailLayers = []; } if (response.features[0].geometry === null) { alert("No trail segment data found."); } currentMultiTrailLayer = L.geoJson(response, { style: function(feature) { var color; if (feature.properties.order === 0 || !feature.properties.order) { // color = getClassBackgroundColor("trailActive"); return { weight: NORMAL_SEGMENT_WEIGHT, color: NORMAL_SEGMENT_COLOR, opacity: 1, clickable: false }; } else if (feature.properties.order === 1) { // color = getClassBackgroundColor("trailActive"); return { weight: NORMAL_SEGMENT_WEIGHT, color: NORMAL_SEGMENT_COLOR, opacity: 1, clickable: false }; } else if (feature.properties.order === 2) { // color = getClassBackgroundColor("trailActive"); return { weight: NORMAL_SEGMENT_WEIGHT, color: NORMAL_SEGMENT_COLOR, opacity: 1, clickable: false }; } }, onEachFeature: function(feature, layer) { currentTrailLayers.push(layer); } }).addTo(map).bringToFront(); //.bringToFront(); zoomToLayer(currentMultiTrailLayer); } // return the calculated CSS background-color for the class given // This may need to be changed since AJW changed it to "border-color" above function getClassBackgroundColor(className) { var $t = $("<div class='" + className + "'>").hide().appendTo("body"); var c = $t.css("background-color"); console.log(c); $t.remove(); return c; } // given the index of a trail within a trailhead, // highlight that trail on the map, and call zoomToLayer with it function setCurrentTrail(index) { console.log("setCurrentTrail"); if (currentHighlightedTrailLayer && typeof currentHighlightedTrailLayer.setStyle == "Function") { currentHighlightedTrailLayer.setStyle({ weight: NORMAL_SEGMENT_WEIGHT, color: NORMAL_SEGMENT_COLOR }); } if (currentTrailLayers[index]) { currentHighlightedTrailLayer = currentTrailLayers[index]; currentHighlightedTrailLayer.setStyle({ weight: ACTIVE_TRAIL_WEIGHT, color: ACTIVE_TRAIL_COLOR }); } else { console.log("ERROR: trail layer missing"); console.log(currentTrailLayers); console.log(index); } } // given a leaflet layer, zoom to fit its bounding box, up to MAX_ZOOM // in and MIN_ZOOM out (commented out for now) function zoomToLayer(layer) { console.log("zoomToLayer"); // figure out what zoom is required to display the entire trail layer var layerBoundsZoom = map.getBoundsZoom(layer.getBounds()); // console.log(layer.getLayers().length); // var layerBoundsZoom = map.getZoom(); // console.log(["layerBoundsZoom:", layerBoundsZoom]); // if the entire trail layer will fit in a reasonable zoom full-screen, // use fitBounds to place the entire layer onscreen if (layerBoundsZoom <= MAX_ZOOM && layerBoundsZoom >= MIN_ZOOM) { map.fitBounds(layer.getBounds(), { paddingTopLeft: centerOffset }); } // otherwise, center on trailhead, with offset, and use MAX_ZOOM or MIN_ZOOM // with setView else { var newZoom = layerBoundsZoom > MAX_ZOOM ? MAX_ZOOM : layerBoundsZoom; newZoom = newZoom < MIN_ZOOM ? MIN_ZOOM : newZoom; map.setView(currentTrailhead.marker.getLatLng(), newZoom); } } function makeAPICall(callData, doneCallback) { console.log('makeAPICall'); if (!($.isEmptyObject(callData.data))) { callData.data = JSON.stringify(callData.data); } var url = API_HOST + callData.path; var request = $.ajax({ type: callData.type, url: url, dataType: "json", contentType: "application/json; charset=utf-8", //beforeSend: function(xhr) { // xhr.setRequestHeader("Accept", "application/json") //}, data: callData.data }).fail(function(jqXHR, textStatus, errorThrown) { console.log("error! " + errorThrown + " " + textStatus); console.log(jqXHR.status); $("#results").text("error: " + JSON.stringify(errorThrown)); }).done(function(response, textStatus, jqXHR) { if (typeof doneCallback === 'function') { console.log("calling doneCallback"); doneCallback.call(this, response); } }); } // get the outerHTML for a jQuery element jQuery.fn.outerHTML = function(s) { return s ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html(); }; function logger(message) { if (typeof console !== "undefined") { console.log(message) } } }
js/trailhead.js
var console = console || { "log": function() {} }; console.log("start"); $(document).ready(startup); /* The Big Nested Function ==========================*/ // Print to ensure file is loaded function startup() { "use strict"; console.log("trailhead.js"); var SMALL; if (Modernizr.mq("only screen and (max-width: 529px)")) { SMALL = true; } else if (Modernizr.mq("only screen and (min-width: 530px)")) { SMALL = false; } var TOUCH = $('html').hasClass('touch'); // Map generated in CfA Account var MAPBOX_MAP_ID = "codeforamerica.map-j35lxf9d"; var AKRON = { lat: 41.1, lng: -81.5 }; // API_HOST: The API server. Here we assign a default server, then // test to check whether we're using the Heroky dev app or the Heroku production app // and reassign API_HOST if necessary // var API_HOST = window.location.hostname; // // var API_HOST = "http://127.0.0.1:3000"; var API_HOST = "http://trailsy-dev.herokuapp.com"; // var API_HOST = "http://trailsyserver-dev.herokuapp.com"; // var API_HOST = "http://trailsyserver-prod.herokuapp.com"; // var API_HOST = "http://10.0.1.102:3000"; // var API_HOST = "http://10.0.2.2:3000" // for virtualbox IE if (window.location.hostname.split(".")[0] == "trailsy-dev") { // API_HOST = "http://trailsyserver-dev.herokuapp.com"; API_HOST = window.location.href; } else if (window.location.hostname.split(".")[0] == "trailsyserver-dev") { API_HOST = window.location.href; } else if (window.location.hostname.split(".")[0] == "trailsy" || window.location.hostname == "www.tothetrails.com") { API_HOST = window.location.href; // API_HOST = "http://trailsyserver-prod.herokuapp.com"; } // Near-Global Variables var METERSTOMILESFACTOR = 0.00062137; var MAX_ZOOM = 17; var MIN_ZOOM = 14; var SECONDARY_TRAIL_ZOOM = 13; var SHORT_MAX_DISTANCE = 2.0; var MEDIUM_MAX_DISTANCE = 5.0; var LONG_MAX_DISTANCE = 10.0; var SHOW_ALL_TRAILS = 1; var USE_LOCAL = SMALL ? false : true; // Set this to a true value to preload/use a local trail segment cache var USE_ALL_SEGMENT_LAYER = SMALL ? false : true; var NORMAL_SEGMENT_COLOR = "#678729"; var NORMAL_SEGMENT_WEIGHT = 3; var HOVER_SEGMENT_COLOR = "#678729"; var HOVER_SEGMENT_WEIGHT = 6; var ACTIVE_TRAIL_COLOR = "#445617"; var ACTIVE_TRAIL_WEIGHT = 9; var NOTRAIL_SEGMENT_COLOR = "#FF0000"; var NOTRAIL_SEGMENT_WEIGHT = 3; var LOCAL_LOCATION_THRESHOLD = 100; // distance in km. less than this, use actual location for map/userLocation var centerOffset = SMALL ? new L.point(0, 0) : new L.Point(450, 0); var MARKER_RADIUS = TOUCH ? 12 : 4; var ALL_SEGMENT_LAYER_SIMPLIFY = 5; var map; var mapDivName = SMALL ? "trailMapSmall" : "trailMapLarge"; var CLOSED = false; var trailData = {}; // all of the trails metadata (from traildata table), with trail ID as key // for yes/no features, check for first letter "y" or "n". // { *id*: { geometry: point(0,0), unused for now // properties: { id: *uniqueID* (same as key), // accessible: *disabled access. yes/no*, // dogs: *dog access. yes/no*, // equestrian: *horse access. yes/no*, // hike: *hiking access. yes/no*, // mtnbike: *mountain bike access. yes/no*, // roadbike: *street bike access. yes/no*, // xcntryski: *cross-country skiing access. yes/no* // conditions: *text field of qualifications to above access/use fields*, // description: *text description of trail*, // length: *length of trail in miles*, // map_url: *URL of trail map*, // name: *name of trail*, // source: *whose data this info came from (abbreviation)*, // source_fullname: *full name of source org*, // source_phone: *phone for source org*, // source_url: *URL of source org*, // status: *trail status. 0=open; 1=notice/warning; 2=closed*, // statustext: *trail status text. only displayed if status != 0 // steward: *org to contact for more information (abbrev)*, // steward_fullname: *full name of steward org*, // steward_phone: *phone for steward org*, // steward_url: *URL of steward org*, // trlsurface: *not currently used* // } // } // } var trailheads = []; // all trailheads (from trailsegments) // for yes/no features, check for first letter "y" or "n". // // [ { marker: *Leaflet marker*, // trails: *[array of matched trail IDs], // popupContent: *HTML of Leaflet popup*, // properties: { id: *uniqueID*, // drinkwater: *water available at this trailhead. yes/no* // distance: *from current location in meters*, // kiosk: *presence of informational kiosk. yes/no*, // name: *name*, // parking: *availability of parking. yes/no*, // restrooms: *availability of restrooms. yes/no*, // source: *whose data this info came from (abbreviation)*, // source_fullname: *full name of source org*, // source_phone: *phone number of source org*, // source_url: *URL of source org*, // steward: *org to contact for more information (abbrev)*, // steward_fullname: *full name of steward org*, // steward_phone: *phone number of steward org*, // steward_url: *URL of steward org*, // trail1: *trail at this trailhead*, // trail2: *trail at this trailhead*, // trail3: *trail at this trailhead*, // trail4: *trail at this trailhead*, // trail5: *trail at this trailhead*, // trail6: *trail at this trailhead*, // updated_at: *update time*, // created_at: *creation time* // }, // }[, ...}] // ] var trailSegments = []; var currentMultiTrailLayer = {}; // We have to know if a trail layer is already being displayed, so we can remove it var currentTrailLayers = []; var currentHighlightedTrailLayer = {}; var currentUserLocation = {}; var anchorLocation = {}; var currentTrailheadLayerGroup; var currentFilters = { lengthFilter: [], activityFilter: [], searchFilter: "" }; var orderedTrails = []; var currentDetailTrail = null; var currentDetailTrailhead = null; var userMarker = null; var allSegmentLayer = null; var closeTimeout = null; var openTimeout = null; var currentWeightedSegment = null; var currentTrailPopup = null; var currentTrailhead = null; var orderedTrailIndex; var geoWatchId = null; var currentTrailheadHover = null; var geoSetupDone = false; var segmentTrailnameCache = {}; var allInvisibleSegmentsArray = []; var allVisibleSegmentsArray = []; // Trailhead Variables // Not sure if these should be global, but hey whatev var trailheadIconOptions = { iconSize: [52 * 0.60, 66 * 0.60], iconAnchor: [13 * 0.60, 33 * 0.60], popupAnchor: [0, -3] }; var trailheadIcon1Options = $.extend(trailheadIconOptions, { iconUrl: 'img/icon_trailhead_active.png' }); var trailheadIcon1 = L.icon(trailheadIcon1Options); var trailheadIcon2Options = $.extend(trailheadIconOptions, { iconUrl: 'img/icon_trailhead_active.png' }); var trailheadIcon2 = L.icon(trailheadIcon2Options); // comment these/uncomment the next set to switch between tables var TRAILHEADS_TABLE = "summit_trailheads"; var TRAILSEGMENTS_TABLE = "summit_trailsegments"; var TRAILDATA_TABLE = "summit_traildata"; // var TRAILHEADS_TABLE = "summit_trailheads_test"; // var TRAILSEGMENTS_TABLE = "summit_trail_segments_test"; // var TRAILDATA_TABLE = "summit_traildata_test"; // =====================================================================// // UI events to react to $("#redoSearch").click(reorderTrailsWithNewLocation); $(document).on('click', '.trailhead-trailname', trailnameClick); // Open the detail panel! $(document).on('click', '.closeDetail', closeDetailPanel); // Close the detail panel! $(document).on('click', '.detailPanelControls', changeDetailPanel); // Shuffle Through Trails Shown in Detail Panel $(document).on('change', '.filter', filterChangeHandler); $(".clearSelection").click(clearSelectionHandler); $(document).on('click', '.trail-popup-line-named', trailPopupLineClick); $(".search-key").keyup(function(e) { // if (e.which == 13) { // console.log($('.search-key').val()); processSearch(e); // } }); $(".offsetZoomControl").click(offsetZoomIn); $(".search-submit").click(processSearch); // Detail Panel Navigation UI events $('.hamburgerLine').click(moveSlideDrawer); // $(document).on('click', closeSlideDrawerOnly); $(document).on('click', '.slider', slideDetailPanel); $(".detailPanel").hover(detailPanelHoverIn, detailPanelHoverOut); $(".aboutLink").click(openAboutPage); $(".closeAbout").click(closeAboutPage); // Shouldn't the UI event of a Map Callout click opening the detail panel go here? // =====================================================================// // Kick things off var overlayHTMLIE = "<h1>Welcome to To The Trails!</h1>" + "<p>We're sorry, but To The Trails is not compatible with Microsoft Internet Explorer 8 or earlier versions of that web browser." + "<p>Please upgrade to the latest version of " + "<a href='http://windows.microsoft.com/en-us/internet-explorer/download-ie'>Internet Explorer</a>, " + "<a href='http://google.com/chrome'>Google Chrome</a>, or " + "<a href='http://getfirefox.com'>Mozilla Firefox</a>." + "<p>If you are currently using Windows XP, you'll need to download and use Chrome or Firefox." + "<img src='/img/Overlay-Image-01.png' alt='trees'>"; var overlayHTML = "<span class='closeOverlay'>x</span>" + "<h1>Welcome To The Trails!</h1>" + "<p>ToTheTrails.com helps you find and navigate the trails of Summit County, Ohio." + "<p>Pick trails, find your way, and keep your bearings as you move between trails and parks in Cuyahoga Valley National Park and Metro Parks, Serving Summit County and beyond." + "<p>For easy access from a mobile device, bookmark ToTheTrails.com." + "<p>ToTheTrails.com is currently in public beta. It's a work in progress! We'd love to hear how this site is working for you." + "<p>Send feedback and report bugs to <a href='mailto:[email protected]?Subject=Feedback' target='_top'>[email protected]</a>. Learn more on our 'About' page."; var closedOverlayHTML = "<h1>Come visit us Nov 13th!</h1>" + "<p>We look forward to seeing you for our public launch." + "<img src='/img/Overlay-Image-01.png' alt='trees'>"; if (window.location.hostname === "www.tothetrails.com" || CLOSED) { console.log("closed"); $(".overlay-panel").html(closedOverlayHTML); $(".overlay").show(); } else { if ($("html").hasClass("lt-ie8")) { $(".overlay-panel").html(overlayHTMLIE); } else { $(".overlay-panel").html(overlayHTML); } $(".overlay-panel").click(function() { $(".overlay").hide(); }); } $(".overlay").show(); initialSetup(); // The next three functions perform trailhead/trail mapping // on a) initial startup, b) requested re-sort of trailheads based on the map, // and c) a change in filter settings // They all call addTrailDataToTrailheads() as their final action // -------------------------------------------------------------- // on startup, get location, display the map, // get and display the trailheads, populate trailData, // add trailData to trailheads function initialSetup() { console.log("initialSetup"); setupGeolocation(function() { if (geoSetupDone) { return; } getOrderedTrailheads(currentUserLocation, function() { getTrailData(function() { if (USE_LOCAL) { getTrailSegments(function() { createSegmentTrailnameCache(); addTrailDataToTrailheads(trailData); // if we haven't added the segment layer yet, add it. if (map.getZoom() >= SECONDARY_TRAIL_ZOOM && !(map.hasLayer(allSegmentLayer))) { map.addLayer(allSegmentLayer); } }); } else { // console.log("no USE_LOCAL"); addTrailDataToTrailheads(trailData); highlightTrailhead(orderedTrails[0].trailheadID, 0); orderedTrailIndex = 0; showTrailDetails(orderedTrails[0].trailhead, orderedTrails[0].trail); } }); }); }); } // set currentUserLocation to the center of the currently viewed map // then get the ordered trailheads and add trailData to trailheads function reorderTrailsWithNewLocation() { setAnchorLocationFromMap(); getOrderedTrailheads(anchorLocation, function() { addTrailDataToTrailheads(trailData); }); } // =====================================================================// // Filter function + helper functions, triggered by UI events declared above. function applyFilterChange(currentFilters, trailData) { var filteredTrailData = $.extend(true, {}, trailData); $.each(trailData, function(trail_id, trail) { if (currentFilters.activityFilter) { for (var i = 0; i < currentFilters.activityFilter.length; i++) { var activity = currentFilters.activityFilter[i]; var trailActivity = trail.properties[activity]; if (!trailActivity || trailActivity.toLowerCase().charAt(0) !== "y") { delete filteredTrailData[trail_id]; } } } if (currentFilters.lengthFilter) { var distInclude = false; if (currentFilters.lengthFilter.length === 0) { distInclude = true; } for (var j = 0; j < currentFilters.lengthFilter.length; j++) { var distance = currentFilters.lengthFilter[j]; var trailDist = trail.properties["length"]; if ((distance.toLowerCase() == "short" && trailDist <= SHORT_MAX_DISTANCE) || (distance.toLowerCase() == "medium" && trailDist > SHORT_MAX_DISTANCE && trailDist <= MEDIUM_MAX_DISTANCE) || (distance.toLowerCase() == "long" && trailDist > MEDIUM_MAX_DISTANCE && trailDist <= LONG_MAX_DISTANCE) || (distance.toLowerCase() == "verylong" && trailDist > LONG_MAX_DISTANCE)) { distInclude = true; break; } } if (!distInclude) { delete filteredTrailData[trail_id]; } } if (currentFilters.searchFilter) { var nameIndex = trail.properties.name.toLowerCase().indexOf(currentFilters.searchFilter.toLowerCase()); var descriptionIndex; if (trail.properties.description === null) { descriptionIndex = -1; } else { descriptionIndex = trail.properties.description.toLowerCase().indexOf(currentFilters.searchFilter.toLowerCase()); } if (nameIndex == -1 && descriptionIndex == -1) { delete filteredTrailData[trail_id]; } } }); addTrailDataToTrailheads(filteredTrailData); } function filterChangeHandler(e) { var $currentTarget = $(e.currentTarget); var filterType = $currentTarget.attr("data-filter"); var currentUIFilterState = $currentTarget.val(); console.log(currentUIFilterState); updateFilterObject(filterType, currentUIFilterState); } function processSearch(e) { var $currentTarget = $(e.currentTarget); var filterType = "searchFilter"; var currentUIFilterState; if (SMALL) { currentUIFilterState = $('#mobile .search-key').val(); } else { currentUIFilterState = $('#desktop .search-key').val(); } if (($currentTarget).hasClass('search-key')) { if (SMALL) { if (e.keyCode === 13) { alert("starting search"); updateFilterObject(filterType, currentUIFilterState); } } else { updateFilterObject(filterType, currentUIFilterState); } } else if (($currentTarget).hasClass('search-submit')) { updateFilterObject(filterType, currentUIFilterState); } // if the event target has a class search-key // see if it is keycode 13 // if true, call updatefilterobject // with filtertype=searchFilter // contents/value of searchbox which we get via jquery // if the event target has a class search-button // check to see if the value does not equal empty string // if it does not equal empty string, call updatefilterobject with filtertype=search filter & contents of box. } function updateFilterObject(filterType, currentUIFilterState) { console.log(currentUIFilterState); var matched = 0; if (filterType == "activityFilter") { var filterlength = currentFilters.activityFilter.length; for (var i = 0; i < currentFilters.activityFilter.length; i++) { var activity = currentFilters.activityFilter[i]; if (activity === currentUIFilterState) { currentFilters.activityFilter.splice(i, 1); matched = 1; break; } } if (matched === 0) { currentFilters.activityFilter.push(currentUIFilterState); } } if (filterType == "lengthFilter") { console.log("length"); console.log(currentFilters.lengthFilter.length); var filterlength = currentFilters.lengthFilter.length; for (var j = 0; j < filterlength; j++) { console.log("j"); console.log(j); var lengthRange = currentFilters.lengthFilter[j]; if (lengthRange == currentUIFilterState) { // console.log("match"); currentFilters.lengthFilter.splice(j, 1); matched = 1; break; } } if (matched === 0) { currentFilters.lengthFilter.push(currentUIFilterState); } } if (filterType == "searchFilter") { // console.log("searchFilter"); currentFilters.searchFilter = currentUIFilterState; } // currentFilters[filterType] = currentUIFilterState; console.log(currentFilters); applyFilterChange(currentFilters, trailData); } function clearSelectionHandler(e) { console.log("clearSelectionHandler"); $(".visuallyhidden_2 input").attr("checked", false); $(".visuallyhidden_3 input").attr("checked", false); $(".search-key").val(""); currentFilters = { lengthFilter: [], activityFilter: [], searchFilter: "" }; applyFilterChange(currentFilters, trailData); } // ====================================== // map generation & geolocation updates function offsetZoomIn(e) { // get map center lat/lng // convert to pixels // add offset // convert to lat/lng // setZoomAround to there with currentzoom + 1 var centerLatLng = map.getCenter(); var centerPoint = map.latLngToContainerPoint(centerLatLng); var offset = centerOffset; var offsetCenterPoint = centerPoint.add(offset.divideBy(2)); var offsetLatLng = map.containerPointToLatLng(offsetCenterPoint); if ($(e.target).hasClass("offsetZoomIn")) { map.setZoomAround(offsetLatLng, map.getZoom() + 1); } else if ($(e.target).hasClass("offsetZoomOut")) { map.setZoomAround(offsetLatLng, map.getZoom() - 1); } } function setAnchorLocationFromMap() { anchorLocation = map.getCenter(); } function setupGeolocation(callback) { console.log("setupGeolocation"); if (navigator.geolocation) { // setup location monitoring var options = { enableHighAccuracy: true, timeout: 5000, maximumAge: 30000 }; geoWatchId = navigator.geolocation.watchPosition( function(position) { if (trailheads.length === 0) { handleGeoSuccess(position, callback); geoSetupDone = true; } else { handleGeoSuccess(position); } }, function(error) { if (trailheads.length === 0) { handleGeoError(error, callback); geoSetupDone = true; } else { handleGeoError(error); } } ); } else { // for now, just returns Akron // should use browser geolocation, // and only return Akron if we're far from home base currentUserLocation = AKRON; handleGeoError("no geolocation", callback); } } function handleGeoSuccess(position, callback) { currentUserLocation = new L.LatLng(position.coords.latitude, position.coords.longitude); var distanceToAkron = currentUserLocation.distanceTo(AKRON) / 1000; // if no map, set it up if (!map) { var startingMapLocation; var startingMapZoom; // if we're close to Akron, start the map and the trailhead distances from // the current location, otherwise just use AKRON for both if (distanceToAkron < LOCAL_LOCATION_THRESHOLD) { anchorLocation = currentUserLocation; startingMapLocation = currentUserLocation; startingMapZoom = 13; } else { anchorLocation = AKRON; startingMapLocation = AKRON; startingMapZoom = 11; } map = createMap(startingMapLocation, startingMapZoom); } // always update the user marker, create if needed if (!userMarker) { userMarker = L.userMarker(currentUserLocation, { smallIcon: true, pulsing: true, accuracy: 0 }).addTo(map); } console.log(currentUserLocation); userMarker.setLatLng(currentUserLocation); if (typeof callback == "function") { callback(); } } function handleGeoError(error, callback) { console.log("handleGeoError"); currentUserLocation = AKRON; console.log(error); if (!map) { console.log("making map anyway"); map = createMap(AKRON, 11); } if (map && userMarker && error.code === 3) { map.removeLayer(userMarker); userMarker = null; } if (typeof callback == "function") { callback(); } } function createMap(startingMapLocation, startingMapZoom) { console.log("createMap"); console.log(mapDivName); var map = L.map(mapDivName, { zoomControl: false, scrollWheelZoom: false }); L.tileLayer.provider('MapBox.' + MAPBOX_MAP_ID).addTo(map); map.setView(startingMapLocation, startingMapZoom); map.fitBounds(map.getBounds(), { paddingTopLeft: centerOffset }); map.on("zoomend", function(e) { // console.log("zoomend"); if (SHOW_ALL_TRAILS && allSegmentLayer) { if (map.getZoom() >= SECONDARY_TRAIL_ZOOM && !(map.hasLayer(allSegmentLayer))) { // console.log(allSegmentLayer); map.addLayer(allSegmentLayer); allSegmentLayer.bringToBack(); } if (map.getZoom() < SECONDARY_TRAIL_ZOOM && map.hasLayer(allSegmentLayer)) { if (currentTrailPopup) { map.removeLayer(currentTrailPopup); } map.removeLayer(allSegmentLayer); } } }); map.on('popupclose', popupCloseHandler); return map; } // =====================================================================// // Getting trailhead data // get all trailhead info, in order of distance from "location" function getOrderedTrailheads(location, callback) { console.log("getOrderedTrailheads"); var callData = { loc: location.lat + "," + location.lng, type: "GET", path: "/trailheads.json?loc=" + location.lat + "," + location.lng }; makeAPICall(callData, function(response) { populateTrailheadArray(response); if (typeof callback == "function") { callback(); } }); } // given the getOrderedTrailheads response, a geoJSON collection of trailheads ordered by distance, // populate trailheads[] with the each trailhead's stored properties, a Leaflet marker, // and a place to put the trails for that trailhead. function populateTrailheadArray(trailheadsGeoJSON) { console.log("populateTrailheadArray"); console.log(trailheadsGeoJSON); trailheads = []; for (var i = 0; i < trailheadsGeoJSON.features.length; i++) { var currentFeature = trailheadsGeoJSON.features[i]; var currentFeatureLatLng = new L.LatLng(currentFeature.geometry.coordinates[1], currentFeature.geometry.coordinates[0]); // var newMarker = L.marker(currentFeatureLatLng, ({ // icon: trailheadIcon1 // })); var newMarker = new L.CircleMarker(currentFeatureLatLng, { color: "#D86930", fillOpacity: 0.5, opacity: 0.8 }).setRadius(MARKER_RADIUS); var trailhead = { properties: currentFeature.properties, geometry: currentFeature.geometry, marker: newMarker, trails: [], popupContent: "" }; setTrailheadEventHandlers(trailhead); trailheads.push(trailhead); } } function setTrailheadEventHandlers(trailhead) { trailhead.marker.on("click", function(trailheadID) { return function() { trailheadMarkerClick(trailheadID); }; }(trailhead.properties.id)); // placeholders for possible trailhead marker hover behavior // trailhead.marker.on("mouseover", function(trailhead) { // }(trailhead)); // trailhead.marker.on("mouseout", function(trailhead) { // }(trailhead)); } function trailheadMarkerClick(id) { console.log("trailheadMarkerClick"); highlightTrailhead(id, 0); var trailhead = getTrailheadById(id); showTrailDetails(trailData[trailhead.trails[0]], trailhead); } function popupCloseHandler(e) { currentTrailPopup = null; } // get the trailData from the API function getTrailData(callback) { console.log("getTrailData"); var callData = { type: "GET", path: "/trails.json" }; makeAPICall(callData, function(response) { populateTrailData(response); if (typeof callback == "function") { callback(); } }); } function populateTrailData(trailDataGeoJSON) { for (var i = 0; i < trailDataGeoJSON.features.length; i++) { trailData[trailDataGeoJSON.features[i].properties.id] = trailDataGeoJSON.features[i]; } } function getTrailSegments(callback) { console.log("getTrailSegments"); var callData = { type: "GET", path: "/trailsegments.json" }; // if (SMALL) { // callData.path = "/trailsegments.json?simplify=" + ALL_SEGMENT_LAYER_SIMPLIFY; // } makeAPICall(callData, function(response) { trailSegments = response; if (USE_ALL_SEGMENT_LAYER) { allSegmentLayer = makeAllSegmentLayer(response); } if (typeof callback == "function") { callback(); } }); } function createSegmentTrailnameCache() { console.log("createSegmentTrailnameCache"); for (var segmentIndex = 0; segmentIndex < trailSegments.features.length; segmentIndex++) { var segment = $.extend(true, {}, trailSegments.features[segmentIndex]); for (var i = 0; i < 6; i++) { var fieldName = "trail" + i; if (segment.properties[fieldName]) { segmentTrailnameCache[segment.properties[fieldName]] = true; } } } } // returns true if trailname is in trailData function trailnameInListOfTrails(trailname) { // console.log("trailnameInListOfTrails"); var result = false; $.each(trailData, function(key, value) { if (trailData[key].properties.name == trailname) { result = key; return false; } }); return result; } function segmentHasTrailWithMetadata(feature) { for (var i = 0; i <= 6; i++) { var trailFieldname = "trail" + i; if (trailnameInListOfTrails(feature.properties[trailFieldname])) { return true; } } return false; } function makeAllSegmentLayer(response) { if (allSegmentLayer !== undefined) { return allSegmentLayer; } console.log("makeAllSegmentLayer"); // make visible layers allVisibleSegmentsArray = []; allInvisibleSegmentsArray = []; var allSegmentLayer = new L.FeatureGroup(); // console.log("visibleAllTrailLayer start"); // make a normal visible layer for the segments, and add each of those layers to the allVisibleSegmentsArray var visibleAllTrailLayer = L.geoJson(response, { style: function visibleStyle() { return { color: NORMAL_SEGMENT_COLOR, weight: NORMAL_SEGMENT_WEIGHT, opacity: 1, clickable: false // dashArray: "5,5" }; }, onEachFeature: function visibleOnEachFeature(feature, layer) { // console.log("visibleAllTrailLayer onEachFeature"); allVisibleSegmentsArray.push(layer); } }); // make invisible layers // make the special invisible layer for mouse/touch events. much wider paths. // make popup html for each segment var invisibleAllTrailLayer = L.geoJson(response, { style: function invisibleStyle() { return { opacity: 0, weight: 20, clickable: true, smoothFactor: 10 }; }, onEachFeature: function invisibleOnEachFeature(feature, layer) { // console.log("invisibleAllTrailLayer onEachFeature"); allInvisibleSegmentsArray.push(layer); } }); // console.log("invisibleAllTrailLayer end"); var numSegments = allInvisibleSegmentsArray.length; for (var i = 0; i < numSegments; i++) { // console.log("numSegments loop"); var invisLayer = allInvisibleSegmentsArray[i]; // make a FeatureGroup including both visible and invisible components // var newTrailFeatureGroup = new L.FeatureGroup([allVisibleSegmentsArray[i]]); var newTrailFeatureGroup = new L.FeatureGroup([allInvisibleSegmentsArray[i], allVisibleSegmentsArray[i]]); var $popupHTML = $("<div class='trail-popup'>"); for (var j = 1; j <= 6; j++) { var trailField = "trail" + j; if (invisLayer.feature.properties[trailField]) { var $trailPopupLineDiv; if (trailnameInListOfTrails(invisLayer.feature.properties[trailField])) { // NOTE: color should be in the css, not here $trailPopupLineDiv = $("<div class='trail-popup-line trail-popup-line-named'>") .attr("data-steward", invisLayer.feature.properties.steward).attr("data-source", invisLayer.feature.properties.source) .attr("data-trailname", invisLayer.feature.properties[trailField]) .html(invisLayer.feature.properties[trailField]); } else { if (trailnameInListOfTrails(invisLayer.feature.properties[trailField].indexOf("_")) === -1) { $trailPopupLineDiv = $("<div class='trail-popup-line trail-popup-line-unnamed'>").html(invisLayer.feature.properties[trailField]) $trailPopupLineDiv.append("<b>"); } else { // console.log("skipping trail segment name because it has an underscore in it"); } } $popupHTML.append($trailPopupLineDiv); } } invisLayer.feature.properties.popupHTML = $popupHTML.outerHTML(); var eventType; // this should be a test for touch, not small if (TOUCH) { eventType = "click"; } else { eventType = "mouseover"; } newTrailFeatureGroup.addEventListener(eventType, function featureGroupEventListener(invisLayer) { return function newMouseover(e) { // console.log("new mouseover"); if (closeTimeout) { clearTimeout(closeTimeout); closeTimeout = null; } if (openTimeout) { clearTimeout(openTimeout); openTimeout = null; } openTimeout = setTimeout(function openTimeoutFunction(originalEvent, target) { return function() { target.setStyle({ weight: HOVER_SEGMENT_WEIGHT, color: HOVER_SEGMENT_COLOR }); // set currentWeightedSegment back to normal if (target != currentWeightedSegment) { if (currentWeightedSegment) { currentWeightedSegment.setStyle({ weight: NORMAL_SEGMENT_WEIGHT, color: NORMAL_SEGMENT_COLOR }); } } var popupHTML = invisLayer.feature.properties.popupHTML; currentTrailPopup = new L.Popup().setContent(popupHTML).setLatLng(originalEvent.latlng).openOn(map); currentWeightedSegment = target; }; }(e, e.target), 250); }; }(invisLayer)); newTrailFeatureGroup.addEventListener("mouseout", function(e) { if (closeTimeout) { clearTimeout(closeTimeout); closeTimeout = null; } if (openTimeout) { clearTimeout(openTimeout); openTimeout = null; } closeTimeout = setTimeout(function(e) { return function() { e.target.setStyle({ weight: 3 }); //map.closePopup(); }; }(e), 1250); }); allSegmentLayer.addLayer(newTrailFeatureGroup); } // use this to just show the network // allSegmentLayer = visibleAllTrailLayer; allVisibleSegmentsArray = null; allInvisibleSegmentsArray = null; return allSegmentLayer; } // after clicking on a trail name in a trail popup, // find the closest matching trailhead and highlight it function trailPopupLineClick(e) { console.log("trailPopupLineClick"); // get all trailheads that have this trailname and source var trailname = $(e.target).attr("data-trailname"); var source = $(e.target).attr("data-source"); var trailheadMatches = []; for (var i = 0; i < trailheads.length; i++) { var trailhead = trailheads[i]; if (trailhead.properties.source == source) { if (trailhead.properties.trail1 == trailname || trailhead.properties.trail2 == trailname || trailhead.properties.trail3 == trailname || trailhead.properties.trail4 == trailname || trailhead.properties.trail5 == trailname || trailhead.properties.trail6) { trailheadMatches.push(trailhead); } } } // find the closest one // popups have no getLatLng, so we're cheating here. var currentLatLng = currentTrailPopup._latlng; var nearestDistance = Infinity; var nearestTrailhead = null; for (var j = 0; j < trailheadMatches.length; j++) { var matchedTrailhead = trailheadMatches[j]; var trailheadLatLng = matchedTrailhead.marker.getLatLng(); var distance = currentLatLng.distanceTo(trailheadLatLng); if (distance < nearestDistance) { nearestTrailhead = matchedTrailhead; nearestDistance = distance; } } // find the index of the clicked trail var trailIndex = 0; var trail = null; for (var k = 0; k < nearestTrailhead.trails.length; k++) { var trailheadTrailID = nearestTrailhead.trails[k]; if (trailData[trailheadTrailID].properties.name == trailname) { trail = trailData[trailheadTrailID]; trailIndex = k; } } // highlight it highlightTrailhead(nearestTrailhead.properties.id, trailIndex); showTrailDetails(trail, nearestTrailhead); } // given trailData, // populate trailheads[x].trails with all of the trails in trailData // that match each trailhead's named trails from the trailhead table. // Also add links to the trails within each trailhead popup function addTrailDataToTrailheads(myTrailData) { console.log("addTrailDataToTrailheads"); for (var j = 0; j < trailheads.length; j++) { var trailhead = trailheads[j]; trailhead.trails = []; // for each original trailhead trail name for (var trailNum = 1; trailNum <= 6; trailNum++) { var trailWithNum = "trail" + trailNum; if (trailhead.properties[trailWithNum] === "") { continue; } var trailheadTrailName = trailhead.properties[trailWithNum]; // TODO: add a test for the case of duplicate trail names. // Right now this // loop through all of the trailData objects, looking for trail names that match // the trailhead trailname. // this works great, except for things like "Ledges Trail," which get added twice, // one for the CVNP instance and one for the MPSSC instance. // we should test for duplicate names and only use the nearest one. // to do that, we'll need to either query the DB for the trail segment info, // or check distance against the (yet-to-be) pre-loaded trail segment info $.each(myTrailData, function(trailID, trail) { if (trailhead.properties[trailWithNum] == trail.properties.name) { if (checkSegmentsForTrailname(trail.properties.name, trail.properties.source) || !USE_LOCAL) { trailhead.trails.push(trailID); } else { console.log("skipping " + trail.properties.name + "/" + trail.properties.source + ": no segment data"); } } }); } } fixDuplicateTrailNames(trailheads); makeTrailheadPopups(trailheads); mapActiveTrailheads(trailheads); makeTrailDivs(trailheads); if (SMALL && USE_LOCAL) { highlightTrailhead(orderedTrails[0].trailheadID, 0); orderedTrailIndex = 0; showTrailDetails(orderedTrails[0].trailhead, orderedTrails[0].trail); } } // this is so very wrong and terrible and makes me want to never write anything again. // alas, it works for now. // for each trailhead, if two or more of the matched trails from addTrailDataToTrailheads() have the same name, // remove any trails that don't match the trailhead source function fixDuplicateTrailNames(trailheads) { console.log("fixDuplicateTrailNames"); for (var trailheadIndex = 0; trailheadIndex < trailheads.length; trailheadIndex++) { var trailhead = trailheads[trailheadIndex]; var trailheadTrailNames = {}; for (var trailsIndex = 0; trailsIndex < trailhead.trails.length; trailsIndex++) { var trailName = trailData[trailhead.trails[trailsIndex]].properties.name; trailheadTrailNames[trailName] = trailheadTrailNames[trailName] || []; var sourceAndTrailID = { source: trailData[trailhead.trails[trailsIndex]].properties.source, trailID: trailData[trailhead.trails[trailsIndex]].properties.id }; trailheadTrailNames[trailName].push(sourceAndTrailID); } for (var trailheadTrailName in trailheadTrailNames) { if (trailheadTrailNames.hasOwnProperty(trailheadTrailName)) { if (trailheadTrailNames[trailheadTrailName].length > 1) { // remove the ID from the trailhead trails array if the source doesn't match for (var i = 0; i < trailheadTrailNames[trailheadTrailName].length; i++) { var mySourceAndTrailID = trailheadTrailNames[trailheadTrailName][i]; if (mySourceAndTrailID.source != trailhead.properties.source) { var idToRemove = mySourceAndTrailID.trailID; var removeIndex = $.inArray(idToRemove.toString(), trailhead.trails); trailhead.trails.splice(removeIndex, 1); } } } } } } } // given the trailheads, // make the popup menu for each one, including each trail present // and add it to the trailhead object // This is really only used in the desktop version function makeTrailheadPopups(trailheads) { for (var trailheadIndex = 0; trailheadIndex < trailheads.length; trailheadIndex++) { var trailhead = trailheads[trailheadIndex]; var $popupContentMainDiv = $("<div>").addClass("trailhead-popup"); var $popupTrailheadDiv = $("<div>").addClass("trailhead-box").html($("<div class='popupTrailheadNames'>" + trailhead.properties.name + "</div>")).appendTo($popupContentMainDiv); $popupTrailheadDiv.append($("<img>").addClass("calloutTrailheadIcon").attr({ src: "img/icon_trailhead_active.png" })); for (var trailsIndex = 0; trailsIndex < trailhead.trails.length; trailsIndex++) { var trail = trailData[trailhead.trails[trailsIndex]]; var $popupTrailDiv = $("<div>").addClass("trailhead-trailname trail" + (trailsIndex + 1)) .attr("data-trailname", trail.properties.name) .attr("data-trailid", trail.properties.id) .attr("data-trailheadname", trailhead.properties.name) .attr("data-trailheadid", trailhead.properties.id) .attr("data-index", trailsIndex); var status = ""; if (trail.properties.status == 1) { $popupTrailDiv.append($("<img>").addClass("status").attr({ src: "img/icon_alert_yellow.png", title: "alert" })); } if (trail.properties.status == 2) { $popupTrailDiv.append($("<img>").addClass("status").attr({ src: "img/icon_alert_red.png", title: "alert" })); } $popupTrailDiv.append("<div class='popupTrailNames'>" + trail.properties.name + "</div>"); $popupTrailDiv.append("<b>") // .append(trail.properties.name) .appendTo($popupTrailheadDiv); } trailhead.popupContent = $popupContentMainDiv.outerHTML(); // trailhead.marker.bindPopup(trailhead.popupContent); } } // given trailheads, add all of the markers to the map in a single Leaflet layer group // except for trailheads with no matched trails function mapActiveTrailheads(trailheads) { console.log("mapActiveTrailheads"); var currentTrailheadMarkerArray = []; for (var i = 0; i < trailheads.length; i++) { if (trailheads[i].trails.length) { currentTrailheadMarkerArray.push(trailheads[i].marker); } else { // console.log(["trailhead not displayed: ", trailheads[i].properties.name]); } } if (currentTrailheadLayerGroup) { console.log("remove"); map.removeLayer(currentTrailheadLayerGroup); } currentTrailheadLayerGroup = L.layerGroup(currentTrailheadMarkerArray); map.addLayer(currentTrailheadLayerGroup); currentTrailheadLayerGroup.eachLayer(function(layer) { if (typeof layer.bringToBack == "function") { layer.bringToBack(); } }); } // given trailheads, now populated with matching trail names, // fill out the left trail(head) pane, // noting if a particular trailhead has no trails associated with it function makeTrailDivs(trailheads) { console.log("makeTrailDivs"); console.log(trailheads); orderedTrails = []; var divCount = 1; $(".trailList").html(""); for (var j = 0; j < trailheads.length; j++) { var trailhead = trailheads[j]; // $.each(trailheads, function(index, trailhead) { var trailheadName = trailhead.properties.name; var trailheadID = trailhead.properties.id; var parkName = trailhead.properties.park; var trailheadTrailIDs = trailhead.trails; if (trailheadTrailIDs.length === 0) { // return true; // next $.each continue; } var trailheadSource = trailhead.properties.source; var trailheadDistance = metersToMiles(trailhead.properties.distance); var $trailDiv; // Making a new div for text / each trail for (var i = 0; i < trailheadTrailIDs.length; i++) { var trailID = trailheadTrailIDs[i]; var trail = trailData[trailID]; var trailName = trailData[trailID].properties.name; var trailLength = trailData[trailID].properties.length; var trailCurrentIndex = divCount++; // Add park name var when it makes it into the database $trailDiv = $("<div>").addClass('trail-box') .attr("data-source", "list") .attr("data-trailid", trailID) .attr("data-trailname", trailName) .attr("data-trail-length", trailLength) .attr("data-trailheadName", trailheadName) .attr("data-trailheadid", trailheadID) .attr("data-index", i) .appendTo(".trailList") .click(populateTrailsForTrailheadDiv) .click(function(trail, trailhead) { return function(e) { showTrailDetails(trail, trailhead); }; }(trail, trailhead)); var $trailInfo = $("<div>").addClass("trailInfo").appendTo($trailDiv); var $trailheadInfo = $("<div>").addClass("trailheadInfo").appendTo($trailDiv); // Making a new div for Detail Panel $("<div class='trailSource' id='" + trailheadSource + "'>" + trailheadSource + "</div>").appendTo($trailDiv); $("<div class='trailCurrentIndex' >" + trailCurrentIndex + "</div>").appendTo($trailInfo); $("<div class='trail' >" + trailName + "</div>").appendTo($trailInfo); var mileString = trailLength == 1 ? "mile" : "miles"; $("<div class='trailLength' >" + trailLength + " " + mileString + " long" + "</div>").appendTo($trailInfo); if (parkName) { // console.log("has a park name"); $("<div class='parkName' >" + trailhead.properties.park + "</div>").appendTo($trailInfo); } // Here we generate icons for each activity filter that is true..? $("<img class='trailheadIcon' src='img/icon_trailhead_active.png'/>").appendTo($trailheadInfo); $("<div class='trailheadName' >" + trailheadName + " Trailhead" + "</div>").appendTo($trailheadInfo); $("<div class='trailheadDistance' >" + trailheadDistance + " miles away" + "</div>").appendTo($trailheadInfo); var trailInfoObject = { trailID: trailID, trail: trail, trailheadID: trailheadID, trailhead: trailhead, index: i }; orderedTrails.push(trailInfoObject); } // diagnostic div to show trailheads with no trail matches // (These shouldn't happen any more because of the trailheadTrailIDs.length check above.) if (trailheadTrailIDs.length === 0) { $trailDiv = $("<div class='trail-box'>").appendTo("#trailList"); $("<span class='trail' id='list|" + trailheadName + "'>" + trailheadName + " - NO TRAILS (" + [val.properties.trail1, val.properties.trail2, val.properties.trail3].join(", ") + ")</span>").appendTo($trailDiv); $("<span class='trailSource'>" + trailheadSource + "</span>").appendTo($trailDiv); } // }); } $(".trails-count").html(orderedTrails.length + " RESULTS FOUND"); console.log("end makeTrailDivs"); console.log(orderedTrails); } function metersToMiles(i) { return (i * METERSTOMILESFACTOR).toFixed(1); } function showTrailDetails(trail, trailhead) { console.log("showTrailDetails"); if ($('.detailPanel').is(':hidden')) { decorateDetailPanel(trail, trailhead); openDetailPanel(); currentDetailTrail = trail; currentDetailTrailhead = trailhead; } else { if (currentDetailTrail == trail && currentDetailTrailhead == trailhead) { currentDetailTrail = null; currentDetailTrailhead = null; closeDetailPanel(); } else { decorateDetailPanel(trail, trailhead); currentDetailTrail = trail; currentDetailTrailhead = trailhead; } } } // About page functions function openAboutPage() { console.log("openAboutPage"); $(".aboutPage").show(); if (!SMALL) { $('.accordion').hide(); } } function closeAboutPage() { console.log("closeAboutPage"); $('.aboutPage').hide(); $('.accordion').show(); } // Helper functions for ShowTrailDetails function openDetailPanel() { console.log("openDetailPanel"); $('.detailPanel').show(); if (!SMALL) { $('.accordion').hide(); } if (SMALL) { if ($(".slideDrawer").hasClass("openDrawer")) { console.log("slide drawer is open"); $(".slideDrawer").removeClass("openDrawer"); $(".slideDrawer").addClass("closedDrawer"); $(".detailPanel").removeClass("hidden"); $(".detailPanel").addClass("contracted"); } } $('.trailhead-trailname.selected').addClass("detail-open"); $(".detailPanel .detailPanelPicture")[0].scrollIntoView(); // map.invalidateSize(); } function closeDetailPanel() { console.log("closeDetailPanel"); $('.detailPanel').hide(); $('.accordion').show(); $('.trailhead-trailname.selected').removeClass("detail-open"); // map.invalidateSize(); } function detailPanelHoverIn(e) { enableTrailControls(); } function detailPanelHoverOut(e) { $(".controlRight").removeClass("enabled").addClass("disabled"); $(".controlLeft").removeClass("enabled").addClass("disabled"); } function changeDetailPanel(e) { console.log("changeDetailPanel"); var trailheadID = currentDetailTrailhead.properties.id; var trailID = String(currentDetailTrail.properties.id); console.log(trailID); var trailhead; for (var i = 0; i < orderedTrails.length; i++) { if (orderedTrails[i].trailID == trailID && orderedTrails[i].trailheadID == trailheadID) { orderedTrailIndex = i; } } var trailChanged = false; if ($(e.target).hasClass("controlRight")) { orderedTrailIndex = orderedTrailIndex + 1; trailChanged = true; } if ($(e.target).hasClass("controlLeft") && orderedTrailIndex > 0) { orderedTrailIndex = orderedTrailIndex - 1; trailChanged = true; } if (trailChanged) { var orderedTrail = orderedTrails[orderedTrailIndex]; // console.log(orderedTrail); trailheadID = orderedTrail.trailheadID; // console.log(["trailheadID", trailheadID]); var trailIndex = orderedTrail.index; // console.log(["trailIndex", trailIndex]); for (var j = 0; j < trailheads.length; j++) { if (trailheads[j].properties.id == trailheadID) { trailhead = trailheads[j]; } } enableTrailControls(); highlightTrailhead(trailheadID, trailIndex); showTrailDetails(trailData[trailhead.trails[trailIndex]], trailhead); $(".detailPanel .detailPanelPicture")[0].scrollIntoView(); } } function enableTrailControls() { if (orderedTrailIndex === 0) { $(".controlLeft").removeClass("enabled").addClass("disabled"); } else { $(".controlLeft").removeClass("disabled").addClass("enabled"); } if (orderedTrailIndex == orderedTrails.length - 1) { $(".controlRight").removeClass("enabled").addClass("disabled"); } else { $(".controlRight").removeClass("disabled").addClass("enabled"); } return orderedTrailIndex; } function resetDetailPanel() { if (!SMALL) { $('.detailPanel .detailPanelPicture').attr("src", "img/ImagePlaceholder.jpg"); $('.detailPanel .detailPanelPictureCredits').remove(); $('.detailPanel .detailConditionsDescription').html(""); $('.detailPanel .detailTrailSurface').html(""); $('.detailPanel .detailTrailheadName').html(""); $('.detailPanel .detailTrailheadPark').html(""); $('.detailPanel .detailTrailheadAddress').html(""); $('.detailPanel .detailTrailheadCity').html(""); $('.detailPanel .detailTrailheadState').html(""); $('.detailPanel .detailTrailheadZip').html(""); $('.detailPanel .detailPanelPictureContainer .statusMessage').remove(); $('.detailPanel .detailTopRow#right .hike').html(""); $('.detailPanel .detailTopRow#right .cycle').html(""); $('.detailPanel .detailTopRow#right .handicap').html(""); $('.detailPanel .detailTopRow#right .horse').html(""); $('.detailPanel .detailTopRow#right .xcountryski').html("") $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons #drinkwater').html(""); $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons #kiosk').html(""); $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons #restrooms').html(""); $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons #parking').html(""); $('.detailPanel .detailDescription').html(""); $('.detailPanel .detailStewardLogo').attr("src", "/img/logoPlaceholder.jpg"); } else { $('.detailPanel .detailPanelPicture').attr("src", "img/ImagePlaceholder.jpg"); $('.detailPanel .detailPanelPictureCredits').remove(); $('.detailPanel .detailConditionsDescription').html(""); $('.detailPanel .detailTrailSurface').html(""); $('.detailPanel .detailTrailheadName').html(""); $('.detailPanel .detailTrailheadPark').html(""); $('.detailPanel .detailTrailheadAddress').html(""); $('.detailPanel .detailTrailheadCity').html(""); $('.detailPanel .detailTrailheadState').html(""); $('.detailPanel .detailTrailheadZip').html(""); $('.detailPanel .detailPanelPictureContainer .statusMessage').remove(); $('.detailPanel .detailActivityRow .hike').html(""); $('.detailPanel .detailActivityRow .cycle').html(""); $('.detailPanel .detailActivityRow .handicap').html(""); $('.detailPanel .detailActivityRow .horse').html(""); $('.detailPanel .detailActivityRow .xcountryski').html(""); $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons #drinkwater').html(""); $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons #kiosk').html(""); $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons #restrooms').html(""); $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons #parking').html(""); $('.detailPanel .detailDescription').html(""); $('.detailPanel .detailStewardLogo').attr("src", "/img/logoPlaceholder.jpg"); } } function decorateDetailPanel(trail, trailhead) { // console.log(orderedTrailIndex); for (var i = 0; i < orderedTrails.length; i++) { if (orderedTrails[i].trailID == trail.properties.id && orderedTrails[i].trailheadID == trailhead.properties.id) { orderedTrailIndex = i; } } enableTrailControls(); resetDetailPanel(); $('.detailPanel .detailPanelBanner .trailIndex').html((orderedTrailIndex + 1) + " of " + orderedTrails.length); $('.detailPanel .detailPanelBanner .trailName').html(trail.properties.name); $('.detailPanel .trailheadName').html(trailhead.properties.name + " Trailhead"); $('.detailPanel .trailheadDistance').html(metersToMiles(trailhead.properties.distance) + " miles away"); if (trail.properties.conditions) { $('.detailPanel .detailConditionsDescription').html(trail.properties.conditions); $('.detailPanel .detailConditionsDescription').show(); $('.detailPanel .detailConditionsHeader').show(); } else { $('.detailPanel .detailConditionsDescription').hide(); $('.detailPanel .detailConditionsHeader').hide(); } if (trail.properties.trlsurface) { $('.detailPanel .detailTrailSurface').html(trail.properties.trlsurface); $('.detailPanel .detailTrailSurface').show(); $('.detailPanel .detailTrailSurfaceHeader').show(); } else { $('.detailPanel .detailTrailSurface').hide(); $('.detailPanel .detailTrailSurfaceHeader').hide(); } if (trailhead.properties.park) { $('.detailPanel .detailTrailheadPark').html(trailhead.properties.park); } if (trailhead.properties.address) { $('.detailPanel .detailTrailheadAddress').html(trailhead.properties.address); } if (trailhead.properties.city) { if (trailhead.properties.state) { $('.detailPanel .detailTrailheadCity').html(trailhead.properties.city + ", "); } else { $('.detailPanel .detailTrailheadCity').html(trailhead.properties.city); } } if (trailhead.properties.state) { $('.detailPanel .detailTrailheadState').html(trailhead.properties.state); } if (trailhead.properties.zip) { $('.detailPanel .detailTrailheadZip').html(trailhead.properties.zip); } if (trail.properties.medium_photo_url) { $('.detailPanel .detailPanelPicture').attr("src", trail.properties.medium_photo_url); $('.detailPanel .detailPanelPictureContainer').append("<div class='detailPanelPictureCredits'>" + trail.properties.photo_credit + "</div>"); } if (trail.properties.status == 1) { $('.detailPanel .detailPanelPictureContainer').append("<div class='statusMessage' id='yellow'>" + "<img src='img/icon_alert_yellow.png'>" + "<span>" + trail.properties.statustext + "</span>" + "</div>"); } if (trail.properties.status == 2) { $('.detailPanel .detailPanelPictureContainer').append("<div class='statusMessage' id='red'>" + "<img src='img/icon_alert_red.png'>" + "<span>" + trail.properties.statustext + "</span>" + "</div>"); } if (trail.properties.hike && trail.properties.hike.toLowerCase().indexOf('y') === 0) { if (!SMALL) { $('.detailPanel .detailTopRow#right .hike').html("<img class='activity-icons' title='Trail is appropriate for hikers. See below for details.' src='img/icon_hike_green.png'>"); } else { $('.detailPanel .detailActivityRow .hike').html("<img class='activity-icons' title='Trail is appropriate for hikers. See below for details.' src='img/icon_hike_green.png'>"); } } if (trail.properties.roadbike && trail.properties.roadbike.toLowerCase().indexOf('y') === 0) { if (!SMALL ) { $('.detailPanel .detailTopRow#right .cycle').html("<img class='activity-icons' title='Trail is appropriate for bicylists. See below for details.' src='img/icon_cycle_green.png'>"); } else { $('.detailPanel .detailActivityRow .cycle').html("<img class='activity-icons' title='Trail is appropriate for bicylists. See below for details.' src='img/icon_cycle_green.png'>"); } } if (trail.properties.accessible && trail.properties.accessible.toLowerCase().indexOf('y') === 0) { if (!SMALL) { $('.detailPanel .detailTopRow#right .handicap').html("<img class='activity-icons' title='Trail is at least in part wheelchair accessible. See below for details.' src='img/icon_handicap_green.png'>"); } else { $('.detailPanel .detailActivityRow .handicap').html("<img class='activity-icons' title='Trail is at least in part wheelchair accessible. See below for details.' src='img/icon_handicap_green.png'>"); } } if (trail.properties.equestrian && trail.properties.equestrian.toLowerCase().indexOf('y') === 0) { if (!SMALL) { $('.detailPanel .detailTopRow#right .horse').html("<img class='activity-icons' title='Trail is appropriate for equestrian use. See below for details.' src='img/icon_horse_green.png'>"); } else { $('.detailPanel .detailActivityRow .horse').html("<img class='activity-icons' title='Trail is appropriate for equestrian use. See below for details.' src='img/icon_horse_green.png'>"); } } if (trail.properties.xcntryski && trail.properties.xcntryski.toLowerCase().indexOf('y') === 0) { if (!SMALL) { $('.detailPanel .detailTopRow#right .xcountryski').html("<img class='activity-icons' title='Trail is appropriate for cross-country skiing. See below for details.' src='img/icon_xcountryski_green.png'>"); } else { $('.detailPanel .detailActivityRow .xcountryski').html("<img class='activity-icons' title='Trail is appropriate for cross-country skiing. See below for details.' src='img/icon_xcountryski_green.png'>"); } } if (trailhead.properties.parking && trailhead.properties.parking.toLowerCase().indexOf('y') === 0) { $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons .parking').html("<img class='amenity-icons' title='Parking available on site.' src='img/icon_parking_green.png'>"); } if (trailhead.properties.drinkwater && trailhead.properties.drinkwater.toLowerCase().indexOf('y') === 0) { $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons .water').html("<img class='amenity-icons' title='NOTE: Drinking water not available during winter temperatures.' src='img/icon_water_green.png'>"); } if (trailhead.properties.restrooms && trailhead.properties.restrooms.toLowerCase().indexOf('y') === 0) { $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons .restrooms').html("<img class='amenity-icons' title='Restrooms on site.' src='img/icon_restroom_green.png'>"); } if (trailhead.properties.kiosk && trailhead.properties.kiosk.toLowerCase().indexOf('y') === 0) { $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons .kiosk').html("<img class='amenity-icons' title='Information kiosk on site.' src='img/icon_kiosk_green.png'>"); } $('.detailPanel .detailSource').html(trailhead.properties.source); if (trail.properties.length) { var mileString = trail.properties.length == "1" ? "mile" : "miles"; $('.detailPanel .detailLength').html(trail.properties.length + " " + mileString); } else { $('.detailPanel .detailLength').html("--"); } $('.detailPanel .detailDescription').html(trail.properties.description); if (trail.properties.map_url) { $('.detailPanel .detailPrintMap a').attr("href", trail.properties.map_url).attr("target", "_blank"); $('.detailPanel .detailPrintMap').show(); } else { $('.detailPanel .detailPrintMap').hide(); } var directionsUrl = "http://maps.google.com?saddr=" + currentUserLocation.lat + "," + currentUserLocation.lng + "&daddr=" + trailhead.geometry.coordinates[1] + "," + trailhead.geometry.coordinates[0]; $('.detailPanel .detailDirections a').attr("href", directionsUrl).attr("target", "_blank"); // $("#email a").attr("href", "mailto:?subject=Heading to the " + trail.properties.name + "&body=Check out more trails at tothetrails.com!").attr("target", "_blank"); $("#twitter a").attr("href", "http://twitter.com/home?status=Headed%20to%20" + trail.properties.name + ".%20Find%20it%20on%20tothetrails.com!").attr("target", "_blank"); $("#facebook a").attr("href", "http://www.facebook.com/sharer/sharer.php?s=100&p[url]=tothetrails.com&p[images][0]=&p[title]=To%20The%20Trails!&p[summary]=Heading to " + trail.properties.name + "!").attr("target", "_blank"); $('.detailPanel .detailBottomRow .detailTrailheadAmenities .detailTrailheadIcons'); if (trail.properties.steward_fullname) { $('.detailPanel .detailFooter').show(); if (trail.properties.steward_logo_url && trail.properties.steward_logo_url.indexOf("missing.png") == -1) { $('.detailPanel .detailStewardLogo').attr("src", trail.properties.steward_logo_url).show(); } $('.detailPanel .detailFooter .detailSource').html(trail.properties.steward_fullname).attr("href", trail.properties.steward_url).attr("target", "_blank"); $('.detailPanel .detailFooter .detailSourcePhone').html(trail.properties.steward_phone); } else { $('.detailPanel .detailFooter').hide(); } } function slideDetailPanel(e) { console.log("slideDetailPanel"); if ($(e.target).parent().hasClass("expanded")) { $('.detailPanel').addClass('contracted'); $('.detailPanel').removeClass('expanded'); $('.trailListColumn').css({ overflow: 'hidden' }); } else { $('.detailPanel').addClass('expanded'); $('.detailPanel').removeClass('contracted'); $('.trailListColumn').css({ overflow: 'scroll' }); } } // Mobile-only function changing the position of the detailPanel function moveSlideDrawer(e) { console.log("moveSlideDrawer") if ($(".slideDrawer").hasClass("closedDrawer")) { console.log("openSlideDrawer"); $('.slideDrawer').removeClass('closedDrawer'); $('.slideDrawer').addClass("openDrawer"); // and move the Detail Panel all the way down if ($(".detailPanel").hasClass("expanded")) { $(".detailPanel").removeClass("expanded"); $(".detailPanel").addClass("hidden"); } else { $(".detailPanel").removeClass("contracted"); $(".detailPanel").addClass("hidden"); } } else { console.log("closeSlideDrawer"); $('.slideDrawer').removeClass('openDrawer'); $('.slideDrawer').addClass('closedDrawer'); // and restore the Detail Panel to contracted $('.detailPanel').removeClass("hidden"); $('.detailPanel').addClass("contracted"); } } // function closeSlideDrawerOnly(e) { // console.log("closeSlideDrawerOnly") // var container = $(".slideDrawer"); // if (!container.is(e.target) // && container.has(e.target).length == 0 // && container.hasClass('openDrawer') { // container.addClass('closedDrawer'); // container.removeClass('openDrawer'); // } // } // event handler for click of a trail name in a trailhead popup // Going to change the function of this trailnameClick function // But currently, it is not logging trailnameClick. // Current: init populateTrailsforTrailheadName(e) // Future: init showTrailDetails function trailnameClick(e) { console.log("trailnameClick"); populateTrailsForTrailheadTrailName(e); } // given jquery function parseTrailElementData($element) { console.log($element); var trailheadID = $element.data("trailheadid"); var highlightedTrailIndex = $element.data("index") || 0; var trailID = $element.data("trailid"); var results = { trailheadID: trailheadID, highlightedTrailIndex: highlightedTrailIndex, trailID: trailID }; return results; } // two event handlers for click of trailDiv and trail in trailhead popup: // get the trailName and trailHead that they clicked on // highlight the trailhead (showing all of the trails there) and highlight the trail path function populateTrailsForTrailheadDiv(e) { console.log("populateTrailsForTrailheadDiv"); var $myTarget; // this makes trailname click do the same thing as general div click // (almost certainly a better solution exists) if (e.target !== this) { $myTarget = $(this); } else { $myTarget = $(e.target); } var parsed = parseTrailElementData($myTarget); highlightTrailhead(parsed.trailheadID, parsed.highlightedTrailIndex); } function populateTrailsForTrailheadTrailName(e) { console.log($(e.target).data("trailheadid")); var $myTarget; if ($(e.target).data("trailheadid")) { $myTarget = $(e.target); } else { $myTarget = $(e.target.parentNode); } var parsed = parseTrailElementData($myTarget); console.log(parsed); var trailhead = getTrailheadById(parsed.trailheadID); // for (var i = 0; i < trailheads.length; i++) { // if (trailheads[i].properties.id == parsed.trailheadID) { // trailhead = trailheads[i]; // } // } // decorateDetailPanel(trailData[parsed.trailID], trailhead); highlightTrailhead(parsed.trailheadID, parsed.highlightedTrailIndex); var trail = trailData[parsed.trailID]; showTrailDetails(trail, trailhead); } function getTrailheadById(trailheadID) { var trailhead; for (var i = 0; i < trailheads.length; i++) { if (trailheads[i].properties.id == trailheadID) { trailhead = trailheads[i]; break; } } return trailhead; } function highlightTrailInPopup(trailhead, highlightedTrailIndex) { // add selected class to selected trail in trailhead popup, and remove it from others, // unless highlightedTrailIndex == -1, then just remove it everywhere var $trailheadPopupContent = $(trailhead.popupContent); $trailheadPopupContent.find(".trailhead-trailname").removeClass("selected").addClass("not-selected"); if (highlightedTrailIndex != -1) { var trailID = trailhead.trails[highlightedTrailIndex]; var selector = '[data-trailid="' + trailID + '"]'; var $trailnameItem = $trailheadPopupContent.find(selector); $trailnameItem.addClass("selected").removeClass("not-selected"); } trailhead.popupContent = $trailheadPopupContent.outerHTML(); if ($('.detailPanel').is(":visible")) { // console.log("detail is open"); // console.log($('.trailhead-trailname.selected')); $('.trailhead-trailname.selected').addClass("detail-open"); } } // given a trailheadID and a trail index within that trailhead // display the trailhead marker and popup, // then call highlightTrailheadDivs() and getAllTrailPathsForTrailhead() // with the trailhead record var currentTrailheadMarker; function highlightTrailhead(trailheadID, highlightedTrailIndex) { console.log("highlightTrailhead"); highlightedTrailIndex = highlightedTrailIndex || 0; var trailhead = null; trailhead = getTrailheadById(trailheadID); // for (var i = 0; i < trailheads.length; i++) { // if (trailheads[i].properties.id == trailheadID) { // trailhead = trailheads[i]; // break; // } // } if ($('.detailPanel').is(":visible")) { $('.trailhead-trailname.selected').removeClass("detail-open"); } if (currentTrailhead) { map.removeLayer(currentTrailhead.marker); currentTrailhead.marker = new L.CircleMarker(currentTrailhead.marker.getLatLng(), { color: "#D86930", fillOpacity: 0.5, opacity: 0.6, zIndexOffset: 100 }).setRadius(MARKER_RADIUS).addTo(map); setTrailheadEventHandlers(currentTrailhead); } if ($('.detailPanel').is(":visible")) { $('.trailhead-trailname.selected').addClass("detail-open"); } currentTrailhead = trailhead; map.removeLayer(currentTrailhead.marker); currentTrailhead.marker = new L.Marker(currentTrailhead.marker.getLatLng(), { icon: trailheadIcon1 }).addTo(map); setTrailheadEventHandlers(currentTrailhead); getAllTrailPathsForTrailhead(trailhead, highlightedTrailIndex); highlightTrailInPopup(trailhead, highlightedTrailIndex); var popup = new L.Popup({ offset: [0, -12], autoPanPadding: [100, 100] }) .setContent(trailhead.popupContent) .setLatLng(trailhead.marker.getLatLng()) .openOn(map); } function getAllTrailPathsForTrailhead(trailhead, highlightedTrailIndex) { console.log("getAllTrailPathsForTrailhead"); if (trailSegments.type == "FeatureCollection" && USE_LOCAL) { getAllTrailPathsForTrailheadLocal(trailhead, highlightedTrailIndex); } else { getAllTrailPathsForTrailheadRemote(trailhead, highlightedTrailIndex); } } // given a trailhead and a trail index within that trailhead // get the paths for any associated trails, // then call drawMultiTrailLayer() and setCurrentTrail() function getAllTrailPathsForTrailheadRemote(trailhead, highlightedTrailIndex) { console.log("getAllTrailPathsForTrailheadRemote"); var responses = []; var queryTaskArray = []; // got trailhead.trails, now get the segment collection for all of them // get segment collection for each for (var i = 0; i < trailhead.trails.length; i++) { var trailID = trailhead.trails[i]; var trailName = trailData[trailID].properties.name; var trail_query = "select st_collect(the_geom) the_geom, '" + trailName + "' trailname from " + TRAILSEGMENTS_TABLE + " segments where " + "(segments.trail1 = '" + trailName + "' or " + "segments.trail2 = '" + trailName + "' or " + "segments.trail3 = '" + trailName + "' or " + "segments.trail4 = '" + trailName + "' or " + "segments.trail5 = '" + trailName + "' or " + "segments.trail6 = '" + trailName + "' or " + "segments.trail1 = '" + trailName + " Trail' or " + "segments.trail2 = '" + trailName + " Trail' or " + "segments.trail3 = '" + trailName + " Trail' or " + "segments.trail4 = '" + trailName + " Trail' or " + "segments.trail5 = '" + trailName + " Trail' or " + "segments.trail6 = '" + trailName + " Trail') and " + "(source = '" + trailData[trailID].properties.source + "' or " + (trailName == "Ohio & Erie Canal Towpath Trail") + ")"; var queryTask = function(trail_query, index) { return function(callback) { var callData = { type: "GET", path: "/trailsegments.json" }; makeAPICall(callData, function(response) { responses[index] = response; callback(null, trailID); }); }; }(trail_query, i); queryTaskArray.push(queryTask); } async.parallel(queryTaskArray, function(err, results) { responses = mergeResponses(responses); drawMultiTrailLayer(responses); setCurrentTrail(highlightedTrailIndex); }); } // LOCAL EDITION: // given a trailhead and a trail index within that trailhead // get the paths for any associated trails, // then call drawMultiTrailLayer() and setCurrentTrail() // (it's a little convoluted because it's trying to return identical GeoJSON to what // CartoDB would return) function getAllTrailPathsForTrailheadLocal(trailhead, highlightedTrailIndex) { console.log("getAllTrailPathsForTrailheadLocal"); var responses = []; var trailFeatureArray = []; // got trailhead.trails, now get the segment collection for all of them // get segment collection for each for (var i = 0; i < trailhead.trails.length; i++) { var trailID = trailhead.trails[i]; var trail = trailData[trailID]; var trailSource = trail.properties.source; var trailName = trail.properties.name; var trailFeatureCollection = { type: "FeatureCollection", features: [{ geometry: { geometries: [], type: "GeometryCollection" }, type: "Feature" }] }; var valid = 0; for (var segmentIndex = 0; segmentIndex < trailSegments.features.length; segmentIndex++) { var segment = $.extend(true, {}, trailSegments.features[segmentIndex]); if ((segment.properties.trail1 == trailName || segment.properties.trail1 + " Trail" == trailName || segment.properties.trail2 == trailName || segment.properties.trail2 + " Trail" == trailName || segment.properties.trail3 == trailName || segment.properties.trail3 + " Trail" == trailName || segment.properties.trail4 == trailName || segment.properties.trail4 + " Trail" == trailName || segment.properties.trail5 == trailName || segment.properties.trail5 + " Trail" == trailName || segment.properties.trail6 == trailName || segment.properties.trail6 + " Trail" == trailName) && (segment.properties.source == trailSource || trailName == "Ohio & Erie Canal Towpath Trail")) { // 1) { trailFeatureCollection.features[0].properties = { trailname: trailName }; valid = 1; // console.log("match"); trailFeatureCollection.features[0].geometry.geometries.push(segment.geometry); } else { // console.log("invalid!"); } } console.log(valid); if (valid) { trailFeatureArray.push(trailFeatureCollection); } } console.log(trailFeatureArray); responses = mergeResponses(trailFeatureArray); drawMultiTrailLayer(responses); setCurrentTrail(highlightedTrailIndex); } // merge multiple geoJSON trail features into one geoJSON FeatureCollection function mergeResponses(responses) { console.log("mergeResponses"); // console.log(responses); // var combined = { type: "FeatureCollection", features: [] }; // for (var i = 0; i < responses.length; i++) { // console.log("xxxx"); // console.log(responses[i]); // // responses[i].properties.order = i; // combined.features.push(responses[i]); // } var combined = $.extend(true, {}, responses[0]); if (combined.features) { combined.features[0].properties.order = 0; for (var i = 1; i < responses.length; i++) { combined.features = combined.features.concat(responses[i].features); combined.features[i].properties.order = i; } } else { console.log("ERROR: missing segment data for trail."); } // console.log("----"); // console.log(combined); return combined; } function checkSegmentsForTrailname(trailName, trailSource) { var segmentsExist = false; segmentsExist = trailName in segmentTrailnameCache || 'trailname + " Trail"' in segmentTrailnameCache; return segmentsExist; } // given a geoJSON set of linestring features, // draw them all on the map (in a single layer we can remove later) function drawMultiTrailLayer(response) { console.log("drawMultiTrailLayer"); if (currentMultiTrailLayer) { map.removeLayer(currentMultiTrailLayer); currentTrailLayers = []; } if (response.features[0].geometry === null) { alert("No trail segment data found."); } currentMultiTrailLayer = L.geoJson(response, { style: function(feature) { var color; if (feature.properties.order === 0 || !feature.properties.order) { // color = getClassBackgroundColor("trailActive"); return { weight: NORMAL_SEGMENT_WEIGHT, color: NORMAL_SEGMENT_COLOR, opacity: 1, clickable: false }; } else if (feature.properties.order === 1) { // color = getClassBackgroundColor("trailActive"); return { weight: NORMAL_SEGMENT_WEIGHT, color: NORMAL_SEGMENT_COLOR, opacity: 1, clickable: false }; } else if (feature.properties.order === 2) { // color = getClassBackgroundColor("trailActive"); return { weight: NORMAL_SEGMENT_WEIGHT, color: NORMAL_SEGMENT_COLOR, opacity: 1, clickable: false }; } }, onEachFeature: function(feature, layer) { currentTrailLayers.push(layer); } }).addTo(map).bringToFront(); //.bringToFront(); zoomToLayer(currentMultiTrailLayer); } // return the calculated CSS background-color for the class given // This may need to be changed since AJW changed it to "border-color" above function getClassBackgroundColor(className) { var $t = $("<div class='" + className + "'>").hide().appendTo("body"); var c = $t.css("background-color"); console.log(c); $t.remove(); return c; } // given the index of a trail within a trailhead, // highlight that trail on the map, and call zoomToLayer with it function setCurrentTrail(index) { console.log("setCurrentTrail"); if (currentHighlightedTrailLayer && typeof currentHighlightedTrailLayer.setStyle == "Function") { currentHighlightedTrailLayer.setStyle({ weight: NORMAL_SEGMENT_WEIGHT, color: NORMAL_SEGMENT_COLOR }); } if (currentTrailLayers[index]) { currentHighlightedTrailLayer = currentTrailLayers[index]; currentHighlightedTrailLayer.setStyle({ weight: ACTIVE_TRAIL_WEIGHT, color: ACTIVE_TRAIL_COLOR }); } else { console.log("ERROR: trail layer missing"); console.log(currentTrailLayers); console.log(index); } } // given a leaflet layer, zoom to fit its bounding box, up to MAX_ZOOM // in and MIN_ZOOM out (commented out for now) function zoomToLayer(layer) { console.log("zoomToLayer"); // figure out what zoom is required to display the entire trail layer var layerBoundsZoom = map.getBoundsZoom(layer.getBounds()); // console.log(layer.getLayers().length); // var layerBoundsZoom = map.getZoom(); // console.log(["layerBoundsZoom:", layerBoundsZoom]); // if the entire trail layer will fit in a reasonable zoom full-screen, // use fitBounds to place the entire layer onscreen if (layerBoundsZoom <= MAX_ZOOM && layerBoundsZoom >= MIN_ZOOM) { map.fitBounds(layer.getBounds(), { paddingTopLeft: centerOffset }); } // otherwise, center on trailhead, with offset, and use MAX_ZOOM or MIN_ZOOM // with setView else { var newZoom = layerBoundsZoom > MAX_ZOOM ? MAX_ZOOM : layerBoundsZoom; newZoom = newZoom < MIN_ZOOM ? MIN_ZOOM : newZoom; map.setView(currentTrailhead.marker.getLatLng(), newZoom); } } function makeAPICall(callData, doneCallback) { console.log('makeAPICall'); if (!($.isEmptyObject(callData.data))) { callData.data = JSON.stringify(callData.data); } var url = API_HOST + callData.path; var request = $.ajax({ type: callData.type, url: url, dataType: "json", contentType: "application/json; charset=utf-8", //beforeSend: function(xhr) { // xhr.setRequestHeader("Accept", "application/json") //}, data: callData.data }).fail(function(jqXHR, textStatus, errorThrown) { console.log("error! " + errorThrown + " " + textStatus); console.log(jqXHR.status); $("#results").text("error: " + JSON.stringify(errorThrown)); }).done(function(response, textStatus, jqXHR) { if (typeof doneCallback === 'function') { console.log("calling doneCallback"); doneCallback.call(this, response); } }); } // get the outerHTML for a jQuery element jQuery.fn.outerHTML = function(s) { return s ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html(); }; function logger(message) { if (typeof console !== "undefined") { console.log(message) } } }
Removed search alert.
js/trailhead.js
Removed search alert.
<ide><path>s/trailhead.js <ide> if (($currentTarget).hasClass('search-key')) { <ide> if (SMALL) { <ide> if (e.keyCode === 13) { <del> alert("starting search"); <ide> updateFilterObject(filterType, currentUIFilterState); <ide> } <ide> }
JavaScript
mit
4d6f4ebba6c93bcc2f2dae1a8071662b8d86304d
0
aclu-people-power/map,aclu-people-power/map,aclu-people-power/map,aclu-people-power/map
import Vue from 'vue'; import { getFilteredEvents } from 'src/util/events'; import mapMarker from 'src/assets/images/mapMarker.png'; import helpers from 'turf-helpers'; import mapboxgl from 'mapbox-gl'; mapboxgl.accessToken = 'pk.eyJ1Ijoia2VubmV0aHBlbm5pbmd0b24iLCJhIjoiY2l6bmJ3MmFiMDMzZTMzbDJtdGxkM3hveSJ9.w4iOGaL2vrIvETimSXUXsw'; export default function(store){ return new Vue({ el: '#event-map', name: 'event-map', template: require('src/templates/EventMap.html'), store, data: { mapRef: null, eventsLayer: null, initialCoordinates: [-96.9 , 37.8], initialZoom: 4 }, computed: { events() { return store.state.events; }, zipcodes() { return store.state.zipcodes; }, filters() { return store.state.filters; }, filteredEvents() { return store.getters.filteredEvents; }, view() { return store.state.view; } }, watch: { events(newEvents, oldEvents) { this.plotEvents(); // events data just showed up on app boot, if applicable // set the map position based on zip if (newEvents.length && !oldEvents.length) { this.setMapPositionBasedOnZip(); } }, // zipcodes should only change once, and when they do, // if applicable, set the map position based on zip zipcodes(newZipcodes, oldZipcodes) { this.plotEvents(); this.setMapPositionBasedOnZip(); }, filters(newFilters, oldFilters) { this.plotEvents(); // zoom to new location when zipcode changes if (newFilters.zipcode !== oldFilters.zipcode) { this.setMapPositionBasedOnZip(); } } }, methods: { plotEvents() { const eventsSource = this.mapRef.getSource("events"); if (eventsSource) { const eventsAsGeoJson = this.filteredEvents.map((event) => helpers.point([event.lng, event.lat])); eventsSource.setData(helpers.featureCollection(eventsAsGeoJson)); } }, setMapPositionBasedOnZip() { let latLng = this.zipcodes[this.filters.zipcode]; if (latLng) latLng = [latLng[1], latLng[0]]; const zoom = (latLng) ? 8 : this.initialZoom; this.mapRef.flyTo({ center: latLng || this.initialCoordinates, zoom: zoom }); }, addCustomIcon(icon, name) { const img = new Image(); img.src = icon; img.onload = function() { this.mapRef.addImage(name, img); }.bind(this); } }, mounted() { this.mapRef = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/bright-v9', center: this.initialCoordinates, zoom: this.initialZoom }); this.mapRef.on("load", function(){ this.mapRef.addSource("events", { "type": "geojson", "data": helpers.featureCollection([]), "cluster": true, "clusterMaxZoom": 8 }); this.addCustomIcon(mapMarker, "custom-marker"); this.mapRef.addLayer({ "id": "unclustered-points", "type": "symbol", "source": "events", "filter": ["!has", "point_count"], "layout": { "icon-image": "custom-marker", "icon-size": 0.5, "icon-offset": [0, -30] } }); this.mapRef.addLayer({ "id": "clusters", "type": "circle", "source": "events", "paint": { "circle-color": "#ff4b4d", "circle-radius": 12, "circle-stroke-width": 2, "circle-stroke-color": "#FFF" }, "filter": [">=", "point_count", 1] }); this.mapRef.addLayer({ "id": "clusters-count", "type": "symbol", "source": "events", "layout": { "text-field": "{point_count}", "text-font": [ "DIN Offc Pro Medium", "Arial Unicode MS Bold" ], "text-size": 12 }, "paint": { "text-color": "#FFF" } }); this.mapRef.addControl(new mapboxgl.NavigationControl()) this.plotEvents(); }.bind(this)) } }) }
src/components/EventMap.js
import Vue from 'vue'; import { getFilteredEvents } from 'src/util/events'; import mapMarker from 'src/assets/images/mapMarker.png'; import helpers from 'turf-helpers'; import mapboxgl from 'mapbox-gl'; mapboxgl.accessToken = 'pk.eyJ1Ijoia2VubmV0aHBlbm5pbmd0b24iLCJhIjoiY2l6bmJ3MmFiMDMzZTMzbDJtdGxkM3hveSJ9.w4iOGaL2vrIvETimSXUXsw'; export default function(store){ return new Vue({ el: '#event-map', name: 'event-map', template: require('src/templates/EventMap.html'), store, data: { mapRef: null, eventsLayer: null, initialCoordinates: [-96.9 , 37.8], initialZoom: 4 }, computed: { events() { return store.state.events; }, zipcodes() { return store.state.zipcodes; }, filters() { return store.state.filters; }, filteredEvents() { return store.getters.filteredEvents; }, view() { return store.state.view; } }, watch: { events(newEvents, oldEvents) { this.plotEvents(); // events data just showed up on app boot, if applicable // set the map position based on zip if (newEvents.length && !oldEvents.length) { this.setMapPositionBasedOnZip(); } }, // zipcodes should only change once, and when they do, // if applicable, set the map position based on zip zipcodes(newZipcodes, oldZipcodes) { this.plotEvents(); this.setMapPositionBasedOnZip(); }, filters(newFilters, oldFilters) { this.plotEvents(); // zoom to new location when zipcode changes if (newFilters.zipcode !== oldFilters.zipcode) { this.setMapPositionBasedOnZip(); } } }, methods: { plotEvents() { const eventsSource = this.mapRef.getSource("events"); if (eventsSource) { const eventsAsGeoJson = this.filteredEvents.map((event) => helpers.point([event.lng, event.lat])); eventsSource.setData(helpers.featureCollection(eventsAsGeoJson)); } }, setMapPositionBasedOnZip() { let latLng = this.zipcodes[this.filters.zipcode]; if (latLng) latLng = [latLng[1], latLng[0]]; const zoom = (latLng) ? 8 : this.initialZoom; this.mapRef.flyTo({ center: latLng || this.initialCoordinates, zoom: zoom }); }, addCustomIcon(icon, name) { const img = new Image(); img.src = icon; img.onload = function() { this.mapRef.addImage(name, img); }.bind(this); } }, mounted() { this.mapRef = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/bright-v9', center: this.initialCoordinates, zoom: this.initialZoom }); this.mapRef.on("load", function(){ this.mapRef.addSource("events", { "type": "geojson", "data": helpers.featureCollection([]), "cluster": true, "clusterMaxZoom": 8 }); this.addCustomIcon(mapMarker, "custom-marker"); this.mapRef.addLayer({ "id": "unclustered-points", "type": "symbol", "source": "events", "filter": ["!has", "point_count"], "layout": { "icon-image": "custom-marker", "icon-size": 0.5, "icon-offset": [0, -30] } }); this.mapRef.addLayer({ "id": "clusters", "type": "circle", "source": "events", "paint": { "circle-color": "#ff4b4d", "circle-radius": 12, "circle-stroke-width": 2, "circle-stroke-color": "#FFF" }, "filter": [">=", "point_count", 1] }); this.mapRef.addLayer({ "id": "clusters-count", "type": "symbol", "source": "events", "layout": { "text-field": "{point_count}", "text-font": [ "DIN Offc Pro Medium", "Arial Unicode MS Bold" ], "text-size": 12 }, "paint": { "text-color": "#FFF" } }); this.plotEvents(); }.bind(this)) } }) }
add controls
src/components/EventMap.js
add controls
<ide><path>rc/components/EventMap.js <ide> "text-color": "#FFF" <ide> } <ide> }); <del> <add> <add> this.mapRef.addControl(new mapboxgl.NavigationControl()) <ide> this.plotEvents(); <ide> }.bind(this)) <ide> }
Java
mit
91b46bd32c9282bead0815f8f2fcbd9a9e4b6a28
0
ana-balica/meow_letters
package anabalica.github.io.meowletters; import android.app.Activity; import android.content.ContentValues; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import anabalica.github.io.meowletters.storage.HighscoresContract; import anabalica.github.io.meowletters.storage.HighscoresDataSource; import anabalica.github.io.meowletters.storage.HighscoresDbHelper; /** * This is the Game Over activity. When there are no more free spots for letters to appear, the * game ends. * * @author Ana Balica */ public class GameOverActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game_over); Intent intent = getIntent(); String score = intent.getStringExtra(GameActivity.SCORE); TextView finalScore = (TextView) findViewById(R.id.finalScore); finalScore.setText("Score " + score); int points = Integer.parseInt(score); insertNewHighscore(points); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_game_over, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * Launch menu on 'Back' press */ public void onBackPressed() { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); this.startActivity(intent); } /** * Start a new game */ public void startNewGame(View view) { Intent intent = new Intent(this, GameActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); this.startActivity(intent); } /** * Insert into the highscores table a new entry * * @param score int amount of game points */ private void insertNewHighscore(int score) { HighscoresDataSource dataSource = new HighscoresDataSource(this); dataSource.open(); dataSource.createHighscore("Chubby bunny", score); dataSource.close(); } }
app/src/main/java/anabalica/github/io/meowletters/GameOverActivity.java
package anabalica.github.io.meowletters; import android.app.Activity; import android.content.ContentValues; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import anabalica.github.io.meowletters.storage.HighscoresContract; import anabalica.github.io.meowletters.storage.HighscoresDbHelper; /** * This is the Game Over activity. When there are no more free spots for letters to appear, the * game ends. * * @author Ana Balica */ public class GameOverActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game_over); Intent intent = getIntent(); String score = intent.getStringExtra(GameActivity.SCORE); TextView finalScore = (TextView) findViewById(R.id.finalScore); finalScore.setText("Score " + score); int points = Integer.parseInt(score); insertNewHighscrore(points); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_game_over, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * Launch menu on 'Back' press */ public void onBackPressed() { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); this.startActivity(intent); } /** * Start a new game */ public void startNewGame(View view) { Intent intent = new Intent(this, GameActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); this.startActivity(intent); } /** * Insert into the database highscores table a new entry. Games that have accumulated 0 points, * are not inserted. * * @param score int amount of game points */ private void insertNewHighscrore(int score) { if (score > 0) { HighscoresDbHelper highscoresDbHelper = new HighscoresDbHelper(this); SQLiteDatabase db = highscoresDbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(HighscoresContract.HighscoreEntry.COLUMN_NAME_USERNAME, "dummy username"); values.put(HighscoresContract.HighscoreEntry.COLUMN_NAME_SCORE, score); db.insert(HighscoresContract.HighscoreEntry.TABLE_NAME, null, values); System.out.println("Inserted the entry"); } } }
use Highscore DAO in the GameOverActivity to insert a new highscore
app/src/main/java/anabalica/github/io/meowletters/GameOverActivity.java
use Highscore DAO in the GameOverActivity to insert a new highscore
<ide><path>pp/src/main/java/anabalica/github/io/meowletters/GameOverActivity.java <ide> import android.widget.TextView; <ide> <ide> import anabalica.github.io.meowletters.storage.HighscoresContract; <add>import anabalica.github.io.meowletters.storage.HighscoresDataSource; <ide> import anabalica.github.io.meowletters.storage.HighscoresDbHelper; <ide> <ide> <ide> finalScore.setText("Score " + score); <ide> <ide> int points = Integer.parseInt(score); <del> insertNewHighscrore(points); <add> insertNewHighscore(points); <ide> } <ide> <ide> <ide> } <ide> <ide> /** <del> * Insert into the database highscores table a new entry. Games that have accumulated 0 points, <del> * are not inserted. <add> * Insert into the highscores table a new entry <ide> * <ide> * @param score int amount of game points <ide> */ <del> private void insertNewHighscrore(int score) { <del> if (score > 0) { <del> HighscoresDbHelper highscoresDbHelper = new HighscoresDbHelper(this); <del> SQLiteDatabase db = highscoresDbHelper.getWritableDatabase(); <del> <del> ContentValues values = new ContentValues(); <del> values.put(HighscoresContract.HighscoreEntry.COLUMN_NAME_USERNAME, "dummy username"); <del> values.put(HighscoresContract.HighscoreEntry.COLUMN_NAME_SCORE, score); <del> <del> db.insert(HighscoresContract.HighscoreEntry.TABLE_NAME, null, values); <del> System.out.println("Inserted the entry"); <del> } <add> private void insertNewHighscore(int score) { <add> HighscoresDataSource dataSource = new HighscoresDataSource(this); <add> dataSource.open(); <add> dataSource.createHighscore("Chubby bunny", score); <add> dataSource.close(); <ide> } <ide> }
JavaScript
mit
79f0f7c8b2777919544088bb3c8862d183efc3b1
0
codehz/blog.js,codehz/blog.js,codehz/blog.js
'use strict' module.exports = function (mongoose, config, db) { const utils = require('../lib/utils')(); function commentResponse(comment, _user) { const user = _user || comment.user; return { id: comment.id, created_at: comment.created_at, user_id: comment.user_id, user: { id: user.id, name: user.name, email: user.email }, target_article_id: comment.target_article_id, target_id: comment.target_id, content: comment.content } } function createComment(res, content, user, article, target) { db.Sequence.getNextSequence('comment', (err, nextCommentId) => { const comment = db.Comment({ nextCommentId, user_id: user.id, user, target_article_id: article.id, article, target_id: target ? target.id : 0, target, content }); comment.save(err => err ? utils.error(res, 422, err.message) : utils.success(res, "update success!", commentResponse(comment, user)) ) }); } return { create(req, res) { db.Article.findOne({ id: req.body.article }, (err, article) => { if (err) return utils.error(res, 422, err); if (!article) return utils.error(res, 404); if (req.body.target) { db.Comment.findOne({ id: req.body.target }, (err, target) => createComment(res, req.body.content, req.user, article, target)); } else { createComment(res, req.body.content, req.user, article); } }); }, delete(req, res) { db.Comment.findOne({ id: req.params.commentId }).populate('target_article').populate('target').exec((err, comment) => { if (err) return utils.error(res, 422, err); if (comment.user_id != req.user.id || comment.target_article.user_id != req.user.id || comment.target.user_id != req.user.id) return utils.error(res, 403, "Forbidden"); if (!comment) return utils.error(res, 404); comment.remove(err => err ? utils.error(res, 422) : utils.success(res)); }) }, get(req, res) { const id = req.params.commentId; let query = {}; let sortBy = null; if (id) { query = { id }; } else { sortBy = {}; sortBy["order_by"] = "created_at"; sortBy["order_type"] = "desc"; if (req.query.user_id) query["user_id"] = req.query.user_id; if (req.query.target_article_id) query["target_article_id"] = req.query.target_article_id; if (req.query.target_id) query["target_id"] = req.query.target_id; } const queryRequest = db.Comment.find(query); if (sortBy) { var sort = {}; sort[sortBy["order_by"]] = sortBy["order_type"] === "asc" ? "ascending" : "descending"; queryRequest.sort(sort); } queryRequest.populate('user').populate('target_article').populate('target').exec((err, dbResponse) => { if (err) return utils.error(res, 422, err.message); if (!dbResponse) return utils.error(res, 404); console.log('response', dbResponse); utils.responseData(res, dbResponse.count, dbResponse); }) } } }
controllers/comment.js
'use strict' module.exports = function (mongoose, config, db) { const utils = require('../lib/utils')(); function commentResponse(comment, _user) { const user = _user || comment.user; return { id: comment.id, created_at: comment.created_at, user_id: comment.user_id, user: { id: user.id, name: user.name, email: user.email }, target_article_id: comment.target_article_id, target_id: comment.target_id, content: comment.content } } function createComment(res, content, user, article, target) { db.Sequence.getNextSequence('comment', (err, nextCommentId) => { const comment = db.Comment({ nextCommentId, user_id: user.id, user, target_article_id: article.id, article, target_id: target ? target.id : 0, target, content }); comment.save(err => err ? utils.error(res, 422, err.message) : utils.success(res, "update success!", commentResponse(comment, user)) ) }); } return { create(req, res) { db.Article.findOne({ id: req.body.article }, (err, article) => { if (err) return utils.error(res, 422, err); if (!article) return utils.error(res, 404); if (req.body.target) { db.Comment.findOne({ id: req.body.target }, (err, target) => createComment(res, req.body.content, req.user, article, target)); } else { createComment(res, req.body.content, req.user, article); } }); }, delete(req, res) { db.Comment.findOne({ id: req.params.commentId }).populate('target_article').populate('target').exec((err, comment) => { if (err) return utils.error(res, 422, err); if (comment.user_id != req.user.id || comment.target_article.user_id != req.user.id || comment.target.user_id != req.user.id) return utils.error(res, 403, "Forbidden"); if (!comment) return utils.error(res, 404); comment.remove(err => err ? utils.error(res, 422) : utils.success(res)); }) }, get(req, res) { const id = req.params.commentId; let query = {}; let sortBy = null; if (id) { query = { id }; } else { sortBy = {}; sortBy["order_by"] = "created_at"; sortBy["order_type"] = "desc"; if (req.query.user_id) query["user_id"] = req.query.user_id; if (req.query.target_article_id) query["target_article_id"] = req.query.target_article_id; if (req.query.target_id) query["target_id"] = req.query.target_id; } const queryRequest = db.Comment.find(query); if (sortBy) { var sort = {}; sort[sortBy["order_by"]] = sortBy["order_type"] === "asc" ? "ascending" : "descending"; queryRequest.sort(sort); } queryRequest.populate('user').populate('target_article').populate('target').exec((err, dbResponse) => { if (err) return utils.error(res, 422, err.message); if (!dbResponse) return utils.error(res, 404); console.log('response', dbResponse); utils.responseData(res, dbResponse.count, dbResponse.map(article => commentResponse(article))); }) } } }
no map Signed-off-by: CodeHz <[email protected]>
controllers/comment.js
no map
<ide><path>ontrollers/comment.js <ide> if (err) return utils.error(res, 422, err.message); <ide> if (!dbResponse) return utils.error(res, 404); <ide> console.log('response', dbResponse); <del> utils.responseData(res, dbResponse.count, dbResponse.map(article => commentResponse(article))); <add> utils.responseData(res, dbResponse.count, dbResponse); <ide> }) <ide> } <ide> }
Java
mit
error: pathspec 'src/main/java/com/nkming/utils/type/RoIterator.java' did not match any file(s) known to git
47ce01f7626e7272680da7e9e2811195a75bcbf9
1
nkming2/libutils-android,nkming2/libutils-android
/* * RoIterator.java * * Author: Ming Tsang * Copyright (c) 2015 Ming Tsang * Refer to LICENSE for details */ package com.nkming.utils.type; import java.util.Iterator; /** * Hack in case remove is not needed and want to save some lines * * @param <T> */ public abstract class RoIterator<T> implements Iterator<T> { @Override public final void remove() { throw new UnsupportedOperationException(); } }
src/main/java/com/nkming/utils/type/RoIterator.java
Add RO hack to iterator
src/main/java/com/nkming/utils/type/RoIterator.java
Add RO hack to iterator
<ide><path>rc/main/java/com/nkming/utils/type/RoIterator.java <add>/* <add> * RoIterator.java <add> * <add> * Author: Ming Tsang <add> * Copyright (c) 2015 Ming Tsang <add> * Refer to LICENSE for details <add> */ <add> <add>package com.nkming.utils.type; <add> <add>import java.util.Iterator; <add> <add>/** <add> * Hack in case remove is not needed and want to save some lines <add> * <add> * @param <T> <add> */ <add>public abstract class RoIterator<T> implements Iterator<T> <add>{ <add> @Override <add> public final void remove() <add> { <add> throw new UnsupportedOperationException(); <add> } <add>}
JavaScript
agpl-3.0
fe328081f6a5cf981e29885f649d85c310b37723
0
bac/juju-gui,bac/juju-gui,mitechie/juju-gui,mitechie/juju-gui,bac/juju-gui,mitechie/juju-gui,bac/juju-gui,mitechie/juju-gui
/* This file is part of the Juju GUI, which lets users view and manage Juju environments within a graphical interface (https://launchpad.net/juju-gui). Copyright (C) 2012-2015 Canonical Ltd. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; /** * Bakery holds the context for making HTTP requests * that automatically acquire and discharge macaroons. * * @module env * @submodule env.bakery */ YUI.add('juju-env-bakery', function(Y) { var module = Y.namespace('juju.environments.web'); var macaroon = Y.namespace('macaroon'); /** * Bakery client inspired by the equivalent GO code. * * This object exposes the ability to perform requests * that automatically acquire and discharge macaroons * * @class Bakery */ var Bakery = Y.Base.create('Bakery', Y.Base, [], { /** Initialize. @method initializer @param {Object} cfg A config object providing webhandler and visit method information. A visitMethod can be provided, which becomes the bakery's visitMethod. Alternatively, the bakery can be configured to non interactive mode. If neither is true, the default method is used. {visitMethod: fn, interactive: boolean, webhandler: obj, serviceName: string} @return {undefined} Nothing. */ initializer: function (cfg) { this.webhandler = cfg.webhandler; if (cfg.visitMethod) { this.visitMethod = cfg.visitMethod; } else if (cfg.interactive !== undefined && !cfg.interactive) { this.visitMethod = this._nonInteractiveVisitMethod; } else { this.visitMethod = this._defaultVisitMethod; } this.macaroonName = 'Macaroons-' + cfg.serviceName; this.setCookiePath = cfg.setCookiePath; }, /** Takes the path supplied by the caller and makes a get request to the requestHandlerWithInteraction instance. If setCookiePath is set then it is used to set a cookie back to the ui after authentication. @param {String} The path to make the api request to. @param {Function} successCallback Called when the api request completes successfully. @param {Function} failureCallback Called when the api request fails with a response of >= 400 except 401/407 where it does authentication. */ sendGetRequest: function (path, successCallback, failureCallback) { var macaroons = this._getMacaroon(); var headers = {'Bakery-Protocol-Version': 1}; if (macaroons !== null) { headers['Macaroons'] = macaroons; } this.webhandler.sendGetRequest( path, headers, null, null, false, null, this._requestHandlerWithInteraction.bind( this, path, successCallback, failureCallback ) ); }, /** Takes the path supplied by the caller and makes a get request to the requestHandlerWithInteraction instance. If setCookiePath is set then it is used to set a cookie back to the ui after authentication. @param path {String} The path to make the api request to. @param data {String} Stringified JSON of parameters to send to the POST endpoint. @param successCallback {Function} Called when the api request completes successfully. @param failureCallback {Function} Called when the api request fails with a response of >= 400 except 401/407 where it does authentication. */ sendPostRequest: function (path, data, successCallback, failureCallback) { var macaroons = this._getMacaroon(); var headers = { 'Bakery-Protocol-Version': 1, 'Content-type': 'application/json' }; if (macaroons !== null) { headers['Macaroons'] = macaroons; } this.webhandler.sendPostRequest( path, headers, data, null, null, false, null, this._requestHandlerWithInteraction.bind( this, path, successCallback, failureCallback) ); }, /** Handles the request response from the _makeRequest method, calling the supplied failure callback if the response status was >= 400 or passing the response object to the supplied success callback. For 407/401 response it will request authentication through the macaroon provided in the 401/407 response. @method _requestHandlerWithInteraction @param {String} The path to make the api request to. @param {Function} successCallback Called when the api request completes successfully. @param {Function} failureCallback Called when the api request fails with a response of >= 400 (except 401/407). @param {Object} response The XHR response object. */ _requestHandlerWithInteraction: function (path, successCallback, failureCallback, response) { var target = response.target; if (target.status === 401 && target.getResponseHeader('Www-Authenticate') === 'Macaroon') { var jsonResponse = JSON.parse(target.responseText); this._authenticate( jsonResponse.Info.Macaroon, this._sendOriginalRequest.bind( this, path, successCallback, failureCallback ), failureCallback ); } else { this._requestHandler(successCallback, failureCallback, response); } }, /** Used to resend the original request without any interaction this time.. @method _sendOriginalRequest @param {String} The path to make the api request to. @param {Function} successCallback Called when the api request completes successfully. @param {Function} failureCallback Called when the api request fails with a response of >= 400 (except 401/407). */ _sendOriginalRequest: function(path, successCallback, failureCallback) { var macaroons = this._getMacaroon(); var headers = {'Bakery-Protocol-Version': 1}; if (macaroons !== null) { headers['Macaroons'] = macaroons; } this.webhandler.sendGetRequest( path, headers, null, null, false, null, this._requestHandler.bind( this, successCallback, failureCallback ) ); }, /** Handles the request response from the _makeRequest method, calling the supplied failure callback if the response status was >= 400 or passing the response object to the supplied success callback. @method _requestHandler @param {Function} successCallback Called when the api request completes successfully. @param {Function} failureCallback Called when the api request fails with a response of >= 400. @param {Object} response The XHR response object. */ _requestHandler: function (successCallback, failureCallback, response) { var target = response.target; if (target.status >= 400) { failureCallback(response); return; } successCallback(response); }, /** Authenticate by discharging the macaroon and then set the cookie by calling the authCookiePath provided @method authenticate @param {Macaroon} The macaroon to be discharged @param {Function} The request to be sent again in case of successful authentication @param {Function} The callback failure in case of wrong authentication */ _authenticate: function (m, requestFunction, failureCallback) { try { macaroon.discharge( macaroon.import(m), this._obtainThirdPartyDischarge.bind(this), this._processDischarges.bind( this, requestFunction, failureCallback ), failureCallback ); } catch (ex) { failureCallback(ex.message); } }, /** Process the discharged macaroon and call the end point to be able to set a cookie for the origin domain only when an auth cookie path is provided, then call the original function. @method _processDischarges @param {Function} The request to be sent again in case of successful authentication @param {Function} The callback failure in case of wrong authentication @param {[Macaroon]} The macaroons being discharged */ _processDischarges: function (requestFunction, failureCallback, discharges) { var jsonMacaroon; try { jsonMacaroon = macaroon.export(discharges); } catch (ex) { failureCallback(ex.message); } var content = JSON.stringify({'Macaroons': jsonMacaroon}); if (this.setCookiePath === undefined) { this._setMacaroonsCookie(requestFunction, jsonMacaroon); return; } this.webhandler.sendPutRequest( this.setCookiePath, null, content, null, null, true, null, this._requestHandler.bind( this, this._setMacaroonsCookie.bind(this, requestFunction, jsonMacaroon), failureCallback ) ); }, /** Process successful discharge by setting Macaroons Cookie and invoke the original request @method _setMacaroonsCookie @param {Function} The path where to send put request to set the cookie back @param {Object} an exported Macaroon */ _setMacaroonsCookie: function (originalRequest, jsonMacaroon) { var prefix = this.macaroonName + '='; document.cookie = prefix + btoa(JSON.stringify(jsonMacaroon)); originalRequest(); }, /** Go to the discharge endpoint to obtain the third party discharge. @method obtainThirdPartyDischarge @param {String} The origin location @param {String} The third party location where to discharge @param {Function} The macaroon to be discharge @param {Function} The request to be sent again in case of successful authentication @param {Function} The callback failure in case of wrong authentication */ _obtainThirdPartyDischarge: function (location, thirdPartyLocation, condition, successCallback, failureCallback) { thirdPartyLocation += '/discharge'; var headers = { 'Bakery-Protocol-Version': 1, 'Content-Type': 'application/x-www-form-urlencoded' }; var content = 'id=' + encodeURI(condition) + '&location=' + encodeURI(location); this.webhandler.sendPostRequest( thirdPartyLocation, headers, content, null, null, false, null, this._requestHandler.bind( this, this._exportMacaroon.bind(this, successCallback, failureCallback), this._interact.bind(this, successCallback, failureCallback) ) ); }, /** Get a JSON response from authentication either trusted or with interaction that contains a macaroon. @method _exportMacaroon @param {Function} The callback function to be sent in case of successful authentication @param {Function} The callback function failure in case of wrong authentication @param {Object} response The XHR response object. */ _exportMacaroon: function (successCallback, failureCallback, response) { try { var dm = macaroon.import( JSON.parse(response.target.responseText).Macaroon ); successCallback(dm); } catch (ex) { failureCallback(ex.message); } }, /** Interact to be able to sign-in to get authenticated. @method _interact @param {Function} The callback function to be sent in case of successful authentication @param {Function} The callback function failure in case of wrong authentication */ _interact: function(successCallback, failureCallback, e) { var response = JSON.parse(e.target.responseText); if (response.Code !== 'interaction required') { failureCallback(response.Code); return; } this.visitMethod(response); this.webhandler.sendGetRequest( response.Info.WaitURL, null, null, null, false, null, this._requestHandler.bind( this, this._exportMacaroon.bind(this, successCallback, failureCallback), failureCallback ) ); }, /** Non interactive visit method which sends the jujugui "auth" blob to the IdM to login. @method _nonInteractiveVisitMethod @param {Object} response An xhr response object. */ _nonInteractiveVisitMethod: function(response) { var acceptHeaders = {'Accept': 'application/json'}; var contentHeaders = {'Content-Type': 'application/json'}; var login = function(response) { var method = JSON.parse(response.target.responseText).jujugui; var data = JSON.stringify({login: window.juju_config.auth}); this.webhandler.sendPostRequest( method, contentHeaders, data, null, null, false, null, null); }; this.webhandler.sendGetRequest( response.Info.VisitURL, acceptHeaders, null, null, false, null, login.bind(this)); }, /** Default visit method which is to open a window to the response.Info.VisitURL. @method _defaultVisitMethod @param {Object} response An xhr response object. */ _defaultVisitMethod: function(response) { window.open(response.Info.VisitURL, 'Login'); }, /** Get macaroon from local cookie. @method _getMacaroon @return {String} Macaroons that was set in local cookie. */ _getMacaroon: function() { var name = this.macaroonName + '='; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(name) == 0) return c.substring(name.length,c.length); } return null; } }); module.Bakery = Bakery; }, '0.1.0', { requires: [ 'base', 'cookie', 'node', 'juju-env-base', 'juju-env-web-handler', 'macaroon' ] });
jujugui/static/gui/src/app/store/env/bakery.js
/* This file is part of the Juju GUI, which lets users view and manage Juju environments within a graphical interface (https://launchpad.net/juju-gui). Copyright (C) 2012-2015 Canonical Ltd. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; /** * Bakery holds the context for making HTTP requests * that automatically acquire and discharge macaroons. * * @module env * @submodule env.bakery */ YUI.add('juju-env-bakery', function(Y) { var module = Y.namespace('juju.environments.web'); var macaroon = Y.namespace('macaroon'); /** * Bakery client inspired by the equivalent GO code. * * This object exposes the ability to perform requests * that automatically acquire and discharge macaroons * * @class Bakery */ var Bakery = Y.Base.create('Bakery', Y.Base, [], { /** Initialize. @method initializer @param {Object} cfg A config object providing webhandler and visit method information. A visitMethod can be provided, which becomes the bakery's visitMethod. Alternatively, the bakery can be configured to non interactive mode. If neither is true, the default method is used. {visitMethod: fn, interactive: boolean, webhandler: obj, serviceName: string} @return {undefined} Nothing. */ initializer: function (cfg) { this.webhandler = cfg.webhandler; if (cfg.visitMethod) { this.visitMethod = cfg.visitMethod; } else if (cfg.interactive !== undefined && !cfg.interactive) { this.visitMethod = this._nonInteractiveVisitMethod; } else { this.visitMethod = this._defaultVisitMethod; } this.macaroonName = 'Macaroons-' + cfg.serviceName; this.setCookiePath = cfg.setCookiePath; }, /** Takes the path supplied by the caller and makes a get request to the requestHandlerWithInteraction instance. If setCookiePath is set then it is used to set a cookie back to the ui after authentication. @param {String} The path to make the api request to. @param {Function} successCallback Called when the api request completes successfully. @param {Function} failureCallback Called when the api request fails with a response of >= 400 except 401/407 where it does authentication. */ sendGetRequest: function (path, successCallback, failureCallback) { var macaroons = this._getMacaroon(); var headers = {'Bakery-Protocol-Version': 1}; if (macaroons !== null) { headers['Macaroons'] = macaroons; } this.webhandler.sendGetRequest( path, headers, null, null, false, null, this._requestHandlerWithInteraction.bind( this, path, successCallback, failureCallback ) ); }, /** Handles the request response from the _makeRequest method, calling the supplied failure callback if the response status was >= 400 or passing the response object to the supplied success callback. For 407/401 response it will request authentication through the macaroon provided in the 401/407 response. @method _requestHandlerWithInteraction @param {String} The path to make the api request to. @param {Function} successCallback Called when the api request completes successfully. @param {Function} failureCallback Called when the api request fails with a response of >= 400 (except 401/407). @param {Object} response The XHR response object. */ _requestHandlerWithInteraction: function (path, successCallback, failureCallback, response) { var target = response.target; if (target.status === 401 && target.getResponseHeader('Www-Authenticate') === 'Macaroon') { var jsonResponse = JSON.parse(target.responseText); this._authenticate( jsonResponse.Info.Macaroon, this._sendOriginalRequest.bind( this, path, successCallback, failureCallback ), failureCallback ); } else { this._requestHandler(successCallback, failureCallback, response); } }, /** Used to resend the original request without any interaction this time.. @method _sendOriginalRequest @param {String} The path to make the api request to. @param {Function} successCallback Called when the api request completes successfully. @param {Function} failureCallback Called when the api request fails with a response of >= 400 (except 401/407). */ _sendOriginalRequest: function(path, successCallback, failureCallback) { var macaroons = this._getMacaroon(); var headers = {'Bakery-Protocol-Version': 1}; if (macaroons !== null) { headers['Macaroons'] = macaroons; } this.webhandler.sendGetRequest( path, headers, null, null, false, null, this._requestHandler.bind( this, successCallback, failureCallback ) ); }, /** Handles the request response from the _makeRequest method, calling the supplied failure callback if the response status was >= 400 or passing the response object to the supplied success callback. @method _requestHandler @param {Function} successCallback Called when the api request completes successfully. @param {Function} failureCallback Called when the api request fails with a response of >= 400. @param {Object} response The XHR response object. */ _requestHandler: function (successCallback, failureCallback, response) { var target = response.target; if (target.status >= 400) { failureCallback(response); return; } successCallback(response); }, /** Authenticate by discharging the macaroon and then set the cookie by calling the authCookiePath provided @method authenticate @param {Macaroon} The macaroon to be discharged @param {Function} The request to be sent again in case of successful authentication @param {Function} The callback failure in case of wrong authentication */ _authenticate: function (m, requestFunction, failureCallback) { try { macaroon.discharge( macaroon.import(m), this._obtainThirdPartyDischarge.bind(this), this._processDischarges.bind( this, requestFunction, failureCallback ), failureCallback ); } catch (ex) { failureCallback(ex.message); } }, /** Process the discharged macaroon and call the end point to be able to set a cookie for the origin domain only when an auth cookie path is provided, then call the original function. @method _processDischarges @param {Function} The request to be sent again in case of successful authentication @param {Function} The callback failure in case of wrong authentication @param {[Macaroon]} The macaroons being discharged */ _processDischarges: function (requestFunction, failureCallback, discharges) { var jsonMacaroon; try { jsonMacaroon = macaroon.export(discharges); } catch (ex) { failureCallback(ex.message); } var content = JSON.stringify({'Macaroons': jsonMacaroon}); if (this.setCookiePath === undefined) { this._setMacaroonsCookie(requestFunction, jsonMacaroon); return; } this.webhandler.sendPutRequest( this.setCookiePath, null, content, null, null, true, null, this._requestHandler.bind( this, this._setMacaroonsCookie.bind(this, requestFunction, jsonMacaroon), failureCallback ) ); }, /** Process successful discharge by setting Macaroons Cookie and invoke the original request @method _setMacaroonsCookie @param {Function} The path where to send put request to set the cookie back @param {Object} an exported Macaroon */ _setMacaroonsCookie: function (originalRequest, jsonMacaroon) { var prefix = this.macaroonName + '='; document.cookie = prefix + btoa(JSON.stringify(jsonMacaroon)); originalRequest(); }, /** Go to the discharge endpoint to obtain the third party discharge. @method obtainThirdPartyDischarge @param {String} The origin location @param {String} The third party location where to discharge @param {Function} The macaroon to be discharge @param {Function} The request to be sent again in case of successful authentication @param {Function} The callback failure in case of wrong authentication */ _obtainThirdPartyDischarge: function (location, thirdPartyLocation, condition, successCallback, failureCallback) { thirdPartyLocation += '/discharge'; var headers = { 'Bakery-Protocol-Version': 1, 'Content-Type': 'application/x-www-form-urlencoded' }; var content = 'id=' + encodeURI(condition) + '&location=' + encodeURI(location); this.webhandler.sendPostRequest( thirdPartyLocation, headers, content, null, null, false, null, this._requestHandler.bind( this, this._exportMacaroon.bind(this, successCallback, failureCallback), this._interact.bind(this, successCallback, failureCallback) ) ); }, /** Get a JSON response from authentication either trusted or with interaction that contains a macaroon. @method _exportMacaroon @param {Function} The callback function to be sent in case of successful authentication @param {Function} The callback function failure in case of wrong authentication @param {Object} response The XHR response object. */ _exportMacaroon: function (successCallback, failureCallback, response) { try { var dm = macaroon.import( JSON.parse(response.target.responseText).Macaroon ); successCallback(dm); } catch (ex) { failureCallback(ex.message); } }, /** Interact to be able to sign-in to get authenticated. @method _interact @param {Function} The callback function to be sent in case of successful authentication @param {Function} The callback function failure in case of wrong authentication */ _interact: function(successCallback, failureCallback, e) { var response = JSON.parse(e.target.responseText); if (response.Code !== 'interaction required') { failureCallback(response.Code); return; } this.visitMethod(response); this.webhandler.sendGetRequest( response.Info.WaitURL, null, null, null, false, null, this._requestHandler.bind( this, this._exportMacaroon.bind(this, successCallback, failureCallback), failureCallback ) ); }, /** Non interactive visit method which sends the jujugui "auth" blob to the IdM to login. @method _nonInteractiveVisitMethod @param {Object} response An xhr response object. */ _nonInteractiveVisitMethod: function(response) { var acceptHeaders = {'Accept': 'application/json'}; var contentHeaders = {'Content-Type': 'application/json'}; var login = function(response) { var method = JSON.parse(response.target.responseText).jujugui; var data = JSON.stringify({login: window.juju_config.auth}); this.webhandler.sendPostRequest( method, contentHeaders, data, null, null, false, null, null); }; this.webhandler.sendGetRequest( response.Info.VisitURL, acceptHeaders, null, null, false, null, login.bind(this)); }, /** Default visit method which is to open a window to the response.Info.VisitURL. @method _defaultVisitMethod @param {Object} response An xhr response object. */ _defaultVisitMethod: function(response) { window.open(response.Info.VisitURL, 'Login'); }, /** Get macaroon from local cookie. @method _getMacaroon @return {String} Macaroons that was set in local cookie. */ _getMacaroon: function() { var name = this.macaroonName + '='; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(name) == 0) return c.substring(name.length,c.length); } return null; } }); module.Bakery = Bakery; }, '0.1.0', { requires: [ 'base', 'cookie', 'node', 'juju-env-base', 'juju-env-web-handler', 'macaroon' ] });
Add POST option to bakery.
jujugui/static/gui/src/app/store/env/bakery.js
Add POST option to bakery.
<ide><path>ujugui/static/gui/src/app/store/env/bakery.js <ide> successCallback, <ide> failureCallback <ide> ) <add> ); <add> }, <add> <add> /** <add> Takes the path supplied by the caller and makes a get request to the <add> requestHandlerWithInteraction instance. If setCookiePath is set then <add> it is used to set a cookie back to the ui after authentication. <add> <add> @param path {String} The path to make the api request to. <add> @param data {String} Stringified JSON of parameters to send to the POST <add> endpoint. <add> @param successCallback {Function} Called when the api request completes <add> successfully. <add> @param failureCallback {Function} Called when the api request fails <add> with a response of >= 400 except 401/407 where it does <add> authentication. <add> */ <add> sendPostRequest: function (path, data, successCallback, failureCallback) { <add> var macaroons = this._getMacaroon(); <add> var headers = { <add> 'Bakery-Protocol-Version': 1, <add> 'Content-type': 'application/json' <add> }; <add> if (macaroons !== null) { <add> headers['Macaroons'] = macaroons; <add> } <add> this.webhandler.sendPostRequest( <add> path, headers, data, null, null, false, null, <add> this._requestHandlerWithInteraction.bind( <add> this, path, successCallback, failureCallback) <ide> ); <ide> }, <ide>
Java
apache-2.0
d98ed92d51a57065e006e430ebe0fa02a3fb5670
0
Sargul/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,Sargul/dbeaver
/* * Copyright (C) 2010-2014 Serge Rieder * [email protected] * * 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 */ package org.jkiss.dbeaver.runtime.sql; import org.jkiss.dbeaver.core.Log; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.ui.IWorkbenchPartSite; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.DBeaverPreferences; import org.jkiss.dbeaver.core.DBeaverCore; import org.jkiss.dbeaver.model.DBPDataKind; import org.jkiss.dbeaver.model.DBPDataSource; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.data.DBDDataFilter; import org.jkiss.dbeaver.model.data.DBDDataReceiver; import org.jkiss.dbeaver.model.exec.*; import org.jkiss.dbeaver.model.impl.local.LocalResultSet; import org.jkiss.dbeaver.model.qm.QMUtils; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.sql.SQLDataSource; import org.jkiss.dbeaver.model.sql.SQLQuery; import org.jkiss.dbeaver.model.sql.SQLQueryParameter; import org.jkiss.dbeaver.model.sql.SQLQueryResult; import org.jkiss.dbeaver.runtime.RunnableWithResult; import org.jkiss.dbeaver.runtime.exec.ExecutionQueueErrorJob; import org.jkiss.dbeaver.runtime.jobs.DataSourceJob; import org.jkiss.dbeaver.ui.DBIcon; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.utils.CommonUtils; import java.util.ArrayList; import java.util.List; /** * SQLQueryJob * * @author Serge Rider */ public class SQLQueryJob extends DataSourceJob { static final Log log = Log.getLog(SQLQueryJob.class); private final List<SQLQuery> queries; private final SQLResultsConsumer resultsConsumer; private final SQLQueryListener listener; private final IWorkbenchPartSite partSite; private DBDDataFilter dataFilter; private boolean connectionInvalidated = false; private SQLScriptCommitType commitType; private SQLScriptErrorHandling errorHandling; private boolean fetchResultSets; private long rsOffset; private long rsMaxRows; private DBCStatement curStatement; private final List<DBCResultSet> curResultSets = new ArrayList<DBCResultSet>(); private Throwable lastError = null; private DBCStatistics statistics; private int fetchResultSetNumber; private int resultSetNumber; public SQLQueryJob( IWorkbenchPartSite partSite, String name, DBPDataSource dataSource, List<SQLQuery> queries, SQLResultsConsumer resultsConsumer, SQLQueryListener listener) { super(name, DBIcon.SQL_SCRIPT_EXECUTE.getImageDescriptor(), dataSource); this.partSite = partSite; this.queries = queries; this.resultsConsumer = resultsConsumer; this.listener = listener; { // Read config form preference store IPreferenceStore preferenceStore = getDataSource().getContainer().getPreferenceStore(); this.commitType = SQLScriptCommitType.valueOf(preferenceStore.getString(DBeaverPreferences.SCRIPT_COMMIT_TYPE)); this.errorHandling = SQLScriptErrorHandling.valueOf(preferenceStore.getString(DBeaverPreferences.SCRIPT_ERROR_HANDLING)); this.fetchResultSets = queries.size() == 1 || preferenceStore.getBoolean(DBeaverPreferences.SCRIPT_FETCH_RESULT_SETS); this.rsMaxRows = preferenceStore.getInt(DBeaverPreferences.RESULT_SET_MAX_ROWS); } } public void setFetchResultSets(boolean fetchResultSets) { this.fetchResultSets = fetchResultSets; } public SQLQuery getLastQuery() { return queries.isEmpty() ? null : queries.get(0); } public boolean hasLimits() { return rsOffset >= 0 && rsMaxRows > 0; } public void setResultSetLimit(long offset, long maxRows) { this.rsOffset = offset; this.rsMaxRows = maxRows; } @Override protected IStatus run(DBRProgressMonitor monitor) { statistics = new DBCStatistics(); try { DBCSession session = getDataSource().openSession(monitor, queries.size() > 1 ? DBCExecutionPurpose.USER_SCRIPT : DBCExecutionPurpose.USER, "SQL Query"); try { // Set transaction settings (only if autocommit is off) QMUtils.getDefaultHandler().handleScriptBegin(session); DBCTransactionManager txnManager = session.getTransactionManager(); boolean oldAutoCommit = txnManager.isAutoCommit(); boolean newAutoCommit = (commitType == SQLScriptCommitType.AUTOCOMMIT); if (!oldAutoCommit && newAutoCommit) { txnManager.setAutoCommit(true); } monitor.beginTask(this.getName(), queries.size()); // Notify job start if (listener != null) { listener.onStartScript(); } resultSetNumber = 0; for (int queryNum = 0; queryNum < queries.size(); ) { // Execute query SQLQuery query = queries.get(queryNum); fetchResultSetNumber = resultSetNumber; boolean runNext = executeSingleQuery(session, query, true); if (!runNext) { // Ask to continue if (lastError != null) { log.error(lastError); } boolean isQueue = queryNum < queries.size() - 1; ExecutionQueueErrorJob errorJob = new ExecutionQueueErrorJob( isQueue ? "SQL script execution" : "SQL query execution", lastError, isQueue); errorJob.schedule(); try { errorJob.join(); } catch (InterruptedException e) { log.error(e); } boolean stopScript = false; switch (errorJob.getResponse()) { case STOP: // just stop execution stopScript = true; break; case RETRY: // just make it again continue; case IGNORE: // Just do nothing break; case IGNORE_ALL: errorHandling = SQLScriptErrorHandling.IGNORE; break; } if (stopScript) { break; } } // Check monitor if (monitor.isCanceled()) { break; } monitor.worked(1); queryNum++; } showExecutionResult(session); monitor.done(); // Commit data if (!oldAutoCommit && commitType != SQLScriptCommitType.AUTOCOMMIT) { if (lastError == null || errorHandling == SQLScriptErrorHandling.STOP_COMMIT) { if (commitType != SQLScriptCommitType.NO_COMMIT) { monitor.beginTask("Commit data", 1); txnManager.commit(); monitor.done(); } } else { monitor.beginTask("Rollback data", 1); txnManager.rollback(null); monitor.done(); } } // Restore transactions settings if (!oldAutoCommit && newAutoCommit) { txnManager.setAutoCommit(false); } QMUtils.getDefaultHandler().handleScriptEnd(session); // Return success return new Status( Status.OK, DBeaverCore.getCorePluginID(), "SQL job completed"); } finally { session.close(); } } catch (Throwable ex) { return new Status( Status.ERROR, DBeaverCore.getCorePluginID(), "Error during SQL job execution: " + ex.getMessage()); } finally { // Notify job end if (listener != null) { listener.onEndScript(statistics, lastError != null); } } } private boolean executeSingleQuery(DBCSession session, SQLQuery sqlStatement, boolean fireEvents) { lastError = null; String sqlQuery = sqlStatement.getQuery(); DBPDataSource dataSource = getDataSource(); SQLQueryResult curResult = new SQLQueryResult(sqlStatement); if (rsOffset > 0) { curResult.setRowOffset(rsOffset); } long startTime = System.currentTimeMillis(); try { // Prepare statement closeStatement(); // Check and invalidate connection if (!connectionInvalidated && dataSource.getContainer().getPreferenceStore().getBoolean(DBeaverPreferences.STATEMENT_INVALIDATE_BEFORE_EXECUTE)) { dataSource.invalidateContext(session.getProgressMonitor()); connectionInvalidated = true; } // Modify query (filters + parameters) if (dataFilter != null && dataFilter.hasFilters() && dataSource instanceof SQLDataSource) { sqlQuery = ((SQLDataSource) dataSource).getSQLDialect().addFiltersToQuery(dataSource, sqlQuery, dataFilter); } Boolean hasParameters = prepareStatementParameters(sqlStatement); if (hasParameters == null) { return false; } if (fireEvents && listener != null) { // Notify query start listener.onStartQuery(sqlStatement); } statistics.setQueryText(sqlQuery); startTime = System.currentTimeMillis(); curStatement = DBUtils.prepareStatement( session, hasParameters ? DBCStatementType.QUERY : DBCStatementType.SCRIPT, sqlQuery, rsOffset, rsMaxRows); curStatement.setStatementSource(sqlStatement); if (hasParameters) { bindStatementParameters(session, sqlStatement); } // Execute statement try { boolean hasResultSet = curStatement.executeStatement(); curResult.setHasResultSet(hasResultSet); statistics.addExecuteTime(System.currentTimeMillis() - startTime); long updateCount = -1; while (hasResultSet || resultSetNumber == 0 || updateCount >= 0) { // Fetch data only if we have to fetch all results or if it is rs requested if (fetchResultSetNumber < 0 || fetchResultSetNumber == resultSetNumber) { if (hasResultSet && fetchResultSets) { DBDDataReceiver dataReceiver = resultsConsumer.getDataReceiver(sqlStatement, resultSetNumber); if (dataReceiver != null) { hasResultSet = fetchQueryData(session, curStatement.openResultSet(), curResult, dataReceiver, true); } } } if (!hasResultSet) { try { updateCount = curStatement.getUpdateRowCount(); if (updateCount >= 0) { curResult.setUpdateCount(updateCount); statistics.addRowsUpdated(updateCount); } } catch (DBCException e) { // In some cases we can't read update count // This is bad but we can live with it // Just print a warning log.warn("Can't obtain update count", e); } } if (hasResultSet && fetchResultSets) { resultSetNumber++; } if (!hasResultSet && updateCount < 0) { // Nothing else to fetch break; } statistics.addStatementsCount(); if (dataSource.getInfo().supportsMultipleResults()) { hasResultSet = curStatement.nextResults(); updateCount = hasResultSet ? -1 : 0; } else { break; } } } finally { //monitor.subTask("Close query"); if (!keepStatementOpen()) { closeStatement(); } // Release parameters releaseStatementParameters(sqlStatement); } } catch (Throwable ex) { if (!(ex instanceof DBException)) { log.error("Unexpected error while processing SQL", ex); } curResult.setError(ex); lastError = ex; } curResult.setQueryTime(System.currentTimeMillis() - startTime); if (fireEvents && listener != null) { // Notify query end listener.onEndQuery(curResult); } if (curResult.getError() != null && errorHandling != SQLScriptErrorHandling.IGNORE) { return false; } // Success return true; } private void showExecutionResult(DBCSession session) throws DBCException { if (statistics.getStatementsCount() > 1 || resultSetNumber == 0) { SQLQuery query = new SQLQuery(this, "", -1, -1); query.setData("Statistics"); // It will set tab name to "Stats" DBDDataReceiver dataReceiver = resultsConsumer.getDataReceiver(query, resultSetNumber); if (dataReceiver != null) { fetchExecutionResult(session, dataReceiver, query); } } } private void fetchExecutionResult(DBCSession session, DBDDataReceiver dataReceiver, SQLQuery query) throws DBCException { // Fetch fake result set LocalResultSet fakeResultSet = new LocalResultSet(session, curStatement); SQLQueryResult resultInfo = new SQLQueryResult(query); if (statistics.getStatementsCount() > 1) { // Multiple statements - show script statistics fakeResultSet.addColumn("Queries", DBPDataKind.NUMERIC); fakeResultSet.addColumn("Updated Rows", DBPDataKind.NUMERIC); fakeResultSet.addColumn("Execute time", DBPDataKind.NUMERIC); fakeResultSet.addColumn("Fetch time", DBPDataKind.NUMERIC); fakeResultSet.addColumn("Total time", DBPDataKind.NUMERIC); fakeResultSet.addRow( statistics.getStatementsCount(), statistics.getRowsUpdated(), statistics.getExecuteTime(), statistics.getFetchTime(), statistics.getTotalTime()); resultInfo.setResultSetName("Statistics"); } else { // Single statement long updateCount = statistics.getRowsUpdated(); if (updateCount >= 0) { fakeResultSet.addColumn("Updated Rows", DBPDataKind.NUMERIC); fakeResultSet.addRow(updateCount); } else { fakeResultSet.addColumn("Result", DBPDataKind.NUMERIC); } resultInfo.setResultSetName("Result"); } fetchQueryData(session, fakeResultSet, resultInfo, dataReceiver, false); } private Boolean prepareStatementParameters(SQLQuery sqlStatement) { // Bind parameters if (!CommonUtils.isEmpty(sqlStatement.getParameters())) { List<SQLQueryParameter> unresolvedParams = new ArrayList<SQLQueryParameter>(); for (SQLQueryParameter param : sqlStatement.getParameters()) { if (!param.isResolved()) { unresolvedParams.add(param); } } if (!CommonUtils.isEmpty(unresolvedParams)) { // Resolve parameters if (!fillStatementParameters(unresolvedParams)) { return null; } } // Set values for all parameters return true; } return false; } private boolean fillStatementParameters(final List<SQLQueryParameter> parameters) { final RunnableWithResult<Boolean> binder = new RunnableWithResult<Boolean>() { @Override public void run() { SQLQueryParameterBindDialog dialog = new SQLQueryParameterBindDialog( partSite, getDataSource(), parameters); result = (dialog.open() == IDialogConstants.OK_ID); } }; UIUtils.runInUI(partSite.getShell(), binder); return binder.getResult(); } private void bindStatementParameters(DBCSession session, SQLQuery sqlStatement) throws DBCException { // Bind them for (SQLQueryParameter param : sqlStatement.getParameters()) { if (param.isResolved()) { // convert value to native form Object realValue = param.getValueHandler().getValueFromObject(session, param, param.getValue(), false); // bind param.getValueHandler().bindValueObject( session, curStatement, param, param.getOrdinalPosition(), realValue); } } } private void releaseStatementParameters(SQLQuery sqlStatement) { if (!CommonUtils.isEmpty(sqlStatement.getParameters())) { for (SQLQueryParameter param : sqlStatement.getParameters()) { if (param.isResolved()) { param.getValueHandler().releaseValueObject(param.getValue()); } } } } private boolean fetchQueryData(DBCSession session, DBCResultSet resultSet, SQLQueryResult result, DBDDataReceiver dataReceiver, boolean updateStatistics) throws DBCException { if (dataReceiver == null) { // No data pump - skip fetching stage return false; } if (resultSet == null) { return false; } curResultSets.add(resultSet); DBRProgressMonitor monitor = session.getProgressMonitor(); monitor.subTask("Fetch result set"); long rowCount = 0; dataReceiver.fetchStart(session, resultSet, rsOffset, rsMaxRows); try { // Retrieve source entity if (result != null) { DBCResultSetMetaData rsMeta = resultSet.getResultSetMetaData(); String sourceName = null; for (DBCAttributeMetaData attr : rsMeta.getAttributes()) { String entityName = attr.getEntityName(); if (!CommonUtils.isEmpty(entityName)) { if (sourceName == null) { sourceName = entityName; } else if (!sourceName.equals(entityName)) { // Multiple source entities sourceName += "(+)"; break; } } } /* if (CommonUtils.isEmpty(sourceName)) { try { sourceName = resultSet.getResultSetName(); } catch (DBCException e) { log.debug(e); } } */ if (!CommonUtils.isEmpty(sourceName)) { result.setResultSetName(sourceName); } } long fetchStartTime = System.currentTimeMillis(); // Fetch all rows while ((!hasLimits() || rowCount < rsMaxRows) && resultSet.nextRow()) { if (monitor.isCanceled()) { break; } rowCount++; if (rowCount > 0 && rowCount % 100 == 0) { monitor.subTask(rowCount + " rows fetched"); monitor.worked(100); } dataReceiver.fetchRow(session, resultSet); } if (updateStatistics) { statistics.setFetchTime(System.currentTimeMillis() - fetchStartTime); } } finally { try { dataReceiver.fetchEnd(session); } catch (DBCException e) { log.error("Error while handling end of result set fetch", e); } dataReceiver.close(); } if (result != null) { result.setRowCount(rowCount); } if (updateStatistics) { statistics.setRowsFetched(rowCount); } monitor.subTask(rowCount + " rows fetched"); return true; } private boolean keepStatementOpen() { // Only in single query mode and if pref option set to true DBPDataSource dataSource = getDataSource(); return queries.size() == 1 && dataSource != null && dataSource.getContainer().getPreferenceStore().getBoolean(DBeaverPreferences.KEEP_STATEMENT_OPEN); } private void closeStatement() { if (curStatement != null) { for (DBCResultSet resultSet : curResultSets) { resultSet.close(); } curResultSets.clear(); curStatement.close(); curStatement = null; } } /* protected void canceling() { // Cancel statement only for the second time cancel is called */ /*if (!statementCancel) { statementCancel = true; } else *//* { if (!statementCanceled && curStatement != null) { try { curStatement.cancelBlock(); } catch (DBException e) { log.error("Can't cancel execution: " + e.getMessage()); } statementCanceled = true; } } } */ public void extractData(DBCSession session) throws DBCException { statistics = new DBCStatistics(); if (queries.size() != 1) { throw new DBCException("Invalid state of SQL Query job"); } resultSetNumber = 0; SQLQuery query = queries.get(0); session.getProgressMonitor().beginTask(query.getQuery(), 1); try { boolean result = executeSingleQuery(session, query, true); if (!result && lastError != null) { if (lastError instanceof DBCException) { throw (DBCException) lastError; } else { throw new DBCException(lastError, getDataSource()); } } else if (result) { showExecutionResult(session); } } finally { session.getProgressMonitor().done(); } } public void setDataFilter(DBDDataFilter dataFilter) { this.dataFilter = dataFilter; } public DBCStatistics getStatistics() { return statistics; } public void setFetchResultSetNumber(int fetchResultSetNumber) { this.fetchResultSetNumber = fetchResultSetNumber; } }
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/runtime/sql/SQLQueryJob.java
/* * Copyright (C) 2010-2014 Serge Rieder * [email protected] * * 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 */ package org.jkiss.dbeaver.runtime.sql; import org.jkiss.dbeaver.core.Log; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.ui.IWorkbenchPartSite; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.DBeaverPreferences; import org.jkiss.dbeaver.core.DBeaverCore; import org.jkiss.dbeaver.model.DBPDataKind; import org.jkiss.dbeaver.model.DBPDataSource; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.data.DBDDataFilter; import org.jkiss.dbeaver.model.data.DBDDataReceiver; import org.jkiss.dbeaver.model.exec.*; import org.jkiss.dbeaver.model.impl.local.LocalResultSet; import org.jkiss.dbeaver.model.qm.QMUtils; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.sql.SQLDataSource; import org.jkiss.dbeaver.model.sql.SQLQuery; import org.jkiss.dbeaver.model.sql.SQLQueryParameter; import org.jkiss.dbeaver.model.sql.SQLQueryResult; import org.jkiss.dbeaver.runtime.RunnableWithResult; import org.jkiss.dbeaver.runtime.exec.ExecutionQueueErrorJob; import org.jkiss.dbeaver.runtime.jobs.DataSourceJob; import org.jkiss.dbeaver.ui.DBIcon; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.utils.CommonUtils; import java.util.ArrayList; import java.util.List; /** * SQLQueryJob * * @author Serge Rider */ public class SQLQueryJob extends DataSourceJob { static final Log log = Log.getLog(SQLQueryJob.class); private final List<SQLQuery> queries; private final SQLResultsConsumer resultsConsumer; private final SQLQueryListener listener; private final IWorkbenchPartSite partSite; private DBDDataFilter dataFilter; private boolean connectionInvalidated = false; private SQLScriptCommitType commitType; private SQLScriptErrorHandling errorHandling; private boolean fetchResultSets; private long rsOffset; private long rsMaxRows; private DBCStatement curStatement; private final List<DBCResultSet> curResultSets = new ArrayList<DBCResultSet>(); private Throwable lastError = null; private DBCStatistics statistics; private int fetchResultSetNumber; private int resultSetNumber; public SQLQueryJob( IWorkbenchPartSite partSite, String name, DBPDataSource dataSource, List<SQLQuery> queries, SQLResultsConsumer resultsConsumer, SQLQueryListener listener) { super(name, DBIcon.SQL_SCRIPT_EXECUTE.getImageDescriptor(), dataSource); this.partSite = partSite; this.queries = queries; this.resultsConsumer = resultsConsumer; this.listener = listener; { // Read config form preference store IPreferenceStore preferenceStore = getDataSource().getContainer().getPreferenceStore(); this.commitType = SQLScriptCommitType.valueOf(preferenceStore.getString(DBeaverPreferences.SCRIPT_COMMIT_TYPE)); this.errorHandling = SQLScriptErrorHandling.valueOf(preferenceStore.getString(DBeaverPreferences.SCRIPT_ERROR_HANDLING)); this.fetchResultSets = queries.size() == 1 || preferenceStore.getBoolean(DBeaverPreferences.SCRIPT_FETCH_RESULT_SETS); this.rsMaxRows = preferenceStore.getInt(DBeaverPreferences.RESULT_SET_MAX_ROWS); } } public void setFetchResultSets(boolean fetchResultSets) { this.fetchResultSets = fetchResultSets; } public SQLQuery getLastQuery() { return queries.isEmpty() ? null : queries.get(0); } public boolean hasLimits() { return rsOffset >= 0 && rsMaxRows > 0; } public void setResultSetLimit(long offset, long maxRows) { this.rsOffset = offset; this.rsMaxRows = maxRows; } @Override protected IStatus run(DBRProgressMonitor monitor) { statistics = new DBCStatistics(); try { DBCSession session = getDataSource().openSession(monitor, queries.size() > 1 ? DBCExecutionPurpose.USER_SCRIPT : DBCExecutionPurpose.USER, "SQL Query"); try { // Set transaction settings (only if autocommit is off) QMUtils.getDefaultHandler().handleScriptBegin(session); DBCTransactionManager txnManager = session.getTransactionManager(); boolean oldAutoCommit = txnManager.isAutoCommit(); boolean newAutoCommit = (commitType == SQLScriptCommitType.AUTOCOMMIT); if (!oldAutoCommit && newAutoCommit) { txnManager.setAutoCommit(true); } monitor.beginTask(this.getName(), queries.size()); // Notify job start if (listener != null) { listener.onStartScript(); } resultSetNumber = 0; for (int queryNum = 0; queryNum < queries.size(); ) { // Execute query SQLQuery query = queries.get(queryNum); fetchResultSetNumber = resultSetNumber; boolean runNext = executeSingleQuery(session, query, true); if (!runNext) { // Ask to continue if (lastError != null) { log.error(lastError); } boolean isQueue = queryNum < queries.size() - 1; ExecutionQueueErrorJob errorJob = new ExecutionQueueErrorJob( isQueue ? "SQL script execution" : "SQL query execution", lastError, isQueue); errorJob.schedule(); try { errorJob.join(); } catch (InterruptedException e) { log.error(e); } boolean stopScript = false; switch (errorJob.getResponse()) { case STOP: // just stop execution stopScript = true; break; case RETRY: // just make it again continue; case IGNORE: // Just do nothing break; case IGNORE_ALL: errorHandling = SQLScriptErrorHandling.IGNORE; break; } if (stopScript) { break; } } // Check monitor if (monitor.isCanceled()) { break; } monitor.worked(1); queryNum++; } showExecutionResult(session); monitor.done(); // Commit data if (!oldAutoCommit && commitType != SQLScriptCommitType.AUTOCOMMIT) { if (lastError == null || errorHandling == SQLScriptErrorHandling.STOP_COMMIT) { if (commitType != SQLScriptCommitType.NO_COMMIT) { monitor.beginTask("Commit data", 1); txnManager.commit(); monitor.done(); } } else { monitor.beginTask("Rollback data", 1); txnManager.rollback(null); monitor.done(); } } // Restore transactions settings if (!oldAutoCommit && newAutoCommit) { txnManager.setAutoCommit(false); } QMUtils.getDefaultHandler().handleScriptEnd(session); // Return success return new Status( Status.OK, DBeaverCore.getCorePluginID(), "SQL job completed"); } finally { session.close(); } } catch (Throwable ex) { return new Status( Status.ERROR, DBeaverCore.getCorePluginID(), "Error during SQL job execution: " + ex.getMessage()); } finally { // Notify job end if (listener != null) { listener.onEndScript(statistics, lastError != null); } } } private boolean executeSingleQuery(DBCSession session, SQLQuery sqlStatement, boolean fireEvents) { lastError = null; String sqlQuery = sqlStatement.getQuery(); DBPDataSource dataSource = getDataSource(); SQLQueryResult curResult = new SQLQueryResult(sqlStatement); if (rsOffset > 0) { curResult.setRowOffset(rsOffset); } long startTime = System.currentTimeMillis(); try { // Prepare statement closeStatement(); // Check and invalidate connection if (!connectionInvalidated && dataSource.getContainer().getPreferenceStore().getBoolean(DBeaverPreferences.STATEMENT_INVALIDATE_BEFORE_EXECUTE)) { dataSource.invalidateContext(session.getProgressMonitor()); connectionInvalidated = true; } // Modify query (filters + parameters) if (dataFilter != null && dataFilter.hasFilters() && dataSource instanceof SQLDataSource) { sqlQuery = ((SQLDataSource) dataSource).getSQLDialect().addFiltersToQuery(dataSource, sqlQuery, dataFilter); } Boolean hasParameters = prepareStatementParameters(sqlStatement); if (hasParameters == null) { return false; } if (fireEvents && listener != null) { // Notify query start listener.onStartQuery(sqlStatement); } statistics.setQueryText(sqlQuery); startTime = System.currentTimeMillis(); curStatement = DBUtils.prepareStatement( session, hasParameters ? DBCStatementType.QUERY : DBCStatementType.SCRIPT, sqlQuery, rsOffset, rsMaxRows); curStatement.setStatementSource(sqlStatement); if (hasParameters) { bindStatementParameters(session, sqlStatement); } // Execute statement try { boolean hasResultSet = curStatement.executeStatement(); curResult.setHasResultSet(hasResultSet); statistics.addExecuteTime(System.currentTimeMillis() - startTime); long updateCount = -1; while (hasResultSet || resultSetNumber == 0 || updateCount >= 0) { // Fetch data only if we have to fetch all results or if it is rs requested if (fetchResultSetNumber < 0 || fetchResultSetNumber == resultSetNumber) { if (hasResultSet && fetchResultSets) { DBDDataReceiver dataReceiver = resultsConsumer.getDataReceiver(sqlStatement, resultSetNumber); if (dataReceiver != null) { hasResultSet = fetchQueryData(session, curStatement.openResultSet(), curResult, dataReceiver, true); } } } if (!hasResultSet) { try { updateCount = curStatement.getUpdateRowCount(); if (updateCount >= 0) { curResult.setUpdateCount(updateCount); statistics.addRowsUpdated(updateCount); } } catch (DBCException e) { // In some cases we can't read update count // This is bad but we can live with it // Just print a warning log.warn("Can't obtain update count", e); } } if (hasResultSet && fetchResultSets) { resultSetNumber++; } if (!hasResultSet && updateCount < 0) { // Nothing else to fetch break; } statistics.addStatementsCount(); if (dataSource.getInfo().supportsMultipleResults()) { hasResultSet = curStatement.nextResults(); updateCount = hasResultSet ? -1 : 0; } else { break; } } } finally { //monitor.subTask("Close query"); if (!keepStatementOpen()) { closeStatement(); } // Release parameters releaseStatementParameters(sqlStatement); } } catch (Throwable ex) { if (!(ex instanceof DBException)) { log.error("Unexpected error while processing SQL", ex); } curResult.setError(ex); lastError = ex; } curResult.setQueryTime(System.currentTimeMillis() - startTime); if (fireEvents && listener != null) { // Notify query end listener.onEndQuery(curResult); } if (curResult.getError() != null && errorHandling != SQLScriptErrorHandling.IGNORE) { return false; } // Success return true; } private void showExecutionResult(DBCSession session) throws DBCException { if (statistics.getStatementsCount() > 1 || resultSetNumber == 0) { SQLQuery query = new SQLQuery(this, "", -1, -1); query.setData("Statistics"); // It will set tab name to "Stats" DBDDataReceiver dataReceiver = resultsConsumer.getDataReceiver(query, resultSetNumber); if (dataReceiver != null) { fetchExecutionResult(session, dataReceiver, query); } } } private void fetchExecutionResult(DBCSession session, DBDDataReceiver dataReceiver, SQLQuery query) throws DBCException { // Fetch fake result set LocalResultSet fakeResultSet = new LocalResultSet(session, curStatement); SQLQueryResult resultInfo = new SQLQueryResult(query); if (statistics.getStatementsCount() > 1) { // Multiple statements - show script statistics fakeResultSet.addColumn("Queries", DBPDataKind.NUMERIC); fakeResultSet.addColumn("Updated Rows", DBPDataKind.NUMERIC); fakeResultSet.addColumn("Execute time", DBPDataKind.NUMERIC); fakeResultSet.addColumn("Fetch time", DBPDataKind.NUMERIC); fakeResultSet.addColumn("Total time", DBPDataKind.NUMERIC); fakeResultSet.addRow( statistics.getStatementsCount(), statistics.getRowsUpdated(), statistics.getExecuteTime(), statistics.getFetchTime(), statistics.getTotalTime()); resultInfo.setResultSetName("Statistics"); } else { // Single statement long updateCount = statistics.getRowsUpdated(); if (updateCount >= 0) { fakeResultSet.addColumn("Updated Rows", DBPDataKind.NUMERIC); fakeResultSet.addRow(updateCount); } else { fakeResultSet.addColumn("Result", DBPDataKind.NUMERIC); } resultInfo.setResultSetName("Result"); } fetchQueryData(session, fakeResultSet, resultInfo, dataReceiver, false); } private Boolean prepareStatementParameters(SQLQuery sqlStatement) { // Bind parameters if (!CommonUtils.isEmpty(sqlStatement.getParameters())) { List<SQLQueryParameter> unresolvedParams = new ArrayList<SQLQueryParameter>(); for (SQLQueryParameter param : sqlStatement.getParameters()) { if (!param.isResolved()) { unresolvedParams.add(param); } } if (!CommonUtils.isEmpty(unresolvedParams)) { // Resolve parameters if (!fillStatementParameters(unresolvedParams)) { return null; } } // Set values for all parameters return true; } return false; } private boolean fillStatementParameters(final List<SQLQueryParameter> parameters) { final RunnableWithResult<Boolean> binder = new RunnableWithResult<Boolean>() { @Override public void run() { SQLQueryParameterBindDialog dialog = new SQLQueryParameterBindDialog( partSite, getDataSource(), parameters); result = (dialog.open() == IDialogConstants.OK_ID); } }; UIUtils.runInUI(partSite.getShell(), binder); return binder.getResult(); } private void bindStatementParameters(DBCSession session, SQLQuery sqlStatement) throws DBCException { // Bind them for (SQLQueryParameter param : sqlStatement.getParameters()) { if (param.isResolved()) { param.getValueHandler().bindValueObject( session, curStatement, param, param.getOrdinalPosition(), param.getValue()); } } } private void releaseStatementParameters(SQLQuery sqlStatement) { if (!CommonUtils.isEmpty(sqlStatement.getParameters())) { for (SQLQueryParameter param : sqlStatement.getParameters()) { if (param.isResolved()) { param.getValueHandler().releaseValueObject(param.getValue()); } } } } private boolean fetchQueryData(DBCSession session, DBCResultSet resultSet, SQLQueryResult result, DBDDataReceiver dataReceiver, boolean updateStatistics) throws DBCException { if (dataReceiver == null) { // No data pump - skip fetching stage return false; } if (resultSet == null) { return false; } curResultSets.add(resultSet); DBRProgressMonitor monitor = session.getProgressMonitor(); monitor.subTask("Fetch result set"); long rowCount = 0; dataReceiver.fetchStart(session, resultSet, rsOffset, rsMaxRows); try { // Retrieve source entity if (result != null) { DBCResultSetMetaData rsMeta = resultSet.getResultSetMetaData(); String sourceName = null; for (DBCAttributeMetaData attr : rsMeta.getAttributes()) { String entityName = attr.getEntityName(); if (!CommonUtils.isEmpty(entityName)) { if (sourceName == null) { sourceName = entityName; } else if (!sourceName.equals(entityName)) { // Multiple source entities sourceName += "(+)"; break; } } } /* if (CommonUtils.isEmpty(sourceName)) { try { sourceName = resultSet.getResultSetName(); } catch (DBCException e) { log.debug(e); } } */ if (!CommonUtils.isEmpty(sourceName)) { result.setResultSetName(sourceName); } } long fetchStartTime = System.currentTimeMillis(); // Fetch all rows while ((!hasLimits() || rowCount < rsMaxRows) && resultSet.nextRow()) { if (monitor.isCanceled()) { break; } rowCount++; if (rowCount > 0 && rowCount % 100 == 0) { monitor.subTask(rowCount + " rows fetched"); monitor.worked(100); } dataReceiver.fetchRow(session, resultSet); } if (updateStatistics) { statistics.setFetchTime(System.currentTimeMillis() - fetchStartTime); } } finally { try { dataReceiver.fetchEnd(session); } catch (DBCException e) { log.error("Error while handling end of result set fetch", e); } dataReceiver.close(); } if (result != null) { result.setRowCount(rowCount); } if (updateStatistics) { statistics.setRowsFetched(rowCount); } monitor.subTask(rowCount + " rows fetched"); return true; } private boolean keepStatementOpen() { // Only in single query mode and if pref option set to true DBPDataSource dataSource = getDataSource(); return queries.size() == 1 && dataSource != null && dataSource.getContainer().getPreferenceStore().getBoolean(DBeaverPreferences.KEEP_STATEMENT_OPEN); } private void closeStatement() { if (curStatement != null) { for (DBCResultSet resultSet : curResultSets) { resultSet.close(); } curResultSets.clear(); curStatement.close(); curStatement = null; } } /* protected void canceling() { // Cancel statement only for the second time cancel is called */ /*if (!statementCancel) { statementCancel = true; } else *//* { if (!statementCanceled && curStatement != null) { try { curStatement.cancelBlock(); } catch (DBException e) { log.error("Can't cancel execution: " + e.getMessage()); } statementCanceled = true; } } } */ public void extractData(DBCSession session) throws DBCException { statistics = new DBCStatistics(); if (queries.size() != 1) { throw new DBCException("Invalid state of SQL Query job"); } resultSetNumber = 0; SQLQuery query = queries.get(0); session.getProgressMonitor().beginTask(query.getQuery(), 1); try { boolean result = executeSingleQuery(session, query, true); if (!result && lastError != null) { if (lastError instanceof DBCException) { throw (DBCException) lastError; } else { throw new DBCException(lastError, getDataSource()); } } else if (result) { showExecutionResult(session); } } finally { session.getProgressMonitor().done(); } } public void setDataFilter(DBDDataFilter dataFilter) { this.dataFilter = dataFilter; } public DBCStatistics getStatistics() { return statistics; } public void setFetchResultSetNumber(int fetchResultSetNumber) { this.fetchResultSetNumber = fetchResultSetNumber; } }
Save parameters' types Former-commit-id: 0904e94dab61306e5c3e1ecb7782d7e788c7232e
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/runtime/sql/SQLQueryJob.java
Save parameters' types
<ide><path>lugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/runtime/sql/SQLQueryJob.java <ide> // Bind them <ide> for (SQLQueryParameter param : sqlStatement.getParameters()) { <ide> if (param.isResolved()) { <add> // convert value to native form <add> Object realValue = param.getValueHandler().getValueFromObject(session, param, param.getValue(), false); <add> // bind <ide> param.getValueHandler().bindValueObject( <ide> session, <ide> curStatement, <ide> param, <ide> param.getOrdinalPosition(), <del> param.getValue()); <add> realValue); <ide> } <ide> } <ide> }